问:
Getting error in LSTM Model while using keras tuner for hyperparameter tuning
I am getting an error

Received incompatible tensor with shape (13, 224) when attempting to restore variable with shape (1, 224) and name layer_with_weights-0/kernel/.ATTRIBUTES/VARIABLE_VALUE.

I don't know what it means. Any lead to this could be helpful.
my Code is following -

```<code>callback = EarlyStopping(monitor='loss', patience=3)

            def build_model(hp):
                model=keras.Sequential() #.reshape(input_shape=(1,len(x_test),totalColumns))
                #model.add(layers.Flatten()) #layers.Flatten(input_shape=(totalColumns,1)))

                for i in range(hp.Int('layers',1,10)):
                    model.add(layers.Dense(units=hp.Int('units_'+str(i),32,512,step = 32),input_shape=(totalColumns,1),
                                           activation=hp.Choice('act_'+str(i),['relu'])))
                model.add(Dropout(hp.Float('Dropout_rate',min_value=0,max_value=0.5,step=0.1)))
                model.add(layers.Dense(10,activation='softmax'))
                model.compile(optimizer = keras.optimizers.Adam(hp.Choice('learning_rate',values=[1e-2,1e-4])),
                                  loss='mean_squared_error',metrics=[tf.keras.metrics.RootMeanSquaredError()])
                return model

            tuner = RandomSearch(build_model,objective=keras_tuner.Objective("root_mean_squared_error", direction="min")
                                 ,max_trials = 1,executions_per_trial=1) #

            tuner.search(x_train,y_train,epochs = 1,validation_data=(x_test,y_test),callbacks=[callback])

            best_model = tuner.get_best_models(num_models=1)[0]
            pred=best_model.predict(x_test)

rows,columns = pred.shape
            test_pred = np.array([])
            for i in range(rows):
                value = pred[i].sum()
                test_pred= np.append(test_pred, value)
</code>```

My x_train is of shape (43130,13) and y_train is of shape (43130,1). and its a time-series data

I also don't know when I use layer.Flatten it works and I get prediction with shape (43130,10) instead of (43130,1)

Please suggest me few things where I am going wrong!

Body:
I am getting an error

Received incompatible tensor with shape (13, 224) when attempting to restore variable with shape (1, 224) and name layer_with_weights-0/kernel/.ATTRIBUTES/VARIABLE_VALUE.

I don't know what it means. Any lead to this could be helpful.
my Code is following -

callback = EarlyStopping(monitor='loss', patience=3)

            def build_model(hp):
                model=keras.Sequential() #.reshape(input_shape=(1,len(x_test),totalColumns))
                #model.add(layers.Flatten()) #layers.Flatten(input_shape=(totalColumns,1)))

                for i in range(hp.Int('layers',1,10)):
                    model.add(layers.Dense(units=hp.Int('units_'+str(i),32,512,step = 32),input_shape=(totalColumns,1),
                                           activation=hp.Choice('act_'+str(i),['relu'])))
                model.add(Dropout(hp.Float('Dropout_rate',min_value=0,max_value=0.5,step=0.1)))
                model.add(layers.Dense(10,activation='softmax'))
                model.compile(optimizer = keras.optimizers.Adam(hp.Choice('learning_rate',values=[1e-2,1e-4])),
                                  loss='mean_squared_error',metrics=[tf.keras.metrics.RootMeanSquaredError()])
                return model

            tuner = RandomSearch(build_model,objective=keras_tuner.Objective("root_mean_squared_error", direction="min")
                                 ,max_trials = 1,executions_per_trial=1) #

            tuner.search(x_train,y_train,epochs = 1,validation_data=(x_test,y_test),callbacks=[callback])

            best_model = tuner.get_best_models(num_models=1)[0]
            pred=best_model.predict(x_test)

rows,columns = pred.shape
            test_pred = np.array([])
            for i in range(rows):
                value = pred[i].sum()
                test_pred= np.append(test_pred, value)

My x_train is of shape (43130,13) and y_train is of shape (43130,1). and its a time-series data

I also don't know when I use layer.Flatten it works and I get prediction with shape (43130,10) instead of (43130,1)

Please suggest me few things where I am going wrong!


来源: stackexchange

问:
How to detect a postcode (5-7 char) always at the right of a string, and insert a SPACE before it, in a SQL update statement
However before the space is inserted, the expression needs to check that its not already inerted the space, so we do not end up with 2 spaces, then 3 and so on, so this...

```<code>HAUGHTON HOUSEALFORDAB33 8NA
BURIAL GROUNDTOUGHALFORDAB33 8ER
TORRYCRIEN CROFTGLENKINDIEALFORDAB33 8SQ
KIRKTON FORBESALFORDG1 1DN
</code>```

Would become...

```<code>HAUGHTON HOUSEALFORD AB33 8NA
BURIAL GROUNDTOUGHALFORD AB33 8ER
TORRYCRIEN CROFTGLENKINDIEALFORD AB33 8SQ
KIRKTON FORBESALFORD G1 1DN
</code>```

This could be tricky - maybe in some way combining with REGEX, however, because letters are before the first letter in POSTCODE it may need to detect a valid POSTCODE

ContentLicense: CC BY-SA 4.0

Body:
However before the space is inserted, the expression needs to check that its not already inerted the space, so we do not end up with 2 spaces, then 3 and so on, so this...

HAUGHTON HOUSEALFORDAB33 8NA
BURIAL GROUNDTOUGHALFORDAB33 8ER
TORRYCRIEN CROFTGLENKINDIEALFORDAB33 8SQ
KIRKTON FORBESALFORDG1 1DN

Would become...

HAUGHTON HOUSEALFORD AB33 8NA
BURIAL GROUNDTOUGHALFORD AB33 8ER
TORRYCRIEN CROFTGLENKINDIEALFORD AB33 8SQ
KIRKTON FORBESALFORD G1 1DN

This could be tricky - maybe in some way combining with REGEX, however, because letters are before the first letter in POSTCODE it may need to detect a valid POSTCODE


问:
New Salesforce custom profile not available in user provisioning via Azure AD
We use Azure AD user provisioning, to create and manage users in Salesforce. In itself this is working correctly. But... we have created a new (custom) profile in Salesforce (which Azure AD refers to as role) and this new profile is not being loaded into Azure AD. When creating a new user, we see our old custom profiles, but not the new one.

We started looking in the provisioning logs and saw a lot of "failed" entries. The first part of these logs reads like this:

The name, id, and claim properties of an app role in Azure AD must be
unique. We are unable to update an app role as one or more properties
are not unique. This is most commonly caused by having non-unique role
names in the directory from which roles are being imported.

And then a bunch of non-unique profiles/roles are listed. These are all standard profiles, such as Standard User and System Administrator. They appear twice in the list.

Going back to the screen where we add users, sure enough, these double entries are there as well. Each duplicate being an inactive choice. And: some old custom profiles are shown, also inactive. But not the new one.

This has worked before, as we see the old custom profiles listed. But somewhere/somehow double entries have been added and now we are stuck.

What is the solution? I have no idea on how to remove those duplicate entries from Azure AD. In Salesforce, there are no duplicate profiles. And even if I could remove the duplicate entries from Azure AD, maybe they would be added again on the first provisioning run.


问:
How to fetch customers in reactjs using shopify api
I am new to API. I want to fetch customers in reactjs using shopify customer api.
I'm using following code:

```<code>const apiUrl = `https://${process.env.GATSBY_SHOPIFY_API_KEY}:${process.env.GATSBY_SHOPIFY_PASSWORD}@${shopify-store}/admin/api/${version}/customers.json`;

useEffect(() => {
        fetch(apiUrl , {
            method: 'GET',
            headers: {
              'Content-Type': 'application/json',
              'Access-Control-Allow-Origin':'*'
            },
            mode: 'cors',
          })
            .then((response) => {
              console.log('response:', response);
            })
            .catch((error) => {
              console.error('Error:', error);
            });
    },[])
</code>```

Above code is producing error:

Url with cedentials can not be used in FETCH

I also tried using AXIOS. Code is following:

```<code>    const getData = async () => {
        try {
            const res = await axios.get(apiUrl);
            console.log("res >>>", res)
        } catch(error) {
            console.log("error >>", error)
        }
    }
</code>```

Above code is also producing error:

Access to XMLHttpRequest at 'apiUrl' from origin 'http://localhost:8000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Please help me out with api!
Thanks in advance

I want to solve the issue as soon as possible. I have tried all the methods I could find on internet.

Body:
I am new to API. I want to fetch customers in reactjs using shopify customer api.
I'm using following code:

const apiUrl = `https://${process.env.GATSBY_SHOPIFY_API_KEY}:${process.env.GATSBY_SHOPIFY_PASSWORD}@${shopify-store}/admin/api/${version}/customers.json`;

useEffect(() => {
        fetch(apiUrl , {
            method: 'GET',
            headers: {
              'Content-Type': 'application/json',
              'Access-Control-Allow-Origin':'*'
            },
            mode: 'cors',
          })
            .then((response) => {
              console.log('response:', response);
            })
            .catch((error) => {
              console.error('Error:', error);
            });
    },[])

Above code is producing error:

Url with cedentials can not be used in FETCH

I also tried using AXIOS. Code is following:

    const getData = async () => {
        try {
            const res = await axios.get(apiUrl);
            console.log("res >>>", res)
        } catch(error) {
            console.log("error >>", error)
        }
    }

Above code is also producing error:

Access to XMLHttpRequest at 'apiUrl' from origin 'http://localhost:8000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Please help me out with api!
Thanks in advance

I want to solve the issue as soon as possible. I have tried all the methods I could find on internet.


问:
After creating an Excel File from an DataTable, comes an Message that the Excel File is Corrupted
So I've have an quite Big DataTable over 10.000 data and I wanted to Export it to an Excel File.

At first I tryd librarys like ClosedXML or Interop.Excel. But for this amount of Data it takes way to long.

So I decided to make it with an FileStream, thats so much faster and the creating of the excel File is working except that when I want to open the File I got an Message from Excel that the File is corrupted, that the FileFormat and File extension not fitting together.

Has someone an Idea how I can create an Excel File without Librarys or getting this Message?

My Code looks like that:

```<code>    string path = path + "someFilename.xlsx";

using (FileStream sw = File.Create(path))
                {
                    var data = Encoding.Unicode.GetBytes("Artikelnummer" + "\t" + "Hersteller" + "\t" + "Beschreibung" + "\t" + "Nettopreis" + "\t" + "Bruttopreis" + "\t" + "Zustand" + "\t" + "P/N" + "\t" + "Kategorie I" + "\t" + "Kategorie II" + "\t" + "Kategorie III" + "\t" + "Shop-Link" + "\n");
                    sw.Write(data, 0, data.Length);

                    foreach (DataRow r in dt.Rows)
                    {
                        data = Encoding.Unicode.GetBytes(r["Artikelnummer"].ToString() + "\t" + r["Hersteller"].ToString() + "\t" + r["Bezeichnung"].ToString() + "\t" + r["Nettopreis"].ToString() + "\t" + r["Bruttopreis"].ToString() + "\t" + r["Zustand"].ToString() + "\t" + r["PN"].ToString() + "\t" + r["Kategorie I"].ToString() + "\t" + r["Kategorie II"].ToString() + "\t" + r["Kategorie III"].ToString() + "\t" + r["Link"].ToString() + "\n");
                        sw.Write(data, 0, data.Length);
                    }

                }
</code>```

dt is my DataTable

Body:
So I've have an quite Big DataTable over 10.000 data and I wanted to Export it to an Excel File.

At first I tryd librarys like ClosedXML or Interop.Excel. But for this amount of Data it takes way to long.

