问:
Defining my own isPrefixOf without recursion using foldr
I am working on a programming assignment where I must define my own version of isPrefixOf from Data.List using only foldr, map, and cons (and thus no recursion). The hint I've been given is that the return value of foldr should itself be a function. Can someone help me understand how I could apply that fact? My guess for the structure is included below.

```<code>startsWith :: String -> String -> Bool
startsWith s1 s2 = (foldr (???) ??? s1) s2
</code>```

I am allowed to define my own helper functions. For the curious this is from an assignment for CIS 552 at Penn.

答:
EDIT: It turns out that by folding over the pattern instead of the string, the code gets a lot simpler and shorter and something like

```<code>"" `isPrefixOf` undefined
</code>```

works. Thank you @dfeuer and @WillNess. This is the updated program:

```<code>isPrefixOf pattern s = foldr g (const True) pattern s
    where
        g x r (h:t)
          | x == h    = r t
          | otherwise = False
</code>```

It works almost the same way as the below program, so refer to that for the explanation.

I managed to solve it using nothing but foldr:

```<code>isPrefixOf :: String -> String -> Bool
p `isPrefixOf` s = isPrefixOfS p
    where
        isPrefixOfS
            = foldr
                (\c acc ->
                    \str -> case str of
                        x:xs -> if c == x
                                then acc xs
                                else False
                        []   -> True
                    )
                null
                s

</code>```

Here's the explanation.

In order to create the function isPrefixOf, we want this:

```<code>isPrefixOf pattern s
  = case pattern of
      [] -> True
      x:xs -> if (null s) then False
              else if (head s) /= x
                   then False
                   else xs `isPrefixOf` (tail s)

</code>```

Well, let's simplify this - let's create a function called isPrefixOfS that only takes a pattern, which it compares to s automatically. We need to build this chain of nested functions:

```<code>-- Pseudocode, not actual Haskell

\p -> case p of
        [] -> True
        x:xs -> if x /= (s !! 0)
                  then False
                  else <apply xs to> \q -> case q of [] -> True
                                                     x:xs -> if x /= (s !! 1) -- Note that we've incremented the index
                                                             then False
                                                             else <apply xs to> \r -> ....
</code>```

This seems pretty self explanatory - let me know in a comment if it requires further explanation.

Well, we can see that this chain has a recursive property to it, where the last character of s will be compared in the most deeply nested lambda. So we need to nest lambdas from right to left. What can we use for that? foldr.

```<code>isPrefixOfS
            = foldr -- Folding from right to left across `s`
                (\c acc -> -- `c` is the current character of `s`, acc is the chain of nested functions so far
                    \str -> -- We return a function in the fold that takes a String
                      case str of
                        -- If the string is not null:
                        x:xs -> if c == x   -- If the head of the string is equal to the current character of s,
                                then acc xs -- Then pass the tail of the string to the nested function which will compare it with subsequent characters of s
                                else False -- Otherwise we return false

                        -- If the string is null, we have completely matched the prefix and so return True
                        []   -> True
                    )
                null -- Innermost nested function - we need to make sure that if the prefix reaches here, it is null, i.e. we have entirely matched it
                s
</code>```

And now we use this function isPrefixOfS on p:

```<code>p `isPrefixOf` s = isPrefixOfS p
</code>```

EDIT: I just found this post which uses a similar logic to implement zip in terms of foldr, you may want to look at that as well.

Body:
I am working on a programming assignment where I must define my own version of isPrefixOf from Data.List using only foldr, map, and cons (and thus no recursion). The hint I've been given is that the return value of foldr should itself be a function. Can someone help me understand how I could apply that fact? My guess for the structure is included below.

startsWith :: String -> String -> Bool
startsWith s1 s2 = (foldr (???) ??? s1) s2

I am allowed to define my own helper functions. For the curious this is from an assignment for CIS 552 at Penn.

Body:
EDIT: It turns out that by folding over the pattern instead of the string, the code gets a lot simpler and shorter and something like

"" `isPrefixOf` undefined

works. Thank you @dfeuer and @WillNess. This is the updated program:

isPrefixOf pattern s = foldr g (const True) pattern s
    where
        g x r (h:t)
          | x == h    = r t
          | otherwise = False

It works almost the same way as the below program, so refer to that for the explanation.

I managed to solve it using nothing but foldr:

isPrefixOf :: String -> String -> Bool
p `isPrefixOf` s = isPrefixOfS p
    where
        isPrefixOfS
            = foldr
                (\c acc ->
                    \str -> case str of
                        x:xs -> if c == x
                                then acc xs
                                else False
                        []   -> True
                    )
                null
                s

Here's the explanation.

In order to create the function isPrefixOf, we want this:

isPrefixOf pattern s
  = case pattern of
      [] -> True
      x:xs -> if (null s) then False
              else if (head s) /= x
                   then False
                   else xs `isPrefixOf` (tail s)

Well, let's simplify this - let's create a function called isPrefixOfS that only takes a pattern, which it compares to s automatically. We need to build this chain of nested functions:

-- Pseudocode, not actual Haskell

\p -> case p of
        [] -> True
        x:xs -> if x /= (s !! 0)
                  then False
                  else <apply xs to> \q -> case q of [] -> True
                                                     x:xs -> if x /= (s !! 1) -- Note that we've incremented the index
                                                             then False
                                                             else <apply xs to> \r -> ....

This seems pretty self explanatory - let me know in a comment if it requires further explanation.

Well, we can see that this chain has a recursive property to it, where the last character of s will be compared in the most deeply nested lambda. So we need to nest lambdas from right to left. What can we use for that? foldr.

isPrefixOfS
            = foldr -- Folding from right to left across `s`
                (\c acc -> -- `c` is the current character of `s`, acc is the chain of nested functions so far
                    \str -> -- We return a function in the fold that takes a String
                      case str of
                        -- If the string is not null:
                        x:xs -> if c == x   -- If the head of the string is equal to the current character of s,
                                then acc xs -- Then pass the tail of the string to the nested function which will compare it with subsequent characters of s
                                else False -- Otherwise we return false

                        -- If the string is null, we have completely matched the prefix and so return True
                        []   -> True
                    )
                null -- Innermost nested function - we need to make sure that if the prefix reaches here, it is null, i.e. we have entirely matched it
                s

And now we use this function isPrefixOfS on p:

p `isPrefixOf` s = isPrefixOfS p

EDIT: I just found this post which uses a similar logic to implement zip in terms of foldr, you may want to look at that as well.


来源: stackexchange

问:
How to fix Google expo auth session sign in Error "Something went wrong when trying to finish signing in"
I'm trying to implement google sign in in my expo using expo-auth-session,
When I click on my gmail to sign in, I'm redirected to this screen saying "Something went wrong when trying to finish signing in. Please close this screen to go back to the app".</p>
```<code>//Google auth code:
    import * as Google from 'expo-auth-session/providers/google';
    const [request, response, promptAsync] = Google.useAuthRequest({
        expoClientId: config.google.expoClientId,
        redirectUri: config.google.redirectUri,
      });

      React.useEffect(() => {
      //Handle google login
      console.log(response)
      if (response?.type === 'success') {
       const { authentication } = response;
      }
      }, [response]);

    //Button that calls the google sign in
    <Button iconName={'google'} iconPressed={() => promptAsync({useProxy: true})} />
</code>```

