问:
async await calling function node.js
I have this function, that queries my database, and then calls getNumOfSessionForTrainerClientList function:

```<code>var select = "select * from USERS WHERE ASSIGNED_TRAINER = ?"
mysqlconn.connect(function(err) {
    if (err) {
        console.error('Database connection failed: ' + err.stack);
        return;
    }

    mysqlconn.query(select, [req.session.username], async function(err, rows) {
        if (err) {
            console.log(err);
        } else {

            let numOfSessionsLeft = {
                numberOfSessionsLeftIs: 0
            }
            for (var i = 0; i < rows.length; i++) {
                getNumOfSessionForTrainerClientList(req, res, rows[i], numOfSessionsLeft)
                rows[i]["NUM_OF_SESSIONS_PER_MONTH"] = (parseInt(rows[i]["NUM_OF_SESSIONS_PER_MONTH"]) - numOfSessionsLeft.numberOfSessionsLeftIs)
                console.log(numOfSessionsLeft)
            }

        }
        mysqlconn.end();

    })
})
</code>```

and then inside the function getNumOfSessionForTrainerClientList, I have this:

```<code>async function getNumOfSessionForTrainerClientList(req, res, rows, numOfSessionsLeft) {

var getNumOfSessionForTrainerClientList = "select * from SCHEDULE WHERE CLIENT_USERNAME = ? AND ASSIGNED_TRAINER = ?"
mysqlconn.connect(async function(err) {
    if (err) {
        console.error('Database connection failed: ' + err.stack);
        return;
    }
        mysqlconn.query(getNumOfSessionForTrainerClientList, [rows["USERNAME"], req.session.username], async function(err, sessionData) {
            if (err) {
                console.log(err);
            } else {
                numOfSessionsLeft.numberOfSessionsLeftIs = 1;
                console.log(numOfSessionsLeft.numberOfSessionsLeftIs)

            }

        })

})

}
</code>```

however, what is happening is that this line : rows[i]["NUM_OF_SESSIONS_PER_MONTH"] = (parseInt(rows[i]["NUM_OF_SESSIONS_PER_MONTH"]) - numOfSessionsLeft.numberOfSessionsLeftIs) is actually assigning 0 to rows[i]["NUM_OF_SESSIONS_PER_MONTH"] because that variable assignment is happening before the function call for getNumOfSessionForTrainerClientList finishes. So it is happening out of sync. I am not sure how to fix this, i have run into issues with async await before, but nothing like this. would appreciate the help.

答:
You call the function that includes async codes therefore getNumOfSessionForTrainerClientList doesn't depend the codes above (starts with(rows[i]["NUM_OF and console) what you should do is

Make the function async by returning prom

execute it with await keyword

```<code>async function trainerClientList(){

return new Promise((resolve,reject)=>{

            var getNumOfSessionForTrainerClientList = "select * from SCHEDULE WHERE CLIENT_USERNAME = ? AND ASSIGNED_TRAINER = ?"
    mysqlconn.connect(async function(err) {
        if (err) {
            console.error('Database connection failed: ' + err.stack);
            resolve()
        }
            mysqlconn.query(getNumOfSessionForTrainerClientList, [rows["USERNAME"], req.session.username], async function(err, sessionData) {
                if (err) {
                    console.log(err);
                } else {
                    numOfSessionsLeft.numberOfSessionsLeftIs = 1;
                    console.log(numOfSessionsLeft.numberOfSessionsLeftIs)

                }

            })

    })

    resolve()

})
</code>```

}

for (var i = 0; i < rows.length; i++) {
await trainerClientList()
rows[i]["NUM_OF_SESSIONS_PER_MONTH"] = (parseInt(rows[i]["NUM_OF_SESSIONS_PER_MONTH"]) - numOfSessionsLeft.numberOfSessionsLeftIs)
console.log(numOfSessionsLeft)
}

Title: async await calling function node.js

Body:
I have this function, that queries my database, and then calls getNumOfSessionForTrainerClientList function:

var select = "select * from USERS WHERE ASSIGNED_TRAINER = ?"
mysqlconn.connect(function(err) {
    if (err) {
        console.error('Database connection failed: ' + err.stack);
        return;
    }

    mysqlconn.query(select, [req.session.username], async function(err, rows) {
        if (err) {
            console.log(err);
        } else {

            let numOfSessionsLeft = {
                numberOfSessionsLeftIs: 0
            }
            for (var i = 0; i < rows.length; i++) {
                getNumOfSessionForTrainerClientList(req, res, rows[i], numOfSessionsLeft)
                rows[i]["NUM_OF_SESSIONS_PER_MONTH"] = (parseInt(rows[i]["NUM_OF_SESSIONS_PER_MONTH"]) - numOfSessionsLeft.numberOfSessionsLeftIs)
                console.log(numOfSessionsLeft)
            }

        }
        mysqlconn.end();

    })
})

and then inside the function getNumOfSessionForTrainerClientList, I have this:

async function getNumOfSessionForTrainerClientList(req, res, rows, numOfSessionsLeft) {

var getNumOfSessionForTrainerClientList = "select * from SCHEDULE WHERE CLIENT_USERNAME = ? AND ASSIGNED_TRAINER = ?"
mysqlconn.connect(async function(err) {
    if (err) {
        console.error('Database connection failed: ' + err.stack);
        return;
    }
        mysqlconn.query(getNumOfSessionForTrainerClientList, [rows["USERNAME"], req.session.username], async function(err, sessionData) {
            if (err) {
                console.log(err);
            } else {
                numOfSessionsLeft.numberOfSessionsLeftIs = 1;
                console.log(numOfSessionsLeft.numberOfSessionsLeftIs)

            }

        })

})

}

however, what is happening is that this line : rows[i]["NUM_OF_SESSIONS_PER_MONTH"] = (parseInt(rows[i]["NUM_OF_SESSIONS_PER_MONTH"]) - numOfSessionsLeft.numberOfSessionsLeftIs) is actually assigning 0 to rows[i]["NUM_OF_SESSIONS_PER_MONTH"] because that variable assignment is happening before the function call for getNumOfSessionForTrainerClientList finishes. So it is happening out of sync. I am not sure how to fix this, i have run into issues with async await before, but nothing like this. would appreciate the help.

Body:
You call the function that includes async codes therefore getNumOfSessionForTrainerClientList doesn't depend the codes above (starts with(rows[i]["NUM_OF and console) what you should do is

Make the function async by returning prom

execute it with await keyword

async function trainerClientList(){

return new Promise((resolve,reject)=>{

            var getNumOfSessionForTrainerClientList = "select * from SCHEDULE WHERE CLIENT_USERNAME = ? AND ASSIGNED_TRAINER = ?"
    mysqlconn.connect(async function(err) {
        if (err) {
            console.error('Database connection failed: ' + err.stack);
            resolve()
        }
            mysqlconn.query(getNumOfSessionForTrainerClientList, [rows["USERNAME"], req.session.username], async function(err, sessionData) {
                if (err) {
                    console.log(err);
                } else {
                    numOfSessionsLeft.numberOfSessionsLeftIs = 1;
                    console.log(numOfSessionsLeft.numberOfSessionsLeftIs)

                }

            })

    })

    resolve()

})

}

for (var i = 0; i < rows.length; i++) {
await trainerClientList()
rows[i]["NUM_OF_SESSIONS_PER_MONTH"] = (parseInt(rows[i]["NUM_OF_SESSIONS_PER_MONTH"]) - numOfSessionsLeft.numberOfSessionsLeftIs)
console.log(numOfSessionsLeft)
}


来源: stackexchange

问:
HTML5 Video — limiting buffer for an MP4
Is it possible to use an HTML5 Video tag to load an MP4, but control how much of the file is downloaded/buffered from the server (assume it supports byte ranges).

Essentially, I'd like to be able to say "only download 60 seconds ahead" so I can avoid the browser downloading an entire 2 GB file when the user is going to end up bouncing anyway.

答: Answer: browsers will automatically buffer only what they need, rather than download the whole file. It is not necessary to try and control the buffering from a "custom" HTML5 player POV.</p>

ContentLicense: CC BY-SA 4.0


问:
how to pick some value from an object {} and put it into an array []
got some information from an API and now  want to pick "correct_answer" property from all of them and then make an array from correct_answer  here is the API information :

```<code>apipresave=[
  {question: "What does the "MP" stand for in MP3?",
   correct_answer: "Moving Picture",
   incorrect_answers: ["Music Player", "Multi Pass", "Micro Point"]},

  {question: "What does GHz stand for?",
   correct_answer: "Gigahertz",
   incorrect_answers: ["Gigahotz", "Gigahetz", "Gigahatz"]},

  {question: "In the programming language Java, which of these keywords would you put on a variable
   to make sure it doesn't get modified?",
   correct_answer: "Final",
   incorrect_answers: ["Static", "Private", "Public"]},
]
</code>```

btw I have already put this information on a const and have full access to them in code
I have tried to loop over them and use push to get them but it didn't work
I put it below :

```<code>   //puting all correct_answer  into an array
   function correct_answer_array_func (){
         const correct_answer_array =[]
         for(let i =0 ; i<4;i++){
             correct_answer_array.push(apipresave[i].correct_answer)
                 return correct_answer_array
         }
    }
</code>```

so how to obtain "correct_answer" from all the objects and put them in an array

the final result will be  :

```<code> correct_answer_array  =["Moving Picture","Gigahertz","Final"]  // correct_answer values
</code>```

答:
You're looking for the .map() Javascript Array method

Here is an example that should give you the array of values you are looking for.

```<code>const correct_answer_array = apipresave.map(item => item.correct_answer)
// ["Moving Picture","Gigahertz","Final"]
</code>```

Body:
got some information from an API and now  want to pick "correct_answer" property from all of them and then make an array from correct_answer  here is the API information :

apipresave=[
  {question: "What does the "MP" stand for in MP3?",
   correct_answer: "Moving Picture",
   incorrect_answers: ["Music Player", "Multi Pass", "Micro Point"]},

  {question: "What does GHz stand for?",
   correct_answer: "Gigahertz",
   incorrect_answers: ["Gigahotz", "Gigahetz", "Gigahatz"]},

  {question: "In the programming language Java, which of these keywords would you put on a variable
   to make sure it doesn't get modified?",
   correct_answer: "Final",
   incorrect_answers: ["Static", "Private", "Public"]},
]

btw I have already put this information on a const and have full access to them in code
I have tried to loop over them and use push to get them but it didn't work
I put it below :

   //puting all correct_answer  into an array
   function correct_answer_array_func (){
         const correct_answer_array =[]
         for(let i =0 ; i<4;i++){
             correct_answer_array.push(apipresave[i].correct_answer)
                 return correct_answer_array
         }
    }

so how to obtain "correct_answer" from all the objects and put them in an array

the final result will be  :

 correct_answer_array  =["Moving Picture","Gigahertz","Final"]  // correct_answer values

Body:
You're looking for the .map() Javascript Array method

Here is an example that should give you the array of values you are looking for.

const correct_answer_array = apipresave.map(item => item.correct_answer)
// ["Moving Picture","Gigahertz","Final"]


问:
how to fill the remaining space inside a row?
i have a row that includes a column widget.now as its second child i want to have a container to fill the remaining space.here is my code:

```<code>Row(
        children: [
          _status(),
          Constants.smallHorizontalSpacer,
          Padding(
            padding: const EdgeInsets.only(
              top: Constants.smallSize,
              bottom: Constants.smallSize,
            ),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                _roundedAvatar(),
                _projectType(),
                _name(),
              ],
            ),
          ),
          _divider(),
          Padding(
            padding: const EdgeInsets.only(
              top: Constants.smallSize,
              bottom: Constants.smallSize,
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    Column(
                      children: [
                        _usageTypes(),
                        Constants.smallVerticalSpacer,
                        _details(),
                      ],
                    ),
                    Expanded(
                      child: Container(

                        height: 60,
                        color: Colors.black,
                        child: const Text('fill the remaining space'),
                      ),
                    ),
                  ],
                ),
                Constants.smallVerticalSpacer,
                _description(),
              ],
            ),
          ),
          // _map(context),
        ],
      ),
</code>```

i have already tried expanded and flexble but all my widgets disappeared.any idea will be greate.

this is my result:
https://i.stack.imgur.com/gFTwX.png

答:
Wrap the container with a flexible widget and give the container a width of the hoal screen:

```<code>Flexible(
  child: Container(
    width: MediaQuery.of(context).size.width,
  ),
),
</code>```

I know it does the same thing like a expanded widget but the expanded widget make's on a real device problems

Body:
i have a row that includes a column widget.now as its second child i want to have a container to fill the remaining space.here is my code:

Row(
        children: [
          _status(),
          Constants.smallHorizontalSpacer,
          Padding(
            padding: const EdgeInsets.only(
              top: Constants.smallSize,
              bottom: Constants.smallSize,
            ),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                _roundedAvatar(),
                _projectType(),
                _name(),
              ],
            ),
          ),
          _divider(),
          Padding(
            padding: const EdgeInsets.only(
              top: Constants.smallSize,
              bottom: Constants.smallSize,
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    Column(
                      children: [
                        _usageTypes(),
                        Constants.smallVerticalSpacer,
                        _details(),
                      ],
                    ),
                    Expanded(
                      child: Container(

                        height: 60,
                        color: Colors.black,
                        child: const Text('fill the remaining space'),
                      ),
                    ),
                  ],
                ),
                Constants.smallVerticalSpacer,
                _description(),
              ],
            ),
          ),
          // _map(context),
        ],
      ),

i have already tried expanded and flexble but all my widgets disappeared.any idea will be greate.

this is my result:
https://i.stack.imgur.com/gFTwX.png

Body:
Wrap the container with a flexible widget and give the container a width of the hoal screen:

Flexible(
  child: Container(
    width: MediaQuery.of(context).size.width,
  ),
),

I know it does the same thing like a expanded widget but the expanded widget make's on a real device problems


问:
Add Online Offline Status in Flutter App Like Whatsapp using Firebase but how i Handle without internet
if I turn off wifi and then close the app, didChangeAppLifecycleState() will try to set the status to 'offline' in Firestore, but as wifi is off Firestore can't set the status to offline... So, other users of the app will see that user 'online'. How can I fix this?

答:
Firestore has no built-in capability to write something in the database after the client has disconnected. In fact, most databases don't have such a capability.

One exception is Firebase's other database: the Realtime Database, which has so-called onDisconnect handlers, which are delayed write instructions that you to the database when you are connection, and which the database then executes once it detects that the connection is gone.

You can combine the Realtime Database with Firestore as shown in the links below.

See:

The FlutterFire documentation on onDisconnect handlers.

The Firebase documentation on building a presence system with the Realtime Database.

The Firebase documentation on connecting Realtime Database and Firestore to get presence information into Firestore too.


问:
Why does this double-ended selectionsort algorithm not work?
I just wrote a simple algorithm to sort integer-values in an array. When I try to debug it, it sometimes works and sometimes it does not. I really don't know why. Can anyone help me?

This is my code:

void swap(int[] array, int left, int right)
{
    int tmp = array[left];
    array[left] = array[right];
    array[right] = tmp;
}

void selectionsort(int[] givenArray)
{
    int maxindex = givenArray.Length - 1;
    for (int border = 0; border < givenArray.Length / 2; border++)
    {
        for (int i = 0; i < givenArray.Length - (border * 2); i++)
        {
            if (i != 0)
            {
                if (givenArray[border + i] < givenArray[border])
                    swap(givenArray, border + i, border);
                if (givenArray[border + i] > givenArray[maxindex - border])
                    swap(givenArray, border + i, maxindex - border);
            }
        }
    }
}
```
<p>Edit: I usually generate 10 random numbers between 1 and 9999 and print them out. Then I start the sorting and then I print them out again. Here is the output:</p>
```[Random] >> 2257 | 2866 | 8796 | 4497 | 4697 | 2393 | 1004 | 4799 | 483  | 8500 |
[Sorted] >> 483  | 2257 | 1004 | 2866 | 2393 | 4497 | 4697 | 4799 | 8500 | 8796 |

Sorting failed at 2/3
sorting failed at 4/5

Array has been sorted in less than 1 ms
```

答:
I updated your example to print the array before every iteration (I also adjusted the inner loop to not pointlessly start at 0):

```<code>    public static void selectionsort(int[] givenArray)
    {
        int maxindex = givenArray.Length - 1;
        for (int border = 0; border < givenArray.Length / 2; border++)
        {
            PrintArray(givenArray);
            for (int i = 1; i < givenArray.Length - (border * 2); i++)
            {
                    if (givenArray[border + i] < givenArray[border])
                        swap(givenArray, border + i, border);
                    if (givenArray[border + i] > givenArray[maxindex - border])
                        swap(givenArray, border + i, maxindex - border);
            }
        }
    }

    public static void PrintArray(int[] givenArray)
    {
        var first = true;
        for (int i = 0; i < givenArray.Length; i++)
        {
            if(!first) Console.Write(" | ");
            Console.Write(givenArray[i]);
            first = false;
        }

        Console.WriteLine();
    }
</code>```

And see this output:

```<code>2257 | 2866 | 8796 | 4497 | 4697 | 2393 | 1004 | 4799 | 483 | 8500
483 | 2866 | 8500 | 4497 | 4697 | 2393 | 2257 | 4799 | 1004 | 8796
483 | 2257 | 1004 | 4497 | 4697 | 2866 | 2393 | 4799 | 8500 | 8796
483 | 2257 | 1004 | 4497 | 4697 | 2866 | 2393 | 4799 | 8500 | 8796
483 | 2257 | 1004 | 2866 | 2393 | 4497 | 4697 | 4799 | 8500 | 8796
483 | 2257 | 1004 | 2866 | 2393 | 4497 | 4697 | 4799 | 8500 | 8796
</code>```

We can see after the first iteration that the second lowest value has moved into the last-but-one position in the array.

During the next iteration, we're trying to place the items in position 1 and position 8 (0-based indexing). But the items in those two positions are never directly compared with each other.

One fix would be to compare givenArray[border] to givenArray[maxindex - border] before your inner loop and swap those two items if necessary.

```<code>    public static void selectionsort(int[] givenArray)
    {
        int maxindex = givenArray.Length - 1;
        for (int border = 0; border < givenArray.Length / 2; border++)
        {
            if(givenArray[border] > givenArray[maxindex - border])
                 swap(givenArray, border, maxindex - border);
            for (int i = 1; i < givenArray.Length - (border * 2); i++)
            {
                    if (givenArray[border + i] < givenArray[border])
                        swap(givenArray, border + i, border);
                    if (givenArray[border + i] > givenArray[maxindex - border])
                        swap(givenArray, border + i, maxindex - border);
            }
        }
    }
</code>```

Body:
I just wrote a simple algorithm to sort integer-values in an array. When I try to debug it, it sometimes works and sometimes it does not. I really don't know why. Can anyone help me?

This is my code:

void swap(int[] array, int left, int right)
{
    int tmp = array[left];
    array[left] = array[right];
    array[right] = tmp;
}

void selectionsort(int[] givenArray)
{
    int maxindex = givenArray.Length - 1;
    for (int border = 0; border < givenArray.Length / 2; border++)
    {
        for (int i = 0; i < givenArray.Length - (border * 2); i++)
        {
            if (i != 0)
            {
                if (givenArray[border + i] < givenArray[border])
                    swap(givenArray, border + i, border);
                if (givenArray[border + i] > givenArray[maxindex - border])
                    swap(givenArray, border + i, maxindex - border);
            }
        }
    }
}

Edit: I usually generate 10 random numbers between 1 and 9999 and print them out. Then I start the sorting and then I print them out again. Here is the output:

[Random] >> 2257 | 2866 | 8796 | 4497 | 4697 | 2393 | 1004 | 4799 | 483  | 8500 |
[Sorted] >> 483  | 2257 | 1004 | 2866 | 2393 | 4497 | 4697 | 4799 | 8500 | 8796 |

Sorting failed at 2/3
sorting failed at 4/5

Array has been sorted in less than 1 ms

Body:
I updated your example to print the array before every iteration (I also adjusted the inner loop to not pointlessly start at 0):

    public static void selectionsort(int[] givenArray)
    {
        int maxindex = givenArray.Length - 1;
        for (int border = 0; border < givenArray.Length / 2; border++)
        {
            PrintArray(givenArray);
            for (int i = 1; i < givenArray.Length - (border * 2); i++)
            {
                    if (givenArray[border + i] < givenArray[border])
                        swap(givenArray, border + i, border);
                    if (givenArray[border + i] > givenArray[maxindex - border])
                        swap(givenArray, border + i, maxindex - border);
            }
        }
    }

    public static void PrintArray(int[] givenArray)
    {
        var first = true;
        for (int i = 0; i < givenArray.Length; i++)
        {
            if(!first) Console.Write(" | ");
            Console.Write(givenArray[i]);
            first = false;
        }

        Console.WriteLine();
    }

And see this output:

2257 | 2866 | 8796 | 4497 | 4697 | 2393 | 1004 | 4799 | 483 | 8500
483 | 2866 | 8500 | 4497 | 4697 | 2393 | 2257 | 4799 | 1004 | 8796
483 | 2257 | 1004 | 4497 | 4697 | 2866 | 2393 | 4799 | 8500 | 8796
483 | 2257 | 1004 | 4497 | 4697 | 2866 | 2393 | 4799 | 8500 | 8796
483 | 2257 | 1004 | 2866 | 2393 | 4497 | 4697 | 4799 | 8500 | 8796
483 | 2257 | 1004 | 2866 | 2393 | 4497 | 4697 | 4799 | 8500 | 8796

We can see after the first iteration that the second lowest value has moved into the last-but-one position in the array.

During the next iteration, we're trying to place the items in position 1 and position 8 (0-based indexing). But the items in those two positions are never directly compared with each other.

One fix would be to compare givenArray[border] to givenArray[maxindex - border] before your inner loop and swap those two items if necessary.

    public static void selectionsort(int[] givenArray)
    {
        int maxindex = givenArray.Length - 1;
        for (int border = 0; border < givenArray.Length / 2; border++)
        {
            if(givenArray[border] > givenArray[maxindex - border])
                 swap(givenArray, border, maxindex - border);
            for (int i = 1; i < givenArray.Length - (border * 2); i++)
            {
                    if (givenArray[border + i] < givenArray[border])
                        swap(givenArray, border + i, border);
                    if (givenArray[border + i] > givenArray[maxindex - border])
                        swap(givenArray, border + i, maxindex - border);
            }
        }
    }


问:
How to add parameters to ServeHTTP?
I would like to add a middleware to Gorilla that "enriches" the call with extra parameters:

```<code>// a middleware that adds a parameter "message"
func authCheck(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        message := "hello"
        log.Info().Msgf("adding message %v", message)
        // the core of my question is here: how to pass "message" further
        next.ServeHTTP(w, r)
    })
}
</code>```

I would like to add message as a parameter that could be ultimately used in a route:

```<code>main() {
    // (...)
    r.HandleFunc("/check", check).Methods(http.MethodGet)
    // (...)
    r.Use(authCheck)
    // (...)
}