So I decided to make it with an FileStream, thats so much faster and the creating of the excel File is working except that when I want to open the File I got an Message from Excel that the File is corrupted, that the FileFormat and File extension not fitting together.

Has someone an Idea how I can create an Excel File without Librarys or getting this Message?

My Code looks like that:

    string path = path + "someFilename.xlsx";

using (FileStream sw = File.Create(path))
                {
                    var data = Encoding.Unicode.GetBytes("Artikelnummer" + "\t" + "Hersteller" + "\t" + "Beschreibung" + "\t" + "Nettopreis" + "\t" + "Bruttopreis" + "\t" + "Zustand" + "\t" + "P/N" + "\t" + "Kategorie I" + "\t" + "Kategorie II" + "\t" + "Kategorie III" + "\t" + "Shop-Link" + "\n");
                    sw.Write(data, 0, data.Length);

                    foreach (DataRow r in dt.Rows)
                    {
                        data = Encoding.Unicode.GetBytes(r["Artikelnummer"].ToString() + "\t" + r["Hersteller"].ToString() + "\t" + r["Bezeichnung"].ToString() + "\t" + r["Nettopreis"].ToString() + "\t" + r["Bruttopreis"].ToString() + "\t" + r["Zustand"].ToString() + "\t" + r["PN"].ToString() + "\t" + r["Kategorie I"].ToString() + "\t" + r["Kategorie II"].ToString() + "\t" + r["Kategorie III"].ToString() + "\t" + r["Link"].ToString() + "\n");
                        sw.Write(data, 0, data.Length);
                    }

                }

dt is my DataTable


问:
Primefaces: SelectOneRadio sets value even when nothing is selected
I use Primefaces 6.2.17 and I want to create a dialog where the user can set a boolean field, with no selection being a valid option. I tried to do it using selectOneRadio, like this:

```<code><p:dialog id="dialogId" widgetVar="dialogId" dynamic="true" modal="true"
                closable="false" closeOnEscape="true" fitViewport="true" >
    <p:outputPanel id="panPersondata">
        <p:panelGrid>

            ...

            <p:row>
                <p:column style="width: 100px;">
                    <p:outputLabel value="Boolean choice"/>
                </p:column>
                <p:column colspan="2">
                    <p:selectOneRadio  id="booleanChoiceSelectone" widgetVar="booleanChoiceSelectone"
                                       layout="lineDirection"  value="#{backBean.choice}">
                        <f:selectItem itemLabel="Yes"  itemValue="#{true}" />
                        <f:selectItem itemLabel="No" itemValue="#{false}" />
                    </p:selectOneRadio>
                </p:column>
            </p:row>

            ...

        </p:panelGrid>
    </p:outputPanel>
</p:dialog>
</code>```

backing bean has an attribute which I initialize with null, like this:

```<code>@Getter @Setter private Boolean choice= null;
</code>```

When I then try to save while not selecting either option on the selectOneRadio it is automatically set to false (instead of remaining at null). What am I doing wrong here?

Body:
I use Primefaces 6.2.17 and I want to create a dialog where the user can set a boolean field, with no selection being a valid option. I tried to do it using selectOneRadio, like this:

            ...

                        <f:selectItem itemLabel="Yes"  itemValue="#{true}" />
                        <f:selectItem itemLabel="No" itemValue="#{false}" />

            ...

backing bean has an attribute which I initialize with null, like this:

@Getter @Setter private Boolean choice= null;

When I then try to save while not selecting either option on the selectOneRadio it is automatically set to false (instead of remaining at null). What am I doing wrong here?


问:
Firebase emulator incoherent hosts?
I am using the Firebase emulator to test my code locally, in a NodeJS project. However I need to use inconsistent hosts or it won't work. Has anyone got an idea why?

This is what I mean:

I initialize Firebase Admin as follows

```<code>    app = admin.initializeApp({
      projectId: projectId,
      databaseURL: `${process.env.FIREBASE_DATABASE_EMULATOR_HOST}?ns=${projectId}`,
      authDomain: `${process.env.FIREBASE_AUTH_EMULATOR_HOST}?ns=${projectId}`
    })

</code>```

Below are the variants of the environment variables I tested.

When I do this:

```<code>    process.env.FIREBASE_DATABASE_EMULATOR_HOST="localhost:9000"
    process.env.FIREBASE_AUTH_EMULATOR_HOST="localhost:9099"
</code>```

It does not work, I get:

```<code>Error: Error while making request: connect ECONNREFUSED ::1:9099. Error code: ECONNREFUSED
</code>```

9099 is the port on which the Auth emulator is running

If I replace localhost with 127.0.0.1 as follows:

```<code>    process.env.FIREBASE_DATABASE_EMULATOR_HOST="127.0.0.1:9000"
    process.env.FIREBASE_AUTH_EMULATOR_HOST="127.0.0.1:9099"
</code>```

the Auth module works, but I get:

```<code>TypeError [ERR_INVALID_URL]: Invalid URL
</code>```

When accessing the database on the following line:

```<code>    const referenceDatabase = admin.database().ref('Locations/10303')

</code>```

However when I put this:

```<code>    process.env.FIREBASE_DATABASE_EMULATOR_HOST="localhost:9000"
    process.env.FIREBASE_AUTH_EMULATOR_HOST="127.0.0.1:9099"
</code>```

Everything works.

Why is that? Why do I need localhost for the database but 127.0.0.1 for Auth?

The installed version of firebase-admin is 10.3.0

Running on Node 18.12.1 on a Mac Studio M1 running MacOS Ventura 13.0.1

Title: Firebase emulator incoherent hosts?

Body:
I am using the Firebase emulator to test my code locally, in a NodeJS project. However I need to use inconsistent hosts or it won't work. Has anyone got an idea why?

This is what I mean:

I initialize Firebase Admin as follows

    app = admin.initializeApp({
      projectId: projectId,
      databaseURL: `${process.env.FIREBASE_DATABASE_EMULATOR_HOST}?ns=${projectId}`,
      authDomain: `${process.env.FIREBASE_AUTH_EMULATOR_HOST}?ns=${projectId}`
    })

Below are the variants of the environment variables I tested.

When I do this:

    process.env.FIREBASE_DATABASE_EMULATOR_HOST="localhost:9000"
    process.env.FIREBASE_AUTH_EMULATOR_HOST="localhost:9099"

It does not work, I get:

Error: Error while making request: connect ECONNREFUSED ::1:9099. Error code: ECONNREFUSED

9099 is the port on which the Auth emulator is running

If I replace localhost with 127.0.0.1 as follows:

    process.env.FIREBASE_DATABASE_EMULATOR_HOST="127.0.0.1:9000"
    process.env.FIREBASE_AUTH_EMULATOR_HOST="127.0.0.1:9099"

the Auth module works, but I get:

TypeError [ERR_INVALID_URL]: Invalid URL

When accessing the database on the following line:

    const referenceDatabase = admin.database().ref('Locations/10303')

However when I put this:

    process.env.FIREBASE_DATABASE_EMULATOR_HOST="localhost:9000"
    process.env.FIREBASE_AUTH_EMULATOR_HOST="127.0.0.1:9099"

Everything works.

Why is that? Why do I need localhost for the database but 127.0.0.1 for Auth?

The installed version of firebase-admin is 10.3.0

Running on Node 18.12.1 on a Mac Studio M1 running MacOS Ventura 13.0.1


问:
Is it possible to compare 2 binary numbers and show only the matching bits from the left?
Using LibreOffice Calc, I need to compare binary numbers starting at the left. My goal is to obtain the matching consecutive bits (again starting from the left).
The non-matching bits need to be replaced with 'x'.

Example:

010010000100000100011010

010010000100000100010011

Preferred result would be 01001000010000010001xxxx

Now I do this manually but can this be automated in the spreadsheet?


问:
Nest post request is working in Swagger, but not when I use axios
last days I faced problem from title, Its my first post so I will try to explain everything with code snippets to better illustrate the issue.

Preflight returns code OK 204 no content

xhr returns error code 500

This is the working swagger request:

curl -X 'POST' \
  'http://localhost:3000/activity/createActivity' \
  -H 'accept: */*' \
  -H 'Content-Type: application/json' \
  -d '{
  "name": "any string",
  "imagePath": "https://www.image.com/image.png",
  "description": "any string",
  "category": 0
}'
```
<p>thats my axios post:</p>
<pre class="lang-ts prettyprint-override"><code>async addActivity(): Promise<Activity> {
  const activity = await http.post<Activity>("/activity/createActivity", {
    name: "x",
    imagePath: "x",
    description: "x",
    category: 0,
  });
  return activity.data;
}
</code>```

and http:

```<code>import axios from "axios";

export default axios.create({
  baseURL: "http://localhost:3000",
  headers: {
    "Content-type": "application/json"
  },
});

</code>```

I guess that I messed something in method above, because Nest returns me this error only when I use addActivity():

```<code>SQLITE_CONSTRAINT: NOT NULL constraint failed: activities.name
QueryFailedError: SQLITE_CONSTRAINT: NOT NULL constraint failed:
activities.name
    at Statement.handler (C:\Users\PC0\WebstormProjects\sprogstimulering-backend\src\driver\sqlite\SqliteQueryRunner.ts:113:26)
</code>```

I enabled cors in backend and other requests works,

{ name: "x", imagePath: "x", description: "x", category: 0 } this part in my request is detcted as "data:",
and I have tried to use body:{ name: "x", imagePath: "x", description: "x", category: 0 } but it didnt make any difference,

no authorisation yet, so its not the problem,

If someone can see mistake or help by providing any good article to the topic. I would be really glad to understand why its acting this way and be smarter in future :/
Thank You in advance!

PS. I have noticed that request header content type is:
"application/x-www-form-urlencoded, application/json",
and response header is:
"Content-Type: application/json; charset=utf-8"

Body:
last days I faced problem from title, Its my first post so I will try to explain everything with code snippets to better illustrate the issue.

Preflight returns code OK 204 no content

xhr returns error code 500

This is the working swagger request:

curl -X 'POST' \
  'http://localhost:3000/activity/createActivity' \
  -H 'accept: */*' \
  -H 'Content-Type: application/json' \
  -d '{
  "name": "any string",
  "imagePath": "https://www.image.com/image.png",
  "description": "any string",
  "category": 0
}'

thats my axios post:

async addActivity(): Promise<Activity> {
  const activity = await http.post<Activity>("/activity/createActivity", {
    name: "x",
    imagePath: "x",
    description: "x",
    category: 0,
  });
  return activity.data;
}

and http:

import axios from "axios";

export default axios.create({
  baseURL: "http://localhost:3000",
  headers: {
    "Content-type": "application/json"
  },
});

I guess that I messed something in method above, because Nest returns me this error only when I use addActivity():

SQLITE_CONSTRAINT: NOT NULL constraint failed: activities.name
QueryFailedError: SQLITE_CONSTRAINT: NOT NULL constraint failed:
activities.name
    at Statement.handler (C:\Users\PC0\WebstormProjects\sprogstimulering-backend\src\driver\sqlite\SqliteQueryRunner.ts:113:26)

I enabled cors in backend and other requests works,

{ name: "x", imagePath: "x", description: "x", category: 0 } this part in my request is detcted as "data:",
and I have tried to use body:{ name: "x", imagePath: "x", description: "x", category: 0 } but it didnt make any difference,

no authorisation yet, so its not the problem,

If someone can see mistake or help by providing any good article to the topic. I would be really glad to understand why its acting this way and be smarter in future :/
Thank You in advance!

PS. I have noticed that request header content type is:
"application/x-www-form-urlencoded, application/json",
and response header is:
"Content-Type: application/json; charset=utf-8"