答:
I think you can try like this</p>
```<code>import * as Google from 'expo-auth-session/providers/google';
import * as WebBrowser from 'expo-web-browser';

WebBrowser.maybeCompleteAuthSession();
....
const [request, response, promptAsync] = Google.useAuthRequest({
        androidClientId: config.androidClientId,
        iosClientId: config.iosClientId,
        expoClientId: config.expoClientId,
        scopes: config.scopes,
    });

useEffect(() => {
   if (response?.type === 'success') {
       const { authentication } = response;
       getGoogleUser((authentication as any).accessToken)
   }
}, [response]);

const getGoogleUser = async (accessToken: string) => {

  try{
        const response = await fetch('https://www.googleapis.com/userinfo/v2/me', {
            headers: { Authorization: `Bearer ${accessToken}`}
        });

        const user = response.json()
        if (user?.email) {
            const { email, name } = user; // you will get more data in the user object
            .......
        }
    }
    catch(error){
        console.log('GoogleUserReq error: ', error);
    }
}

 return (
    <View>
      <Button
        onPress={() => promptAsync() }
      />
    </View>
  );
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to implement google sign in in my expo using expo-auth-session,
When I click on my gmail to sign in, I'm redirected to this screen saying "Something went wrong when trying to finish signing in. Please close this screen to go back to the app".

//Google auth code:
    import * as Google from 'expo-auth-session/providers/google';
    const [request, response, promptAsync] = Google.useAuthRequest({
        expoClientId: config.google.expoClientId,
        redirectUri: config.google.redirectUri,
      });

      React.useEffect(() => {
      //Handle google login
      console.log(response)
      if (response?.type === 'success') {
       const { authentication } = response;
      }
      }, [response]);

    //Button that calls the google sign in
    <Button iconName={'google'} iconPressed={() => promptAsync({useProxy: true})} />

Body:
I think you can try like this

import * as Google from 'expo-auth-session/providers/google';
import * as WebBrowser from 'expo-web-browser';

WebBrowser.maybeCompleteAuthSession();
....
const [request, response, promptAsync] = Google.useAuthRequest({
        androidClientId: config.androidClientId,
        iosClientId: config.iosClientId,
        expoClientId: config.expoClientId,
        scopes: config.scopes,
    });

useEffect(() => {
   if (response?.type === 'success') {
       const { authentication } = response;
       getGoogleUser((authentication as any).accessToken)
   }
}, [response]);

const getGoogleUser = async (accessToken: string) => {

  try{
        const response = await fetch('https://www.googleapis.com/userinfo/v2/me', {
            headers: { Authorization: `Bearer ${accessToken}`}
        });

        const user = response.json()
        if (user?.email) {
            const { email, name } = user; // you will get more data in the user object
            .......
        }
    }
    catch(error){
        console.log('GoogleUserReq error: ', error);
    }
}

 return (
    <View>
      <Button
        onPress={() => promptAsync() }
      />
    </View>
  );


问:
Is it possible to check if a function with a string as its name exists?(C++)
I want to be able to do something like this:</p>

```<code>if (Is_Function("helloworld")
    // Run code
</code>```

答: One technique you can use on ELF-based systmes (Linux and most Unix variants, including MacOS X), is to link with -rdynamic, and then call dlsym(RTLD_DEFAULT, "helloworld") to get a pointer to the function helloworld if it exists in the current executable or any shared lib that has been loaded.  This has issues with C++ due to name mangling, so really only works for functions declared with extern "C" or in C code.

ContentLicense: CC BY-SA 3.0

Body:
I want to be able to do something like this:

if (Is_Function("helloworld")
    // Run code


问:
Can't use conda environment in VSCode
Today I can't use my env in Visual Studio Code. I've tried to restart my computer, reinstall Jupyter extensions in VSCode but nothing works. Here are some pictures of the "errors":

Here it can't even print 1

Main error

This message shows up and never ends

I've tried using other envs and they seem to be fine and working. What's' the problem with this env?

答: Apparently, it was giving me this error due to not updating tensorflow to version 2.8. The issue here is that I was succesfully using this env for the past 6 months without any problem, so I don't know why now sstarted failing...

Title: Can't use conda environment in VSCode


问:
Swift: How to prevent navigation to Google Maps when a user presses on the Google logo on Google Maps
I am using Google map framework to display map. How to prevent navigation to Google Maps when a user presses on the Google logo on Google Maps.</p>

答:
Go to info.plist and remove the second item (the one that has the value of 'comgooglemaps').

Google Maps uses this URL scheme to navigate to Google Maps when the logo is pressed. Since this is an optional behavior, you can safely delete it.


问:
React doesn't call useEffect on firebase (v9) auth update
I'm uploading a user profile image into firebase storage, then updating the photoURL value of the auth user with updateProfile(). After that I want the user to be updated without manually refreshing the page. I've been trying this for days now and the issue gets more weird every time I try to debug it.

The interesting thing is the user object seems to be already updated when I log it with console.log(currentUser) after the then promise of updateProfile() is fulfilled. So the new photoURL is already present in the currentUser object. But it seems to not call a state update or console.log("!!!!currentAuthUserUpdate", user);. So the user image wouldn't refresh in my page.

I even tried it with doing a useEffect with the currentUser as a dependency but it wasn't fired. Still, the currentUser object changed when logging it after updateProfile()

Updating the profile, UpdateUserImage.tsx:

```<code>import { useAuth } from "../../contexts/AuthContext";

const { currentUser } = useAuth();

// updating the user profile
updateProfile(currentUser, { photoURL })
</code>```

AuthContext.tsx:

```<code>import { auth } from "./../firebase/firebase";

const [currentUser, setCurrentUser] = useState(null);

const auth = getAuth(app);

  useEffect(() => {
    const unsubscribe = auth.onAuthStateChanged((user) => {
      console.log("!!!!currentAuthUserUpdate", user);

      // I tried setting the user as a custom new object: const userData = { ...user };
      setCurrentUser(user);
    });
    return unsubscribe;
  }, []);
</code>```

firebase.js

```<code>import { getAuth } from "firebase/auth";

// Initialize Firebase
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);

export {
  auth
};
</code>```

What I tried additionally: (But this wouldn't work as the user is already updated without a state refresh from react, so it's trying to replace the same object)

```<code>const reloadUser = async () => {
    try {
      const res = await currentUser.reload();
      const user = auth.currentUser;
      console.log("currentUser:", user);

      setCurrentUser(auth.currentUser);

      console.log("res", res);
    } catch (err) {
      console.log(err);
    }
  };