func check(w http.ResponseWriter, r *http.Request) {
    // I would like to use "message" here, having it passed somehow to the function
    w.Write([]byte(message))
}
</code>```

Is such an approach possible in Go?

答:
Thanks to the comments and pointers, I managed to pass the variable. For reference:</p>
```<code>type httpContextStruct struct {
    user  string
    wazaa string
}

var httpContext httpContextStruct

func authCheck(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        httpContext = httpContextStruct{}
        r = r.WithContext(context.WithValue(
            r.Context(),
            httpContext,
            httpContextStruct{
                user:  "thisisme",
                wazaa: "aaa",
            },
        ))
        next.ServeHTTP(w, r)
    })
}

func check(w http.ResponseWriter, r *http.Request) {
    myc := r.Context().Value(httpContext).(httpContextStruct)
    w.Write([]byte(fmt.Sprintf("user: %v", myc.user)))
}

// output
// user: thisisme
</code>```

Title: How to add parameters to ServeHTTP?

Body:
I would like to add a middleware to Gorilla that "enriches" the call with extra parameters:

// a middleware that adds a parameter "message"
func authCheck(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        message := "hello"
        log.Info().Msgf("adding message %v", message)
        // the core of my question is here: how to pass "message" further
        next.ServeHTTP(w, r)
    })
}

I would like to add message as a parameter that could be ultimately used in a route:

main() {
    // (...)
    r.HandleFunc("/check", check).Methods(http.MethodGet)
    // (...)
    r.Use(authCheck)
    // (...)
}

func check(w http.ResponseWriter, r *http.Request) {
    // I would like to use "message" here, having it passed somehow to the function
    w.Write([]byte(message))
}

Is such an approach possible in Go?

Body:
Thanks to the comments and pointers, I managed to pass the variable. For reference:

type httpContextStruct struct {
    user  string
    wazaa string
}

var httpContext httpContextStruct

func authCheck(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        httpContext = httpContextStruct{}
        r = r.WithContext(context.WithValue(
            r.Context(),
            httpContext,
            httpContextStruct{
                user:  "thisisme",
                wazaa: "aaa",
            },
        ))
        next.ServeHTTP(w, r)
    })
}

func check(w http.ResponseWriter, r *http.Request) {
    myc := r.Context().Value(httpContext).(httpContextStruct)
    w.Write([]byte(fmt.Sprintf("user: %v", myc.user)))
}

// output
// user: thisisme


问:
Create sql query - MSSQL with distinct
I have a table with columns Id,DoucmentId,Name,Created,MinorVersion,MajorVersion

with example data  :

```<code>GUID,1,'document1',GETDATE(),1,0)
GUID,1,'document1',GETDATE(),2,0)
GUID,1,'document1',GETDATE(),1,1)
GUID,2,'document2',GETDATE(),1,0)
</code>```

In query i need get all unique with higest major and minor version :

```<code>GUID,1,'document1',GETDATE(),1,1)
GUID,2,'document2',GETDATE(),1,0)
</code>```

I have this query, but i need return all column in table...

```<code>SELECT DISTINCT
          DocumentId,
          MAX(MajorVersion),
          MAX(MinorVersion)
FROM ComDoc_Document
GROUP BY(DocumentId)
</code>```

Is here some trick to get this?

Thanks for help

EDIT : My configuration is MSSQL 2008R2 standart

答: you should not be able to do this. however mysql has bug, which allow you to take other column names as well. you can simple do ComDoc_Document.* (or just *) (you will not need documentid anymore). however as I said, it should not be able to work like this - what if you had in second column values "A", "B", "C" for the same documentid? which value should be returned? in principle you should be able to take only those values, for which you make group by or agregate function (like you do with MAX, MIN etc)</p>

ContentLicense: CC BY-SA 3.0

Title: Create sql query - MSSQL with distinct

Body:
I have a table with columns Id,DoucmentId,Name,Created,MinorVersion,MajorVersion

with example data  :

GUID,1,'document1',GETDATE(),1,0)
GUID,1,'document1',GETDATE(),2,0)
GUID,1,'document1',GETDATE(),1,1)
GUID,2,'document2',GETDATE(),1,0)

In query i need get all unique with higest major and minor version :

GUID,1,'document1',GETDATE(),1,1)
GUID,2,'document2',GETDATE(),1,0)

I have this query, but i need return all column in table...

SELECT DISTINCT
          DocumentId,
          MAX(MajorVersion),
          MAX(MinorVersion)
FROM ComDoc_Document
GROUP BY(DocumentId)

Is here some trick to get this?

Thanks for help

EDIT : My configuration is MSSQL 2008R2 standart


问:
navigator.push in flutter, no errors but it can not move to another page
<pre class="lang-dart prettyprint-override"><code> class _MyHomePageState extends State<MyHomePage>
    @override
     Widget build(BuildContext context) {
     return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        appBar: AppBar(
          title: Text("Main page"),
          backgroundColor: Colors.black,
        ),
        body: Center(
          child: Column(
            children: [
              Text(
                'this is main page',
                textAlign: TextAlign.center,
                style: TextStyle(
                  fontSize: 50,
                ),
              ),
              RaisedButton(
                onPressed: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(builder: (context) {
                      return TestPage();
                    }),
                  );
                },
                child: Text('go to test page'),
              ),

            ],
          ),
        ),
       ),
     );
    }
   }

</code>```
<p>Navigator does not give error, but it does not go to another page, just giving a lot in console</p>
```<code>======== Exception caught by gesture
The following assertion was thrown while handling a gesture:
Navigator operation requested with a context that does not include a Navigator.

The context used to push or pop routes from the Navigator must be that of a widget that is a descendant of a Navigator widget.
When the exception was thrown, this was the stack:
#0      Navigator.of.<anonymous closure> (package:flutter/src/widgets/navigator.dart:2741:9)
#1      Navigator.of (package:flutter/src/widgets/navigator.dart:2748:6)
#2      Navigator.push (package:flutter/src/widgets/navigator.dart:2137:22)
#3      _MyHomePageState.build.<anonymous closure> (package:navigator_push_route/main.dart:43:29)
#4      _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:989:21)
#5      GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:193:24)
#6      TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:608:11)
#7      BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:296:5)
#8      BaseTapGestureRecognizer.handlePrimaryPointer (package:flutter/src/gestures/tap.dart:230:7)
#9      PrimaryPointerGestureRecognizer.handleEvent (package:flutter/src/gestures/recognizer.dart:558:9)
#10     PointerRouter._dispatch (package:flutter/src/gestures/pointer_router.dart:94:12)
#11     PointerRouter._dispatchEventToRoutes.<anonymous closure> (package:flutter/src/gestures/pointer_router.dart:139:9)
#12     _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:400:8)
#13     PointerRouter._dispatchEventToRoutes (package:flutter/src/gestures/pointer_router.dart:137:18)
#14     PointerRouter.route (package:flutter/src/gestures/pointer_router.dart:123:7)
#15     GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:440:19)
#16     GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:420:22)
#17     RendererBinding.dispatchEvent (package:flutter/src/rendering/binding.dart:278:11)
#18     GestureBinding._handlePointerEventImmediately (package:flutter/src/gestures/binding.dart:374:7)
#19     GestureBinding.handlePointerEvent (package:flutter/src/gestures/binding.dart:338:5)
#20     GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:296:7)
#21     GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:279:7)
#25     _invoke1 (dart:ui/hooks.dart:185:10)
#26     PlatformDispatcher._dispatchPointerDataPacket (dart:ui/platform_dispatcher.dart:293:7)
#27     _dispatchPointerDataPacket (dart:ui/hooks.dart:98:31)
(elided 3 frames from dart:async)
Handler: "onTap"
Recognizer: TapGestureRecognizer#b9e3b
  debugOwner: GestureDetector
  state: possible
  won arena
  finalPosition: Offset(194.0, 253.0)
  finalLocalPosition: Offset(66.0, 24.0)
  button: 1
  sent tap down
</code>```

答:
Separate MaterialApp on parent widget.

void main() {
  runApp(
    const MaterialApp(
      home: MyHomePage(),
    ),
  );
}
```
<p>Or for context create a widget,</p>
<pre class="lang-dart prettyprint-override"><code>void main() {
  runApp(
    const MyApp(),
  );
}

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

  @override
  Widget build(BuildContext context) {
    return  MaterialApp(
      home: MyHomePage(),
    );
  }
}
</code>```

Body:
 class _MyHomePageState extends State<MyHomePage>
    @override
     Widget build(BuildContext context) {
     return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        appBar: AppBar(
          title: Text("Main page"),
          backgroundColor: Colors.black,
        ),
        body: Center(
          child: Column(
            children: [
              Text(
                'this is main page',
                textAlign: TextAlign.center,
                style: TextStyle(
                  fontSize: 50,
                ),
              ),
              RaisedButton(
                onPressed: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(builder: (context) {
                      return TestPage();
                    }),
                  );
                },
                child: Text('go to test page'),
              ),

            ],
          ),
        ),
       ),
     );
    }
   }

Navigator does not give error, but it does not go to another page, just giving a lot in console

======== Exception caught by gesture
The following assertion was thrown while handling a gesture:
Navigator operation requested with a context that does not include a Navigator.

The context used to push or pop routes from the Navigator must be that of a widget that is a descendant of a Navigator widget.
When the exception was thrown, this was the stack:
#0      Navigator.of.<anonymous closure> (package:flutter/src/widgets/navigator.dart:2741:9)
#1      Navigator.of (package:flutter/src/widgets/navigator.dart:2748:6)
#2      Navigator.push (package:flutter/src/widgets/navigator.dart:2137:22)
#3      _MyHomePageState.build.<anonymous closure> (package:navigator_push_route/main.dart:43:29)
#4      _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:989:21)
#5      GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:193:24)
#6      TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:608:11)
#7      BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:296:5)
#8      BaseTapGestureRecognizer.handlePrimaryPointer (package:flutter/src/gestures/tap.dart:230:7)
#9      PrimaryPointerGestureRecognizer.handleEvent (package:flutter/src/gestures/recognizer.dart:558:9)
#10     PointerRouter._dispatch (package:flutter/src/gestures/pointer_router.dart:94:12)
#11     PointerRouter._dispatchEventToRoutes.<anonymous closure> (package:flutter/src/gestures/pointer_router.dart:139:9)
#12     _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:400:8)
#13     PointerRouter._dispatchEventToRoutes (package:flutter/src/gestures/pointer_router.dart:137:18)
#14     PointerRouter.route (package:flutter/src/gestures/pointer_router.dart:123:7)
#15     GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:440:19)
#16     GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:420:22)
#17     RendererBinding.dispatchEvent (package:flutter/src/rendering/binding.dart:278:11)
#18     GestureBinding._handlePointerEventImmediately (package:flutter/src/gestures/binding.dart:374:7)
#19     GestureBinding.handlePointerEvent (package:flutter/src/gestures/binding.dart:338:5)
#20     GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:296:7)
#21     GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:279:7)
#25     _invoke1 (dart:ui/hooks.dart:185:10)
#26     PlatformDispatcher._dispatchPointerDataPacket (dart:ui/platform_dispatcher.dart:293:7)
#27     _dispatchPointerDataPacket (dart:ui/hooks.dart:98:31)
(elided 3 frames from dart:async)
Handler: "onTap"
Recognizer: TapGestureRecognizer#b9e3b
  debugOwner: GestureDetector
  state: possible
  won arena
  finalPosition: Offset(194.0, 253.0)
  finalLocalPosition: Offset(66.0, 24.0)
  button: 1
  sent tap down