问:
BotFramework losing AuthToken - so causes OAuthPrompt to show the login dialog for every API request
We are having a problem where the OAuthPrompt showing multiple times. We've started getting a problem (since Tues) where it gets an Authtoken, but then seems to lose it the next time we ask the OAuthPrompt - it doesn't remember it already has the auth token. This was previously working fine, and we believe this is the recommended approach for auth. We know the token it is receiving is valid, and have tested the Oauth connection in Azure portal and that works fine.

Update:
We believe we've noticed that it seems related to this API call (https://api.botframework.com/api/usertoken/GetToken?userId=XYZ&connectionName=ABC&channelId=msteams&code=128749). Sometimes the 'code' queryparam is missing, in those cases the API response is a 404 - and then that seems to exhibit the amnesia with the auth token.


问:
Make c# 11 raw string literals' newline use \r\n instead of \n
New C# 11 feature "raw string literals" seems to be using \n to break the line:

```<code>const string text = """
    "header1";"header2"
    "value1";"value2"
    """;
</code>```

This will produce "header1";"header2"\n"value1";"value2"\n

How can I make it produce "header1";"header2"\r\n"value1";"value2"\r\n?

Body:
New C# 11 feature "raw string literals" seems to be using \n to break the line:

const string text = """
    "header1";"header2"
    "value1";"value2"
    """;

This will produce "header1";"header2"\n"value1";"value2"\n

How can I make it produce "header1";"header2"\r\n"value1";"value2"\r\n?


问:
How to secure the routes using JWT?
In short, the problem is that, with the help of JWT, I want to create secure routes that will be available after login authorization, a token is generated during login, but it's enough to introduce the middleware function and it already gives me an error of the middleware catch block, obviously there is some error in that function or I'm doing something wrong I don't know, I'm learning JWT now, I want to save the resulting token in the header of the browser so that during other api calls the user can go to secure routes</p>
```<code>const jwt = require('jsonwebtoken');

const auth =  (req, res, next) => {
    try{
    const token = req.headers.authorization;
    console.log(token);
    const decoded = jwt.verify(req.body.token, process.env.JWT_KEY);
    req.user = decoded;
    next();
    } catch (error) {
        return res.status(401).json({ message: 'Authentication failed'});
    }
};

module.exports = auth
</code>```

```<code>router.post('/login', auth, async (req, res) => {

   let user = await User.findOne({ email: req.body.email });
   if (!user) return res.status(400).send('Invalid email or password');

   const validPassword = await bcrypt.compare(req.body.password, user.password);
   if (!validPassword) return res.status(400).send('Invalid email or password')
   const token = jwt.sign({
      email: user.email,
      userId: user._id
   },
      process.env.JWT_KEY
   ,
   {
      expiresIn:"1h"
   });

   return res.status(200).json({
      message: 'Auth successful',
      token: token
   })

   // res.redirect('/blog/home')

});
</code>```

Title: How to secure the routes using JWT?

Body:
In short, the problem is that, with the help of JWT, I want to create secure routes that will be available after login authorization, a token is generated during login, but it's enough to introduce the middleware function and it already gives me an error of the middleware catch block, obviously there is some error in that function or I'm doing something wrong I don't know, I'm learning JWT now, I want to save the resulting token in the header of the browser so that during other api calls the user can go to secure routes

const jwt = require('jsonwebtoken');

const auth =  (req, res, next) => {
    try{
    const token = req.headers.authorization;
    console.log(token);
    const decoded = jwt.verify(req.body.token, process.env.JWT_KEY);
    req.user = decoded;
    next();
    } catch (error) {
        return res.status(401).json({ message: 'Authentication failed'});
    }
};

module.exports = auth

router.post('/login', auth, async (req, res) => {

   let user = await User.findOne({ email: req.body.email });
   if (!user) return res.status(400).send('Invalid email or password');

   const validPassword = await bcrypt.compare(req.body.password, user.password);
   if (!validPassword) return res.status(400).send('Invalid email or password')
   const token = jwt.sign({
      email: user.email,
      userId: user._id
   },
      process.env.JWT_KEY
   ,
   {
      expiresIn:"1h"
   });

   return res.status(200).json({
      message: 'Auth successful',
      token: token
   })

   // res.redirect('/blog/home')

});


问:
Compose UI recompositioned multiple times and start navigation start destination set too late
I have weird behavior in my compose app, it looks like UI is being recompositioned multiple times, but I don’t really know why. Problem is related to main activity and root nav graph:

@AndroidEntryPoint
class AppMainActivity : ComponentActivity() {
    private val viewModel: UserStateViewModel by viewModels()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        installSplashScreen().apply {
            setKeepOnScreenCondition {
                Log.d("TESTOWO", "ViewModel addr in MainActivity: ${viewModel.hashCode()}")
                viewModel.userState.value == UserAuthState.UNKNOWN
            }
        }

        setContent {
            CarsLocalizerTheme {
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colors.background
                ) {
                    RootNavGraph(navController = rememberNavController(), viewModel = hiltViewModel())
                }
            }
        }
    }
}
```
<p>RootNavGraph</p>
<pre class="lang-kotlin prettyprint-override"><code>@Composable
fun RootNavGraph(
    navController: NavHostController,
    viewModel: UserStateViewModel,
) {
    Log.d("TESTOWO", "ViewModel addr in RootNavGraph: ${viewModel.hashCode()}")

    NavHost(
        navController = navController,
        startDestination = if (viewModel.userState.value == UserAuthState.AUTHENTICATED) HOME_ROUTE else AUTH_ROUTE,
        route = ROOT_ROUTE
    ) {
        authNavGraph(navController = navController)
        composable(route = HOME_ROUTE) {
            HomeScreen()
        }
    }
}
</code>```

UserStateViewModel

@HiltViewModel
class UserStateViewModel @Inject constructor(private val repository: UserStateRepository): ViewModel() {

    private var _userState = mutableStateOf<UserAuthState>(UserAuthState.UNKNOWN)
    val userState: State<UserAuthState> get() = _userState

    private var authStateListenerCallback: FirebaseAuth.AuthStateListener = FirebaseAuth.AuthStateListener {
        _userState.value = if (it.currentUser != null) UserAuthState.AUTHENTICATED else UserAuthState.UNAUTHENTICATED
    }

    init {
        Log.d("TESTOWO", "View model created")
        startListeningToAuthState()
    }

    override fun onCleared() {
        super.onCleared()
        stopListeningToAuthState()
    }

    private fun startListeningToAuthState() {
        repository.setupAuthStateListener(authStateListenerCallback)
    }