</code>```

答:
it's not auth.onAuthStateChanged. You need to import onAuthStateChanged from 'firebase/auth'

```<code>import { getAuth, onAuthStateChanged } from "firebase/auth"
const auth = getAuth(); // leave getAuth empty if you only have one app
</code>```

Then in your useEffect it should be

```<code> onAuthStateChanged(auth, async (currentUser) => { ... }
</code>```

Body:
I'm uploading a user profile image into firebase storage, then updating the photoURL value of the auth user with updateProfile(). After that I want the user to be updated without manually refreshing the page. I've been trying this for days now and the issue gets more weird every time I try to debug it.

The interesting thing is the user object seems to be already updated when I log it with console.log(currentUser) after the then promise of updateProfile() is fulfilled. So the new photoURL is already present in the currentUser object. But it seems to not call a state update or console.log("!!!!currentAuthUserUpdate", user);. So the user image wouldn't refresh in my page.

I even tried it with doing a useEffect with the currentUser as a dependency but it wasn't fired. Still, the currentUser object changed when logging it after updateProfile()

Updating the profile, UpdateUserImage.tsx:

import { useAuth } from "../../contexts/AuthContext";

const { currentUser } = useAuth();

// updating the user profile
updateProfile(currentUser, { photoURL })

AuthContext.tsx:

import { auth } from "./../firebase/firebase";

const [currentUser, setCurrentUser] = useState(null);

const auth = getAuth(app);

  useEffect(() => {
    const unsubscribe = auth.onAuthStateChanged((user) => {
      console.log("!!!!currentAuthUserUpdate", user);

      // I tried setting the user as a custom new object: const userData = { ...user };
      setCurrentUser(user);
    });
    return unsubscribe;
  }, []);

firebase.js

import { getAuth } from "firebase/auth";

// Initialize Firebase
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);

export {
  auth
};

What I tried additionally: (But this wouldn't work as the user is already updated without a state refresh from react, so it's trying to replace the same object)

const reloadUser = async () => {
    try {
      const res = await currentUser.reload();
      const user = auth.currentUser;
      console.log("currentUser:", user);

      setCurrentUser(auth.currentUser);

      console.log("res", res);
    } catch (err) {
      console.log(err);
    }
  };

Body:
it's not auth.onAuthStateChanged. You need to import onAuthStateChanged from 'firebase/auth'

import { getAuth, onAuthStateChanged } from "firebase/auth"
const auth = getAuth(); // leave getAuth empty if you only have one app

Then in your useEffect it should be

 onAuthStateChanged(auth, async (currentUser) => { ... }


问:
Calculating the 3 largest colums in excel and summing them
I am trying to calculate the total for the PT colums. I want it to calculate the top 3 PT colums and add them together. Excell noob so hoping someone can point me in the right direction. You can see my attempt in the screenshot below

答:
An alternative to Jos Woolley's answers which does not need the array formula entry as the function performs array operation is as follows:

=SUM(AGGREGATE(14,6,$B$2:$P$2/($B$1:$P$1=$S$1),{1,2,3}))

Note I set cell S1 to be a drop down list of possible column names instead of hardcoding the "PT" value.


问:
One dimensional array but multiple string
I want to make a multiple string of array but with just a one dimensional array, Is it possible?

```<code>#include <stdio.h>

int main()
{
    char name1[10];
    char name2[10];

    printf("Enter name1: ");
    scanf("%s", name1);

    printf("Enter name2: ");
    scanf("%s", name2);

    printf("\n%s", name1);
    printf("\n%s", name2);

    return 0;
}
</code>```

I just started to learn array and I wanted to try to get multiple input from user and display only specific of the elements.
This is one of the code I tried before but it does not run.

```<code>int main()
{
    char *name[10];

    int i = 1, input;
    printf("How many days a week: ");
    scanf("%d", &input);

    do{
        printf("enter day %d: ", i);
        scanf("%s", name[i]);
        i++;
    }while(i < input);

    //output wanted
    printf("\n%s", name[0]);
    printf("\n%s", name[4]);

    return 0;
}
</code>```

答:
Your question is very unclear, but it sounds to me that you do not want a one-dimensional array, but rather a two-dimensional array (despite your question explicitly stating the opposite).

I suggest that you change char *name[10]; to char name[10][10]; Also, you may want to change the variable name of the 2D-array name to names, because that name is misleading, as it implies that it contains only a single string.

Also, you must start the loop counter i at 0, not 1, as array indexes are zero-based in C.

After making these changes, your program should look like this:

```<code>#include <stdio.h>

int main( void )
{
    char names[10][10];

    int i = 0, input;
    printf("How many days a week: ");
    scanf("%d", &input);

    do{
        printf("Enter day %d: ", i+1);
        scanf("%s", names[i]);
        i++;
    }while(i < input);

    //output wanted
    printf("The first day is: %s\n", names[0]);
    printf("The fifth day is: %s\n", names[4]);

    return 0;
}
</code>```

This program has the following behavior:

How many days a week: 7
Enter day 1: Monday
Enter day 2: Tuesday
Enter day 3: Wednesday
Enter day 4: Thursday
Enter day 5: Friday
Enter day 6: Saturday
Enter day 7: Sunday
The first day is: Monday
The fifth day is: Friday
```
<p>Note that the program will write to the array out of bounds if the user enters an integer larger than <code>10</code> or if any of the days has a length larger than <code>9</code> (<code>10</code> including the terminating null character).</p>
<p>Also, your program would have a cleaner structure if you used a <code>for</code> loop instead of a <code>while</code> loop, as it reduces the scope of the loop counter.</p>
<p>Another issue is that the program will misbehave if the user does not enter a number. Instead, it should check if the function <code>scanf</code> succeeded, and to print an error message if it did not.</p>
<p>Therefore, it would be better to write it like this:</p>
```#include <stdio.h>
#include <stdlib.h>

#define MAX_DAYS 10

//MAX_DAY_LENGTH_FORMAT_STRING, which is used by scanf,
//should always be set to one less than MAX_DAY_LENGTH,
//because the latter also needs room for the terminating
//null character
#define MAX_DAY_LENGTH 10
#define MAX_DAY_LENGTH_FORMAT_STRING "%9s"

int main( void )
{
    char names[MAX_DAYS][MAX_DAY_LENGTH];
    int num_days;

    //prompt user for input
    printf( "How many days a week: " );

    //attempt to read input
    if ( scanf( "%d", &num_days ) != 1 )
    {
        printf( "Input error!\n" );
        exit( EXIT_FAILURE );
    }

    //verify that input is in desired range
    if ( ! ( 1 <= num_days && num_days <= 10 ) )
    {
        printf( "Input out of range!\n" );
        exit( EXIT_FAILURE );
    }

    for ( int i = 0; i < num_days; i++ )
    {
        int num_read;

        //prompt user for input
        printf( "Enter day %d: ", i+1 );

        //attempt to read input
        if ( scanf( MAX_DAY_LENGTH_FORMAT_STRING "%n", names[i], &num_read ) != 1 )
        {
            printf( "input error!" );
            exit( EXIT_FAILURE );
        }

        //check whether input was small enough to fit in buffer
        if ( num_read == MAX_DAY_LENGTH && getchar() != '\n' )
        {
            printf( "Input too long to fit in buffer!\n" );
            exit( EXIT_FAILURE );
        }
    }

    //print input back to user
    printf("The first day is: %s\n", names[0]);
    printf("The fifth day is: %s\n", names[4]);

    return EXIT_SUCCESS;
}
```
<p>The program will now perform proper input validation instead of causing undefined behavior on bad input:</p>
<pre class="lang-none prettyprint-override"><code>How many days a week: abc
Input error!
</code>```

How many days a week: 11
Input out of range!
```
<pre class="lang-none prettyprint-override"><code>How many days a week: 7
Enter day 1: Monday
Enter day 2: Tuesday
Enter day 3: Wednesdaay
Input too long to fit in buffer!
</code>```

Body:
I want to make a multiple string of array but with just a one dimensional array, Is it possible?

#include <stdio.h>

int main()
{
    char name1[10];
    char name2[10];

    printf("Enter name1: ");
    scanf("%s", name1);

    printf("Enter name2: ");
    scanf("%s", name2);

    printf("\n%s", name1);
    printf("\n%s", name2);

    return 0;
}

I just started to learn array and I wanted to try to get multiple input from user and display only specific of the elements.
This is one of the code I tried before but it does not run.

int main()
{
    char *name[10];

    int i = 1, input;
    printf("How many days a week: ");
    scanf("%d", &input);

    do{
        printf("enter day %d: ", i);
        scanf("%s", name[i]);
        i++;
    }while(i < input);

    //output wanted
    printf("\n%s", name[0]);
    printf("\n%s", name[4]);

    return 0;
}

Body:
Your question is very unclear, but it sounds to me that you do not want a one-dimensional array, but rather a two-dimensional array (despite your question explicitly stating the opposite).

I suggest that you change char *name[10]; to char name[10][10]; Also, you may want to change the variable name of the 2D-array name to names, because that name is misleading, as it implies that it contains only a single string.

Also, you must start the loop counter i at 0, not 1, as array indexes are zero-based in C.

After making these changes, your program should look like this:

#include <stdio.h>

int main( void )
{
    char names[10][10];

    int i = 0, input;
    printf("How many days a week: ");
    scanf("%d", &input);

    do{
        printf("Enter day %d: ", i+1);
        scanf("%s", names[i]);
        i++;
    }while(i < input);

    //output wanted
    printf("The first day is: %s\n", names[0]);
    printf("The fifth day is: %s\n", names[4]);

    return 0;
}

This program has the following behavior:

How many days a week: 7
Enter day 1: Monday
Enter day 2: Tuesday
Enter day 3: Wednesday
Enter day 4: Thursday
Enter day 5: Friday
Enter day 6: Saturday
Enter day 7: Sunday
The first day is: Monday
The fifth day is: Friday

Note that the program will write to the array out of bounds if the user enters an integer larger than 10 or if any of the days has a length larger than 9 (10 including the terminating null character).

Also, your program would have a cleaner structure if you used a for loop instead of a while loop, as it reduces the scope of the loop counter.

Another issue is that the program will misbehave if the user does not enter a number. Instead, it should check if the function scanf succeeded, and to print an error message if it did not.

Therefore, it would be better to write it like this:

#include <stdio.h>
#include <stdlib.h>

#define MAX_DAYS 10

//MAX_DAY_LENGTH_FORMAT_STRING, which is used by scanf,
//should always be set to one less than MAX_DAY_LENGTH,
//because the latter also needs room for the terminating
//null character
#define MAX_DAY_LENGTH 10
#define MAX_DAY_LENGTH_FORMAT_STRING "%9s"

int main( void )
{
    char names[MAX_DAYS][MAX_DAY_LENGTH];
    int num_days;

    //prompt user for input
    printf( "How many days a week: " );

    //attempt to read input
    if ( scanf( "%d", &num_days ) != 1 )
    {
        printf( "Input error!\n" );
        exit( EXIT_FAILURE );
    }

    //verify that input is in desired range
    if ( ! ( 1 <= num_days && num_days <= 10 ) )
    {
        printf( "Input out of range!\n" );
        exit( EXIT_FAILURE );
    }

    for ( int i = 0; i < num_days; i++ )
    {
        int num_read;

        //prompt user for input
        printf( "Enter day %d: ", i+1 );

        //attempt to read input
        if ( scanf( MAX_DAY_LENGTH_FORMAT_STRING "%n", names[i], &num_read ) != 1 )
        {
            printf( "input error!" );
            exit( EXIT_FAILURE );
        }

        //check whether input was small enough to fit in buffer
        if ( num_read == MAX_DAY_LENGTH && getchar() != '\n' )
        {
            printf( "Input too long to fit in buffer!\n" );
            exit( EXIT_FAILURE );
        }
    }

    //print input back to user
    printf("The first day is: %s\n", names[0]);
    printf("The fifth day is: %s\n", names[4]);

    return EXIT_SUCCESS;
}

The program will now perform proper input validation instead of causing undefined behavior on bad input:

How many days a week: abc
Input error!

How many days a week: 11
Input out of range!

How many days a week: 7
Enter day 1: Monday
Enter day 2: Tuesday
Enter day 3: Wednesdaay
Input too long to fit in buffer!


问:
Replace logical values conditionally in R
I am sure this question has been asked before and has an easy solution, but I can't seem to find it.

I am trying to conditionally replace the logical value of a variable based on the value of other variables in the data. Specifically, I am trying to determine eligibility based on survey responses.

I have created my eligibility variable in dataframe screen:

```<code>screen$eligible <- ifelse (
                            (screen$age > 17 & screen$age < 23)
                           & (screen$alcohol > 3 | screen$marijuana > 3)
                           & (screen$country == 0 | screen$ageus < 12)
                           & (screen$county_1 == 17 | screen$county_1 == 27 | screen$county_1 == 31)
                           & (screen$residence_1 == 47),
                           TRUE,
                             FALSE)
</code>```

And now, based on study changes, I would like to further limit eligibility. I tried the code below, and it works in part, but it appears that I am introducing NAs to my eligibility variable and missing out on folks who should be eligible.

```<code>screen$eligible <- ifelse( screen$eligible ==TRUE, ifelse(
  (screen$gender_1 == 1 & screen$age > 18)
  |(screen$gender_8 == 1 & screen$age > 20),
  FALSE, TRUE), FALSE)
</code>```

I ultimately want TRUE or FALSE values.

Two questions

Is there a clearer or more concise way to update the code to update my eligibility requirements?

Any ideas as to why I might be introducing NAs?

答:
continuing from what @zephryl wrote, an even more readable code is:

screen$eligible <- with(screen,
   (age > 17 & age < 23)
   & (alcohol > 3 | marijuana > 3)
   & (country == 0 | ageus < 12)
   & county_1 %in% c(17, 27, 31)
   & (residence_1 == 47))
```
<ol start="2">
<li>to detect where are the NAs:</li>
</ol>
<pre class="lang-r prettyprint-override"><code>sapply(screen, anyNA)
</code>```

Body:
I am sure this question has been asked before and has an easy solution, but I can't seem to find it.

I am trying to conditionally replace the logical value of a variable based on the value of other variables in the data. Specifically, I am trying to determine eligibility based on survey responses.

I have created my eligibility variable in dataframe screen:

screen$eligible <- ifelse (
                            (screen$age > 17 & screen$age < 23)
                           & (screen$alcohol > 3 | screen$marijuana > 3)
                           & (screen$country == 0 | screen$ageus < 12)
                           & (screen$county_1 == 17 | screen$county_1 == 27 | screen$county_1 == 31)
                           & (screen$residence_1 == 47),
                           TRUE,
                             FALSE)

And now, based on study changes, I would like to further limit eligibility. I tried the code below, and it works in part, but it appears that I am introducing NAs to my eligibility variable and missing out on folks who should be eligible.

screen$eligible <- ifelse( screen$eligible ==TRUE, ifelse(
  (screen$gender_1 == 1 & screen$age > 18)
  |(screen$gender_8 == 1 & screen$age > 20),
  FALSE, TRUE), FALSE)

I ultimately want TRUE or FALSE values.

Two questions

Is there a clearer or more concise way to update the code to update my eligibility requirements?

Any ideas as to why I might be introducing NAs?

Body:
continuing from what @zephryl wrote, an even more readable code is:

screen$eligible <- with(screen,
   (age > 17 & age < 23)
   & (alcohol > 3 | marijuana > 3)
   & (country == 0 | ageus < 12)
   & county_1 %in% c(17, 27, 31)
   & (residence_1 == 47))

to detect where are the NAs:

sapply(screen, anyNA)


问:
Could not open input file: C:\Users\MyUsername
When trying to install a new laravel project
I type in this code on my cmd

```<code>    laravel new sitename
</code>```

and then the cmd shows this error:

Could not open input file: C:\Users\Leon

答:
To create a new laravel project use this in your cmd :</p>
```<code>composer create-project laravel/laravel your-project-name 4.2.*
</code>```

Body:
When trying to install a new laravel project
I type in this code on my cmd

    laravel new sitename

and then the cmd shows this error:

Could not open input file: C:\Users\Leon

Body:
To create a new laravel project use this in your cmd :

composer create-project laravel/laravel your-project-name 4.2.*


问:
SQL - Converting one value into two or more possible values
I have one table I would like to convert into another set of values.

Table A's Letter Column
Converts into

A
AA AND AB

B
BB

C
CC

So, what I am doing is...

SELECT all the values from Table A

Convert Table A's values using a CASE

```<code>CASE TABLE A COLUMN
 WHEN 'A' THEN 'AA'
 WHEN 'A' THEN 'AB'
 WHEN 'B' THEN 'BB'
 WHEN 'C' THEN 'CC'
 ELSE NULL
END
</code>```

Of course, a CASE statement can only have one outcome and thus I can't get it show both 'AA' and 'AB' when it converts 'A' from Table A. What can I do in this situation?

The expected outcome I want is that it would show (AA, AB, BB, and CC) using the input of (A, B, and C).

Let me know if this sounds confusing!
Thank you!

EDIT: For clarification... I modified the orignal above and added details below.

I have three values that I pulled from one table using a SELECT.

I want these three values to be shown in the converted form as 'AA', 'AB', 'BB', and 'CC'.

答:
You can join with subquery:

```<code>with mytable as (--this is example, use your table instead mytable CTE
select 'A' letter union all
select 'B' letter union all
select 'C' letter
)

select t.letter, conv.conv
  from mytable t
       inner join (--conversion data
                   select 'A' letter, 'AA' conv union all
                   select 'A' letter, 'AB' conv union all
                   select 'B' letter, 'BB' conv union all
                   select 'C' letter, 'CC' conv
                  ) conv on t.letter=conv.letter
</code>```

Result:

```<code>letter   conv
A        AA
A        AB
B        BB
C        CC
</code>```

Body:
I have one table I would like to convert into another set of values.

Table A's Letter Column
Converts into

A
AA AND AB

B
BB

C
CC

So, what I am doing is...

SELECT all the values from Table A

Convert Table A's values using a CASE

CASE TABLE A COLUMN
 WHEN 'A' THEN 'AA'
 WHEN 'A' THEN 'AB'
 WHEN 'B' THEN 'BB'
 WHEN 'C' THEN 'CC'
 ELSE NULL
END

Of course, a CASE statement can only have one outcome and thus I can't get it show both 'AA' and 'AB' when it converts 'A' from Table A. What can I do in this situation?

The expected outcome I want is that it would show (AA, AB, BB, and CC) using the input of (A, B, and C).

Let me know if this sounds confusing!
Thank you!

EDIT: For clarification... I modified the orignal above and added details below.

I have three values that I pulled from one table using a SELECT.

I want these three values to be shown in the converted form as 'AA', 'AB', 'BB', and 'CC'.

Body:
You can join with subquery:

with mytable as (--this is example, use your table instead mytable CTE
select 'A' letter union all
select 'B' letter union all
select 'C' letter
)

select t.letter, conv.conv
  from mytable t
       inner join (--conversion data
                   select 'A' letter, 'AA' conv union all
                   select 'A' letter, 'AB' conv union all
                   select 'B' letter, 'BB' conv union all
                   select 'C' letter, 'CC' conv
                  ) conv on t.letter=conv.letter

Result:

letter   conv
A        AA
A        AB
B        BB
C        CC


问:
ViewComponent does not render on _Layout file
I have added a ViewComponent  <vc:my-profile-menu /> in the _Layout file. On the development computer, it displays correctly, but when I deploy it to the server, it does not render. In the source view, I can see the code as plain text. I use ViewComponents in other areas of the site and those work fine. I also tried to render using @await Component.InvokeAsync("MyProfileMenu"), but then the page crashed on the server. It rendered fine on the local computer. Any suggestions would be appreciated. The application is in dotnet 6.

答: It seems like the problem has resolved itself as it is no longer an issue without any changes in the code.</p>


问:
How important is optimization?
I got into a bit of a debate yesterday with my boss about the proper role of optimization when building software. Essentially, his position was that optimization needs to be a primary concern during the entire process of development.

My opinion is that you need to make the right algorithmic decisions during development, but you should never be counting cycles during development. In fact, I feel so strongly about this I had to walk away from the conversation. I've seen too many bad programming decisions in the name of "optimization", and too much bad code defended with the excuse "this way is faster".

What does the StackOverflow.com community think?

答: Since with going with pithy, I'll say that optimization is as important as the impact of not doing it.</p>

OwnerDisplayName: dicroce

ContentLicense: CC BY-SA 2.5

Title: How important is optimization?

LastEditorDisplayName: jpalecek

OwnerDisplayName: MSN


问:
Why is QWidget's destructor not virtual?
Looking at qwidget.h, I found the destructor as below:

```<code>~QWidget();
</code>```

I was wondering why this is not declared as virtual

答: The destructor is virtual, because QWidget derives from QObject which does have a virtual destructor. Why it's not declared virtual in the code is a either style issue or a harmless mistake. I would have declared it virtual myself.</p>

Body:
Looking at qwidget.h, I found the destructor as below:

~QWidget();

I was wondering why this is not declared as virtual


问:
queryparm support in spring for restful web services
How can I get queryparam support of restful web service by spring in true restful manner...

for example  i have url like following

localhost:8080/myapp/booksearch/title/{title}/author/{author}?sortby=relevance&year=2013

title and author I can get by @PathVariable .....

where i want sortby and year optional..

答:
Spring annotation @RequestParam is used to get the query parameter while @PathVariable is used to get the variables in path or url which are declared with curly braces like localhost:8080/myapp/booksearch/title/{title}.

So in your case you need @RequestParam to get the sortedBy and year values. you can simply write public String getBooks(@RequestParam("sortby") String sortBy)


问:
Update application in already scaled out App Service
I'm generally confident in Azure App Service, however I can't find good documentation on how exactly Azure serves my new application if I deployed to an already scaled out App Service.

Say I have an app running and scaled to 5 instances (manually or auto scale, doesn't matter).

I now deploy a new version without staging slots. Directly into production.

How does Azure handle the scaled units now? Will new workers be warmed up and provisioned before my new application goes 'live'? Will there temporarily be 10 workers running my app?
Could it theoretically happen that 2/5 workers run the new version while 3/5 run the old one (for some time)?

Maybe I'm overseeing something or I'm thinking too complicated.

The only documentation I found was this web app architecture post. Still, it doesn't really answer my question.

答:
This is exactly why you use slots, so you can deploy to slots and make sure all is warmed up and then perform a slot swap.

If you deploy directly to production depending on how fast your application starts you might experience down time.


问:
Using regex to drop duplicated elements in columns of an R dataframe
I have a dummy dataframe df which has dimensions 6 X 4.

```<code>df <- data.frame(
 Hits = c("Hit1", "Hit2", "Hit3", "Hit4", "Hit5", "Hit6"),
 GO = c("GO:0005634~nucleus,", "", "GO:0005737~cytoplasm,", "GO:0005634~nucleus,GO:0005737~cytoplasm,", "",
            "GO:0005634~nucleus,GO:0005654~nucleoplasm,"),
 KEGG = c("", "", "", "", "", ""),
 SMART = c("SM00394:RIIa,", "SM00394:RIIa,", "", "SM00054:EFh,",
            "", "SM00394:RIIa,SM00239:C2,"))
</code>```

df looks like this

The elements in the columns consist of two parts:

an identifier (e.g. GO:0005634~, SM00394: etc.)

a term (e.g. nucleus, EFh etc.)

For each column I want to retain a row if it contains atleast one term which is not present in any row above it. e.g. in the column GO rows 1 and 3 contain unique terms, so these should be retained. Row 4 contains terms which are already present in rows 1 and 3, so it should be dropped. Row 6 has one term which is not present in any row above it, hence it should also be retained.

I have been able to come up with regular expressions to extract the terms from the columns GO and SMART

```<code>Regex for GO: (?<=~).*?(?=,(?:GO:\\d+~|$))
Regex for SMART: (?<=:).*?(?=,(?:\\w+\\d+:|$))
</code>```

But I'm unable to figure out a way to integrate the regex and the conditions mentioned above into a solution. The output should look like this

Any suggestions on how to solve this?

答:
Here is a general approach that will handle GO, SMART, and potentially KEGG, though it is impossible to say without any information about KEGG.

The function f below takes as arguments

x, a character vector

split, the delimiter separating items in lists

sep, the delimiter separating identifiers and terms within items

and returns a logical vector indexing the elements of x with at least one non-duplicated term.

f <- function(x, split, sep) {
    l1 <- strsplit(x, split)
    tt <- sub(paste0("^[^", sep, "]*", sep), "", unlist(l1))
    l2 <- relist(duplicated(tt), l1)
    !vapply(l2, all, NA)
}
```
<p>Applying <code>f</code> to <code>GO</code> and <code>SMART</code>:</p>
<pre class="lang-r prettyprint-override"><code>nms <- c("GO", "SMART")
l <- Map(f, x = df[nms], split = ",", sep = c("~", ":"))
l
## $GO
## [1]  TRUE FALSE  TRUE FALSE FALSE  TRUE
##
## $SMART
## [1]  TRUE FALSE FALSE  TRUE FALSE  TRUE
</code>```

Setting to "" elements of GO and SMART with zero non-duplicated terms, then filtering out empty rows, we obtain the desired result:

df2 <- df
df2[nms] <- Map(replace, df2[nms], lapply(l, `!`), "")
df2[Reduce(`|`, l), ]
##   Hits                                         GO KEGG                    SMART
## 1 Hit1                        GO:0005634~nucleus,                 SM00394:RIIa,
## 3 Hit3                      GO:0005737~cytoplasm,
## 4 Hit4                                                             SM00054:EFh,
## 6 Hit6 GO:0005634~nucleus,GO:0005654~nucleoplasm,      SM00394:RIIa,SM00239:C2,
```

Body:
I have a dummy dataframe df which has dimensions 6 X 4.

df <- data.frame(
 Hits = c("Hit1", "Hit2", "Hit3", "Hit4", "Hit5", "Hit6"),
 GO = c("GO:0005634~nucleus,", "", "GO:0005737~cytoplasm,", "GO:0005634~nucleus,GO:0005737~cytoplasm,", "",
            "GO:0005634~nucleus,GO:0005654~nucleoplasm,"),
 KEGG = c("", "", "", "", "", ""),
 SMART = c("SM00394:RIIa,", "SM00394:RIIa,", "", "SM00054:EFh,",
            "", "SM00394:RIIa,SM00239:C2,"))

df looks like this

The elements in the columns consist of two parts:

an identifier (e.g. GO:0005634~, SM00394: etc.)

a term (e.g. nucleus, EFh etc.)

For each column I want to retain a row if it contains atleast one term which is not present in any row above it. e.g. in the column GO rows 1 and 3 contain unique terms, so these should be retained. Row 4 contains terms which are already present in rows 1 and 3, so it should be dropped. Row 6 has one term which is not present in any row above it, hence it should also be retained.

I have been able to come up with regular expressions to extract the terms from the columns GO and SMART

Regex for GO: (?<=~).*?(?=,(?:GO:\\d+~|$))
Regex for SMART: (?<=:).*?(?=,(?:\\w+\\d+:|$))

But I'm unable to figure out a way to integrate the regex and the conditions mentioned above into a solution. The output should look like this

Any suggestions on how to solve this?

Body:
Here is a general approach that will handle GO, SMART, and potentially KEGG, though it is impossible to say without any information about KEGG.

The function f below takes as arguments

x, a character vector

split, the delimiter separating items in lists

sep, the delimiter separating identifiers and terms within items

and returns a logical vector indexing the elements of x with at least one non-duplicated term.

f <- function(x, split, sep) {
    l1 <- strsplit(x, split)
    tt <- sub(paste0("^[^", sep, "]*", sep), "", unlist(l1))
    l2 <- relist(duplicated(tt), l1)
    !vapply(l2, all, NA)
}

Applying f to GO and SMART:

nms <- c("GO", "SMART")
l <- Map(f, x = df[nms], split = ",", sep = c("~", ":"))
l
## $GO
## [1]  TRUE FALSE  TRUE FALSE FALSE  TRUE
##
## $SMART
## [1]  TRUE FALSE FALSE  TRUE FALSE  TRUE

Setting to "" elements of GO and SMART with zero non-duplicated terms, then filtering out empty rows, we obtain the desired result:

df2 <- df
df2[nms] <- Map(replace, df2[nms], lapply(l, `!`), "")
df2[Reduce(`|`, l), ]
##   Hits                                         GO KEGG                    SMART
## 1 Hit1                        GO:0005634~nucleus,                 SM00394:RIIa,
## 3 Hit3                      GO:0005737~cytoplasm,
## 4 Hit4                                                             SM00054:EFh,
## 6 Hit6 GO:0005634~nucleus,GO:0005654~nucleoplasm,      SM00394:RIIa,SM00239:C2,


问:
Is there a decent command Reference for VBA and Access 97?
I've spent the last weeks looking at some codes @ microsoft's website just to realize that I was looking @ VB.NET code instead of VBA.

Not that I know the diference between them.

But a good ref. library and documentation would help a lot, something similar to the javadocs.

I've been working with some export functions latetly and I can't find the full command list inside the software.

Any hints? Tips?
I'm not a total n00b at the subject and I'm just looking for a good place to start learning more than the basics.
But I don't wanna spend another week looking for a command to delete a file or to reorganize a CVS.

答:
Try using the Access 2003 VBA reference. It should be the same for most questions.

Also, there are an incredible number of discussions on other, less-distinguished forums about nearly anything you could want to do in VBA. I've never had trouble finding the answer to specific questions.


问:
Calling super method from interface
I want to call a super method from overriden method with the same name from an interface thats extending another interface

Example:

```<code>    default private interface A {
        void foo() {
            System.out.println("B");
        }
    }

    private interface B extends A {
        @Override
        default void foo() {
            System.out.println("B");
        }
    }
</code>```

I want to call classC(implements interface B).foo() ending with output

```<code>B
A.foo() call
</code>```

How can i achive this?

In my case i dont want to implement interface B, because it's a interface thats extending JpaRepository, and I'm just calling repository methods using only this interface.

UPDATE:

I gave the wrong example, thats not describing my problem. Below is the description of my specific problem.

Before saving object to db i want to make some actoions on this object. I'm using interface repositories. I want to override a Repository.save(Object o) method, and make changes there, but im just not able to call a super method from extended repository.

Example:

```<code>public interface FooRepository extends MongoRepository<Foo, String> {

    @Override
    default <S extends Foo> S save(S s) {
        s.doSth();
        return MongoRepository.super.save(s);   //This doesn't compile
    }
}
</code>```

I know i can do this by creating the class and injecting FooRepository in there, but is there any way to do this by overriding a save() method in FooRepository?

答:
In B interface in method foo() you can call A.foo() such way:

```<code>    @Override
    default void foo() {
        System.out.println("B");
        A.super.foo();
    }
</code>```

Title: Calling super method from interface

Body:
I want to call a super method from overriden method with the same name from an interface thats extending another interface

Example:

    default private interface A {
        void foo() {
            System.out.println("B");
        }
    }

    private interface B extends A {
        @Override
        default void foo() {
            System.out.println("B");
        }
    }

I want to call classC(implements interface B).foo() ending with output

B
A.foo() call

How can i achive this?

In my case i dont want to implement interface B, because it's a interface thats extending JpaRepository, and I'm just calling repository methods using only this interface.

UPDATE:

I gave the wrong example, thats not describing my problem. Below is the description of my specific problem.

Before saving object to db i want to make some actoions on this object. I'm using interface repositories. I want to override a Repository.save(Object o) method, and make changes there, but im just not able to call a super method from extended repository.

Example:

public interface FooRepository extends MongoRepository<Foo, String> {

    @Override
    default <S extends Foo> S save(S s) {
        s.doSth();
        return MongoRepository.super.save(s);   //This doesn't compile
    }
}

I know i can do this by creating the class and injecting FooRepository in there, but is there any way to do this by overriding a save() method in FooRepository?

Body:
In B interface in method foo() you can call A.foo() such way:

    @Override
    default void foo() {
        System.out.println("B");
        A.super.foo();
    }


问:
Why is this recursive solution faster than the iterative solution?
I wrote a recursive solution for something today, and as it goes, curiosity led me down a weird path. I wanted to see how an optimized recursive solution compares to an iterative solution so I chose a classic, the Nth Fibonacci to test with.

I was surprised to find that the recursive solution with memoization is much faster than the iterative solution and I would like to know why.

Here is the code (using python3):

import time
import sys
sys.setrecursionlimit(10000)

## recursive:
def fibr(n, memo = {}):
    if n <= 1:
        return n

    if n in memo:
        return memo[n]

    memo[n] = fibr(n-1, memo) + fibr(n-2, memo)

    return memo[n]

## iterative:
def fibi(n):
    a, b = 0, 1
    for _ in range(n):
        a, b = b, a + b
    return a

rstart = time.time()
for n in range(10000):
    fibr(n)
rend = time.time()

istart = time.time()
for n in range(10000):
    fibi(n)
iend = time.time()

print(f"recursive: {rend-rstart}")
print(f"iterative: {iend-istart}")
```
<p>My results:</p>
```recursive: 0.010010004043579102
iterative: 6.274333238601685
```
<p>Unless I'm mistaken, both the recursive solution and the iterative solution are about as optimized as they can get?  If I'm wrong about that, I'd like to know why.</p>
<p>If not, what would cause the iterative solution to be so much slower?  It seems to be slower for all values of <code>n</code>, but harder to notice when <code>n</code> is something more reasonable, like <code><1000</code>. (I'm using <code>10000</code> as you can see above)</p>
<p><strong>Some things I've tried:</strong></p>
<ol>
<li>I thought it might be the magic swapping in the iterative solution <code>a, b = b, a + b</code>, so I tried replacing it with a more traditional "swap" pattern:</li>
</ol>
<pre class="lang-py prettyprint-override"><code>tmp = a + b
a = b
b = tmp
#a, b = b, a + b
</code>```

But the results are basically the same, so that's not the problem there.

Re-arrange the code so that the iterative solution runs first, just to see if there was some weird cache issue at the OS level? It doesn't change the results so that's not it, probably?

My understanding here (and it might be wrong) is that the recursive solution with memoization is O(n). And the iterative solution is also O(n) simply because it iterates from 0..n.

Am I missing something really obvious?  I feel like I must be missing something here.

答:
You might expect that def fibr(n, memo = {}): — when called without a supplied memo — turns into something translated a bit like:

```<code>def _fibr_without_defaults(n, memo):
   ...

def fibr(n):
    return _fibr_without_defaults(n, {})
</code>```

That is, if memo is missing it implicitly gets a blank dictionary per your default.

In actuality, it translates into something more like:

```<code>def _fibr_without_defaults(n, memo):
   ...

_fibr_memo_default = {}
def fibr(n):
    return _fibr_without_defaults(n, _fibr_memo_default)
</code>```

That is, a default argument value is not "use this to construct a default value" but instead "use this actual value by default". Every single call to fibr you make (without supplying memo) is sharing a default memo dictionary.

That means in:

```<code>for n in range(10000):
    fibr(n)
</code>```

The prior iterations of your loop are filling out memo for the future iterations. When n is 1000, for example, all the work performed by n<=999 is still stored.

By contrast, the iterative version always starts iterating from 0, no matter what work prior iterative calls performed.

If you perform the translation above by hand, so that you really do get a fresh empty memo for each call, you'll see the iterative version is faster. (Makes sense; inserting things into a dictionary and retrieving them just to do the same work as simple iteration will be slower.)

Body:
I wrote a recursive solution for something today, and as it goes, curiosity led me down a weird path. I wanted to see how an optimized recursive solution compares to an iterative solution so I chose a classic, the Nth Fibonacci to test with.

I was surprised to find that the recursive solution with memoization is much faster than the iterative solution and I would like to know why.

Here is the code (using python3):

import time
import sys
sys.setrecursionlimit(10000)

## recursive:
def fibr(n, memo = {}):
    if n <= 1:
        return n

    if n in memo:
        return memo[n]

    memo[n] = fibr(n-1, memo) + fibr(n-2, memo)

    return memo[n]

## iterative:
def fibi(n):
    a, b = 0, 1
    for _ in range(n):
        a, b = b, a + b
    return a

rstart = time.time()
for n in range(10000):
    fibr(n)
rend = time.time()

istart = time.time()
for n in range(10000):
    fibi(n)
iend = time.time()

print(f"recursive: {rend-rstart}")
print(f"iterative: {iend-istart}")

My results:

recursive: 0.010010004043579102
iterative: 6.274333238601685

Unless I'm mistaken, both the recursive solution and the iterative solution are about as optimized as they can get?  If I'm wrong about that, I'd like to know why.

If not, what would cause the iterative solution to be so much slower?  It seems to be slower for all values of n, but harder to notice when n is something more reasonable, like <1000. (I'm using 10000 as you can see above)

Some things I've tried:

I thought it might be the magic swapping in the iterative solution a, b = b, a + b, so I tried replacing it with a more traditional "swap" pattern:

tmp = a + b
a = b
b = tmp
#a, b = b, a + b

But the results are basically the same, so that's not the problem there.

Re-arrange the code so that the iterative solution runs first, just to see if there was some weird cache issue at the OS level? It doesn't change the results so that's not it, probably?

My understanding here (and it might be wrong) is that the recursive solution with memoization is O(n). And the iterative solution is also O(n) simply because it iterates from 0..n.

Am I missing something really obvious?  I feel like I must be missing something here.

Body:
You might expect that def fibr(n, memo = {}): — when called without a supplied memo — turns into something translated a bit like:

def _fibr_without_defaults(n, memo):
   ...

def fibr(n):
    return _fibr_without_defaults(n, {})

That is, if memo is missing it implicitly gets a blank dictionary per your default.

In actuality, it translates into something more like:

def _fibr_without_defaults(n, memo):
   ...

_fibr_memo_default = {}
def fibr(n):
    return _fibr_without_defaults(n, _fibr_memo_default)

That is, a default argument value is not "use this to construct a default value" but instead "use this actual value by default". Every single call to fibr you make (without supplying memo) is sharing a default memo dictionary.

That means in:

for n in range(10000):
    fibr(n)

The prior iterations of your loop are filling out memo for the future iterations. When n is 1000, for example, all the work performed by n<=999 is still stored.

By contrast, the iterative version always starts iterating from 0, no matter what work prior iterative calls performed.

If you perform the translation above by hand, so that you really do get a fresh empty memo for each call, you'll see the iterative version is faster. (Makes sense; inserting things into a dictionary and retrieving them just to do the same work as simple iteration will be slower.)


问:
how to stop or wait other api call untill token is stored in angular12
Hi im calling a token api from my app.component. Reason why im calling it from app.component is that, i dont have any login page. After getting the access token, im storing it in local storage.
Issue is that the token is not getting attached to the http headers for other apis. They are asynchronously called from other components. So they doesnt wait for my token api to execute.

But when im trying to call it again , it is working fine as expected. My requirement is that other request should be called after the execution of token api,

I have tried so many things like delay(),timer() but doesn't work. Please help me

Httpinterceptor

```<code>intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
request = request.clone({
    headers: new HttpHeaders({
      'Content-Type': 'application/json',
      'Access-Token': localStorage.getItem('accessToken') || '',
    })

  })
     return next.handle(request)
   }
</code>```

答:
You can use tap(). I'm using this in my Authgard in canActivate(). It will wait until your service has loaded and stored the datas locally.

```<code>canActivate(): Observable<boolean> {
    return this.yourService.yourFunction().pipe(
            tap(yourBoolean => {
                if (!yourBoolean ) {
                    this.router.navigate(['/otherpage']);
                }
            }),
        );
}
</code>```

-> https://rxjs.dev/api/operators/tap

Body:
Hi im calling a token api from my app.component. Reason why im calling it from app.component is that, i dont have any login page. After getting the access token, im storing it in local storage.
Issue is that the token is not getting attached to the http headers for other apis. They are asynchronously called from other components. So they doesnt wait for my token api to execute.

But when im trying to call it again , it is working fine as expected. My requirement is that other request should be called after the execution of token api,

I have tried so many things like delay(),timer() but doesn't work. Please help me

Httpinterceptor

intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
request = request.clone({
    headers: new HttpHeaders({
      'Content-Type': 'application/json',
      'Access-Token': localStorage.getItem('accessToken') || '',
    })

  })
     return next.handle(request)
   }

Body:
You can use tap(). I'm using this in my Authgard in canActivate(). It will wait until your service has loaded and stored the datas locally.

canActivate(): Observable<boolean> {
    return this.yourService.yourFunction().pipe(
            tap(yourBoolean => {
                if (!yourBoolean ) {
                    this.router.navigate(['/otherpage']);
                }
            }),
        );
}

-> https://rxjs.dev/api/operators/tap


问:
Publishing markers in rviz
I am new to ros and I'm following the tutorials on ros wiki.
Now I am trying to visualize a marker in rviz, but it doesn't work.
I have followed the steps and created the file basic_shapes.cpp but when I run it and chance the fixed frame I don't see anything.
If I do the command "rostopic echo /visualisation_markers" it returns "WARNING: topic [/visualisation_markers] does not appear to be published yet".
Does somebody know what I do wrong?

Thanks!

答: You need to add "Marker" to RViz. Click on Add button in the RViz window and then add it. Then you can check that whether this topic exists by doing "rostopic list". If you see /visualization_marker in it, you're good to go!</p>

Title: Publishing markers in rviz


问:
How do I modify a look and feel system class such as com.sun.java.swing.plaf.windows.WindowsTableHeaderUI
I need to make a change to this class, there is no way for me to just subclass in normal way. So I can modify the java file (or make a copy of it) but how do I get my Swing application to use this version instead of the one provided by the Java runtime?

What I am trying to do is make a copy of  com.sun.java.swing.plaf.windows.WindowsTableHeaderUI and fix it, so I cant just create a copy of the class sand put it into my own pacakage hierachy as I dont have access to many of the classes referred to in the class (such as XPStyle) so how do i replace the system class?

答:
So I got it working as follows:

git clone https://github.com/AdoptOpenJDK/openjdk-jdk11.git

Copied the following files from src/java.desktop/windows/classes/com/sun/java/swing/plaf/windows - WindowsTableHeaderUI.java, TMSchema.java, XPStyle.java into my code tree

Modified the package statement for these three files to match they have been placed

Added the following to allow the internal classes to be found

--add-exports java.desktop/sun.awt.windows=ALL-UNNAMED

--add-exports java.desktop/sun.awt.image=ALL-UNNAMED

--add-exports java.desktop/sun.swing.table=ALL-UNNAMED

--add-exports java.desktop/sun.swing=ALL-UNNAMED

--add-exports java.desktop/com.sun.java.swing.plaf.windows=ALL-UNNAMED
--add-exports java.base/sun.security.action=ALL-UNNAMED

A few minor changes to allow classes to compile

Implemented my fix for the WindowsTableHeaderUI class

Used in application but only if on Windows with

```<code> if(Platform.isWindows())
 {
      UIManager.put("TableHeaderUI","com.jthink.jaikoz.tablerenderer.windows.WindowsTableHeaderUI");
 }
</code>```

When build on other platforms such as MacOS/Linux I delete the windows java files (WindowsTableHeaderUI.java, TMSchema.java, XPStyle.java)  as we only every use these classes on Windows to allow code to be built.

Body:
So I got it working as follows:

git clone https://github.com/AdoptOpenJDK/openjdk-jdk11.git

Copied the following files from src/java.desktop/windows/classes/com/sun/java/swing/plaf/windows - WindowsTableHeaderUI.java, TMSchema.java, XPStyle.java into my code tree

Modified the package statement for these three files to match they have been placed

Added the following to allow the internal classes to be found

--add-exports java.desktop/sun.awt.windows=ALL-UNNAMED

--add-exports java.desktop/sun.awt.image=ALL-UNNAMED

--add-exports java.desktop/sun.swing.table=ALL-UNNAMED

--add-exports java.desktop/sun.swing=ALL-UNNAMED

--add-exports java.desktop/com.sun.java.swing.plaf.windows=ALL-UNNAMED
--add-exports java.base/sun.security.action=ALL-UNNAMED

A few minor changes to allow classes to compile

Implemented my fix for the WindowsTableHeaderUI class

Used in application but only if on Windows with

 if(Platform.isWindows())
 {
      UIManager.put("TableHeaderUI","com.jthink.jaikoz.tablerenderer.windows.WindowsTableHeaderUI");
 }

When build on other platforms such as MacOS/Linux I delete the windows java files (WindowsTableHeaderUI.java, TMSchema.java, XPStyle.java)  as we only every use these classes on Windows to allow code to be built.


问:
Android Studio : Dialog Box not keeping the same format as its custom layout
On completing an order in my application a dialog box opens with a custom layout .xml file, for some further options. The dialog box has some of the features of the custom layout like color and some of the buttons but doesn't show it correctly. I tried playing with the dimensions of the layout but unfortunately it doesn't fix the format issue.

Any help appreciated!

Here is the code for the dialog box

`

```<code>private AlertDialog.Builder dialogBuilder;
private AlertDialog dialog;
private Button btnCard, btn50, btn20, btn10, btn5, btnCancel, btnReturnO;
private int stopperDialog =0;
public void finishOrderDialog(){
    dialogBuilder = new AlertDialog.Builder(this);
    final View finishPopupView = getLayoutInflater().inflate(R.layout.popup, null);
    btnCard = (Button) finishPopupView.findViewById(R.id.btnCard);
    btn50 = (Button) finishPopupView.findViewById(R.id.btn50);
    btn20 = (Button) finishPopupView.findViewById(R.id.btn20);
    btn10 = (Button) finishPopupView.findViewById(R.id.btn10);
    btn5 = (Button) finishPopupView.findViewById(R.id.btn5);
    btnCancel = (Button) finishPopupView.findViewById(R.id.btnCancel);
    btnReturnO = (Button) finishPopupView.findViewById(R.id.btnReturnO);

    DisplayMetrics metrics = getResources().getDisplayMetrics();
    int width = metrics.widthPixels;
    int height = metrics.heightPixels;

    dialogBuilder.setView(finishPopupView);
    dialog = dialogBuilder.create();
    dialog.show();
    dialog.getWindow().setLayout(width, (4*height)/5);

    btnReturnO.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            dialog.dismiss();
        }
    });
}`
</code>```