Body:
Separate MaterialApp on parent widget.

void main() {
  runApp(
    const MaterialApp(
      home: MyHomePage(),
    ),
  );
}

Or for context create a widget,

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

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

  @override
  Widget build(BuildContext context) {
    return  MaterialApp(
      home: MyHomePage(),
    );
  }
}


问:
Can't render component diagram with PlantUML in IntelliJ
I am trying to create a component diagram using the PlantUML plugin for IntelliJ.
I have installed the plugin and worked with it before. However, when I try to render a component diagram, I get an error:

Cannot find Graphviz

I've also checked with other diagrams and a sequence diagram is still working just fine.

What is the problem here?

答:
On a mac using Intellij, if Intellij cannot find graphviz, testdot doesn't work and graphviz was installed with brew install graphviz:

In Intellij, click the wrench icon on the far right of the menu panel that contains the plantuml view and editor arrangement.

Click 'Open settings'

For 'Graphviz dot executable' add /opt/homebrew/bin/dot.

Click OK and restart Intellij.

This fixes the issue for me.

You can check first that you really are missing the /opt/local/bin/dot (or whatever path you're shown is broken) and the /opt/homebrew/bin/dot exists, but likely the reason is that brew put dot under its own path.


问:
Backend Error with Google Admin SDK Group Settings having "/" in Group Email Id/Address
i m having issues with GWS API Group Settings when group email (when use as groupUniqueId) having a "/" character as part of the email id. Python code below:

```<code>service = gws_service('groupsettings') # internal func that initiate the service
results = service.groups().get(groupUniqueId = "xxxxxx/xx@xxxx.com").execute()
</code>```

above code will return "Not Found" error.

I tried using the online API try page (from the Group Settings API documentation page) will produce http 500 with "Backend Error" xml as attached below:

Google Online API Test

I think there is bugs/issues related to Groups email having a "/" character as part of the group email id, for Group Settings API either via online or using the Python client lib package.

答: I found the solution, i need to replace "/" character with "%2F" when making queries using group settings API</p>

Body:
i m having issues with GWS API Group Settings when group email (when use as groupUniqueId) having a "/" character as part of the email id. Python code below:

service = gws_service('groupsettings') # internal func that initiate the service
results = service.groups().get(groupUniqueId = "xxxxxx/xx@xxxx.com").execute()

above code will return "Not Found" error.

I tried using the online API try page (from the Group Settings API documentation page) will produce http 500 with "Backend Error" xml as attached below:

Google Online API Test

I think there is bugs/issues related to Groups email having a "/" character as part of the group email id, for Group Settings API either via online or using the Python client lib package.


问:
HTML to PDF with cyrillic characters
I'm making a Spring Boot application. I want to generate PDF from HTML code:

```<code>        String htmlString = "<!DOCTYPE html>\n" +
                "<html lang=\"ru\">\n" +
                "<head>\n" +
                "    <meta charset=\"UTF-8\"/>\n" +
                "    <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"/>\n" +
                "    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"/>\n" +
                "</head>\n" +
                "<body>\n" +
                "    <h3>ПРЕДСТАВЛЕНИЕ</h3>\n" +
                "</body>\n" +
                "</html>";

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        String path = FileSystemView.getFileSystemView().getDefaultDirectory().getPath() + "/A.pdf";
        OutputStream outputStream = new FileOutputStream(path);

        ITextRenderer renderer = new ITextRenderer();
        renderer.setDocumentFromString(htmlString);
        renderer.layout();
        renderer.createPDF(outputStream);

        byteArrayOutputStream.writeTo(outputStream);
</code>```

As you can see there is a h3 tag with cyrillic symbols. The problem is that after conversion and  saving the symbols are not presented in PDF (it's simply empty, because there is nothing more in html code to be visible). Other symbols are being displayed properly btw.

For html-to-pdf conversion i use:

```<code><dependency>
    <groupId>org.xhtmlrenderer</groupId>
    <artifactId>flying-saucer-pdf-itext5</artifactId>
    <version>9.0.1</version>
</dependency>
</code>```

I suppose there is a problem with charset, fonts etc. How can I fix it?

答:
You must add a font that support Cyrillic to the renderer. (For example Deja Vu.)

String htmlString = getHtml();
ITextRenderer renderer = new ITextRenderer();
renderer.getFontResolver().addFont("font/dejavu-sans/DejaVuSans.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
OutputStream out = new FileOutputStream(new File("so.pdf"));
renderer.setDocumentFromString(html);
renderer.layout();
renderer.createPDF(out);
out.close();
```
<p>And in your HTML, you should set the font-family to use:</p>
<pre class="lang-html prettyprint-override"><code><html>
<head>
    <style>
        body{font-family: "DejaVu Sans", Arial, sans-serif }
    </style>
</head>
<body>
Лорем ипсум долор сит амет, цу вел оратио постеа импедит
</body>
</html>
</code>```

Title: HTML to PDF with cyrillic characters

Body:
I'm making a Spring Boot application. I want to generate PDF from HTML code:

        String htmlString = "<!DOCTYPE html>\n" +
                "\n" +
                "\n" +
                "    <meta charset=\"UTF-8\"/>\n" +
                "    <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"/>\n" +
                "    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"/>\n" +
                "\n" +
                "\n" +
                "
ПРЕДСТАВЛЕНИЕ
\n" +
                "\n" +
                "";

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        String path = FileSystemView.getFileSystemView().getDefaultDirectory().getPath() + "/A.pdf";
        OutputStream outputStream = new FileOutputStream(path);

        ITextRenderer renderer = new ITextRenderer();
        renderer.setDocumentFromString(htmlString);
        renderer.layout();
        renderer.createPDF(outputStream);

        byteArrayOutputStream.writeTo(outputStream);

As you can see there is a h3 tag with cyrillic symbols. The problem is that after conversion and  saving the symbols are not presented in PDF (it's simply empty, because there is nothing more in html code to be visible). Other symbols are being displayed properly btw.

For html-to-pdf conversion i use:

<dependency>
    <groupId>org.xhtmlrenderer</groupId>
    <artifactId>flying-saucer-pdf-itext5</artifactId>
    <version>9.0.1</version>
</dependency>

I suppose there is a problem with charset, fonts etc. How can I fix it?

Body:
You must add a font that support Cyrillic to the renderer. (For example Deja Vu.)

String htmlString = getHtml();
ITextRenderer renderer = new ITextRenderer();
renderer.getFontResolver().addFont("font/dejavu-sans/DejaVuSans.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
OutputStream out = new FileOutputStream(new File("so.pdf"));
renderer.setDocumentFromString(html);
renderer.layout();
renderer.createPDF(out);
out.close();

And in your HTML, you should set the font-family to use:

<html>
<head>
    <style>
        body{font-family: "DejaVu Sans", Arial, sans-serif }
    </style>
</head>
<body>
Лорем ипсум долор сит амет, цу вел оратио постеа импедит
</body>
</html>


问:
Displaying number of messages sent by each category of users
This is what message_user_id contains:

```<code>message_user_id = Message.objects.all()
</code>```

This is my context dictionary in admin.py:

```<code>'msg' : message_user_id,
</code>```

This is my Message class in models.py:

```<code>class Message(models.Model):
  message_text = fields.EncryptedTextField(blank=True, null=True)
  conversation_id = models.ForeignKey(Conversation, on_delete=models.CASCADE)
  origin_user = models.ForeignKey(UserInfo, on_delete=models.CASCADE, blank=False, default=None)
  timestamp = models.DateTimeField(default=datetime.now, blank=True)

</code>```

This is UserInfo class:

```<code>class UserInfo(models.Model):
  id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
  is_buyer = models.BooleanField(default=False)
  is_seller = models.BooleanField(default=False)
  is_professional = models.BooleanField(default=False)
</code>```

There are different roles for users that they can choose from while sign up. That information stays in UserInfo table which I'm referencing to as a foreign key in origin_user field in Message class. origin_user in Message contains the same information as id in UserInfo.

I want to display the number of messages sent by each category of users. How do I achieve this?.

答:
As there are not many types you can do a search for each type and count how many messages there are, e.g. for Buyer:</p>
```<code>messages_of_buyers = Message.objects.select_related(
        'user_info'
    ).filter(
       user_info__is_buyer=True
    ).count()
</code>```

Body:
This is what message_user_id contains:

message_user_id = Message.objects.all()

This is my context dictionary in admin.py:

'msg' : message_user_id,

This is my Message class in models.py:

class Message(models.Model):
  message_text = fields.EncryptedTextField(blank=True, null=True)
  conversation_id = models.ForeignKey(Conversation, on_delete=models.CASCADE)
  origin_user = models.ForeignKey(UserInfo, on_delete=models.CASCADE, blank=False, default=None)
  timestamp = models.DateTimeField(default=datetime.now, blank=True)

This is UserInfo class:

class UserInfo(models.Model):
  id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
  is_buyer = models.BooleanField(default=False)
  is_seller = models.BooleanField(default=False)
  is_professional = models.BooleanField(default=False)

There are different roles for users that they can choose from while sign up. That information stays in UserInfo table which I'm referencing to as a foreign key in origin_user field in Message class. origin_user in Message contains the same information as id in UserInfo.

I want to display the number of messages sent by each category of users. How do I achieve this?.

Body:
As there are not many types you can do a search for each type and count how many messages there are, e.g. for Buyer:

messages_of_buyers = Message.objects.select_related(
        'user_info'
    ).filter(
       user_info__is_buyer=True
    ).count()


问:
asp.net mvc3 and multi-level navigation
i am writing new asp.net mvc application and i have question about creating multi-level navigation system.

For example i have web with main navigation (Cpu --- Gpu ---- Ram)

and sub-navigation with (intel,amd --- ati,nvidia --- DDR2,DD3)

Well, my first implementation is here :

```<code>public class NavigationItem
{
    public virtual int Id { get; set; }
    public virtual string Title { get; set; }
    public virtual string Controller { get; set; }
    public virtual string Action { get; set; }
    public virtual string Url { get; set; }
    public virtual string Section { get; set; }
}

public class NavigationController : Controller
{
    private readonly IUnitOfWork _unitOfWork;

    public NavigationController(IUnitOfWork unitOfWork)
    {
        _unitOfWork = unitOfWork;
    }

    public ActionResult MainMenu()
    {
        return View(_unitOfWork.NavigationItems.Where(x => x.Section == null).ToList());
    }

    public ActionResult SectionMenu()
    {

        return View(_unitOfWork.NavigationItems.Where(x => x.Section == "// name of section").ToLis());
    }
}
</code>```

And finally my layout page is :

```<code><!DOCTYPE html>
<html>
<head>
    <title>@ViewBag.Title</title>
</head>
<body>
 <div class="main-menu">
  @{Html.RenderAction("MainMenu", "Navigation");}
 </div>

 <div class="section-menu">
  @{Html.RenderAction("SectionMenu", "Navigation");}
 </div>

    @RenderBody()
</body>
</html>
</code>```

With this implementation i have problem how i handle in SectionMenu with MainMenu is active, because i want generate SectionMenu depends on MainMenu and highlight them.

One workaround of witch i think is handle url(controller) in SectionMenu.
For example :

```<code>    if (RouteData.Values["controller"].ToString() == "Administration")
    {
        // Generate section menu for Administration main menu
    }
</code>```

I dont like this solution because i work with "magic string" values and i havent only one controller per one MainMenu.

How implement this solution?

Thanks for advice

答: Ok, I use  ViewBag feature. Not clean, but works</p>

ContentLicense: CC BY-SA 2.5

Title: asp.net mvc3 and multi-level navigation

Body:
i am writing new asp.net mvc application and i have question about creating multi-level navigation system.

For example i have web with main navigation (Cpu --- Gpu ---- Ram)

and sub-navigation with (intel,amd --- ati,nvidia --- DDR2,DD3)

Well, my first implementation is here :

public class NavigationItem
{
    public virtual int Id { get; set; }
    public virtual string Title { get; set; }
    public virtual string Controller { get; set; }
    public virtual string Action { get; set; }
    public virtual string Url { get; set; }
    public virtual string Section { get; set; }
}

public class NavigationController : Controller
{
    private readonly IUnitOfWork _unitOfWork;

    public NavigationController(IUnitOfWork unitOfWork)
    {
        _unitOfWork = unitOfWork;
    }

    public ActionResult MainMenu()
    {
        return View(_unitOfWork.NavigationItems.Where(x => x.Section == null).ToList());
    }

    public ActionResult SectionMenu()
    {

        return View(_unitOfWork.NavigationItems.Where(x => x.Section == "// name of section").ToLis());
    }
}

And finally my layout page is :

<!DOCTYPE html>

    <title>@ViewBag.Title</title>

  @{Html.RenderAction("MainMenu", "Navigation");}

  @{Html.RenderAction("SectionMenu", "Navigation");}

    @RenderBody()

With this implementation i have problem how i handle in SectionMenu with MainMenu is active, because i want generate SectionMenu depends on MainMenu and highlight them.

One workaround of witch i think is handle url(controller) in SectionMenu.
For example :

    if (RouteData.Values["controller"].ToString() == "Administration")
    {
        // Generate section menu for Administration main menu
    }

I dont like this solution because i work with "magic string" values and i havent only one controller per one MainMenu.

How implement this solution?

Thanks for advice


问:
http request not executed when run in isolate
Why is the request not executed?

```<code>import 'package:http/http.dart' as http;

String req(String x) {
  print("$x req");
  doReq() async {
    final url = Uri.parse("http://google.com");
    print("$x $url");
    final re = await http.get(url);
    print("$x re:");
    print(re.body);
  }
  doReq();
  print("$x done");
  return "ok";
}

// somewhere in the UI
ElevatedButton(
  child: const Text("run"),
  onPressed: () {
    print("in main isolate");
    req("1");
    print("in separate isolate");
    compute(req, "2");
  },
);
</code>```

Output:

```<code>I/flutter (20379): in main isolate
I/flutter (20379): 1 req
I/flutter (20379): 1 http://google.com
I/flutter (20379): 1 done
I/flutter (20379): in separate isolate
I/flutter (20379): 1 re:
I/flutter (20379): <!doctype html>...
I/flutter (20379): 2 req
I/flutter (20379): 2 http://google.com
I/flutter (20379): 2 done
</code>```

The request is not executed when req runs in an isolate - why and how can I fix this?

答:
Flutter's compute immediately closes the spawned isolate after the method returns and any returned Future is completed.  Since your req function synchronously returns a string, the HTTP request will not have completed by the time the isolate is destroyed.

If you await the doReq() call (and return a Future<String> from req), you will probably see the response body both times.

Body:
Why is the request not executed?

import 'package:http/http.dart' as http;

String req(String x) {
  print("$x req");
  doReq() async {
    final url = Uri.parse("http://google.com");
    print("$x $url");
    final re = await http.get(url);
    print("$x re:");
    print(re.body);
  }
  doReq();
  print("$x done");
  return "ok";
}

// somewhere in the UI
ElevatedButton(
  child: const Text("run"),
  onPressed: () {
    print("in main isolate");
    req("1");
    print("in separate isolate");
    compute(req, "2");
  },
);

Output:

I/flutter (20379): in main isolate
I/flutter (20379): 1 req
I/flutter (20379): 1 http://google.com
I/flutter (20379): 1 done
I/flutter (20379): in separate isolate
I/flutter (20379): 1 re:
I/flutter (20379): <!doctype html>...
I/flutter (20379): 2 req
I/flutter (20379): 2 http://google.com
I/flutter (20379): 2 done

The request is not executed when req runs in an isolate - why and how can I fix this?


问:
binding form using formGroup in angular component
I'm facing below error while binding the form

```<code>cart.component.html
<h3>Cart</h3>

<p>
  <a routerLink="/shipping">Shipping Prices</a>
</p>

<div class="cart-item" *ngFor="let item of items">
  <span>{{ item.name }} </span>
  <span>{{ item.price | currency }}</span>
</div>

<form [formGroup]="checkoutForm" (ngSubmit)="onSubmit()">

    <div>
      <label for="name">
        Name
      </label>
      <input id="name" type="text" formControlName="name">
    </div>

    <div>
      <label for="address">
        Address
      </label>
      <input id="address" type="text" formControlName="address">
    </div>

    <button class="button" type="submit">Purchase</button>

  </form>

cart.component.ts

import { Component } from '@angular/core';
import { FormBuilder } from '@angular/forms';

import { CartService } from '../cart.service';

@Component({
  selector: 'app-cart',
  templateUrl: './cart.component.html',
  styleUrls: ['./cart.component.css']
})
export class CartComponent {
  items = this.cartService.getItems();
  checkoutForm = this.formBuilder.group({
    name: '',
    address: ''
  });
  constructor(
    private cartService: CartService,
    private formBuilder: FormBuilder,
    ) {}

  onSubmit(): void {
    // Process checkout data here
    this.items = this.cartService.clearCart();
    console.warn('Your order has been submitted', this.checkoutForm.value);
    this.checkoutForm.reset();
  }
}
</code>```

error :
Failed to compile.

src/app/cart/cart.component.html:12:7 - error NG8002: Can't bind to 'formGroup' since it isn't a known property of 'form'.

12 <form [formGroup]="checkoutForm" (ngSubmit)="onSubmit()">
~~~~~~~~~~~~~~~~~~~~~~~~~~

src/app/cart/cart.component.ts:8:16
8   templateUrl: './cart.component.html',
~~~~~~~~~~~~~~~~~~~~~~~
Error occurs in the template of component CartComponent.

答:
just add into your app.module.ts

```<code>import { FormsModule, ReactiveFormsModule } from '@angular/forms';
</code>```

and under @NgModule

```<code> @NgModule({
   imports: [
     FormsModule,
     ReactiveFormsModule,
</code>```

Body:
I'm facing below error while binding the form

cart.component.html

Cart

  Shipping Prices

  {{ item.name }}
  {{ item.price | currency }}

<form [formGroup]="checkoutForm" (ngSubmit)="onSubmit()">

        Name

      <input id="name" type="text" formControlName="name">

        Address

      <input id="address" type="text" formControlName="address">

    <button class="button" type="submit">Purchase</button>

  </form>

cart.component.ts

import { Component } from '@angular/core';
import { FormBuilder } from '@angular/forms';

import { CartService } from '../cart.service';

@Component({
  selector: 'app-cart',
  templateUrl: './cart.component.html',
  styleUrls: ['./cart.component.css']
})
export class CartComponent {
  items = this.cartService.getItems();
  checkoutForm = this.formBuilder.group({
    name: '',
    address: ''
  });
  constructor(
    private cartService: CartService,
    private formBuilder: FormBuilder,
    ) {}

  onSubmit(): void {
    // Process checkout data here
    this.items = this.cartService.clearCart();
    console.warn('Your order has been submitted', this.checkoutForm.value);
    this.checkoutForm.reset();
  }
}

error :
Failed to compile.

src/app/cart/cart.component.html:12:7 - error NG8002: Can't bind to 'formGroup' since it isn't a known property of 'form'.

12 <form [formGroup]="checkoutForm" (ngSubmit)="onSubmit()">
~~~~~~~~~~~~~~~~~~~~~~~~~~

src/app/cart/cart.component.ts:8:16
8   templateUrl: './cart.component.html',
~~~~~~~~~~~~~~~~~~~~~~~
Error occurs in the template of component CartComponent.

Body:
just add into your app.module.ts

import { FormsModule, ReactiveFormsModule } from '@angular/forms';

and under @NgModule

 @NgModule({
   imports: [
     FormsModule,
     ReactiveFormsModule,


答:
You are using the wrong context.

move your RaisedButton to another page with new context or wrap it with builder like this :

```<code> Builder(
             builder: (context) {
               return RaisedButton(
                 onPressed: () {
                   Navigator.push(
                     context,
                     MaterialPageRoute(builder: (context) {
                       return TestPage();
                     }),
                   );
                 },
                 child: Text('go to test page'),
               );
             }
           ),
</code>```

this should work

Title: navigator.push in flutter, no errors but it can not move to another page

Body:
You are using the wrong context.

move your RaisedButton to another page with new context or wrap it with builder like this :

 Builder(
             builder: (context) {
               return RaisedButton(
                 onPressed: () {
                   Navigator.push(
                     context,
                     MaterialPageRoute(builder: (context) {
                       return TestPage();
                     }),
                   );
                 },
                 child: Text('go to test page'),
               );
             }
           ),

this should work


问:
Can I use the output of a function in another R file?
I built a function that retrieves data from an Azure table via a REST API. I sourced the function, so I can reuse it in other R scripts.

The function is as below:

```<code>Connect_To_Azure_Table(Account, Container, Key)
</code>```

and it returns as an output a table called Azure-table. The very last line of the code in the function is

```<code>head(Azure_table)
</code>```

In my next script, I'm going to call that function and execute some data transformation.

However, while the function executes (and my Azure_table is previewed), I don't seem to be able to use it in the code to start performing my data transformation. For example, this is the beginning of my ETL function:

```<code>library(dplyr)
library(vroom)
library(tidyverse)
library(stringr)

#Connects to datasource

if(exists("Connect_To_Azure_Table", mode = "function")) {
source("ConnectToAzureTable.R")
}

Account <- "storageaccount"
Container <- "Usage"
Key <- "key"

Connect_To_Azure_Table(Account, Container, Key)

# Performs ETL process

colnames(Azure_table) <- gsub("value.", "", colnames(Azure_table))                # Removes prefix from column headers
</code>```

Both the function and the table get warning. But while the function executes anyway, the Azure_table throws an error:

```<code>> # Performs ETL process
>
> colnames(Azure_table) <- gsub("value.", "", colnames(Azure_table))                # Removes prefix from column headers
Error in is.data.frame(x) : object 'Azure_table' not found
</code>```

What should I be doing to use Azure_table in my script?

Thanks in advance!

~Alienvolm

答:
You can ignore the RStudio warnings, they are based on a heuristic, and in this case it’s very imprecise and misleading.

However, there are some errors in your code.

Firstly, you’re only sourceing the code if the function was already defined. Surely you want to do it the other way round: source the code if the function does not yet exist. But furthermore that check is completely redundant: if you haven’t sourced the code which defines the function yet, the function won’t be defined. The existence check is unnecessary and misleading. Remove it:

```<code>source("ConnectToAzureTable.R")
</code>```

Secondly, when you’re calling the function you’re not assigning its return value to any name. You probably meant to write the following:

```<code>Azure_table <- Connect_To_Azure_Table(Account, Container, Key)
</code>```

Body:
I built a function that retrieves data from an Azure table via a REST API. I sourced the function, so I can reuse it in other R scripts.

The function is as below:

Connect_To_Azure_Table(Account, Container, Key)

and it returns as an output a table called Azure-table. The very last line of the code in the function is

head(Azure_table)

In my next script, I'm going to call that function and execute some data transformation.

However, while the function executes (and my Azure_table is previewed), I don't seem to be able to use it in the code to start performing my data transformation. For example, this is the beginning of my ETL function:

library(dplyr)
library(vroom)
library(tidyverse)
library(stringr)

#Connects to datasource

if(exists("Connect_To_Azure_Table", mode = "function")) {
source("ConnectToAzureTable.R")
}

Account <- "storageaccount"
Container <- "Usage"
Key <- "key"

Connect_To_Azure_Table(Account, Container, Key)

# Performs ETL process

colnames(Azure_table) <- gsub("value.", "", colnames(Azure_table))                # Removes prefix from column headers

Both the function and the table get warning. But while the function executes anyway, the Azure_table throws an error:

> # Performs ETL process
>
> colnames(Azure_table) <- gsub("value.", "", colnames(Azure_table))                # Removes prefix from column headers
Error in is.data.frame(x) : object 'Azure_table' not found

What should I be doing to use Azure_table in my script?

Thanks in advance!

~Alienvolm

Body:
You can ignore the RStudio warnings, they are based on a heuristic, and in this case it’s very imprecise and misleading.

However, there are some errors in your code.

Firstly, you’re only sourceing the code if the function was already defined. Surely you want to do it the other way round: source the code if the function does not yet exist. But furthermore that check is completely redundant: if you haven’t sourced the code which defines the function yet, the function won’t be defined. The existence check is unnecessary and misleading. Remove it:

source("ConnectToAzureTable.R")

Secondly, when you’re calling the function you’re not assigning its return value to any name. You probably meant to write the following:

Azure_table <- Connect_To_Azure_Table(Account, Container, Key)


问:
How to return values from C/++ functions correctly?
I have made some app and the method im using is this:

```<code>INT name(char *one,char *two,char buffer[]){
memcpy(buffer,"omg",4);//or using std::string::copy ... that's how I actually return value
...}
</code>```

and I call it like:

```<code>char returned[255];
name(first,second,returned);
printf/cout;
</code>```

Everything is fine. Now my question is, is this method terrible or a disaster? Also, what is going on with allocated memory for 255 chars, I mean is there a way to re-allocate it somehow to save memory a little?

This is so called pass-by-reference, in either case I have to return multiple values (from 2 to 10). If I would need only 1 I would use return buffer with static type I guess.

Thanks. Write your favourite methods please while I read similar questions to this one hehe.

答:
Just use a return value.

```<code>std::string name(const std::string& one, const std::string& two)
{
    return "omg";
}
</code>```

If you need to return a variable number of values, return a vector:

```<code>std::vector<std::string> name(const std::string& one, const std::string& two)
{
    std::vector ret;
    ret.push_back("omg1");
    ret.push_back("omg2");
    ret.push_back("omg3");
    return ret;
}
</code>```

If you need to return a fixed number of values, use pass-by-reference like you suggested.

```<code>void name(const std::string& one, const std::string& two, std::string& ret1, std::string& ret2)
{
    ret1 = "omg1";
    ret2 = "omg2";
}
</code>```

Body:
I have made some app and the method im using is this:

INT name(char *one,char *two,char buffer[]){
memcpy(buffer,"omg",4);//or using std::string::copy ... that's how I actually return value
...}

and I call it like:

char returned[255];
name(first,second,returned);
printf/cout;

Everything is fine. Now my question is, is this method terrible or a disaster? Also, what is going on with allocated memory for 255 chars, I mean is there a way to re-allocate it somehow to save memory a little?

This is so called pass-by-reference, in either case I have to return multiple values (from 2 to 10). If I would need only 1 I would use return buffer with static type I guess.

Thanks. Write your favourite methods please while I read similar questions to this one hehe.

Body:
Just use a return value.

std::string name(const std::string& one, const std::string& two)
{
    return "omg";
}

If you need to return a variable number of values, return a vector:

std::vector<std::string> name(const std::string& one, const std::string& two)
{
    std::vector ret;
    ret.push_back("omg1");
    ret.push_back("omg2");
    ret.push_back("omg3");
    return ret;
}

If you need to return a fixed number of values, use pass-by-reference like you suggested.

void name(const std::string& one, const std::string& two, std::string& ret1, std::string& ret2)
{
    ret1 = "omg1";
    ret2 = "omg2";
}


答:
To answer the question in terms of the code you provide:

In the function correct_answer_array_func you immediately return after pushing one correct_answer to the array. Also, you hardcoded the length of the array, which I believe is not the best thing to do (is the API response guaranteed to be 4 objects?)

So, to make the function work, you need something similar to:

   //puting all correct_answer  into an array
   function correct_answer_array_func (){
         const correct_answer_array =[]
         for(let i =0 ; i<apipresave.length;i++){
             correct_answer_array.push(apipresave[i].correct_answer)
         }
         return correct_answer_array

    }
```

Title: how to pick some value from an object {} and put it into an array []

Body:
got some information from an API and now  want to pick "correct_answer" property from all of them and then make an array from correct_answer  here is the API information :

apipresave=[
  {question: "What does the "MP" stand for in MP3?",
   correct_answer: "Moving Picture",
   incorrect_answers: ["Music Player", "Multi Pass", "Micro Point"]},

  {question: "What does GHz stand for?",
   correct_answer: "Gigahertz",
   incorrect_answers: ["Gigahotz", "Gigahetz", "Gigahatz"]},

  {question: "In the programming language Java, which of these keywords would you put on a variable
   to make sure it doesn't get modified?",
   correct_answer: "Final",
   incorrect_answers: ["Static", "Private", "Public"]},
]

btw I have already put this information on a const and have full access to them in code
I have tried to loop over them and use push to get them but it didn't work
I put it below :

   //puting all correct_answer  into an array
   function correct_answer_array_func (){
         const correct_answer_array =[]
         for(let i =0 ; i<4;i++){
             correct_answer_array.push(apipresave[i].correct_answer)
                 return correct_answer_array
         }
    }

so how to obtain "correct_answer" from all the objects and put them in an array

the final result will be  :

 correct_answer_array  =["Moving Picture","Gigahertz","Final"]  // correct_answer values


问:
How to create backups from user interface CRM?
i am trying to make a backup option for my CRM. I have install this package https://spatie.be/docs/laravel-backup/v5/taking-backups/overview and i am using laravel 6^. I can backup my db and all system configuration with this package if i run backup:run from Terminal but this is not all i want. What i am looking for is to crate an interface where admin of page can make backup manually by clicking on options. For example like this: https://jobclass.laraclassifier.com/admin/backups (email: admin@demosite.com password: 123456) Does any one know how can i do something like this?</p>

答:
Calling Commands Via Code

Executing an Artisan command outside of the CLI. For example, you may wish to fire an Artisan command from a route or controller. You may use the call method on the Artisan facade to accomplish this. The on your controller you can do this:

```<code>public function createBackup(){
 Artisan::call('backup:run',['--only-db'=>true]);
 /// whatever you want to display

}
</code>```

Body:
Calling Commands Via Code

Executing an Artisan command outside of the CLI. For example, you may wish to fire an Artisan command from a route or controller. You may use the call method on the Artisan facade to accomplish this. The on your controller you can do this:

public function createBackup(){
 Artisan::call('backup:run',['--only-db'=>true]);
 /// whatever you want to display

}


问:
Splunk HEC - Disable multiline event splitting due to timestamp
I have a multi-line event that has timestamps on different lines as shown in the below example

```<code>[2022-02-08 08:30:23:776] [INFO] [com.example.monitoring.ServiceMonitor] Status report for services
Service 1 - Available
Service 2 - Unavailable since 2022-02-08T07:00:00 UTC
Service 3 - Available
</code>```

When the log is sent to an HEC, the lines are split into multiple events as highlighted in the Splunk data pipeline's parsing phase. Due to the presence of a timestamp on line 3, it creates 2 different events.

When searching in Splunk, I see the two events as shown below while they are supposed to be part of a single event.

Event 1

```<code>[2022-02-08 08:30:23:776] [INFO] [com.example.monitoring.ServiceMonitor] Status report for services
Service 1 - Available
</code>```

Event 2

```<code>Service 2 - Unavailable since 2022-02-08T07:00:00 UTC
Service 3 - Available
</code>```

I can solve the issue by setting DATETIME_CONFIG to NONE in props.conf but that creates another issue, Splunk will stop recognizing timestamps in the event.

Is it possible to achieve the same result but without disabling the above property?

答:
The trick is to set TIME_PREFIX correctly:

https://ibb.co/PCG5TqY

This will only look for timestamps in lines starting with a "[".

Here is the entry for props.conf:

```<code>[changeme]
disabled = false
pulldown_type = true
category = Custom
DATETIME_CONFIG =
NO_BINARY_CHECK = true
TIME_PREFIX = ^\[
TIME_FORMAT = %Y-%m-%d %H:%M:%S:%3N
SHOULD_LINEMERGE = true
</code>```

Body:
I have a multi-line event that has timestamps on different lines as shown in the below example

[2022-02-08 08:30:23:776] [INFO] [com.example.monitoring.ServiceMonitor] Status report for services
Service 1 - Available
Service 2 - Unavailable since 2022-02-08T07:00:00 UTC
Service 3 - Available

When the log is sent to an HEC, the lines are split into multiple events as highlighted in the Splunk data pipeline's parsing phase. Due to the presence of a timestamp on line 3, it creates 2 different events.

When searching in Splunk, I see the two events as shown below while they are supposed to be part of a single event.

Event 1

[2022-02-08 08:30:23:776] [INFO] [com.example.monitoring.ServiceMonitor] Status report for services
Service 1 - Available

Event 2

Service 2 - Unavailable since 2022-02-08T07:00:00 UTC
Service 3 - Available

I can solve the issue by setting DATETIME_CONFIG to NONE in props.conf but that creates another issue, Splunk will stop recognizing timestamps in the event.

Is it possible to achieve the same result but without disabling the above property?

Body:
The trick is to set TIME_PREFIX correctly:

https://ibb.co/PCG5TqY

This will only look for timestamps in lines starting with a "[".

Here is the entry for props.conf:

[changeme]
disabled = false
pulldown_type = true
category = Custom
DATETIME_CONFIG =
NO_BINARY_CHECK = true
TIME_PREFIX = ^\[
TIME_FORMAT = %Y-%m-%d %H:%M:%S:%3N
SHOULD_LINEMERGE = true


问:
Facebook Graph API not returning email
I have the following code:

```<code>$fb = new Facebook([
    'app_id' => $appId,
    'app_secret' => $appSecret,
    'default_graph_version' => 'v2.9',
]);

$oAuth2Client = $fb->getOAuth2Client();
$tokenMetaData = $oAuth2Client->debugToken($accessToken);
dump($tokenMetaData);

$graphUser = $fb->get('/me?fields=first_name,last_name,email', $accessToken)->getGraphUser()->asArray();
dump($graphUser);
</code>```

The output for the above is the following:

$metaData:

```<code> [
   "app_id" => "..."
   "application" => "My App Name"
   "expires_at" => "2017-07-01 11:40:09.000000"
   "is_valid" => true
   "issued_at" => "2017-05-02 11:40:09.000000"
   "metadata" => array:2 [
     "auth_type" => "rerequest"
     "sso" => "ios"
    ]
    "scopes" => array:2 [
      0 => "email"
      1 => "public_profile"
    ]
    "user_id" => "102..."
  ]
}
</code>```

$graphUser:

```<code>array:3 [
  "first_name" => "John"
  "last_name" => "Smith"
  "id" => "102...",
]
</code>```

As you can see, the scopes in $metaData clearly has email so it isn't a permission issue. Despite this, the graph user sometimes does not have the email (although in some cases it does).

Why is this and how can I solve this issue?

答:
Goto your app > App review > Permissions and Features

Request Advanced access for email which should turn Standard Access into Advanced Access

Title: Facebook Graph API not returning email

Body:
I have the following code:

$fb = new Facebook([
    'app_id' => $appId,
    'app_secret' => $appSecret,
    'default_graph_version' => 'v2.9',
]);

$oAuth2Client = $fb->getOAuth2Client();
$tokenMetaData = $oAuth2Client->debugToken($accessToken);
dump($tokenMetaData);

$graphUser = $fb->get('/me?fields=first_name,last_name,email', $accessToken)->getGraphUser()->asArray();
dump($graphUser);

The output for the above is the following:

$metaData:

 [
   "app_id" => "..."
   "application" => "My App Name"
   "expires_at" => "2017-07-01 11:40:09.000000"
   "is_valid" => true
   "issued_at" => "2017-05-02 11:40:09.000000"
   "metadata" => array:2 [
     "auth_type" => "rerequest"
     "sso" => "ios"
    ]
    "scopes" => array:2 [
      0 => "email"
      1 => "public_profile"
    ]
    "user_id" => "102..."
  ]
}

$graphUser:

array:3 [
  "first_name" => "John"
  "last_name" => "Smith"
  "id" => "102...",
]

As you can see, the scopes in $metaData clearly has email so it isn't a permission issue. Despite this, the graph user sometimes does not have the email (although in some cases it does).

Why is this and how can I solve this issue?


问:
async wait for element to load in so i can find it with jquery
i don't really understand async. i have a function like this:

function getTeam() {
    let sir = setInterval(() => {
        const teamsGrid = $('[class*="teamsgrid"]').find("p");
        const firstTeam = $(teamsGrid[0]).text();
        if (firstTeam != '') {
          clearInterval(sir)
          return firstTeam.trim()
        }
    }, 100)
}
```

im not js master.  i just want to get that element when it loads in,  this code is running in a userscript and // @run-at document-idle doesnt help either. i knew i would have to get into async js promises callbacks and whatever someday but i really dont understand how it works after pages of docs and other stackoverflow.
when i console.log this function it will print undefined once then if i have a console.log inside the if it will print the actual team name.
how do i wait for that result

答:
```<code>function getTeam() {
    let sir = new Promise((res, rej) => {
    const teamsGrid = $('[class*="teamsgrid"]').find("p");
        const firstTeam = $(teamsGrid[0]).text();
        if (firstTeam != '') {
          clearInterval(sir);
          res(firstTeam.trim());
        }
    });
    return sir();
}
</code>```

From what I understood, you are looking for firstTeam. Also, we assume that there is always firstTeam, so there isnt a case when there would be no team name.
I am not sure where you are making a req that will take time to process honestly from this code. So far it looks that sync function should do just fine. Are you reaching out to any API?

Body:
i don't really understand async. i have a function like this:

function getTeam() {
    let sir = setInterval(() => {
        const teamsGrid = $('[class*="teamsgrid"]').find("p");
        const firstTeam = $(teamsGrid[0]).text();
        if (firstTeam != '') {
          clearInterval(sir)
          return firstTeam.trim()
        }
    }, 100)
}

im not js master.  i just want to get that element when it loads in,  this code is running in a userscript and // @run-at document-idle doesnt help either. i knew i would have to get into async js promises callbacks and whatever someday but i really dont understand how it works after pages of docs and other stackoverflow.
when i console.log this function it will print undefined once then if i have a console.log inside the if it will print the actual team name.
how do i wait for that result

Body:
function getTeam() {
    let sir = new Promise((res, rej) => {
    const teamsGrid = $('[class*="teamsgrid"]').find("p");
        const firstTeam = $(teamsGrid[0]).text();
        if (firstTeam != '') {
          clearInterval(sir);
          res(firstTeam.trim());
        }
    });
    return sir();
}

From what I understood, you are looking for firstTeam. Also, we assume that there is always firstTeam, so there isnt a case when there would be no team name.
I am not sure where you are making a req that will take time to process honestly from this code. So far it looks that sync function should do just fine. Are you reaching out to any API?


问:
MVC Filtering A-Z
I have made the MVC Music Store from the tutorials and am editing it and adding new features, recently I made the browse store page have links from A-Z with an All button at the end.
How can I bring up a message that says "There are no artists beginning with the letter A, B, C " or whatever letter has been clicked with no artists.

Here is my code from my Store Index:

```<code>@model IEnumerable<MVCMusicStore.Models.Artist>
@{
    ViewBag.Title = "Store";
}

<h3>Browse Artists</h3>
@Html.ActionLink("A", "Index", new { letter = "A" })
@Html.ActionLink("B", "Index", new { letter = "B" })
@Html.ActionLink("C", "Index", new { letter = "C" })
@Html.ActionLink("D", "Index", new { letter = "D" })
@Html.ActionLink("E", "Index", new { letter = "E" })
@Html.ActionLink("F", "Index", new { letter = "F" })
@Html.ActionLink("G", "Index", new { letter = "G" })
@Html.ActionLink("H", "Index", new { letter = "H" })
@Html.ActionLink("I", "Index", new { letter = "I" })
@Html.ActionLink("J", "Index", new { letter = "J" })
@Html.ActionLink("K", "Index", new { letter = "K" })
@Html.ActionLink("L", "Index", new { letter = "L" })
@Html.ActionLink("M", "Index", new { letter = "M" })
@Html.ActionLink("N", "Index", new { letter = "N" })
@Html.ActionLink("O", "Index", new { letter = "O" })
@Html.ActionLink("P", "Index", new { letter = "P" })
@Html.ActionLink("Q", "Index", new { letter = "Q" })
@Html.ActionLink("R", "Index", new { letter = "R" })
@Html.ActionLink("S", "Index", new { letter = "S" })
@Html.ActionLink("T", "Index", new { letter = "T" })
@Html.ActionLink("U", "Index", new { letter = "U" })
@Html.ActionLink("V", "Index", new { letter = "V" })
@Html.ActionLink("W", "Index", new { letter = "W" })
@Html.ActionLink("X", "Index", new { letter = "X" })
@Html.ActionLink("Y", "Index", new { letter = "Y" })
@Html.ActionLink("Z", "Index", new { letter = "Z" })
@Html.ActionLink("All", "Index", new { letter = "all" })

<ul>
    @foreach (var artist in Model)
    {
        <li>@Html.ActionLink(artist.Name,
"Browse", new { id = artist.ArtistId })</li>
    }
</ul>
</code>```

This is the code from my Controller:

```<code>    public ActionResult Index(string letter = "")
    {
        IEnumerable<Artist> artist;

        if (letter == "all")
        {
            artist = storeDB.Artists.OrderBy(x =>x.Name).ToList();
        }
        else if (letter != "")
        {
artist = storeDB.Artists.Where(a => a.Name.StartsWith(letter)).OrderBy(x => x.Name).ToList();
        }
        else
        {
            artist = new List<Artist>();
        }
</code>```

答:
```<code>@if(Model.Any())
{
    foreach (var artist in Model)
    {
        <li>@Html.ActionLink(artist.Name,
"Browse", new { id = artist.ArtistId })</li>
    }
}
else
{
    <span>There are no artists</span>
}
</code>```

Title: MVC Filtering A-Z

Body:
I have made the MVC Music Store from the tutorials and am editing it and adding new features, recently I made the browse store page have links from A-Z with an All button at the end.
How can I bring up a message that says "There are no artists beginning with the letter A, B, C " or whatever letter has been clicked with no artists.

Here is my code from my Store Index:

@model IEnumerable<MVCMusicStore.Models.Artist>
@{
    ViewBag.Title = "Store";
}

Browse Artists

@Html.ActionLink("A", "Index", new { letter = "A" })
@Html.ActionLink("B", "Index", new { letter = "B" })
@Html.ActionLink("C", "Index", new { letter = "C" })
@Html.ActionLink("D", "Index", new { letter = "D" })
@Html.ActionLink("E", "Index", new { letter = "E" })
@Html.ActionLink("F", "Index", new { letter = "F" })
@Html.ActionLink("G", "Index", new { letter = "G" })
@Html.ActionLink("H", "Index", new { letter = "H" })
@Html.ActionLink("I", "Index", new { letter = "I" })
@Html.ActionLink("J", "Index", new { letter = "J" })
@Html.ActionLink("K", "Index", new { letter = "K" })
@Html.ActionLink("L", "Index", new { letter = "L" })
@Html.ActionLink("M", "Index", new { letter = "M" })
@Html.ActionLink("N", "Index", new { letter = "N" })
@Html.ActionLink("O", "Index", new { letter = "O" })
@Html.ActionLink("P", "Index", new { letter = "P" })
@Html.ActionLink("Q", "Index", new { letter = "Q" })
@Html.ActionLink("R", "Index", new { letter = "R" })
@Html.ActionLink("S", "Index", new { letter = "S" })
@Html.ActionLink("T", "Index", new { letter = "T" })
@Html.ActionLink("U", "Index", new { letter = "U" })
@Html.ActionLink("V", "Index", new { letter = "V" })
@Html.ActionLink("W", "Index", new { letter = "W" })
@Html.ActionLink("X", "Index", new { letter = "X" })
@Html.ActionLink("Y", "Index", new { letter = "Y" })
@Html.ActionLink("Z", "Index", new { letter = "Z" })
@Html.ActionLink("All", "Index", new { letter = "all" })

    @foreach (var artist in Model)
    {

@Html.ActionLink(artist.Name,
"Browse", new { id = artist.ArtistId })

    }

This is the code from my Controller:

    public ActionResult Index(string letter = "")
    {
        IEnumerable<Artist> artist;

        if (letter == "all")
        {
            artist = storeDB.Artists.OrderBy(x =>x.Name).ToList();
        }
        else if (letter != "")
        {
artist = storeDB.Artists.Where(a => a.Name.StartsWith(letter)).OrderBy(x => x.Name).ToList();
        }
        else
        {
            artist = new List<Artist>();
        }


问:
Add "No results found" message on div search
I'm making an audio player, and I have a list of divs acting as my playlist... I'm using JS to make the list, and I'm using this script to search through them:

```<code>/*Search Songs*/
function searchSongs(){
  let input = _('#songSearch').value.toLowerCase();
  let items = _all('.item');
  let dividers = _all(".divider");

  for (let i = 0; i < items.length; i++) {
    if (!items[i].innerHTML.toLowerCase().includes(input)) {
      items[i].style.display = "none";
    }
    else {
      items[i].style.display = "";
    }
  }

  // add noresults message at end if all list divs are hidden
  if (!items.innerHTML.toLowerCase().includes(input)) {
    _('.noResults').innerHTML = `<p>No results found for "${input}"`
  }
}
</code>```

I have a paragraph element at the end of my list (with nothing in it) and I want to show the message (
No results found for "${input}") is there some js I can use to accomplish this? The script above is working for the searching, but not working for the message.

答:
Finished result:

```<code>/*Search Songs*/
function searchSongs(){
  let input = _('#songSearch').value.toLowerCase();
  let items = _all('.item');
  let dividers = _all(".divider");
  let counter = 0;

  for (let i = 0; i < items.length; i++) {
    if (!items[i].innerHTML.toLowerCase().includes(input)) {
      items[i].style.display = "none";
      counter++;
    }
    else {
      items[i].style.display = "";
    }
  }

  // keeping the result 22 letters long (for asthetic purposes)
  let maxLen = 22;
  if (input.length > maxLen) {
    input = input.substring(0, maxLen - 3) + "...";
  }

  if (counter >= items.length) {
    _('#noResults').innerHTML = `No results found for "${input}"` //add no results message if all items are hidden...
  } else {
    _('#noResults').innerHTML = `` //else hide the message by removing text.
  }
}
</code>```

Thanks, @Asif !!

Body:
I'm making an audio player, and I have a list of divs acting as my playlist... I'm using JS to make the list, and I'm using this script to search through them:

/*Search Songs*/
function searchSongs(){
  let input = _('#songSearch').value.toLowerCase();
  let items = _all('.item');
  let dividers = _all(".divider");

  for (let i = 0; i < items.length; i++) {
    if (!items[i].innerHTML.toLowerCase().includes(input)) {
      items[i].style.display = "none";
    }
    else {
      items[i].style.display = "";
    }
  }

  // add noresults message at end if all list divs are hidden
  if (!items.innerHTML.toLowerCase().includes(input)) {
    _('.noResults').innerHTML = `<p>No results found for "${input}"`
  }
}

I have a paragraph element at the end of my list (with nothing in it) and I want to show the message (
No results found for "${input}") is there some js I can use to accomplish this? The script above is working for the searching, but not working for the message.

Body:
Finished result:

/*Search Songs*/
function searchSongs(){
  let input = _('#songSearch').value.toLowerCase();
  let items = _all('.item');
  let dividers = _all(".divider");
  let counter = 0;

  for (let i = 0; i < items.length; i++) {
    if (!items[i].innerHTML.toLowerCase().includes(input)) {
      items[i].style.display = "none";
      counter++;
    }
    else {
      items[i].style.display = "";
    }
  }

  // keeping the result 22 letters long (for asthetic purposes)
  let maxLen = 22;
  if (input.length > maxLen) {
    input = input.substring(0, maxLen - 3) + "...";
  }

  if (counter >= items.length) {
    _('#noResults').innerHTML = `No results found for "${input}"` //add no results message if all items are hidden...
  } else {
    _('#noResults').innerHTML = `` //else hide the message by removing text.
  }
}

Thanks, @Asif !!


问:
Angular reactive form: Displaying error text when form has error
I´m struggling with displaying error message under the textarea in my form. I have custom-textarea which is a normal texarea component with some handy attributes. One of them is helper text which is displayed below the textarea box. I find the logic of my conditional rendering okay, although it is not being displayed on the screen when the specific error occurs. Hardcoded value for my helper text works, so there is no problem with the text being displayed. Do you have any idea what could be the problem here?</p>
```<code><form [formGroup]="editForm" (ngSubmit)="editComment()">
    <custom-textarea
      formControlName="text"
      helper-text="{{!editForm.valid ? ((editForm.controls.text.errors?.['required'] ? 'Text for the comment is required!' : null) || (editForm.controls.text.errors?.['minlength'] ? 'Minimal length of text is 3 characters!' : null)) : null}}"
    ></custom-textarea>
</form>
</code>```
```<code>export class EditCommentComponent implements OnInit {
@Input() comment: Comment;
editForm: FormGroup;
ngOnInit(): void {
    this.editForm = new FormGroup({
      text: new FormControl('', [Validators.required, Validators.minLength(3)]),
    });
}

ngOnChanges(): void {
    this.editForm.controls.text.setValue(this.comment.text);
  }
</code>```

答:
Use property binding for helper-text. Change :

```<code>helper-text="{{!editForm.valid ? ((editForm.controls.text.errors?.['required'] ? 'Text for the comment is required!' : null) || (editForm.controls.text.errors?.['minlength'] ? 'Minimal length of text is 3 characters!' : null)) : null}}"
</code>```

by :

```<code>[helper-text] = "!editForm.valid ? ((editForm.controls.text.errors?.['required'] ? 'Text for the comment is required!' : null) || (editForm.controls.text.errors?.['minlength'] ? 'Minimal length of text is 3 characters!' : null)) : null"
</code>```

This way, helper-text property will no longer be static but dynamic (Check  Angular Documentation  on Property Binding)

Body:
I´m struggling with displaying error message under the textarea in my form. I have custom-textarea which is a normal texarea component with some handy attributes. One of them is helper text which is displayed below the textarea box. I find the logic of my conditional rendering okay, although it is not being displayed on the screen when the specific error occurs. Hardcoded value for my helper text works, so there is no problem with the text being displayed. Do you have any idea what could be the problem here?

<form [formGroup]="editForm" (ngSubmit)="editComment()">
    <custom-textarea
      formControlName="text"
      helper-text="{{!editForm.valid ? ((editForm.controls.text.errors?.['required'] ? 'Text for the comment is required!' : null) || (editForm.controls.text.errors?.['minlength'] ? 'Minimal length of text is 3 characters!' : null)) : null}}"
    ></custom-textarea>
</form>

export class EditCommentComponent implements OnInit {
@Input() comment: Comment;
editForm: FormGroup;
ngOnInit(): void {
    this.editForm = new FormGroup({
      text: new FormControl('', [Validators.required, Validators.minLength(3)]),
    });
}

ngOnChanges(): void {
    this.editForm.controls.text.setValue(this.comment.text);
  }

Body:
Use property binding for helper-text. Change :

helper-text="{{!editForm.valid ? ((editForm.controls.text.errors?.['required'] ? 'Text for the comment is required!' : null) || (editForm.controls.text.errors?.['minlength'] ? 'Minimal length of text is 3 characters!' : null)) : null}}"

by :

[helper-text] = "!editForm.valid ? ((editForm.controls.text.errors?.['required'] ? 'Text for the comment is required!' : null) || (editForm.controls.text.errors?.['minlength'] ? 'Minimal length of text is 3 characters!' : null)) : null"

This way, helper-text property will no longer be static but dynamic (Check  Angular Documentation  on Property Binding)


问:
Firebase authentication in desktop application
After the announcement of Flutter v2.10, I start working on my desktop application and I want to implement firebase authentication but unfortunately, firebase_auth packages don't support desktop till now so is there any way to authenticate the user with firebase in a desktop application.

Since we have desktop support so I planning to authenticate on the web and after authentication redirect again on the desktop application but I don't know how this works anyone has any idea about this or any other way?

答: If you're on a platform for which no Firebase Authentication SDK is available, you can call its REST APIs instead. This can be done from any platform that can call HTTP endpoints, including Flutter.</p>


问:
Fastlane, invoke multiple platforms
I have a React Native project. I am able to build iOS and Android builds like so:

```<code>fastlane android build
fastlane ios build
</code>```

However, here is what I want to do, so both iOS and Android are built.

```<code>fastlane all build
</code>```

Here's what a simplified version of my Fastfile looks like:

```<code>default_platform(:android)

platform :android do
  desc "Simply build a release apk"
  lane :build do |options|
    gradle(
        project_dir: "android",
        task: "clean assemble",
        build_type: "Release",
    )
  end
end

platform :ios do
  desc "Simply build a release ipa"
  lane :build do |options|
    build_app(workspace: "ios/myproject.xcworkspace")
  end
end
</code>```

I'm being told that this is all Ruby code, and I should be able to do whatever I want. So, I want "all" to invoke both Android and iOS. However, I do not know any Ruby, so your help would be much appreciated.

答:
The only way I've found to achieve this is to get rid of platforms altogether and create 3 separate lanes:

```<code>desc 'Build iOS and Android'
lane :build do
  build_android
  build_ios
end

desc 'Compiles the Android project'
lane :build_android do
   ....
end

desc 'Compiles the iOS project'
lane :build_ios do
  ....
end
</code>```

I know this defeats the purpose of having platforms but I've not yet found a neater way of doing this since it does not appear to be possible to call lanes in a platform block from outside that block.

Title: Fastlane, invoke multiple platforms

Body:
I have a React Native project. I am able to build iOS and Android builds like so:

fastlane android build
fastlane ios build

However, here is what I want to do, so both iOS and Android are built.

fastlane all build

Here's what a simplified version of my Fastfile looks like:

default_platform(:android)

platform :android do
  desc "Simply build a release apk"
  lane :build do |options|
    gradle(
        project_dir: "android",
        task: "clean assemble",
        build_type: "Release",
    )
  end
end

platform :ios do
  desc "Simply build a release ipa"
  lane :build do |options|
    build_app(workspace: "ios/myproject.xcworkspace")
  end
end

I'm being told that this is all Ruby code, and I should be able to do whatever I want. So, I want "all" to invoke both Android and iOS. However, I do not know any Ruby, so your help would be much appreciated.

Body:
The only way I've found to achieve this is to get rid of platforms altogether and create 3 separate lanes:

desc 'Build iOS and Android'
lane :build do
  build_android
  build_ios
end

desc 'Compiles the Android project'
lane :build_android do
   ....
end

desc 'Compiles the iOS project'
lane :build_ios do
  ....
end

I know this defeats the purpose of having platforms but I've not yet found a neater way of doing this since it does not appear to be possible to call lanes in a platform block from outside that block.