    private fun stopListeningToAuthState() {
        repository.removeAuthStateListener(authStateListenerCallback)
    }
```
<p>AuthNavGraph</p>
<pre class="lang-kotlin prettyprint-override"><code>fun NavGraphBuilder.authNavGraph(
    navController: NavController
) {
    navigation(
        route = AUTH_ROUTE,
        startDestination = Screen.Login.route
    ) {
        composable(
            route = Screen.Login.route
        ) {
            LoginScreen(navController = navController, viewModel = hiltViewModel())
        }
        composable(
            route = Screen.Register.route
        ) {
            RegisterScreen(navController = navController, viewModel = hiltViewModel())
        }
        composable(
            route = Screen.Onboarding.route
        ) {
            OnboardingScreen(navController = navController, viewModel = hiltViewModel())
        }
    }
}
</code>```

At app start I see the following logs:

```<code>2022-12-08 12:09:15.668 22945-22945 TESTOWO                 com.example.carslocalizer            D  View model created
2022-12-08 12:09:15.668 22945-22945 TESTOWO                 com.example.carslocalizer            D  ViewModel addr in RootNavGraph: 15070924
2022-12-08 12:09:15.695 22945-22945 TESTOWO                 com.example.carslocalizer            D  ViewModel addr in MainActivity: 15070924
2022-12-08 12:09:15.728 22945-22945 TESTOWO                 com.example.carslocalizer            D  ViewModel addr in MainActivity: 15070924
2022-12-08 12:09:15.742 22945-22945 TESTOWO                 com.example.carslocalizer            D  ViewModel addr in RootNavGraph: 15070924
2022-12-08 12:09:15.747 22945-22945 TESTOWO                 com.example.carslocalizer            D  ViewModel addr in MainActivity: 15070924
</code>```

At startup I need to check if user is already authenticated. If yes, he should be navigated to home screen, if not then navigate to authentication. It works almost correct. When splash screen ends I am still able to see login view for about 1s and after that app navigates to home. I was thinking that thanks to this splash screen check

setKeepOnScreenCondition {
    Log.d("TESTOWO", "ViewModel addr in MainActivity: ${viewModel.hashCode()}")
    viewModel.userState.value == UserAuthState.UNKNOWN
}
```

when RootNavGraph will be reached, user auth state will be already known and correct start destination will be set. But it looks like it’s not working this way… Does anybody know why UI is recompositioned so many times and why start destination is updated late?

Body:
I have weird behavior in my compose app, it looks like UI is being recompositioned multiple times, but I don’t really know why. Problem is related to main activity and root nav graph:

@AndroidEntryPoint
class AppMainActivity : ComponentActivity() {
    private val viewModel: UserStateViewModel by viewModels()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        installSplashScreen().apply {
            setKeepOnScreenCondition {
                Log.d("TESTOWO", "ViewModel addr in MainActivity: ${viewModel.hashCode()}")
                viewModel.userState.value == UserAuthState.UNKNOWN
            }
        }

        setContent {
            CarsLocalizerTheme {
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colors.background
                ) {
                    RootNavGraph(navController = rememberNavController(), viewModel = hiltViewModel())
                }
            }
        }
    }
}

RootNavGraph

@Composable
fun RootNavGraph(
    navController: NavHostController,
    viewModel: UserStateViewModel,
) {
    Log.d("TESTOWO", "ViewModel addr in RootNavGraph: ${viewModel.hashCode()}")

    NavHost(
        navController = navController,
        startDestination = if (viewModel.userState.value == UserAuthState.AUTHENTICATED) HOME_ROUTE else AUTH_ROUTE,
        route = ROOT_ROUTE
    ) {
        authNavGraph(navController = navController)
        composable(route = HOME_ROUTE) {
            HomeScreen()
        }
    }
}

UserStateViewModel

@HiltViewModel
class UserStateViewModel @Inject constructor(private val repository: UserStateRepository): ViewModel() {

    private var _userState = mutableStateOf<UserAuthState>(UserAuthState.UNKNOWN)
    val userState: State<UserAuthState> get() = _userState

    private var authStateListenerCallback: FirebaseAuth.AuthStateListener = FirebaseAuth.AuthStateListener {
        _userState.value = if (it.currentUser != null) UserAuthState.AUTHENTICATED else UserAuthState.UNAUTHENTICATED
    }

    init {
        Log.d("TESTOWO", "View model created")
        startListeningToAuthState()
    }

    override fun onCleared() {
        super.onCleared()
        stopListeningToAuthState()
    }

    private fun startListeningToAuthState() {
        repository.setupAuthStateListener(authStateListenerCallback)
    }

    private fun stopListeningToAuthState() {
        repository.removeAuthStateListener(authStateListenerCallback)
    }

AuthNavGraph

fun NavGraphBuilder.authNavGraph(
    navController: NavController
) {
    navigation(
        route = AUTH_ROUTE,
        startDestination = Screen.Login.route
    ) {
        composable(
            route = Screen.Login.route
        ) {
            LoginScreen(navController = navController, viewModel = hiltViewModel())
        }
        composable(
            route = Screen.Register.route
        ) {
            RegisterScreen(navController = navController, viewModel = hiltViewModel())
        }
        composable(
            route = Screen.Onboarding.route
        ) {
            OnboardingScreen(navController = navController, viewModel = hiltViewModel())
        }
    }
}

At app start I see the following logs:

2022-12-08 12:09:15.668 22945-22945 TESTOWO                 com.example.carslocalizer            D  View model created
2022-12-08 12:09:15.668 22945-22945 TESTOWO                 com.example.carslocalizer            D  ViewModel addr in RootNavGraph: 15070924
2022-12-08 12:09:15.695 22945-22945 TESTOWO                 com.example.carslocalizer            D  ViewModel addr in MainActivity: 15070924
2022-12-08 12:09:15.728 22945-22945 TESTOWO                 com.example.carslocalizer            D  ViewModel addr in MainActivity: 15070924
2022-12-08 12:09:15.742 22945-22945 TESTOWO                 com.example.carslocalizer            D  ViewModel addr in RootNavGraph: 15070924
2022-12-08 12:09:15.747 22945-22945 TESTOWO                 com.example.carslocalizer            D  ViewModel addr in MainActivity: 15070924

At startup I need to check if user is already authenticated. If yes, he should be navigated to home screen, if not then navigate to authentication. It works almost correct. When splash screen ends I am still able to see login view for about 1s and after that app navigates to home. I was thinking that thanks to this splash screen check

setKeepOnScreenCondition {
    Log.d("TESTOWO", "ViewModel addr in MainActivity: ${viewModel.hashCode()}")
    viewModel.userState.value == UserAuthState.UNKNOWN
}

when RootNavGraph will be reached, user auth state will be already known and correct start destination will be set. But it looks like it’s not working this way… Does anybody know why UI is recompositioned so many times and why start destination is updated late?


问:
the request for my login and register route is in pending , but i dont see any error
I am new to this and i have this 2 routes wrote in js for authentication:

```<code>router.post('/register', catchAsync (async(req, res, next) => {
    try{
    const{email, username, password} = req.body;
    const user = new User({email, username})
    const registeredUser = await User.register(user, password);
    req.login(registeredUser, err => {
        if(err) return next(err);
        req.flash('success','Welcome !');
        res.redirect('/camp')
         })
    } catch(e) {
    req.flash('error', e.message);
    res.redirect('register');

}));

`
router.get('/login',(req, res) => {
    res.render('users/login');

});

router.post('/login', authenticate,(req, res) => {
    req.flash('success', 'You are logged in!');
    res.redirect('/camp');

})
</code>```

But the server doesnt respond. The others routes are working just fine.

im using passport.js

Body:
I am new to this and i have this 2 routes wrote in js for authentication:

router.post('/register', catchAsync (async(req, res, next) => {
    try{
    const{email, username, password} = req.body;
    const user = new User({email, username})
    const registeredUser = await User.register(user, password);
    req.login(registeredUser, err => {
        if(err) return next(err);
        req.flash('success','Welcome !');
        res.redirect('/camp')
         })
    } catch(e) {
    req.flash('error', e.message);
    res.redirect('register');

}));

`
router.get('/login',(req, res) => {
    res.render('users/login');

});

router.post('/login', authenticate,(req, res) => {
    req.flash('success', 'You are logged in!');
    res.redirect('/camp');

})

But the server doesnt respond. The others routes are working just fine.

im using passport.js


问:
axios / fetch / superagent unable to perform network request in react native application
We've an RN 0.68 (update to 0.7x is planned) app which is mainly used in wifi environments. We're facing a very weird issue: sometimes the Axios (v 0.26.2 / 1.2.1) app api client isn't able to perform a network request. Only restarting the app will solve the issue.

We see this issue pop up after cases of bad / poor wifi connections. We can reproduce the issue by using a network manipulation tool and drops up to 60% of the data. When the drop is turned off the Axios client is permanently broken.

The app has also an MQTT (native) and Sip (native) connection, these connections, will sometimes interrupt, but restores their connection.

What have we tried so far:

added the cancel / signal to each request => no effect

replace the axios client when we detect the request isn't answered with a new axios instance => no effect

added a superagent next to the axios to find out if superagent will work when axios is broken => superagent is also broken.

added a plain fetch() next to the axios to find out if fetch() will work when axios is broken => fetch() is also broken.

While no OS / ADB logging is written, we've really no idea where this is coming from.

It looks like the "connection" between the (javascript part of the) app and the network stack is broken, but this feels unlikely while SIP and MQTT are still running.

Ayone some ideas for further investigation?


问:
How to create new Branch on existing github repo, but with completely new project? Using visual studio
I'm completely new to GitHub I don't even know what keywords I need to use to search for my answer.
My client gave me a rar file containing a visual studio solution. Then after I did all the changes he asked to add it as a new branch to the already existing repository.
In The visual studio, I don't know how to do that.
Should I clone the project and then migrate my changes there? Or I can directly add my code as a new branch</p>


问:
minSdkVersion is 26 in config.xml, but google play store showing 5.1 instead of 8.0
Good day,

I have a cordova android mobile app, the minSdkVersion is 26 in my config.xml:

```<code><uses-sdk android:minSdkVersion="26" />
</code>```

As my understanding, sdkversion = 26 should equal to android 8.0:

However, in google play store, it showing 5.1 and above:

May I know where is this 5.1 come from? and how can I control it?

Body:
Good day,

I have a cordova android mobile app, the minSdkVersion is 26 in my config.xml:

<uses-sdk android:minSdkVersion="26" />

As my understanding, sdkversion = 26 should equal to android 8.0:

However, in google play store, it showing 5.1 and above:

May I know where is this 5.1 come from? and how can I control it?


问:
startActivityForResult, but not on my app's activity stack?
My app reaches out to the camera activity to take a picture.

On most devices, this works just fine.  On lower end devices, like the moto droid, my app pushes the heap to almost the max.  As a result, calling the camera activity kills my app in the background on these lower devices.

Is there a way to call the camera activity without it adding to MY app's heap size?  Can it be it's own heap?

ContentLicense: CC BY-SA 3.0


问:
Nested exception is org.hibernate.exception.JDBCConnectionException:Unable to acquire JDBC Connection
We have legacy software that was running properly for the last 6-7 years. Recently we started getting the below error:

```<code>Could not open JPA EntityManager for transaction; nested exception is org.hibernate.exception.JDBCConnectionException: Unable to acquire JDBC Connection
</code>```

We only see this error when the EC2 CPU utilization goes high(Approx above 80%). The backend is developed in spring boot. However, we use DriverManagerDataSource for DB connection and do not use any connection pooling.

```<code>@Bean(name = "datasource")
@Primary
public DriverManagerDataSource getDataSourceFactory() {
DriverManagerDataSource database = new DriverManagerDataSource();
database.setDriverClassName("com.mysql.cj.jdbc.Driver");
database.setUsername(System.getenv("USER"));
database.setPassword(System.getenv("PASSWORD"));
database.setUrl(System.getenv("URL"));
return database;
}
</code>```

MySql version is 5.7 and DB wait_timeout and interactive_timeout are 60 minutes. Can someone help me to find out what's the possible issue and the solution for this?
Also, does the JDBC connector has any limit on how many max connections it can create at any given time?

Body:
We have legacy software that was running properly for the last 6-7 years. Recently we started getting the below error:

Could not open JPA EntityManager for transaction; nested exception is org.hibernate.exception.JDBCConnectionException: Unable to acquire JDBC Connection

We only see this error when the EC2 CPU utilization goes high(Approx above 80%). The backend is developed in spring boot. However, we use DriverManagerDataSource for DB connection and do not use any connection pooling.

@Bean(name = "datasource")
@Primary
public DriverManagerDataSource getDataSourceFactory() {
DriverManagerDataSource database = new DriverManagerDataSource();
database.setDriverClassName("com.mysql.cj.jdbc.Driver");
database.setUsername(System.getenv("USER"));
database.setPassword(System.getenv("PASSWORD"));
database.setUrl(System.getenv("URL"));
return database;
}

MySql version is 5.7 and DB wait_timeout and interactive_timeout are 60 minutes. Can someone help me to find out what's the possible issue and the solution for this?
Also, does the JDBC connector has any limit on how many max connections it can create at any given time?


问:
Why is GCC not using builtin memcpy()?
I am using GCC 12.1.0. I tend to always use memcpy() to copy blocks of memory rather than using a hand written loop, since I always read that memcpy() should always provide the most efficient implementation, as a builtin compiler-specific function.

But to my great disappointment, even using -O3, the following test function:

```<code>#include <cstring>

void copy(char *from, char *to, int size)
{
  memcpy(to,from,size);
}

</code>```

always results in a jmp to the library memcpy() function, and NOT to some builtin inlined assembly as one would expect. This is IMHO very inefficient, possibly (to my knowledge) much less efficient than simply using a loop like

```<code>while (size--) *(to--) = *(src--);
</code>```

because a jump to a function is always expensive, in particular when it is about a very simple function which the compiler could efficiently inline!

Before somebody points me on the same topic being already covered here When __builtin_memcpy is replaced with libc's memcpy I must specify that my problem is different. There it was simply replied that the compiler may generate a jmp to memcpy() when the copy size is not known at compiling time. I allow myself to insist that, despite the size is unknown, a jmp is still much less efficient than any inlined code, so I am very puzzled on why GCC insists to use a jmp even with a high optimization setting as -O3.

Is there any particular flag I must specify expressly for GCC to use the builtin memcpy or however an inlined loop ? Why isn't -O3 enough ?

Edit: I changed the float* to char* in the sample code because one could easily point out that was an error, however that was irrelevant to my question

Edit: I can confirm by inspecting the resulting asm that a jmp is generated to clib's memcpy(). Being working extensively with optimized math functions and benchmarks, I can easily confirm that a jmp to a clib's function is always taxing. I have always been taught there is an overhead involved with function calls.

Title: Why is GCC not using builtin memcpy()?

Body:
I am using GCC 12.1.0. I tend to always use memcpy() to copy blocks of memory rather than using a hand written loop, since I always read that memcpy() should always provide the most efficient implementation, as a builtin compiler-specific function.

But to my great disappointment, even using -O3, the following test function:

#include <cstring>

void copy(char *from, char *to, int size)
{
  memcpy(to,from,size);
}

always results in a jmp to the library memcpy() function, and NOT to some builtin inlined assembly as one would expect. This is IMHO very inefficient, possibly (to my knowledge) much less efficient than simply using a loop like

while (size--) *(to--) = *(src--);

because a jump to a function is always expensive, in particular when it is about a very simple function which the compiler could efficiently inline!

Before somebody points me on the same topic being already covered here When __builtin_memcpy is replaced with libc's memcpy I must specify that my problem is different. There it was simply replied that the compiler may generate a jmp to memcpy() when the copy size is not known at compiling time. I allow myself to insist that, despite the size is unknown, a jmp is still much less efficient than any inlined code, so I am very puzzled on why GCC insists to use a jmp even with a high optimization setting as -O3.

Is there any particular flag I must specify expressly for GCC to use the builtin memcpy or however an inlined loop ? Why isn't -O3 enough ?

Edit: I changed the float* to char* in the sample code because one could easily point out that was an error, however that was irrelevant to my question

Edit: I can confirm by inspecting the resulting asm that a jmp is generated to clib's memcpy(). Being working extensively with optimized math functions and benchmarks, I can easily confirm that a jmp to a clib's function is always taxing. I have always been taught there is an overhead involved with function calls.


问:
Persist Class as key value pair SQL Table
I have a class with multiple value types.

I want to save it as key-value pair.

Let's say we have a class

```<code>class MyClass{
String p1;
Double p2;
}
</code>```

I want it in DB as

```<code>id | a | b  | c
1  | - | -  | -

id |fkId  | propetyName | propertyValue
1  |1     | p1           | hello
2  |1     | p2           | 10
</code>```

Body:
I have a class with multiple value types.

I want to save it as key-value pair.

Let's say we have a class

class MyClass{
String p1;
Double p2;
}

I want it in DB as

id | a | b  | c
1  | - | -  | -

id |fkId  | propetyName | propertyValue
1  |1     | p1           | hello
2  |1     | p2           | 10


问:
Ansible - how to answer a question in a bash window
I want to write an ansible playbook that will install something for me.

The code I currently have is:

```<code>  hosts: "*"

  vars_prompt:
    - name: node_password
      prompt: Enter the password for your node user
      private: false

  tasks:
    - name: update and upgrade
      become: yes
      apt:
        update_cache: yes
        upgrade: 'yes'

    - name: get multitoolbox shell
      ansible.builtin.uri:
        url: https://raw.githubusercontent.com/RunOnFlux/fluxnode-multitool/master/multitoolbox.sh
        dest: /tmp/multitoolbox.sh

    - name: install docker
      become: yes
      ansible.builtin.expect:
        command: bash -i /tmp/multitoolbox.sh
        responses:
          (.*)Pick an option and hit ENTER:(.*): 1
          (.*)Enter your username(.*): 'cumulus'
          (.*)New password:(.*): "{{ node_password }}"
          (.*)Retype new password:(.*): "{{ node_password }}"
          (.*)Would you like switch to user account Y/N?(.*): Y
</code>```

However, when the prompt asks for "Pick an option and hit ENTER", the ansible playbook is entering 1, and then hits enter. The next step is somehow not working, and I have no idea why.

This is the first qestion:

The script then asks for a username:

I expect ansible to enter cumulus and hit enter, but this does not happen for some reason. Can you give me any pointers?

Here is the output of the playbook run:

```<code>fatal: [192.168.31.29]: FAILED! => {"changed": true, "cmd": "bash -i /tmp/multitoolbox.sh", "delta": "0:00:32.578751", "end": "2022-12-08 12:46:13.039480", "msg": "command exceeded timeout", "rc": null, "start": "2022-12-08 12:45:40.460729", "stdout": "\u001b[H\u001b[2J\u001b[3J\u001b[38;5;27m\r\n    __  ___      ____  _ __              ____              \r\n   /  |/  /_  __/ / /_(_) /_____  ____  / / /_  ____  _  __\r\n  / /|_/ / / / / / __/ / __/ __ \\/ __ \\/ / __ \\/ __ \\| |/_/\r\n / /  / / /_/ / / /_/ / /_/ /_/ / /_/ / / /_/ / /_/ />  <  \r\n/_/  /_/\\__,_/_/\\__/_/\\__/\\____/\\____/_/_.___/\\____/_/|_|  \r\n                                                           \r\n\u001b[1;33m================================================================\u001b[0m\r\n\u001b[1;32mVersion: v7.4\u001b[0m\r\n\u001b[1;32mBranch: master\u001b[0m\r\n\u001b[1;32mOS: Ubuntu 16/18/19/20, Debian 9/10 \u001b[0m\r\n\u001b[1;32mCreated by: X4MiLX from Flux's team\u001b[0m\r\n\u001b[1;32mSpecial thanks to dk808, CryptoWrench, jriggs28 && TechDufus\u001b[0m\r\n\u001b[1;33m================================================================\u001b[0m\r\n\u001b[1;36m1  - Install Docker\u001b[0m\r\n\u001b[1;36m2  - Install FluxNode\u001b[0m\r\n\u001b[1;36m3  - FluxNode analyzer and fixer\u001b[0m\r\n\u001b[1;36m4  - Install watchdog for FluxNode\u001b[0m\r\n\u001b[1;36m5  - Restore Flux blockchain from bootstrap\u001b[0m\r\n\u001b[1;36m6  - Create FluxNode installation config file\u001b[0m\r\n\u001b[1;36m7  - Re-install FluxOS\u001b[0m\r\n\u001b[1;36m8  - Flux Daemon Reconfiguration\u001b[0m\r\n\u001b[1;36m9  - Create Flux daemon service ( for old nodes )\u001b[0m\r\n\u001b[1;36m10 - Create Self-hosting cron ip service \u001b[0m\r\n\u001b[1;36m11 - FluxOS reconfiguration \u001b[0m\r\n\u001b[1;36m12 - Install fluxwatchtower for docker images autoupdate\u001b[0m\r\n\u001b[1;36m13 - MongoDB FiX action\u001b[0m\r\n\u001b[1;36m14 - Multinode configuration with UPNP communication (Needs Router with UPNP support)  \u001b[0m\r\n\u001b[1;36m15 - Node reconfiguration from install config\u001b[0m\r\n\u001b[1;33m================================================================\u001b[0m\r\nPick an option and hit ENTER: \u001b[H\u001b[2J\u001b[3J\u001b[1;32mModule: Install Docker\u001b[0m\r\n\u001b[1;33m================================================================\u001b[0m\r\n\u001b[?1049h\u001b[22;0;0t\u001b[1;24r\u001b[4l\u001b[?25l\u001b(B\u001b[m\u001b[37m\u001b[40m\u001b[1;24r\u001b[H\u001b[2J\u001b[1;1H\u001b[97m\u001b[44m\u001b[K\n\u001b[K\n\u001b[K\n\u001b[K\n\u001b[K\n\u001b[K\n\u001b[K\n\u001b[K\n\u001b[K\n\u001b[K\n\u001b[K\n\u001b[K\n\u001b[K\n\u001b[K\n\u001b[K\n\u001b[K\n\u001b[K\n\u001b[K\n\u001b[K\n\u001b[K\n\u001b[K\n\u001b[K\n\u001b[K\n\u001b[K\u001b[1;1H\u001b[?25l\u001b[?12l\u001b[?25h\u001b[9;5H\u001b[30m\u001b[47m┌────────────────────────┤ MULTITOOLBOX v7.4 ├─────────────────────────┐\u001b[10;5H│ Enter your username                                                  │\u001b[97m\u001b[40m \u001b[11;5H\u001b[30m\u001b[47m│                                                                      │\u001b[97m\u001b[40m \u001b[12;5H\u001b[30m\u001b[47m│ \u001b[37m\u001b[44m____________________________________________________________________\u001b[30m\u001b[47m │\u001b[97m\u001b[40m \u001b[13;5H\u001b[30m\u001b[47m│                                                                      │\u001b[97m\u001b[40m \u001b[14;5H\u001b[30m\u001b[47m│                  <Ok>                      <Cancel>                  │\u001b[97m\u001b[40m \u001b[15;5H\u001b[30m\u001b[47m│                                                                      │\u001b[97m\u001b[40m \u001b[16;5H\u001b[30m\u001b[47m└──────────────────────────────────────────────────────────────────────┘\u001b[97m\u001b[40m \u001b[17;6H                                                                        \u001b[12;7H\u001b[37m\u001b[44mcumulus", "stdout_lines": ["\u001b[H\u001b[2J\u001b[3J\u001b[38;5;27m", "    __  ___      ____  _ __              ____              ", "   /  |/  /_  __/ / /_(_) /_____  ____  / / /_  ____  _  __", "  / /|_/ / / / / / __/ / __/ __ \\/ __ \\/ / __ \\/ __ \\| |/_/", " / /  / / /_/ / / /_/ / /_/ /_/ / /_/ / / /_/ / /_/ />  <  ", "/_/  /_/\\__,_/_/\\__/_/\\__/\\____/\\____/_/_.___/\\____/_/|_|  ", "                                                           ", "\u001b[1;33m================================================================\u001b[0m", "\u001b[1;32mVersion: v7.4\u001b[0m", "\u001b[1;32mBranch: master\u001b[0m", "\u001b[1;32mOS: Ubuntu 16/18/19/20, Debian 9/10 \u001b[0m", "\u001b[1;32mCreated by: X4MiLX from Flux's team\u001b[0m", "\u001b[1;32mSpecial thanks to dk808, CryptoWrench, jriggs28 && TechDufus\u001b[0m", "\u001b[1;33m================================================================\u001b[0m", "\u001b[1;36m1  - Install Docker\u001b[0m", "\u001b[1;36m2  - Install FluxNode\u001b[0m", "\u001b[1;36m3  - FluxNode analyzer and fixer\u001b[0m", "\u001b[1;36m4  - Install watchdog for FluxNode\u001b[0m", "\u001b[1;36m5  - Restore Flux blockchain from bootstrap\u001b[0m", "\u001b[1;36m6  - Create FluxNode installation config file\u001b[0m", "\u001b[1;36m7  - Re-install FluxOS\u001b[0m", "\u001b[1;36m8  - Flux Daemon Reconfiguration\u001b[0m", "\u001b[1;36m9  - Create Flux daemon service ( for old nodes )\u001b[0m", "\u001b[1;36m10 - Create Self-hosting cron ip service \u001b[0m", "\u001b[1;36m11 - FluxOS reconfiguration \u001b[0m", "\u001b[1;36m12 - Install fluxwatchtower for docker images autoupdate\u001b[0m", "\u001b[1;36m13 - MongoDB FiX action\u001b[0m", "\u001b[1;36m14 - Multinode configuration with UPNP communication (Needs Router with UPNP support)  \u001b[0m", "\u001b[1;36m15 - Node reconfiguration from install config\u001b[0m", "\u001b[1;33m================================================================\u001b[0m", "Pick an option and hit ENTER: \u001b[H\u001b[2J\u001b[3J\u001b[1;32mModule: Install Docker\u001b[0m", "\u001b[1;33m================================================================\u001b[0m", "\u001b[?1049h\u001b[22;0;0t\u001b[1;24r\u001b[4l\u001b[?25l\u001b(B\u001b[m\u001b[37m\u001b[40m\u001b[1;24r\u001b[H\u001b[2J\u001b[1;1H\u001b[97m\u001b[44m\u001b[K", "\u001b[K", "\u001b[K", "\u001b[K", "\u001b[K", "\u001b[K", "\u001b[K", "\u001b[K", "\u001b[K", "\u001b[K", "\u001b[K", "\u001b[K", "\u001b[K", "\u001b[K", "\u001b[K", "\u001b[K", "\u001b[K", "\u001b[K", "\u001b[K", "\u001b[K", "\u001b[K", "\u001b[K", "\u001b[K", "\u001b[K\u001b[1;1H\u001b[?25l\u001b[?12l\u001b[?25h\u001b[9;5H\u001b[30m\u001b[47m┌────────────────────────┤ MULTITOOLBOX v7.4 ├─────────────────────────┐\u001b[10;5H│ Enter your username                                                  │\u001b[97m\u001b[40m \u001b[11;5H\u001b[30m\u001b[47m│                                                                      │\u001b[97m\u001b[40m \u001b[12;5H\u001b[30m\u001b[47m│ \u001b[37m\u001b[44m____________________________________________________________________\u001b[30m\u001b[47m │\u001b[97m\u001b[40m \u001b[13;5H\u001b[30m\u001b[47m│                                                                      │\u001b[97m\u001b[40m \u001b[14;5H\u001b[30m\u001b[47m│                  <Ok>                      <Cancel>                  │\u001b[97m\u001b[40m \u001b[15;5H\u001b[30m\u001b[47m│                                                                      │\u001b[97m\u001b[40m \u001b[16;5H\u001b[30m\u001b[47m└──────────────────────────────────────────────────────────────────────┘\u001b[97m\u001b[40m \u001b[17;6H                                                                        \u001b[12;7H\u001b[37m\u001b[44mcumulus"]}
</code>```

Body:
I want to write an ansible playbook that will install something for me.

The code I currently have is:

  hosts: "*"

  vars_prompt:
    - name: node_password
      prompt: Enter the password for your node user
      private: false

  tasks:
    - name: update and upgrade
      become: yes
      apt:
        update_cache: yes
        upgrade: 'yes'

    - name: get multitoolbox shell
      ansible.builtin.uri:
        url: https://raw.githubusercontent.com/RunOnFlux/fluxnode-multitool/master/multitoolbox.sh
        dest: /tmp/multitoolbox.sh

    - name: install docker
      become: yes
      ansible.builtin.expect:
        command: bash -i /tmp/multitoolbox.sh
        responses:
          (.*)Pick an option and hit ENTER:(.*): 1
          (.*)Enter your username(.*): 'cumulus'
          (.*)New password:(.*): "{{ node_password }}"
          (.*)Retype new password:(.*): "{{ node_password }}"
          (.*)Would you like switch to user account Y/N?(.*): Y

However, when the prompt asks for "Pick an option and hit ENTER", the ansible playbook is entering 1, and then hits enter. The next step is somehow not working, and I have no idea why.

This is the first qestion:

The script then asks for a username:

I expect ansible to enter cumulus and hit enter, but this does not happen for some reason. Can you give me any pointers?

Here is the output of the playbook run:

fatal: [192.168.31.29]: FAILED! => {"changed": true, "cmd": "bash -i /tmp/multitoolbox.sh", "delta": "0:00:32.578751", "end": "2022-12-08 12:46:13.039480", "msg": "command exceeded timeout", "rc": null, "start": "2022-12-08 12:45:40.460729", "stdout": "\u001b[H\u001b[2J\u001b[3J\u001b[38;5;27m\r\n    __  ___      ____  _ __              ____              \r\n   /  |/  /_  __/ / /_(_) /_____  ____  / / /_  ____  _  __\r\n  / /|_/ / / / / / __/ / __/ __ \\/ __ \\/ / __ \\/ __ \\| |/_/\r\n / /  / / /_/ / / /_/ / /_/ /_/ / /_/ / / /_/ / /_/ />  <  \r\n/_/  /_/\\__,_/_/\\__/_/\\__/\\____/\\____/_/_.___/\\____/_/|_|  \r\n                                                           \r\n\u001b[1;33m================================================================\u001b[0m\r\n\u001b[1;32mVersion: v7.4\u001b[0m\r\n\u001b[1;32mBranch: master\u001b[0m\r\n\u001b[1;32mOS: Ubuntu 16/18/19/20, Debian 9/10 \u001b[0m\r\n\u001b[1;32mCreated by: X4MiLX from Flux's team\u001b[0m\r\n\u001b[1;32mSpecial thanks to dk808, CryptoWrench, jriggs28 && TechDufus\u001b[0m\r\n\u001b[1;33m================================================================\u001b[0m\r\n\u001b[1;36m1  - Install Docker\u001b[0m\r\n\u001b[1;36m2  - Install FluxNode\u001b[0m\r\n\u001b[1;36m3  - FluxNode analyzer and fixer\u001b[0m\r\n\u001b[1;36m4  - Install watchdog for FluxNode\u001b[0m\r\n\u001b[1;36m5  - Restore Flux blockchain from bootstrap\u001b[0m\r\n\u001b[1;36m6  - Create FluxNode installation config file\u001b[0m\r\n\u001b[1;36m7  - Re-install FluxOS\u001b[0m\r\n\u001b[1;36m8  - Flux Daemon Reconfiguration\u001b[0m\r\n\u001b[1;36m9  - Create Flux daemon service ( for old nodes )\u001b[0m\r\n\u001b[1;36m10 - Create Self-hosting cron ip service \u001b[0m\r\n\u001b[1;36m11 - FluxOS reconfiguration \u001b[0m\r\n\u001b[1;36m12 - Install fluxwatchtower for docker images autoupdate\u001b[0m\r\n\u001b[1;36m13 - MongoDB FiX action\u001b[0m\r\n\u001b[1;36m14 - Multinode configuration with UPNP communication (Needs Router with UPNP support)  \u001b[0m\r\n\u001b[1;36m15 - Node reconfiguration from install config\u001b[0m\r\n\u001b[1;33m================================================================\u001b[0m\r\nPick an option and hit ENTER: \u001b[H\u001b[2J\u001b[3J\u001b[1;32mModule: Install Docker\u001b[0m\r\n\u001b[1;33m================================================================\u001b[0m\r\n\u001b[?1049h\u001b[22;0;0t\u001b[1;24r\u001b[4l\u001b[?25l\u001b(B\u001b[m\u001b[37m\u001b[40m\u001b[1;24r\u001b[H\u001b[2J\u001b[1;1H\u001b[97m\u001b[44m\u001b[K\n\u001b[K\n\u001b[K\n\u001b[K\n\u001b[K\n\u001b[K\n\u001b[K\n\u001b[K\n\u001b[K\n\u001b[K\n\u001b[K\n\u001b[K\n\u001b[K\n\u001b[K\n\u001b[K\n\u001b[K\n\u001b[K\n\u001b[K\n\u001b[K\n\u001b[K\n\u001b[K\n\u001b[K\n\u001b[K\n\u001b[K\u001b[1;1H\u001b[?25l\u001b[?12l\u001b[?25h\u001b[9;5H\u001b[30m\u001b[47m┌────────────────────────┤ MULTITOOLBOX v7.4 ├─────────────────────────┐\u001b[10;5H│ Enter your username                                                  │\u001b[97m\u001b[40m \u001b[11;5H\u001b[30m\u001b[47m│                                                                      │\u001b[97m\u001b[40m \u001b[12;5H\u001b[30m\u001b[47m│ \u001b[37m\u001b[44m____________________________________________________________________\u001b[30m\u001b[47m │\u001b[97m\u001b[40m \u001b[13;5H\u001b[30m\u001b[47m│                                                                      │\u001b[97m\u001b[40m \u001b[14;5H\u001b[30m\u001b[47m│                  <Ok>                      <Cancel>                  │\u001b[97m\u001b[40m \u001b[15;5H\u001b[30m\u001b[47m│                                                                      │\u001b[97m\u001b[40m \u001b[16;5H\u001b[30m\u001b[47m└──────────────────────────────────────────────────────────────────────┘\u001b[97m\u001b[40m \u001b[17;6H                                                                        \u001b[12;7H\u001b[37m\u001b[44mcumulus", "stdout_lines": ["\u001b[H\u001b[2J\u001b[3J\u001b[38;5;27m", "    __  ___      ____  _ __              ____              ", "   /  |/  /_  __/ / /_(_) /_____  ____  / / /_  ____  _  __", "  / /|_/ / / / / / __/ / __/ __ \\/ __ \\/ / __ \\/ __ \\| |/_/", " / /  / / /_/ / / /_/ / /_/ /_/ / /_/ / / /_/ / /_/ />  <  ", "/_/  /_/\\__,_/_/\\__/_/\\__/\\____/\\____/_/_.___/\\____/_/|_|  ", "                                                           ", "\u001b[1;33m================================================================\u001b[0m", "\u001b[1;32mVersion: v7.4\u001b[0m", "\u001b[1;32mBranch: master\u001b[0m", "\u001b[1;32mOS: Ubuntu 16/18/19/20, Debian 9/10 \u001b[0m", "\u001b[1;32mCreated by: X4MiLX from Flux's team\u001b[0m", "\u001b[1;32mSpecial thanks to dk808, CryptoWrench, jriggs28 && TechDufus\u001b[0m", "\u001b[1;33m================================================================\u001b[0m", "\u001b[1;36m1  - Install Docker\u001b[0m", "\u001b[1;36m2  - Install FluxNode\u001b[0m", "\u001b[1;36m3  - FluxNode analyzer and fixer\u001b[0m", "\u001b[1;36m4  - Install watchdog for FluxNode\u001b[0m", "\u001b[1;36m5  - Restore Flux blockchain from bootstrap\u001b[0m", "\u001b[1;36m6  - Create FluxNode installation config file\u001b[0m", "\u001b[1;36m7  - Re-install FluxOS\u001b[0m", "\u001b[1;36m8  - Flux Daemon Reconfiguration\u001b[0m", "\u001b[1;36m9  - Create Flux daemon service ( for old nodes )\u001b[0m", "\u001b[1;36m10 - Create Self-hosting cron ip service \u001b[0m", "\u001b[1;36m11 - FluxOS reconfiguration \u001b[0m", "\u001b[1;36m12 - Install fluxwatchtower for docker images autoupdate\u001b[0m", "\u001b[1;36m13 - MongoDB FiX action\u001b[0m", "\u001b[1;36m14 - Multinode configuration with UPNP communication (Needs Router with UPNP support)  \u001b[0m", "\u001b[1;36m15 - Node reconfiguration from install config\u001b[0m", "\u001b[1;33m================================================================\u001b[0m", "Pick an option and hit ENTER: \u001b[H\u001b[2J\u001b[3J\u001b[1;32mModule: Install Docker\u001b[0m", "\u001b[1;33m================================================================\u001b[0m", "\u001b[?1049h\u001b[22;0;0t\u001b[1;24r\u001b[4l\u001b[?25l\u001b(B\u001b[m\u001b[37m\u001b[40m\u001b[1;24r\u001b[H\u001b[2J\u001b[1;1H\u001b[97m\u001b[44m\u001b[K", "\u001b[K", "\u001b[K", "\u001b[K", "\u001b[K", "\u001b[K", "\u001b[K", "\u001b[K", "\u001b[K", "\u001b[K", "\u001b[K", "\u001b[K", "\u001b[K", "\u001b[K", "\u001b[K", "\u001b[K", "\u001b[K", "\u001b[K", "\u001b[K", "\u001b[K", "\u001b[K", "\u001b[K", "\u001b[K", "\u001b[K\u001b[1;1H\u001b[?25l\u001b[?12l\u001b[?25h\u001b[9;5H\u001b[30m\u001b[47m┌────────────────────────┤ MULTITOOLBOX v7.4 ├─────────────────────────┐\u001b[10;5H│ Enter your username                                                  │\u001b[97m\u001b[40m \u001b[11;5H\u001b[30m\u001b[47m│                                                                      │\u001b[97m\u001b[40m \u001b[12;5H\u001b[30m\u001b[47m│ \u001b[37m\u001b[44m____________________________________________________________________\u001b[30m\u001b[47m │\u001b[97m\u001b[40m \u001b[13;5H\u001b[30m\u001b[47m│                                                                      │\u001b[97m\u001b[40m \u001b[14;5H\u001b[30m\u001b[47m│                  <Ok>                      <Cancel>                  │\u001b[97m\u001b[40m \u001b[15;5H\u001b[30m\u001b[47m│                                                                      │\u001b[97m\u001b[40m \u001b[16;5H\u001b[30m\u001b[47m└──────────────────────────────────────────────────────────────────────┘\u001b[97m\u001b[40m \u001b[17;6H                                                                        \u001b[12;7H\u001b[37m\u001b[44mcumulus"]}


问:
scanf to read multiple numbers
I am writing a c program to read two fractions and enter the sum of the fractions. I keep on getting 6487612 and 6487608 as the answer. please help thank you

```<code>#include <stdio.h>
int main ()
{
  int num1, num2, denom1, denom2, result_num, result_den;

  printf("enter first fraction\n");
  scanf("%d/%d", &num1, &denom1);

  printf("enter  second fraction\n");
  scanf("%d/%d", &num2, &denom2);

result_num = (denom2 * num1) + (denom1 * num2);
result_den = (denom1 * denom2);

printf("the result is %d/%d", &result_num, &result_den);

  return 0;
}
</code>```

just wanted sum of the two fractions

Title: scanf to read multiple numbers

Body:
I am writing a c program to read two fractions and enter the sum of the fractions. I keep on getting 6487612 and 6487608 as the answer. please help thank you

#include <stdio.h>
int main ()
{
  int num1, num2, denom1, denom2, result_num, result_den;

  printf("enter first fraction\n");
  scanf("%d/%d", &num1, &denom1);

  printf("enter  second fraction\n");
  scanf("%d/%d", &num2, &denom2);

result_num = (denom2 * num1) + (denom1 * num2);
result_den = (denom1 * denom2);

printf("the result is %d/%d", &result_num, &result_den);

  return 0;
}

just wanted sum of the two fractions


问:
How to check if a Thread in a thread pool is actually working long or blocked or stuck for any reason?
I launch threads as:

```<code>ScheduledExecutorService threadPool = Executors.newScheduledThreadPool(workerCount);
threadPool.scheduleWithFixedDelay(new WorkerThread("<required info for worker>"), 1, interval, TimeUnit.SECONDS);
threadPool.awaitTermination(-1, TimeUnit.SECONDS);
</code>```

I need to see periodically if any WorkerThread is 'stuck' during processing a long task or it's really proceeding with the work.
If it's stuck, I would need to kill/stop that thread and put the work item in the work queue again so that another WorkerThread could pick it up.

In my case, WorkerThread is actually loading a large document from Elasticsearch.

Body:
I launch threads as:

ScheduledExecutorService threadPool = Executors.newScheduledThreadPool(workerCount);
threadPool.scheduleWithFixedDelay(new WorkerThread("<required info for worker>"), 1, interval, TimeUnit.SECONDS);
threadPool.awaitTermination(-1, TimeUnit.SECONDS);

I need to see periodically if any WorkerThread is 'stuck' during processing a long task or it's really proceeding with the work.
If it's stuck, I would need to kill/stop that thread and put the work item in the work queue again so that another WorkerThread could pick it up.

In my case, WorkerThread is actually loading a large document from Elasticsearch.


问:
Error list' object cannot be coerced to type 'double'
I'm trying to get the "EvolvabilityMeans" (evolvability package) of covariance matrices from 14 species. First, I'm getting the list of covariance matrices and list of means (17 cranial distances). To test evolvability, I need to adjust the matrices according to the means. Remembering that all matrices are positive definite. The error appears when the evolvability means is calculated.

`

```<code>cov.matrices <- list(matriz.cov.1, matriz.cov.2, matriz.cov.3,
                     matriz.cov.4, matriz.cov.5, matriz.cov.6, matriz.cov.7,
                     matriz.cov.8, matriz.cov.9, matriz.cov.10, matriz.cov.11, matriz.cov.12,
                     matriz.cov.13, matriz.cov.14)

means.list<- list(Mean_1, Mean_2, Mean_3, Mean_4, Mean_5, Mean_6, Mean_7, Mean_8, Mean_9, Mean_10,  Mean_11,  Mean_12, Mean_13, Mean_14)

mean.std.matrices = function (cov.matrix, means){
  return(cov.matrix/(means%*%t(means)))
}

mean.std.cov.matrices <- list()
for(i in 1:length(cov.matrices)){
  mean.std.cov.matrices[[i]] <- mean.std.matrices(cov.matrices[[i]], means.list[[i]])
}
names(mean.std.cov.matrices) <- names(cov.matrices)

mean.std.cov.matrices

evolvabilityMeans(mean.std.cov.matrices, means = means.list)
list' object cannot be coerced to type 'double'
</code>```

`

Body:
I'm trying to get the "EvolvabilityMeans" (evolvability package) of covariance matrices from 14 species. First, I'm getting the list of covariance matrices and list of means (17 cranial distances). To test evolvability, I need to adjust the matrices according to the means. Remembering that all matrices are positive definite. The error appears when the evolvability means is calculated.

`

cov.matrices <- list(matriz.cov.1, matriz.cov.2, matriz.cov.3,
                     matriz.cov.4, matriz.cov.5, matriz.cov.6, matriz.cov.7,
                     matriz.cov.8, matriz.cov.9, matriz.cov.10, matriz.cov.11, matriz.cov.12,
                     matriz.cov.13, matriz.cov.14)

means.list<- list(Mean_1, Mean_2, Mean_3, Mean_4, Mean_5, Mean_6, Mean_7, Mean_8, Mean_9, Mean_10,  Mean_11,  Mean_12, Mean_13, Mean_14)

mean.std.matrices = function (cov.matrix, means){
  return(cov.matrix/(means%*%t(means)))
}

mean.std.cov.matrices <- list()
for(i in 1:length(cov.matrices)){
  mean.std.cov.matrices[[i]] <- mean.std.matrices(cov.matrices[[i]], means.list[[i]])
}
names(mean.std.cov.matrices) <- names(cov.matrices)

mean.std.cov.matrices

evolvabilityMeans(mean.std.cov.matrices, means = means.list)
list' object cannot be coerced to type 'double'

`


问:
failed assertion:line 5054 : '_dependents.isEmpty' is not true
I'm fluter newbie. I wrote some basic code like below and run symulator but it has error like a picture.

I searched with those keywords but couldn't find result related flutter..
How can I work arrange this problem?

Source code below attatched!

```<code>import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.teal,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
      initialIndex: 1,
      length: 3,
      child: Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
          actions: [IconButton(icon: Icon(Icons.person), onPressed: (){},)],
          bottom: TabBar(
            tabs: <Widget>[
              Tab(
                icon: Icon(Icons.note_alt),
              ),
              Tab(
                icon: Icon(Icons.list_alt),
              ),
              Tab(
                icon: Icon(Icons.settings),
              ),
            ],
          ),
        ),
        body: TabBarView(
          children: <Widget>[
            Center(
              child: Text("You can upload here"),
            ),
            Center(
              child: Text("You can load data here"),
            ),
            Center(
              child: Text("Settings Page"),
            ),
          ],
        )

      ),
    );
  }
}