XML File

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

<Button
    android:id="@+id/btnCancel"
    android:layout_width="159dp"
    android:layout_height="79dp"
    android:text="Cancel Order"
    android:textStyle="bold"
    android:textColor="@color/black"
    android:textSize="20dp"
    android:backgroundTint="#F80000"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.616"
    app:layout_constraintHorizontal_bias="0.346"/>

<Button
    android:id="@+id/btnReturnO"
    android:layout_width="159dp"
    android:layout_height="79dp"
    android:text="Return to Order"
    android:textStyle="bold"
    android:textColor="@color/black"
    android:textSize="20dp"
    android:backgroundTint="#F80000"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.616"
    app:layout_constraintHorizontal_bias="0.646"/>

<Button
    android:id="@+id/btn50"
    android:layout_width="159dp"
    android:layout_height="79dp"
    android:text="50"
    android:textStyle="bold"
    android:textColor="@color/black"
    android:textSize="20dp"
    android:backgroundTint="#00BEF8"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.046"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<Button
    android:id="@+id/btnCard"
    android:layout_width="159dp"
    android:layout_height="79dp"
    android:text="Card"
    android:textStyle="bold"
    android:textColor="@color/black"
    android:textSize="20dp"
    android:backgroundTint="#85F800"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.398" />

<Button
    android:id="@+id/btn20"
    android:layout_width="159dp"
    android:layout_height="79dp"
    android:text="20"
    android:textStyle="bold"
    android:textColor="@color/black"
    android:textSize="20dp"
    android:backgroundTint="#00BEF8"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.346"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<Button
    android:id="@+id/btn10"
    android:layout_width="159dp"
    android:layout_height="79dp"
    android:text="10"
    android:textStyle="bold"
    android:textColor="@color/black"
    android:textSize="20dp"
    android:backgroundTint="#00BEF8"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.646"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<Button
    android:id="@+id/btn5"
    android:layout_width="159dp"
    android:layout_height="79dp"
    android:text="5"
    android:textStyle="bold"
    android:textColor="@color/black"
    android:textSize="20dp"
    android:backgroundTint="#00BEF8"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.946"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

答:
you can try change your xml like this

your problem is to set layout_constraint every button,
hope can solve your problem :)

Body:
On completing an order in my application a dialog box opens with a custom layout .xml file, for some further options. The dialog box has some of the features of the custom layout like color and some of the buttons but doesn't show it correctly. I tried playing with the dimensions of the layout but unfortunately it doesn't fix the format issue.

Any help appreciated!

Here is the code for the dialog box

`

private AlertDialog.Builder dialogBuilder;
private AlertDialog dialog;
private Button btnCard, btn50, btn20, btn10, btn5, btnCancel, btnReturnO;
private int stopperDialog =0;
public void finishOrderDialog(){
    dialogBuilder = new AlertDialog.Builder(this);
    final View finishPopupView = getLayoutInflater().inflate(R.layout.popup, null);
    btnCard = (Button) finishPopupView.findViewById(R.id.btnCard);
    btn50 = (Button) finishPopupView.findViewById(R.id.btn50);
    btn20 = (Button) finishPopupView.findViewById(R.id.btn20);
    btn10 = (Button) finishPopupView.findViewById(R.id.btn10);
    btn5 = (Button) finishPopupView.findViewById(R.id.btn5);
    btnCancel = (Button) finishPopupView.findViewById(R.id.btnCancel);
    btnReturnO = (Button) finishPopupView.findViewById(R.id.btnReturnO);

    DisplayMetrics metrics = getResources().getDisplayMetrics();
    int width = metrics.widthPixels;
    int height = metrics.heightPixels;

    dialogBuilder.setView(finishPopupView);
    dialog = dialogBuilder.create();
    dialog.show();
    dialog.getWindow().setLayout(width, (4*height)/5);

    btnReturnO.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            dialog.dismiss();
        }
    });
}`