</code>```

I used the codes following flutter's formal page about TabBar class.

Body:
I'm fluter newbie. I wrote some basic code like below and run symulator but it has error like a picture.

I searched with those keywords but couldn't find result related flutter..
How can I work arrange this problem?

Source code below attatched!

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.teal,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
      initialIndex: 1,
      length: 3,
      child: Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
          actions: [IconButton(icon: Icon(Icons.person), onPressed: (){},)],
          bottom: TabBar(
            tabs: <Widget>[
              Tab(
                icon: Icon(Icons.note_alt),
              ),
              Tab(
                icon: Icon(Icons.list_alt),
              ),
              Tab(
                icon: Icon(Icons.settings),
              ),
            ],
          ),
        ),
        body: TabBarView(
          children: <Widget>[
            Center(
              child: Text("You can upload here"),
            ),
            Center(
              child: Text("You can load data here"),
            ),
            Center(
              child: Text("Settings Page"),
            ),
          ],
        )

      ),
    );
  }
}

I used the codes following flutter's formal page about TabBar class.


问:
TypeScript 4.9 error (can`t use satisfies)
Why after npm install -g typescript@latest (for lates version at 2022.12 - 4.9v) i can`t use satisfies?
Error ... ! (error: Newline or semicolon expected)
At the package.json

"devDependencies": {

"typescript": "^4.9.4"

}

enter image description here
enter image description here


问:
Linux firewalld discards local UDP packet although ACCEPT rule is hit
On a RHEL8 system, I'm receiving UDP packet for destination port 2152 (gtp-user) from an external interface and they are not reaching the application listening on the UDP socket opened for that port.  I see packets reaching the application fine if I stop firewalld. As soon as firewalld is started, packets get discarded.

I added a rule to explicitly accept these packets and I see my ACCEPT rule is now being hit with counter matching exactly the number of packets generated (1987 packets in dump below)

```<code>iptables  -L -v
Chain INPUT (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination
 6755 4273K ACCEPT     all  --  any    any     anywhere             anywhere             state RELATED,ESTABLISHED
    1    28 ACCEPT     icmp --  any    any     anywhere             anywhere
  150 10358 ACCEPT     all  --  lo     any     anywhere             anywhere
    0     0 ACCEPT     tcp  --  any    any     anywhere             anywhere             state NEW tcp dpt:ssh
 1987 1492K ACCEPT     udp  --  any    any     anywhere             anywhere             udp dpt:gtp-user
   11  3849 REJECT     all  --  any    any     anywhere             anywhere             reject-with icmp-host-prohibited

Chain FORWARD (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination
    0     0 REJECT     all  --  any    any     anywhere             anywhere             reject-with icmp-host-prohibited
</code>```

Still packets are not reaching the application and when enabling log-denied=all I see in /var/log/messages  a FINAL_REJECT entry for each packet sent while firewalld is running

```<code>kernel: FINAL_REJECT: IN=ens161 OUT= MAC=00:50:56:8a:de:55:00:50:56:8a:93:57:08:00 SRC=168.168.31.201 DST=168.168.31.31 LEN=751 TOS=0x18 PREC=0x60 TTL=100 ID=3109 DF PROTO=UDP SPT=2152 DPT=2152
</code>```

Any ideas of why firewalld would reject these UDP packets after hitting the ACCEPT rule ?

Body:
On a RHEL8 system, I'm receiving UDP packet for destination port 2152 (gtp-user) from an external interface and they are not reaching the application listening on the UDP socket opened for that port.  I see packets reaching the application fine if I stop firewalld. As soon as firewalld is started, packets get discarded.

I added a rule to explicitly accept these packets and I see my ACCEPT rule is now being hit with counter matching exactly the number of packets generated (1987 packets in dump below)

iptables  -L -v
Chain INPUT (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination
 6755 4273K ACCEPT     all  --  any    any     anywhere             anywhere             state RELATED,ESTABLISHED
    1    28 ACCEPT     icmp --  any    any     anywhere             anywhere
  150 10358 ACCEPT     all  --  lo     any     anywhere             anywhere
    0     0 ACCEPT     tcp  --  any    any     anywhere             anywhere             state NEW tcp dpt:ssh
 1987 1492K ACCEPT     udp  --  any    any     anywhere             anywhere             udp dpt:gtp-user
   11  3849 REJECT     all  --  any    any     anywhere             anywhere             reject-with icmp-host-prohibited

Chain FORWARD (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination
    0     0 REJECT     all  --  any    any     anywhere             anywhere             reject-with icmp-host-prohibited

Still packets are not reaching the application and when enabling log-denied=all I see in /var/log/messages  a FINAL_REJECT entry for each packet sent while firewalld is running

kernel: FINAL_REJECT: IN=ens161 OUT= MAC=00:50:56:8a:de:55:00:50:56:8a:93:57:08:00 SRC=168.168.31.201 DST=168.168.31.31 LEN=751 TOS=0x18 PREC=0x60 TTL=100 ID=3109 DF PROTO=UDP SPT=2152 DPT=2152

Any ideas of why firewalld would reject these UDP packets after hitting the ACCEPT rule ?


问:
How to fully hide the test from the pytest output?
I want to delete all test information from the pytest output for some tests.

For example:

def test_something(ctx):
    if ctx.value > 10:
        pytest.hide()

    ...
```

I know about pytest.skip, but when i use it, i see information about skipped tests in the output.

My real case is a lot of parameterized tests with many skip conditions.

Body:
I want to delete all test information from the pytest output for some tests.

For example:

def test_something(ctx):
    if ctx.value > 10:
        pytest.hide()

    ...

I know about pytest.skip, but when i use it, i see information about skipped tests in the output.

My real case is a lot of parameterized tests with many skip conditions.


问:
Converting req.params values to a number to carry out simply calculation and return result
I am new to express and have a task where I need to create a separate router for all requests which start with the path '/calc'. I then have to handle a GET /calc/:num1/:operation/:num2 request where num1 and num2 will be numbers and operation will be an operator (add, subtract, multiply, divide or modulo).

Unfortunately, I am having trouble with converting the req.params into numbers to carry out the simply calculations. I have tried using the Number() and parseInt() methods but I am getting the following error in postman: RangeError [ERR_HTTP_INVALID_STATUS_CODE]: Invalid status code: 1

I have the below code in my app.js file:

```<code>const express = require("express");
const calc = require("./calc.js");
const app = express();

app.use("/calc", calc);

app.listen(3000, function () {
  console.log("Listening on port 3000");
});
</code>```

And the following code in the calc.js file:

```<code>const express = require("express");
let router = express.Router();
router.get("/:num1/:operation/:num2", (req, res) => {
  const num1 = req.params.num1;
  const num2 = req.params.num2;
  const operation = req.params.operation;

  const result = resultFunction(operation, num1, num2);

  res.send();
});

module.exports = router;

const resultFunction = (operator, a, b) => {
  if (operator === "+") {
    return a + b;
  } else if (operator === "-") {
    return a - b;
  } else if (operator === "*") {
    return a * b;
  } else if (operator === "/") {
    return a / b;
  } else if (operator === "%") {
    return a % b;
  }
};
</code>```

Body:
I am new to express and have a task where I need to create a separate router for all requests which start with the path '/calc'. I then have to handle a GET /calc/:num1/:operation/:num2 request where num1 and num2 will be numbers and operation will be an operator (add, subtract, multiply, divide or modulo).

Unfortunately, I am having trouble with converting the req.params into numbers to carry out the simply calculations. I have tried using the Number() and parseInt() methods but I am getting the following error in postman: RangeError [ERR_HTTP_INVALID_STATUS_CODE]: Invalid status code: 1

I have the below code in my app.js file:

const express = require("express");
const calc = require("./calc.js");
const app = express();

app.use("/calc", calc);

app.listen(3000, function () {
  console.log("Listening on port 3000");
});

And the following code in the calc.js file:

const express = require("express");
let router = express.Router();
router.get("/:num1/:operation/:num2", (req, res) => {
  const num1 = req.params.num1;
  const num2 = req.params.num2;
  const operation = req.params.operation;

  const result = resultFunction(operation, num1, num2);

  res.send();
});

module.exports = router;

const resultFunction = (operator, a, b) => {
  if (operator === "+") {
    return a + b;
  } else if (operator === "-") {
    return a - b;
  } else if (operator === "*") {
    return a * b;
  } else if (operator === "/") {
    return a / b;
  } else if (operator === "%") {
    return a % b;
  }
};


问:
Proper stdin / stdout redirection for automated testing in C
This is a fairly simple question, however I haven't been able to find a straightforward answer :

What file and mode should I restore stdin and stdout to after having redirected them ? (to test a function that uses plain printf and / or scanf instead of asking for a file pointer)

Currently, I'm doing this :

/* Error detection code omitted for conciseness, the real code checks return values */
freopen("/dev/tty", "r", stdin);
freopen("/dev/tty", "w", stdout);
```

However, this is more or less a complete guess on my part, and I'd like to be sure I'm doing things right. Reopening stdout in "a" mode also would make sense, and I'm not sure them both interacting with the same file is the default behavior ? Can someone tel me if this is right ?

Body:
This is a fairly simple question, however I haven't been able to find a straightforward answer :

What file and mode should I restore stdin and stdout to after having redirected them ? (to test a function that uses plain printf and / or scanf instead of asking for a file pointer)

Currently, I'm doing this :

/* Error detection code omitted for conciseness, the real code checks return values */
freopen("/dev/tty", "r", stdin);
freopen("/dev/tty", "w", stdout);

However, this is more or less a complete guess on my part, and I'd like to be sure I'm doing things right. Reopening stdout in "a" mode also would make sense, and I'm not sure them both interacting with the same file is the default behavior ? Can someone tel me if this is right ?


问:
Restrict Supabase signup to a specific membership table
Similar to this question Restrict Supabase Sign up to a specific domain ... I am needing to restrict signup to my SPA Supabase project to specific emails contained in a membership table.  Work flow would be: web page has sign up form submitted - form's email address is checked to see if it is exists in a members table - if yes, proceed with sign up - if rejected, inform with message on the client.  I know I could send sign up requests thru a backend similar to the other question's reply but the point of using Supabase is to take away the backend.  Could I create a function/trigger similar to the previous question here: Restrict Supabase Sign up to a specific domain  to solve this?  Project is a Vue3 SPA.  Thanks for any replies!</p>


问:
How to run ogr2ogr copy from GML to Postgres from Gdal.netcore library (C#)?
Can I run the same functionality as from beneath commandline in C# using gdal.netcore?:

ogr2ogr -update -append PG:"dbname='postgres' host='***' port='5432' user='***' password='***' -f XML mygml.xml -lco SCHEMA=myschema -lco OVERWRITE=yes
```
<p>I'm looking at both source code from gdal 3.3.3 and gdal.netcore (github clone) but can't find the append option in the later.</p>
<p>What I have so far in C# is:</p>
<pre class="lang-cs prettyprint-override"><code>var srcConnStr = "MyGML_V2.xml";

var dstConnStr = "PG:" +
"dbname='postgres' " +
"active_schema='myschema' " +
"schemas='myschema, public, pg_catalog' " +
"sslmode='require' " +
"host='myhost' " +
"port='5432' " +
"user='me' " +
"password='***'";

GdalBase.ConfigureAll();

const int GDAL_OF_READONLY = 0x00;
const int GDAL_OF_UPDATE = 0x01;
const int GDAL_OF_VECTOR = 0x04;

var srcDriver = Gdal.GetDriverByName("GML");
if ( srcDriver != null)
{
    srcDriver.Register();
    Console.WriteLine("Src Driver name: {0}", srcDriver.LongName);
}
else
{
    Console.WriteLine("GML Driver not found!");
    return;
}

var srcDS = Gdal.OpenEx(srcConnStr, GDAL_OF_READONLY | GDAL_OF_VECTOR, new[] {"GML"}, null, null);
if (srcDS == null)
{
    Console.WriteLine("Error opening source!");
    return;
}

var dstDriver = Gdal.GetDriverByName("Postgresql");
if (dstDriver != null)
{
    dstDriver.Register();
}
else
{
    Console.WriteLine("Postgresql driver not found!");
    return;
}

var dstDS = Gdal.OpenEx(dstConnStr, GDAL_OF_UPDATE | GDAL_OF_VECTOR, new[] {"Postgresql"}, null, null);
if (dstDS == null)
{
    Console.WriteLine("Error opening destination!");
    return;
}

var options = new GDALVectorTranslateOptions(new[] { "mypolygonlayer" });

Gdal.wrapper_GDALVectorTranslateDestDS(dstDS, srcDS, options, (p, b, c) => { return 1; }, null);
</code>```

Above fails with errors:

```<code>ERROR 1: Layer mypolygonlayer already exists, and -append not specified.
        Consider using -append, or -overwrite.
ERROR 1: Terminating translation prematurely after failed
</code>```

Can anyone point me in the right direction?

Body:
Can I run the same functionality as from beneath commandline in C# using gdal.netcore?:

ogr2ogr -update -append PG:"dbname='postgres' host='***' port='5432' user='***' password='***' -f XML mygml.xml -lco SCHEMA=myschema -lco OVERWRITE=yes

I'm looking at both source code from gdal 3.3.3 and gdal.netcore (github clone) but can't find the append option in the later.

What I have so far in C# is:

var srcConnStr = "MyGML_V2.xml";

var dstConnStr = "PG:" +
"dbname='postgres' " +
"active_schema='myschema' " +
"schemas='myschema, public, pg_catalog' " +
"sslmode='require' " +
"host='myhost' " +
"port='5432' " +
"user='me' " +
"password='***'";

GdalBase.ConfigureAll();

const int GDAL_OF_READONLY = 0x00;
const int GDAL_OF_UPDATE = 0x01;
const int GDAL_OF_VECTOR = 0x04;

var srcDriver = Gdal.GetDriverByName("GML");
if ( srcDriver != null)
{
    srcDriver.Register();
    Console.WriteLine("Src Driver name: {0}", srcDriver.LongName);
}
else
{
    Console.WriteLine("GML Driver not found!");
    return;
}

var srcDS = Gdal.OpenEx(srcConnStr, GDAL_OF_READONLY | GDAL_OF_VECTOR, new[] {"GML"}, null, null);
if (srcDS == null)
{
    Console.WriteLine("Error opening source!");
    return;
}

var dstDriver = Gdal.GetDriverByName("Postgresql");
if (dstDriver != null)
{
    dstDriver.Register();
}
else
{
    Console.WriteLine("Postgresql driver not found!");
    return;
}

var dstDS = Gdal.OpenEx(dstConnStr, GDAL_OF_UPDATE | GDAL_OF_VECTOR, new[] {"Postgresql"}, null, null);
if (dstDS == null)
{
    Console.WriteLine("Error opening destination!");
    return;
}

var options = new GDALVectorTranslateOptions(new[] { "mypolygonlayer" });

Gdal.wrapper_GDALVectorTranslateDestDS(dstDS, srcDS, options, (p, b, c) => { return 1; }, null);

Above fails with errors:

ERROR 1: Layer mypolygonlayer already exists, and -append not specified.
        Consider using -append, or -overwrite.
ERROR 1: Terminating translation prematurely after failed

Can anyone point me in the right direction?


问:
Get variant that was added to cart
I am using the Shopify Storefront API for a headless website, I have run into a specific issue where, when I add a variant of a product in the Cart, I can't seem to find a solid way of knowing which variant was added, the current API as is from Storefront doesn't seem to offer an option from the graphQL to know which variant was added.

Thanks in advance!

Technically, I can get this information from the variantBySelectedOptions field, however this only works when adding items to cart, since when I add a product I can send the options of the variant, however this doesn't work when I am simply trying to fetch the current items in my Cart, when for example I'm simply reloading the page, this field always expects some sort of input!

Title: Get variant that was added to cart


问:
how to define a anim layer blueprint interface with code in UE4/5?
As we know, we can create a blueprint interface asset in editor, but how can we define an anim layer blueprint interface by code in UE4/5?
I just read all relevent doc but I cant find the answers. Hope someone`s answer.</p>


问:
why am i not able to install any package?
since 2 days ago Whenever i try to insrall a package R gives me this error:

package installation in ‘C:/Users/Win10/AppData/Local/R/win-library/4.2’
(because ‘lib’ is not specified)
trying URL 'https://cran.rstudio.com/bin/windows/contrib/4.2/dplyr_1.0.10.zip'
Content type 'application/zip' length 1306071 bytes (1.2 MB)
downloaded 1.2 MB

package ‘dplyr’ opened with success with sum cntrol MD5
Error in install.packages : ERROR:  faild change lock for the directory ‘C:\Users\Win10\AppData\Local\R\win-library\4.2’
Removal ‘C:\Users\Win10\AppData\Local\R\win-library\4.2/00LOCK’

i try to reinstall R and to remove "00LOCK"


问:
Cannot Ctrl+Click when using a variable in the path?

On Qt Creator qmake project (on Windows), it seems I cannot Ctrl+Click when using a variable in the path of a source file.

The Ctrl+Click is very useful function to open the file.

Am I making a mistake at any point?


问:
Group how many times a Sales Rep worked with a customer Descending
Display a count of customers each sales rep has worked with. Sort by the count in descending order.

Rep_Name

Cust_Name

I have tried many ways to write this out but just not getting the results I am looking for...

Select Rep_Name From finaldb.rep
count(customer) Desc


问:
Alternative of withNavigationFocus from @react-navigation/native in react navigation v6
Is there any alternate to withNavigationFocus imported from @react-navigation/native? or can we write our own withNavigationFocus just like we can write our own withNavigation like this https://stackoverflow.com/a/63818841/14341861.