XML File

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

<Button
    android:id="@+id/btnCancel"
    android:layout_width="159dp"
    android:layout_height="79dp"
    android:text="Cancel Order"
    android:textStyle="bold"
    android:textColor="@color/black"
    android:textSize="20dp"
    android:backgroundTint="#F80000"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.616"
    app:layout_constraintHorizontal_bias="0.346"/>

<Button
    android:id="@+id/btnReturnO"
    android:layout_width="159dp"
    android:layout_height="79dp"
    android:text="Return to Order"
    android:textStyle="bold"
    android:textColor="@color/black"
    android:textSize="20dp"
    android:backgroundTint="#F80000"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.616"
    app:layout_constraintHorizontal_bias="0.646"/>

<Button
    android:id="@+id/btn50"
    android:layout_width="159dp"
    android:layout_height="79dp"
    android:text="50"
    android:textStyle="bold"
    android:textColor="@color/black"
    android:textSize="20dp"
    android:backgroundTint="#00BEF8"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.046"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<Button
    android:id="@+id/btnCard"
    android:layout_width="159dp"
    android:layout_height="79dp"
    android:text="Card"
    android:textStyle="bold"
    android:textColor="@color/black"
    android:textSize="20dp"
    android:backgroundTint="#85F800"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.398" />

<Button
    android:id="@+id/btn20"
    android:layout_width="159dp"
    android:layout_height="79dp"
    android:text="20"
    android:textStyle="bold"
    android:textColor="@color/black"
    android:textSize="20dp"
    android:backgroundTint="#00BEF8"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.346"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<Button
    android:id="@+id/btn10"
    android:layout_width="159dp"
    android:layout_height="79dp"
    android:text="10"
    android:textStyle="bold"
    android:textColor="@color/black"
    android:textSize="20dp"
    android:backgroundTint="#00BEF8"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.646"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<Button
    android:id="@+id/btn5"
    android:layout_width="159dp"
    android:layout_height="79dp"
    android:text="5"
    android:textStyle="bold"
    android:textColor="@color/black"
    android:textSize="20dp"
    android:backgroundTint="#00BEF8"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.946"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>


问:
C++ unordered_set of vectors
Can I create a unordered_set of vectors in C++? something like this

```<code>std::unordered_set<std::vector<int>> s1;
</code>```

because I know that is possible with the "set" class of the std lib but seems that it doesn't work for the unordered version
thanks

Update:
this is the exactly code that I'm trying to use

```<code>typedef int CustomerId;
typedef std::vector<CustomerId> Route;
typedef std::unordered_set<Route> Plan;

// ... in the main
Route r1 = { 4, 5, 2, 10 };
Route r2 = { 1, 3, 8 , 6 };
Route r3 = { 9, 7 };
Plan p = { r1, r2 };
</code>```

and it's all right if I use set, but I receive a compilation error when try to use the unordered version

```<code>main.cpp:46:11: error: non-aggregate type 'Route' (aka 'vector<CustomerId>') cannot be initialized with an initializer list
    Route r3 = { 9, 7 };
</code>```

答:
As an alternative to a custom-written hasher, Boost provides a hasher for many standard library types. This should work in your case:

```<code>#include <boost/container_hash/hash.hpp>

std::unordered_set<
  std::vector<int>,
  boost::hash<std::vector<int>>
> s1;
</code>```

Reference: https://www.boost.org/doc/libs/1_78_0/doc/html/hash/reference.html

In older Boost versions, the header file was boost/functional/hash.hpp.

Title: C++ unordered_set of vectors

Body:
Can I create a unordered_set of vectors in C++? something like this

std::unordered_set<std::vector<int>> s1;

because I know that is possible with the "set" class of the std lib but seems that it doesn't work for the unordered version
thanks

Update:
this is the exactly code that I'm trying to use

typedef int CustomerId;
typedef std::vector<CustomerId> Route;
typedef std::unordered_set<Route> Plan;

// ... in the main
Route r1 = { 4, 5, 2, 10 };
Route r2 = { 1, 3, 8 , 6 };
Route r3 = { 9, 7 };
Plan p = { r1, r2 };

and it's all right if I use set, but I receive a compilation error when try to use the unordered version

main.cpp:46:11: error: non-aggregate type 'Route' (aka 'vector<CustomerId>') cannot be initialized with an initializer list
    Route r3 = { 9, 7 };

Body:
As an alternative to a custom-written hasher, Boost provides a hasher for many standard library types. This should work in your case:

#include <boost/container_hash/hash.hpp>

std::unordered_set<
  std::vector<int>,
  boost::hash<std::vector<int>>
> s1;

Reference: https://www.boost.org/doc/libs/1_78_0/doc/html/hash/reference.html

In older Boost versions, the header file was boost/functional/hash.hpp.


问:
Variables get corrupted
I’m developing an iPhone App using Objective-C, based on Apple’s UIKit.

I’ve created some class instance in UIViewController and found my class instance pointer get corrupted randomly. Due to class instance pointer corrupted, I always get an EXC_BAD_ACCESS crash like this:
    Exception Type:  EXC_BAD_ACCESS (SIGSEGV)
    Exception Codes: KERN_INVALID_ADDRESS at 0xa095633c
    Crashed Thread:  0

It shows that when my code is trying to access the class instance, it’s already turned into a ridiculous address:0xa095633c, which is beyond memory space and even binary image space.

Does any have any suggestion what kind of incorrect coding could possibly lead to class instance get corrupted?

答: EXC_BAD_ACCESS usually indicates a memory management error. Read the Memory Management Programming Guide and make sure you conform to all the rules about alloc/retain/release/etc.</p>

Title: Variables get corrupted


问:
mongoose convert all leaned ObjectIds to String format
I'm using mongoose-paginate-v2 to paginate my documents, and I use lean=true to make them a plain Object (I want to filter them using accesscontrol.

When I get the leaned Objects , all ObjectIds are in Object formate like below:

```<code>{"_id":{"_bsontype":"ObjectID","id":{"type":"Buffer","data":[95,94,16,4,98,8,156,8,236,35,179,155]}}
</code>```

I get that its the way that MongoDB handles it but I want to send String ObjectId to the client (so that it can access resources with that Id). I know that by using vituals and id instead of _id I can get the string representation of that object's _id, but the problem is I want All ids to be string, not just the id of the object.

If I try to write a middleware that changes all id objects to string representation, I'll need a way to deep find all ids in my result , which I don't know how to do.

How an I have all ids in string format, yet still have leaned object?

答:
May be a little late in replying, we can use lodash transform for this-

var transform = require('lodash.transform');
var isObject = require('lodash.isobject');
const ObjectId = require('mongoose').Types.ObjectId;

const transformObjectId = obj => transform(obj, (acc, value, key, target) => {
    if(value instanceof ObjectId){
        acc[key] = value ? value.toString() : '';
    } else if(value instanceof Date){
        acc[key] = value;
    }else{
        acc[key] = isObject(value) ? transformObjectId(value) : value;
    }
  })

module.exports = {
    transformObjectId: transformObjectId
}```

Body:
I'm using mongoose-paginate-v2 to paginate my documents, and I use lean=true to make them a plain Object (I want to filter them using accesscontrol.

When I get the leaned Objects , all ObjectIds are in Object formate like below:

{"_id":{"_bsontype":"ObjectID","id":{"type":"Buffer","data":[95,94,16,4,98,8,156,8,236,35,179,155]}}

I get that its the way that MongoDB handles it but I want to send String ObjectId to the client (so that it can access resources with that Id). I know that by using vituals and id instead of _id I can get the string representation of that object's _id, but the problem is I want All ids to be string, not just the id of the object.

If I try to write a middleware that changes all id objects to string representation, I'll need a way to deep find all ids in my result , which I don't know how to do.

How an I have all ids in string format, yet still have leaned object?