问:
Firebase OAuth2 signInWithRedirect() occasionally infinite loop, but not always
I am using google firebase 11.4.2 with React 18.2.0
I have implemented Google and Yahoo OAuth2 login on my app using firebase's authentication methods.

My problem is that only with certain users, about 1/10, experience being redirected to select the Oauth login page, an infinite loop according to other similarly posted problems.

I have two questions: Why are only certain users having this issue, and the second question is: where in my code am I going wrong with the proper order of operations. The order of my code is as follows:

```<code>useEffect(() => {
        redirResults();
}, [])

const handleLogin = async (e) => {
        e.preventDefault()
        // there are Google & Yahoo buttons for the user to click/choose
        let authP = e.target.name

        try {
            switch(authP) {
                case "google":
                    await signInWithRedirect(auth, gProvider)
                    break;
                case "yahoo":
                    await signInWithRedirect(auth, yProvider)
                    break;
                default:
                    console.log('Error, try again.')
            }
        } catch (error) {
            if (error) {
                console.log(error)
            }
        }
    }

const redirResults = async () => {

        await getRedirectResult(auth)
            .then((result) => {
                const user = result.user;

                if (result) {
                    Swal.fire({
                        title: 'Loading...',
                        timer: 1000,
                        didOpen: () => {
                            Swal.showLoading()
                        }
                    })
                }
                // sets my user object internally
                dispatch({ type: 'LOGIN', payload: user })
                // checking for existing account, if not one,
                // automatically make one based
                // on the users OAuth data
                checkForExistingUser(user);

            })
            .catch((error) => {
                //  console.log(error.code)
                //  console.log(error.message)
                //  console.log(error.customData?.email)
            })
    }

const checkForExistingUser = async (user) => {

        const userRef = doc(db, 'users', user.uid)
        const docSnap = await getDoc(userRef)

        if (docSnap.exists()) {
            console.log('already exists!!!!!!');
            navigate('/dashboard')
        } else {
            // console.log('doesnt exist yet');
            await setDoc(doc(db, 'users', user.uid), {
                email: user.email,
                emailVerified: true,
                img: user.photoURL || '',
                timeStamp: serverTimestamp(),
                username: user.displayName || '',
            })
            navigate('/dashboard')
        }
    }
</code>```

Please advise if there is more information that you need to help me come to a conclusion. Thanks in advance to everyone for their help, as always.
Cheers~

Body:
I am using google firebase 11.4.2 with React 18.2.0
I have implemented Google and Yahoo OAuth2 login on my app using firebase's authentication methods.

My problem is that only with certain users, about 1/10, experience being redirected to select the Oauth login page, an infinite loop according to other similarly posted problems.

I have two questions: Why are only certain users having this issue, and the second question is: where in my code am I going wrong with the proper order of operations. The order of my code is as follows:

useEffect(() => {
        redirResults();
}, [])

const handleLogin = async (e) => {
        e.preventDefault()
        // there are Google & Yahoo buttons for the user to click/choose
        let authP = e.target.name

        try {
            switch(authP) {
                case "google":
                    await signInWithRedirect(auth, gProvider)
                    break;
                case "yahoo":
                    await signInWithRedirect(auth, yProvider)
                    break;
                default:
                    console.log('Error, try again.')
            }
        } catch (error) {
            if (error) {
                console.log(error)
            }
        }
    }

const redirResults = async () => {

        await getRedirectResult(auth)
            .then((result) => {
                const user = result.user;

                if (result) {
                    Swal.fire({
                        title: 'Loading...',
                        timer: 1000,
                        didOpen: () => {
                            Swal.showLoading()
                        }
                    })
                }
                // sets my user object internally
                dispatch({ type: 'LOGIN', payload: user })
                // checking for existing account, if not one,
                // automatically make one based
                // on the users OAuth data
                checkForExistingUser(user);

            })
            .catch((error) => {
                //  console.log(error.code)
                //  console.log(error.message)
                //  console.log(error.customData?.email)
            })
    }

const checkForExistingUser = async (user) => {

        const userRef = doc(db, 'users', user.uid)
        const docSnap = await getDoc(userRef)

        if (docSnap.exists()) {
            console.log('already exists!!!!!!');
            navigate('/dashboard')
        } else {
            // console.log('doesnt exist yet');
            await setDoc(doc(db, 'users', user.uid), {
                email: user.email,
                emailVerified: true,
                img: user.photoURL || '',
                timeStamp: serverTimestamp(),
                username: user.displayName || '',
            })
            navigate('/dashboard')
        }
    }

Please advise if there is more information that you need to help me come to a conclusion. Thanks in advance to everyone for their help, as always.
Cheers~


来源: stackexchange

问:
Subroutine to convert inputted string into lowercase letters
I am trying to make a subroutine that takes inputs from another subroutine and turn them into lowercase letters.

`

```<code>

Load StringAddress
Store AddressString
JnS subInputString
JnS subToLower
JnS subPrintString

Halt

StringAddress,  HEX 287 / This is the starting address of the string

////////////////////////////////////////////////////////////////////////
// Task 2.2 - Subroutine for printing strings
////////////////////////////////////////////////////////////////////////

subPrintString, HEX 000 / subroutine start
        Load StringAddress
                Store Temp

LoopExit, LoadI Temp
          Skipcond 800
          Jump EndOut
          Output
          Load Temp
          Add One
          Store Temp
          Jump LoopExit

EndOut, Load NewLine
    JumpI subPrintString

One, DEC 1
NewLine, HEX 0A

Temp, HEX 0
CurrentCharacterADR, ADR TheName
TheName, HEX 41
         HEX 68
         HEX 6D
         HEX 61
         HEX 64
         HEX 20
         HEX 4D
         HEX 75
         HEX 69
         HEX 7A
         HEX 7A
         HEX 0

////////////////////////////////////////////////////////////////////////
// Task 2.3 - Subroutine for string input
////////////////////////////////////////////////////////////////////////

subInputString, HEX 000 / subroutine start
stringIn,       Input
                Skipcond 800
                Jump EndOut2
                StoreI AddressString
                Load AddressString
        Add One2
                Store AddressString
                Jump stringIn

EndOut2, Load NewLine2
     JumpI subInputString

NewLine2, HEX 0A
One2, DEC 1
AddressString, HEX 0
////////////////////////////////////////////////////////////////////////
// Task 2.4 - Subroutine to convert to lower case
////////////////////////////////////////////////////////////////////////

subToLower, HEX 000     / subroutine start
toLowerLoop,    Load AddressString
        Add stringIterate
        Store stringIndex
        Clear
                Add stringIndex
                Skipcond 400
                Jump lowerConversion
                JumpI subToLower

lowerConversion, Add upperToLower
             Output
                 Load stringIterate
         Add One3
         Store stringIterate
         Jump toLowerLoop

One3, DEC 1
lowerCase, HEX 0
upperToLower, HEX 20
lowerString, HEX 0
stringIndex, HEX 0
stringIterate, DEC 0
</code>```

For example, if I input in 'GO' in unicode (and then 0 in hexadecimal or decimal to stop the input subroutine), the expected output is 'go' but instead the output is still 'GO'. I don't understand why it's still printing in uppercase?

ContentLicense: CC BY-SA 4.0

Body:
I am trying to make a subroutine that takes inputs from another subroutine and turn them into lowercase letters.

`

Load StringAddress
Store AddressString
JnS subInputString
JnS subToLower
JnS subPrintString

Halt

StringAddress,  HEX 287 / This is the starting address of the string

////////////////////////////////////////////////////////////////////////
// Task 2.2 - Subroutine for printing strings
////////////////////////////////////////////////////////////////////////

subPrintString, HEX 000 / subroutine start
        Load StringAddress
                Store Temp

LoopExit, LoadI Temp
          Skipcond 800
          Jump EndOut
          Output
          Load Temp
          Add One
          Store Temp
          Jump LoopExit

EndOut, Load NewLine
    JumpI subPrintString

One, DEC 1
NewLine, HEX 0A

Temp, HEX 0
CurrentCharacterADR, ADR TheName
TheName, HEX 41
         HEX 68
         HEX 6D
         HEX 61
         HEX 64
         HEX 20
         HEX 4D
         HEX 75
         HEX 69
         HEX 7A
         HEX 7A
         HEX 0

////////////////////////////////////////////////////////////////////////
// Task 2.3 - Subroutine for string input
////////////////////////////////////////////////////////////////////////

subInputString, HEX 000 / subroutine start
stringIn,       Input
                Skipcond 800
                Jump EndOut2
                StoreI AddressString
                Load AddressString
        Add One2
                Store AddressString
                Jump stringIn

EndOut2, Load NewLine2
     JumpI subInputString

NewLine2, HEX 0A
One2, DEC 1
AddressString, HEX 0
////////////////////////////////////////////////////////////////////////
// Task 2.4 - Subroutine to convert to lower case
////////////////////////////////////////////////////////////////////////

subToLower, HEX 000     / subroutine start
toLowerLoop,    Load AddressString
        Add stringIterate
        Store stringIndex
        Clear
                Add stringIndex
                Skipcond 400
                Jump lowerConversion
                JumpI subToLower

lowerConversion, Add upperToLower
             Output
                 Load stringIterate
         Add One3
         Store stringIterate
         Jump toLowerLoop

One3, DEC 1
lowerCase, HEX 0
upperToLower, HEX 20
lowerString, HEX 0
stringIndex, HEX 0
stringIterate, DEC 0

For example, if I input in 'GO' in unicode (and then 0 in hexadecimal or decimal to stop the input subroutine), the expected output is 'go' but instead the output is still 'GO'. I don't understand why it's still printing in uppercase?


问:
Having trouble with content projection from a remote server?
I'm trying to build an e-commerce store through angular. As I'm migrating my data from a local server to a remote server, the content that is intended to show up on my product detail page is not showing up. Buttons and headers are appearing but not the product details. The product list data is showing up with not problems. However, when I try to use a get request to obtain product data by ID, nothing is showing up.

Here is my detail page's get request:
`

```<code>    getProduct(): void {
        const id = parseInt(this.route.snapshot.paramMap.get('id')!, 10);
        this.cartService.getProduct(id)
        .subscribe(product => this.product = product);
</code>```

Here is my method from my cart service page:

```<code>    getProduct(id:number): Observable<Product> {
      const url = `${this.productsURL}/?${id}`;
      return this.http.get<Product>(this.productsURL).pipe(
        tap(),
           );
     }
</code>```

Here is the data that I am trying to retrieve from my remote server:

```<code>    {
        "products": [
          {
            "id": 1,
            "name": "Autographed picture of the BRC CEO",
            "price": 69,
            "productImage":   "https://lh5.googleusercontent.com"
            "preview": "Be you Be Andy2",
            "description": ""

          },

          {
        "id": 2,
        "name": "JT's  Clothes ",
        "price": 42,
        "productImage": "https://lh6.googleusercontent.com/",
        "preview": "Buy Now ",
        "description": ""

          }
        ]
    }
</code>```

Lastly, Here is the HTML Page where the content is to be projected:

```<code>
    <div *ngIf="product">
      <h3 class="details-product-name" >  {{product.name }}</h3>
      <img src={{product.productImage}}>
      <h3 class="description-header">Description</h3>
      <p class="product-description">{{ product.description }}</p>
      <h4 class="item-price">{{ product.price | currency }}</h4>
     <button (click)="addToCart(product)" class="add-to-cart">Add to Cart</button>
     <button (click)=onBuy() class="buy-it-now"> Buy </button>

    </div>

</code>```

Any help would be greatly appreciated.

Using the angular tutorial page,googling other e-commerce store examples, checking for other similar issues on stack overflow.

Body:
I'm trying to build an e-commerce store through angular. As I'm migrating my data from a local server to a remote server, the content that is intended to show up on my product detail page is not showing up. Buttons and headers are appearing but not the product details. The product list data is showing up with not problems. However, when I try to use a get request to obtain product data by ID, nothing is showing up.

Here is my detail page's get request:
`

    getProduct(): void {
        const id = parseInt(this.route.snapshot.paramMap.get('id')!, 10);
        this.cartService.getProduct(id)
        .subscribe(product => this.product = product);

Here is my method from my cart service page:

    getProduct(id:number): Observable<Product> {
      const url = `${this.productsURL}/?${id}`;
      return this.http.get<Product>(this.productsURL).pipe(
        tap(),
           );
     }

Here is the data that I am trying to retrieve from my remote server:

    {
        "products": [
          {
            "id": 1,
            "name": "Autographed picture of the BRC CEO",
            "price": 69,
            "productImage":   "https://lh5.googleusercontent.com"
            "preview": "Be you Be Andy2",
            "description": ""

          },

          {
        "id": 2,
        "name": "JT's  Clothes ",
        "price": 42,
        "productImage": "https://lh6.googleusercontent.com/",
        "preview": "Buy Now ",
        "description": ""

          }
        ]
    }

Lastly, Here is the HTML Page where the content is to be projected:

  {{product.name }}

Description

{{ product.description }}

{{ product.price | currency }}

     <button (click)="addToCart(product)" class="add-to-cart">Add to Cart</button>
     <button (click)=onBuy() class="buy-it-now"> Buy </button>

Any help would be greatly appreciated.

Using the angular tutorial page,googling other e-commerce store examples, checking for other similar issues on stack overflow.


问:
Retrieving links of previous and next posts in the same Category and Tag as current post - WordPress
Currently I have WordPress posts in a Category and a Tag called 'Blog post'. I want to navigate through the posts with the same Tag (Blog post / same tag as current post) and the same Category as current post, by getting the links to previous and next post. Each post only has one Category and one Tag.

I know I can get and echo my current post Category and Tag like this (I have tested the code):

global $post; $postcat = get_the_category( $post->ID ); /*ECHO POST CATEGORY NAME*/ if ( ! empty( $postcat ) ) {     echo esc_html( $postcat[0]->name );  } $posttags = get_the_tags($post->ID); /*ECHO POST TAG NAME*/ if ( ! empty( $posttags) ) {     echo esc_html( $posttags[0]->name );  }

But what I don't know is how I could loop through WordPress posts and get the links to previous and next post with the same Category and Tag. I'm not a very experienced coder and I'm in a bit of a pickle here.
I'd really appreciate it if someone helped out, thanks!


问:
Flutter Incorrectly Rendering Array Of Values
In a Flutter app I'm making, users can create "listings" of objects they are interested in selling.  All listings for a user are displayed on their profile page in an array  On the profile page the user can click a floating action button which will take them to another page where they can create an additional listing.

Profile Page Image

When the user creates this new listing, and clicks the back arrow to go back to the profile home page, I return the new listing they just created, add it to the array that holds all listings, and call setstate.

```<code>onTap: () {
  Navigator.of(context).push(MaterialPageRoute(
      builder: (context) =>
          CreateNewListing(local_user: widget.local_user)))
  .then((value) { // if new listing is created, it's returned and inserted at start of list
    if(value != null) {
      setState(() {
        user_listings.insert(0, value);
      });
    }
  });
},
</code>```

The problem is that the new listing shows up, but it has all the information of the listing that used to be in the first index of the array.

Example Image Of Problem

So in the image above ^, the top listing is entriely different from the "English Book" one, but visually they seem the same.  The title of the top listing should actually be "Science Book", and all of its values (price, description, etc..) should be different. If I click on the top listing it redirects me to a page where I can view that listings information, and I can then see that it's not a duplicate listing.  If I insert the new listing at the end of the array it works fine, but I want to be able to insert it at index 0 so the most recently created listing is at the top.  Below is the important parts of my code:

```<code>class _ProfileHomeState extends State<ProfileHome> with AutomaticKeepAliveClientMixin<ProfileHome> {
  @override
  bool get wantKeepAlive => true;

  bool data_retrieved = false;
  late List<Listing> user_listings; // USER LISTINGS STORED HERE

  @override
  void initState() {
    super.initState();
    retrieveData(); // GETS ALL USER LISTINGS FROM API CALL
    setPresets(); // SETS VARIABLES ABOUT USER (NAME, EMAIL, ETC..)
  }

  @override
  Widget build(BuildContext context) {
    if (data_retrieved) {
      return Scaffold(
        floatingActionButton: SizedBox(
          height: 60,
          width: 60,
          child: Material(
            type: MaterialType.transparency,
            child: Ink(
              decoration: BoxDecoration(
                border: Border.all(color: Colors.green, width: 3.0),
                color: Colors.greenAccent,
                shape: BoxShape.circle,
              ),
              child: InkWell(
                borderRadius: BorderRadius.circular(500.0),
                onTap: () {
                  Navigator.of(context).push(MaterialPageRoute(
                      builder: (context) =>
                          CreateNewListing(local_user: widget.local_user))) // new listings created in this page
                  .then((value) { // if new listing is created, it's returned and inserted at start of list
                    if(value != null) {
                      setState(() {
                        user_listings.insert(0, value); // listing inserted at front of array here
                      });
                    }
                  });
                },
                child: const Icon(
                  Icons.add,
                  //size: 50,
                ),
              ),
            ),
          ),
        ),
        resizeToAvoidBottomInset: false,
        backgroundColor: BODY_BACKGROUND_COLOR,
        body: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              // safe area containing the title of the page the user is on
              returnPageHeader(context, "profile", widget.local_user, updateUserState),
              // Row will contain profile pic, name, and email address
              Row(
                children: <Widget>[
                  // profile pic
                  Align(
                      alignment: Alignment.centerLeft,
                      child: CircleAvatar(
                        backgroundImage: using_default_image
                            ? AssetImage(profile_pic) as ImageProvider
                            : NetworkImage(profile_pic),
                        radius: 50,
                      )),
                  // full name and email address
                  Align(
                      alignment: Alignment.centerRight,
                      child: Column(
                        children: <Widget>[
                          Text(first_name + " " + last_name),
                          Text(email),
                          Text(school),
                        ],
                      )),
                ],
              ),
              // list is iterated through and listings are displayed
              Expanded(
                  child: RefreshIndicator(
                    child: ListView.builder(
                        itemCount: user_listings.length,
                        shrinkWrap: true,
                        padding: const EdgeInsets.only(top: 0),
                        itemBuilder: (context, index) {
                          return UserListing(listing: user_listings[index]);
                        }),
                    onRefresh: () async {
                      var cancel_loading_indicator = showLoadingIndicator();
                      await retrieveData(); // if refresh is trigged, the listings are retrieved from the api
                      cancel_loading_indicator();
                    },
                  )), // And rest of them in ListView
            ]),
      );
    } else {
      //data hasn't been retrieved yet so return progress indicator
      return Container(
        color: Colors.grey.shade700,
        child: CircularProgressIndicator(
          backgroundColor: Colors.grey.shade700,
          color: Colors.deepOrange[300],
        ),
      );
    }
  }
}
</code>```

The wrapper class I'm using to display the listings is a stateful widget:

```<code>class UserListing extends StatefulWidget {
  Listing listing;

  UserListing({Key? key, required this.listing}) : super(key: key);

  @override
  State<UserListing> createState() => _UserListingState();
}

class _UserListingState extends State<UserListing> {
  late String listing_name;
  late String listing_description;
  late String listing_category;
  late String listing_condition;
  late String listing_price;
  late String listing_pic;
  late bool using_default_image;
  late bool is_archived;

  void setPresets() {
    listing_name = widget.listing.getListingName;
    listing_description = widget.listing.getListingDescription;
    listing_category = widget.listing.getListingCategory;
    listing_condition = widget.listing.getListingCondition;
    listing_price = widget.listing.getListingPrice;
    is_archived = widget.listing.isArchived;
    listing_pic = widget.listing.getListingImage;
    using_default_image = widget.listing.usingDefaultImage;
  }

  @override
  void initState() {
    super.initState();
    setPresets();
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
        onTap: () {
          Navigator.of(context)
              .push(MaterialPageRoute(
                  builder: (context) =>
                      IndividualListingView(listing: widget.listing)))
              .then((value) {
            setState(() {
              widget.listing = value;
              setPresets();
            });
          });
        },
        child: returnListingEntry(
            context,
            using_default_image,
            listing_pic,
            listing_name,
            listing_description,
            listing_category,
            listing_condition,
            listing_price,
            is_archived));
  }
}
</code>```

Inserting the new listing at the end of the array works fine, but I would like it to be inserted in index 0, so the most recent listing is always displayed at the top of the page.

Body:
In a Flutter app I'm making, users can create "listings" of objects they are interested in selling.  All listings for a user are displayed on their profile page in an array  On the profile page the user can click a floating action button which will take them to another page where they can create an additional listing.

Profile Page Image

When the user creates this new listing, and clicks the back arrow to go back to the profile home page, I return the new listing they just created, add it to the array that holds all listings, and call setstate.

onTap: () {
  Navigator.of(context).push(MaterialPageRoute(
      builder: (context) =>
          CreateNewListing(local_user: widget.local_user)))
  .then((value) { // if new listing is created, it's returned and inserted at start of list
    if(value != null) {
      setState(() {
        user_listings.insert(0, value);
      });
    }
  });
},

The problem is that the new listing shows up, but it has all the information of the listing that used to be in the first index of the array.

Example Image Of Problem

So in the image above ^, the top listing is entriely different from the "English Book" one, but visually they seem the same.  The title of the top listing should actually be "Science Book", and all of its values (price, description, etc..) should be different. If I click on the top listing it redirects me to a page where I can view that listings information, and I can then see that it's not a duplicate listing.  If I insert the new listing at the end of the array it works fine, but I want to be able to insert it at index 0 so the most recently created listing is at the top.  Below is the important parts of my code:

class _ProfileHomeState extends State<ProfileHome> with AutomaticKeepAliveClientMixin<ProfileHome> {
  @override
  bool get wantKeepAlive => true;

  bool data_retrieved = false;
  late List<Listing> user_listings; // USER LISTINGS STORED HERE

  @override
  void initState() {
    super.initState();
    retrieveData(); // GETS ALL USER LISTINGS FROM API CALL
    setPresets(); // SETS VARIABLES ABOUT USER (NAME, EMAIL, ETC..)
  }

  @override
  Widget build(BuildContext context) {
    if (data_retrieved) {
      return Scaffold(
        floatingActionButton: SizedBox(
          height: 60,
          width: 60,
          child: Material(
            type: MaterialType.transparency,
            child: Ink(
              decoration: BoxDecoration(
                border: Border.all(color: Colors.green, width: 3.0),
                color: Colors.greenAccent,
                shape: BoxShape.circle,
              ),
              child: InkWell(
                borderRadius: BorderRadius.circular(500.0),
                onTap: () {
                  Navigator.of(context).push(MaterialPageRoute(
                      builder: (context) =>
                          CreateNewListing(local_user: widget.local_user))) // new listings created in this page
                  .then((value) { // if new listing is created, it's returned and inserted at start of list
                    if(value != null) {
                      setState(() {
                        user_listings.insert(0, value); // listing inserted at front of array here
                      });
                    }
                  });
                },
                child: const Icon(
                  Icons.add,
                  //size: 50,
                ),
              ),
            ),
          ),
        ),
        resizeToAvoidBottomInset: false,
        backgroundColor: BODY_BACKGROUND_COLOR,
        body: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              // safe area containing the title of the page the user is on
              returnPageHeader(context, "profile", widget.local_user, updateUserState),
              // Row will contain profile pic, name, and email address
              Row(
                children: <Widget>[
                  // profile pic
                  Align(
                      alignment: Alignment.centerLeft,
                      child: CircleAvatar(
                        backgroundImage: using_default_image
                            ? AssetImage(profile_pic) as ImageProvider
                            : NetworkImage(profile_pic),
                        radius: 50,
                      )),
                  // full name and email address
                  Align(
                      alignment: Alignment.centerRight,
                      child: Column(
                        children: <Widget>[
                          Text(first_name + " " + last_name),
                          Text(email),
                          Text(school),
                        ],
                      )),
                ],
              ),
              // list is iterated through and listings are displayed
              Expanded(
                  child: RefreshIndicator(
                    child: ListView.builder(
                        itemCount: user_listings.length,
                        shrinkWrap: true,
                        padding: const EdgeInsets.only(top: 0),
                        itemBuilder: (context, index) {
                          return UserListing(listing: user_listings[index]);
                        }),
                    onRefresh: () async {
                      var cancel_loading_indicator = showLoadingIndicator();
                      await retrieveData(); // if refresh is trigged, the listings are retrieved from the api
                      cancel_loading_indicator();
                    },
                  )), // And rest of them in ListView
            ]),
      );
    } else {
      //data hasn't been retrieved yet so return progress indicator
      return Container(
        color: Colors.grey.shade700,
        child: CircularProgressIndicator(
          backgroundColor: Colors.grey.shade700,
          color: Colors.deepOrange[300],
        ),
      );
    }
  }
}

The wrapper class I'm using to display the listings is a stateful widget:

class UserListing extends StatefulWidget {
  Listing listing;

  UserListing({Key? key, required this.listing}) : super(key: key);

  @override
  State<UserListing> createState() => _UserListingState();
}

class _UserListingState extends State<UserListing> {
  late String listing_name;
  late String listing_description;
  late String listing_category;
  late String listing_condition;
  late String listing_price;
  late String listing_pic;
  late bool using_default_image;
  late bool is_archived;

  void setPresets() {
    listing_name = widget.listing.getListingName;
    listing_description = widget.listing.getListingDescription;
    listing_category = widget.listing.getListingCategory;
    listing_condition = widget.listing.getListingCondition;
    listing_price = widget.listing.getListingPrice;
    is_archived = widget.listing.isArchived;
    listing_pic = widget.listing.getListingImage;
    using_default_image = widget.listing.usingDefaultImage;
  }

  @override
  void initState() {
    super.initState();
    setPresets();
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
        onTap: () {
          Navigator.of(context)
              .push(MaterialPageRoute(
                  builder: (context) =>
                      IndividualListingView(listing: widget.listing)))
              .then((value) {
            setState(() {
              widget.listing = value;
              setPresets();
            });
          });
        },
        child: returnListingEntry(
            context,
            using_default_image,
            listing_pic,
            listing_name,
            listing_description,
            listing_category,
            listing_condition,
            listing_price,
            is_archived));
  }
}

Inserting the new listing at the end of the array works fine, but I would like it to be inserted in index 0, so the most recent listing is always displayed at the top of the page.


问:
Spring Boot Spring-Data-JPA and Hibernate - java.lang.IllegalStateException: Required identifier property not found for class
I have simple Spring-boot application, I am using spring-data-jpa and hibernate. Looks like my
LocalContainerEntityManagerFactoryBean is not recognizing hibernate., It complaints my Entity class does not have identifier.

```<code>package com.abc.xyz.config;

import com.zaxxer.hikari.HikariDataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import java.util.Properties;

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        //basePackages = {"com.abc.xyz.jpa"},
        entityManagerFactoryRef = "localContainerEntityManagerFactoryBean",
        transactionManagerRef = "platformTransactionManager"
)
@PropertySource("classpath:db_config.properties")
public class OracleConfig {

    @Bean
    @ConfigurationProperties("spring.datasource.oracle.hikari")
    public DataSource dbvpOracleDataSource() {
        return new HikariDataSource();
    }

    @Bean
    @ConfigurationProperties("spring.jpa.properties.oracle")
    public Properties oracleProperties() {
        return new Properties();
    }

    @Bean
    public LocalContainerEntityManagerFactoryBean oracleEntityManagerFactory(
            DataSource  dbvpOracleDataSource,  Properties  oracleProperties
                        )
    {
        LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
        factory.setDataSource(dbvpOracleDataSource);
        factory.setPackagesToScan(new String[]{"com.abc.xyz.model.dto"});
        factory.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
        factory.setJpaProperties(oracleProperties);
        return factory;
    }

    @Bean
    public PlatformTransactionManager oracleTransactionManager(
            LocalContainerEntityManagerFactoryBean oracleEntityManagerFactory)
    {
        return  new JpaTransactionManager(oracleEntityManagerFactory.getObject());
    }

}

</code>```
```<code>import lombok.*;

import javax.persistence.*;
import java.sql.Timestamp;

@Data
@Entity
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Setter
@Getter
@Table(name = "ENDPNT_DEF", schema = "DBVP", uniqueConstraints = @UniqueConstraint(columnNames = {"NM_VAL", "STAT_CDE"}))
public class Endpoint  {

    @Id
    @SequenceGenerator(name = "abcseq", sequenceName="XYZ.ABC_SEQ", allocationSize=1)
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "abcdSeq")
    @Column(name = "ENDPNT_DEF_ID", unique = true, nullable = false, precision = 10, scale = 0)
    //@org.springframework.data.annotation.Id
    private Long id;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "ABC_BUS_UNT_ID", nullable = false)
    private BusinessUnit businessUnit;

    @Column(name = "TYP_CDE", nullable = false, length = 14)
    private String type;

    @Column(name = "PRTY_NBR", nullable = false, precision = 2, scale = 0)
    private Integer priority ;

    @Column(name = "NM_VAL", unique = true, nullable = false, length = 40)
    private String name;

    @Column(name = "DSC_VAL", nullable = false, length = 400)
    private String description;

    @Column(name = "MK_DMMY_FL_IND", nullable = false, length = 1)
    private String makeDummy;

    @Column(name = "STAT_CDE", nullable = false, length = 10)
    private String status;

    @Column(name = "CRTE_TMS", insertable = false, updatable = false, length = 6)
    private Timestamp createdTimestamp;

    @Column(name = "UPD_USR_NM", nullable = false, length = 20)
    private String updatedBy;

    @Column(name = "UPD_TMS", insertable = false, updatable = false, length = 6)
    private Timestamp updatedTimestamp;

    @Column(name = "ACCT_NBR_VAL", nullable = true, length = 40)
    private String accountNumber;

    @Column(name = "RLTNSHP", length = 20)
    private String relationship;

}
</code>```

I Think LocalContainerEntityManagerFactoryBean not recognizing hibernate vendor.

If I add the spring-data-annotations @org.springframework.data.annotation.Id - Id then code works But It ignores the @Name Entity and generates the code with bean name convention I have tried adding the

```<code>spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
</code>```

but No luck

Logs:

```<code>Caused by: java.lang.IllegalStateException: Required identifier property not found for class com.abc.xyz.model.dto.Endpoint!
    at org.springframework.data.mapping.PersistentEntity.getRequiredIdProperty(PersistentEntity.java:105) ~[spring-data-commons-2.1.6.RELEASE.jar:2.1.6.RELEASE]
    at org.springframework.data.relational.core.mapping.RelationalPersistentEntityImpl.getIdColumn(RelationalPersistentEntityImpl.java:65) ~[spring-data-jdbc-1.0.6.RELEASE.jar:1.0.6.RELEASE]
    at org.springframework.data.jdbc.core.SqlGenerator.lambda$addColumnsAndJoinsForOneToOneReferences$3(SqlGenerator.java:199) ~[spring-data-jdbc-1.0.6.RELEASE.jar:1.0.6.RELEASE]
    at org.springframework.data.jdbc.core.SelectBuilder.join(SelectBuilder.java:83) ~[spring-data-jdbc-1.0.6.RELEASE.jar:1.0.6.RELEASE]
    at org.springframework.data.jdbc.core.SqlGenerator.addColumnsAndJoinsForOneToOneReferences(SqlGenerator.java:198) ~[spring-data-jdbc-1.0.6.RELEASE.jar:1.0.6.RELEASE]
    at org.springframework.data.jdbc.core.SqlGenerator.createSelectBuilder(SqlGenerator.java:175) ~[spring-data-jdbc-1.0.6.RELEASE.jar:1.0.6.RELEASE]
    at org.springframework.data.jdbc.core.SqlGenerator.createFindAllSql(SqlGenerator.java:242) ~[spring-data-jdbc-1.0.6.RELEASE.jar:1.0.6.RELEASE]
    at org.springframework.data.util.Lazy.getNullable(Lazy.java:211) ~[spring-data-commons-2.1.6.RELEASE.jar:2.1.6.RELEASE]
    at org.springframework.data.util.Lazy.get(Lazy.java:94) ~[spring-data-commons-2.1.6.RELEASE.jar:2.1.6.RELEASE]
    at org.springframework.data.jdbc.core.SqlGenerator.getFindAll(SqlGenerator.java:106) ~[spring-data-jdbc-1.0.6.RELEASE.jar:1.0.6.RELEASE]
    at org.springframework.data.jdbc.core.DefaultDataAccessStrategy.findAll(DefaultDataAccessStrategy.java:217) ~[spring-data-jdbc-1.0.6.RELEASE.jar:1.0.6.RELEASE]
    at org.springframework.data.jdbc.core.JdbcAggregateTemplate.findAll(JdbcAggregateTemplate.java:158) ~[spring-data-jdbc-1.0.6.RELEASE.jar:1.0.6.RELEASE]
    at org.springframework.data.jdbc.repository.support.SimpleJdbcRepository.findAll(SimpleJdbcRepository.java:84) ~[spring-data-jdbc-1.0.6.RELEASE.jar:1.0.6.RELEASE]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.8.0_241]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[?:1.8.0_241]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:1.8.0_241]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[?:1.8.0_241]
    at org.springframework.data.repository.core.support.RepositoryComposition$RepositoryFragments.invoke(RepositoryComposition.java:359) ~[spring-data-commons-2.1.6.RELEASE.jar:2.1.6.RELEASE]
    at org.springframework.data.repository.core.support.RepositoryComposition.invoke(RepositoryComposition.java:200) ~[spring-data-commons-2.1.6.RELEASE.jar:2.1.6.RELEASE]
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$ImplementationMethodExecutionInterceptor.invoke(RepositoryFactorySupport.java:644) ~[spring-data-commons-2.1.6.RELEASE.jar:2.1.6.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:608) ~[spring-data-commons-2.1.6.RELEASE.jar:2.1.6.RELEASE]
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.lambda$invoke$3(RepositoryFactorySupport.java:595) ~[spring-data-commons-2.1.6.RELEASE.jar:2.1.6.RELEASE]
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:595) ~[spring-data-commons-2.1.6.RELEASE.jar:2.1.6.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:59) ~[spring-data-commons-2.1.6.RELEASE.jar:2.1.6.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:294) ~[spring-tx-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:98) ~[spring-tx-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139) ~[spring-tx-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:93) ~[spring-aop-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.data.repository.core.support.SurroundingTransactionDetectorMethodInterceptor.invoke(SurroundingTransactionDetectorMethodInterceptor.java:61) ~[spring-data-commons-2.1.6.RELEASE.jar:2.1.6.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212) ~[spring-aop-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at com.sun.proxy.$Proxy87.findAll(Unknown Source) ~[?:?]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.8.0_241]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[?:1.8.0_241]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:1.8.0_241]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[?:1.8.0_241]
    at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:343) ~[spring-aop-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:198) ~[spring-aop-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163) ~[spring-aop-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139) ~[spring-tx-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212) ~[spring-aop-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at com.sun.proxy.$Proxy87.findAll(Unknown Source) ~[?:?]
    at com.discover.dbvorg.BenchmarkConfigSync.run(BenchmarkConfigSync.java:37) ~[main/:?]
</code>```

I tried adding

```<code>@org.springframework.data.annotation.Id
</code>```

It slove the problem but it generate the query but it Ignores the @Name and @Column annotations. The query is generated using default strategy. I have also added

```<code>spring:
  jpa:
    hibernate:
      naming:
        physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
        implicit-strategy: org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl
</code>```

Still the query generated used the bean name and property names.

Body:
I have simple Spring-boot application, I am using spring-data-jpa and hibernate. Looks like my
LocalContainerEntityManagerFactoryBean is not recognizing hibernate., It complaints my Entity class does not have identifier.

package com.abc.xyz.config;

import com.zaxxer.hikari.HikariDataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import java.util.Properties;

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        //basePackages = {"com.abc.xyz.jpa"},
        entityManagerFactoryRef = "localContainerEntityManagerFactoryBean",
        transactionManagerRef = "platformTransactionManager"
)
@PropertySource("classpath:db_config.properties")
public class OracleConfig {

    @Bean
    @ConfigurationProperties("spring.datasource.oracle.hikari")
    public DataSource dbvpOracleDataSource() {
        return new HikariDataSource();
    }

    @Bean
    @ConfigurationProperties("spring.jpa.properties.oracle")
    public Properties oracleProperties() {
        return new Properties();
    }

    @Bean
    public LocalContainerEntityManagerFactoryBean oracleEntityManagerFactory(
            DataSource  dbvpOracleDataSource,  Properties  oracleProperties
                        )
    {
        LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
        factory.setDataSource(dbvpOracleDataSource);
        factory.setPackagesToScan(new String[]{"com.abc.xyz.model.dto"});
        factory.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
        factory.setJpaProperties(oracleProperties);
        return factory;
    }

    @Bean
    public PlatformTransactionManager oracleTransactionManager(
            LocalContainerEntityManagerFactoryBean oracleEntityManagerFactory)
    {
        return  new JpaTransactionManager(oracleEntityManagerFactory.getObject());
    }

}

import lombok.*;

import javax.persistence.*;
import java.sql.Timestamp;

@Data
@Entity
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Setter
@Getter
@Table(name = "ENDPNT_DEF", schema = "DBVP", uniqueConstraints = @UniqueConstraint(columnNames = {"NM_VAL", "STAT_CDE"}))
public class Endpoint  {

    @Id
    @SequenceGenerator(name = "abcseq", sequenceName="XYZ.ABC_SEQ", allocationSize=1)
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "abcdSeq")
    @Column(name = "ENDPNT_DEF_ID", unique = true, nullable = false, precision = 10, scale = 0)
    //@org.springframework.data.annotation.Id
    private Long id;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "ABC_BUS_UNT_ID", nullable = false)
    private BusinessUnit businessUnit;

    @Column(name = "TYP_CDE", nullable = false, length = 14)
    private String type;

    @Column(name = "PRTY_NBR", nullable = false, precision = 2, scale = 0)
    private Integer priority ;

    @Column(name = "NM_VAL", unique = true, nullable = false, length = 40)
    private String name;

    @Column(name = "DSC_VAL", nullable = false, length = 400)
    private String description;

    @Column(name = "MK_DMMY_FL_IND", nullable = false, length = 1)
    private String makeDummy;

    @Column(name = "STAT_CDE", nullable = false, length = 10)
    private String status;

    @Column(name = "CRTE_TMS", insertable = false, updatable = false, length = 6)
    private Timestamp createdTimestamp;

    @Column(name = "UPD_USR_NM", nullable = false, length = 20)
    private String updatedBy;

    @Column(name = "UPD_TMS", insertable = false, updatable = false, length = 6)
    private Timestamp updatedTimestamp;

    @Column(name = "ACCT_NBR_VAL", nullable = true, length = 40)
    private String accountNumber;

    @Column(name = "RLTNSHP", length = 20)
    private String relationship;

}

I Think LocalContainerEntityManagerFactoryBean not recognizing hibernate vendor.

If I add the spring-data-annotations @org.springframework.data.annotation.Id - Id then code works But It ignores the @Name Entity and generates the code with bean name convention I have tried adding the

spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl

but No luck

Logs:

Caused by: java.lang.IllegalStateException: Required identifier property not found for class com.abc.xyz.model.dto.Endpoint!
    at org.springframework.data.mapping.PersistentEntity.getRequiredIdProperty(PersistentEntity.java:105) ~[spring-data-commons-2.1.6.RELEASE.jar:2.1.6.RELEASE]
    at org.springframework.data.relational.core.mapping.RelationalPersistentEntityImpl.getIdColumn(RelationalPersistentEntityImpl.java:65) ~[spring-data-jdbc-1.0.6.RELEASE.jar:1.0.6.RELEASE]
    at org.springframework.data.jdbc.core.SqlGenerator.lambda$addColumnsAndJoinsForOneToOneReferences$3(SqlGenerator.java:199) ~[spring-data-jdbc-1.0.6.RELEASE.jar:1.0.6.RELEASE]
    at org.springframework.data.jdbc.core.SelectBuilder.join(SelectBuilder.java:83) ~[spring-data-jdbc-1.0.6.RELEASE.jar:1.0.6.RELEASE]
    at org.springframework.data.jdbc.core.SqlGenerator.addColumnsAndJoinsForOneToOneReferences(SqlGenerator.java:198) ~[spring-data-jdbc-1.0.6.RELEASE.jar:1.0.6.RELEASE]
    at org.springframework.data.jdbc.core.SqlGenerator.createSelectBuilder(SqlGenerator.java:175) ~[spring-data-jdbc-1.0.6.RELEASE.jar:1.0.6.RELEASE]
    at org.springframework.data.jdbc.core.SqlGenerator.createFindAllSql(SqlGenerator.java:242) ~[spring-data-jdbc-1.0.6.RELEASE.jar:1.0.6.RELEASE]
    at org.springframework.data.util.Lazy.getNullable(Lazy.java:211) ~[spring-data-commons-2.1.6.RELEASE.jar:2.1.6.RELEASE]
    at org.springframework.data.util.Lazy.get(Lazy.java:94) ~[spring-data-commons-2.1.6.RELEASE.jar:2.1.6.RELEASE]
    at org.springframework.data.jdbc.core.SqlGenerator.getFindAll(SqlGenerator.java:106) ~[spring-data-jdbc-1.0.6.RELEASE.jar:1.0.6.RELEASE]
    at org.springframework.data.jdbc.core.DefaultDataAccessStrategy.findAll(DefaultDataAccessStrategy.java:217) ~[spring-data-jdbc-1.0.6.RELEASE.jar:1.0.6.RELEASE]
    at org.springframework.data.jdbc.core.JdbcAggregateTemplate.findAll(JdbcAggregateTemplate.java:158) ~[spring-data-jdbc-1.0.6.RELEASE.jar:1.0.6.RELEASE]
    at org.springframework.data.jdbc.repository.support.SimpleJdbcRepository.findAll(SimpleJdbcRepository.java:84) ~[spring-data-jdbc-1.0.6.RELEASE.jar:1.0.6.RELEASE]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.8.0_241]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[?:1.8.0_241]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:1.8.0_241]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[?:1.8.0_241]
    at org.springframework.data.repository.core.support.RepositoryComposition$RepositoryFragments.invoke(RepositoryComposition.java:359) ~[spring-data-commons-2.1.6.RELEASE.jar:2.1.6.RELEASE]
    at org.springframework.data.repository.core.support.RepositoryComposition.invoke(RepositoryComposition.java:200) ~[spring-data-commons-2.1.6.RELEASE.jar:2.1.6.RELEASE]
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$ImplementationMethodExecutionInterceptor.invoke(RepositoryFactorySupport.java:644) ~[spring-data-commons-2.1.6.RELEASE.jar:2.1.6.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:608) ~[spring-data-commons-2.1.6.RELEASE.jar:2.1.6.RELEASE]
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.lambda$invoke$3(RepositoryFactorySupport.java:595) ~[spring-data-commons-2.1.6.RELEASE.jar:2.1.6.RELEASE]
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:595) ~[spring-data-commons-2.1.6.RELEASE.jar:2.1.6.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:59) ~[spring-data-commons-2.1.6.RELEASE.jar:2.1.6.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:294) ~[spring-tx-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:98) ~[spring-tx-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139) ~[spring-tx-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:93) ~[spring-aop-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.data.repository.core.support.SurroundingTransactionDetectorMethodInterceptor.invoke(SurroundingTransactionDetectorMethodInterceptor.java:61) ~[spring-data-commons-2.1.6.RELEASE.jar:2.1.6.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212) ~[spring-aop-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at com.sun.proxy.$Proxy87.findAll(Unknown Source) ~[?:?]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.8.0_241]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[?:1.8.0_241]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:1.8.0_241]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[?:1.8.0_241]
    at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:343) ~[spring-aop-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:198) ~[spring-aop-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163) ~[spring-aop-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139) ~[spring-tx-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212) ~[spring-aop-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at com.sun.proxy.$Proxy87.findAll(Unknown Source) ~[?:?]
    at com.discover.dbvorg.BenchmarkConfigSync.run(BenchmarkConfigSync.java:37) ~[main/:?]

I tried adding

@org.springframework.data.annotation.Id

It slove the problem but it generate the query but it Ignores the @Name and @Column annotations. The query is generated using default strategy. I have also added

spring:
  jpa:
    hibernate:
      naming:
        physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
        implicit-strategy: org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl

Still the query generated used the bean name and property names.


问:
Write to Firestore Emulator from Angular throws security rules error: `Missing or insufficient permissions.`
I wrote a Triggerable Firebase Cloud Function which triggers and runs in the emulator. I also wrote a Callable Firebase Cloud Function that I can call from Angular and I see the logs in the Firebase Emulator.

What's not working is to trigger a Firebase Cloud Function running in the emulator from Angular. The problem is that I can't write from Angular to the Firestore Emulator. This throws a security rules error:

```<code>Error adding document:  FirebaseError: Missing or insufficient permissions.
</code>```

The Firestore Emulator doesn't have security rules. In the Requests Monitor you can see security rules, apparently, but my Requests Monitor shows no activity.

The documentation says that you can connect your app to the Cloud Firestore Emulator. I've tried both a demo- project and a real project. Here's my code:

app.module.ts hooks up the emulators. environment.ts sets production: false.

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { environment } from '../environments/environment';

// Angular
import { FormsModule } from '@angular/forms';

// AngularFire
import { provideFirebaseApp, initializeApp } from '@angular/fire/app';
import { provideFirestore, getFirestore, connectFirestoreEmulator } from '@angular/fire/firestore';
import { provideFunctions,getFunctions, connectFunctionsEmulator } from '@angular/fire/functions';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    provideFirebaseApp(() => initializeApp(environment.firebaseConfig)),
    provideFirestore(() => {
      const firestore = getFirestore();
      if (!environment.production) {
        connectFirestoreEmulator(firestore, 'localhost', 8080);
      }
      return firestore;
    }),
    provideFunctions(() => {
      const functions = getFunctions();
      if (!environment.production) {
        connectFunctionsEmulator(functions, 'localhost', 5001);
      }
      return functions;
    }),
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
```
<p><em>app.component.html</em> makes two simple forms.</p>
<pre class="lang-html prettyprint-override"><code><h3>Trigger Firebase Cloud Function</h3>
<form (ngSubmit)="triggerMe(triggerText)">
    <input type="text" [(ngModel)]="triggerText" name="message" placeholder="message" required>
    <button type="submit" value="Submit">Submit</button>
</form>

<h3>Call Firebase Cloud Function</h3>
<form (ngSubmit)="callMe(messageText)">
    <input type="text" [(ngModel)]="messageText" name="message" placeholder="message" required>
    <button type="submit" value="Submit">Submit</button>
</form>
</code>```

app.component.ts has two handler functions.

import { Component } from '@angular/core';
import { getFunctions, httpsCallable, httpsCallableFromURL } from "firebase/functions";
import { initializeApp } from 'firebase/app';
import { getFirestore, setDoc, doc } from "firebase/firestore";
import { environment } from '../environments/environment';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  firebaseConfig = environment.firebaseConfig;
  firebaseApp = initializeApp(this.firebaseConfig);
  firestore = getFirestore(this.firebaseApp);
  functions = getFunctions(this.firebaseApp);

  triggerText: string = "";
  messageText: string = "";

  async triggerMe(triggerText: string) {
    try {
      console.log("Triggering Cloud Function: " + triggerText);
      await setDoc(doc(this.firestore, "Messages", triggerText), {
        original: triggerText,
        createdAt: new Date()
      });
    } catch(error) {
      console.error("Error adding document: ", error);
    }
  };

  callMe(messageText: string | null) {
    console.log("Calling Cloud Function: " + messageText);
    // const addMessage = httpsCallable(this.functions, 'addMessage'); // throws CORS error
    const addMessage = httpsCallableFromURL(this.functions, 'http://localhost:5001/demo-test/us-central1/addMessage');
    addMessage({ text: messageText })
      .then((result) => {
        console.log(result.data)
      });
  };
}
```
<p><em>index.js</em> has two Firebase Cloud Functions. The first triggers, the second is called.</p>
<pre class="lang-js prettyprint-override"><code>import * as functions from "firebase-functions";

export const MakeUppercase = functions.firestore.document('Messages/{docId}').onCreate((snap, context) => {
  try {
    const original = snap.data().original;
    const uppercase = original.toUpperCase();
    functions.logger.log('Uppercasing', context.params.docId, original);
    return snap.ref.set({ uppercase }, { merge: true });
  } catch (error) {
    console.error(error); // emulator always throws an "unhandled error": "Your function timed out after ~60s."
  }
});

export const addMessage = functions.https.onCall((data, context) => {
  try {
    const original = data.text;
    const uppercase = original.toUpperCase();
    functions.logger.log('addMessage', original, uppercase);
    return uppercase;
  } catch (error) {
    console.error(error); // emulator always throws an "unhandled error": "Your function timed out after ~60s."
  }
});

</code>```

Body:
I wrote a Triggerable Firebase Cloud Function which triggers and runs in the emulator. I also wrote a Callable Firebase Cloud Function that I can call from Angular and I see the logs in the Firebase Emulator.

What's not working is to trigger a Firebase Cloud Function running in the emulator from Angular. The problem is that I can't write from Angular to the Firestore Emulator. This throws a security rules error:

Error adding document:  FirebaseError: Missing or insufficient permissions.

The Firestore Emulator doesn't have security rules. In the Requests Monitor you can see security rules, apparently, but my Requests Monitor shows no activity.

The documentation says that you can connect your app to the Cloud Firestore Emulator. I've tried both a demo- project and a real project. Here's my code:

app.module.ts hooks up the emulators. environment.ts sets production: false.

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { environment } from '../environments/environment';

// Angular
import { FormsModule } from '@angular/forms';

// AngularFire
import { provideFirebaseApp, initializeApp } from '@angular/fire/app';
import { provideFirestore, getFirestore, connectFirestoreEmulator } from '@angular/fire/firestore';
import { provideFunctions,getFunctions, connectFunctionsEmulator } from '@angular/fire/functions';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    provideFirebaseApp(() => initializeApp(environment.firebaseConfig)),
    provideFirestore(() => {
      const firestore = getFirestore();
      if (!environment.production) {
        connectFirestoreEmulator(firestore, 'localhost', 8080);
      }
      return firestore;
    }),
    provideFunctions(() => {
      const functions = getFunctions();
      if (!environment.production) {
        connectFunctionsEmulator(functions, 'localhost', 5001);
      }
      return functions;
    }),
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

app.component.html makes two simple forms.

Trigger Firebase Cloud Function

<form (ngSubmit)="triggerMe(triggerText)">
    <input type="text" [(ngModel)]="triggerText" name="message" placeholder="message" required>
    <button type="submit" value="Submit">Submit</button>
</form>

Call Firebase Cloud Function

<form (ngSubmit)="callMe(messageText)">
    <input type="text" [(ngModel)]="messageText" name="message" placeholder="message" required>
    <button type="submit" value="Submit">Submit</button>
</form>

app.component.ts has two handler functions.

import { Component } from '@angular/core';
import { getFunctions, httpsCallable, httpsCallableFromURL } from "firebase/functions";
import { initializeApp } from 'firebase/app';
import { getFirestore, setDoc, doc } from "firebase/firestore";
import { environment } from '../environments/environment';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  firebaseConfig = environment.firebaseConfig;
  firebaseApp = initializeApp(this.firebaseConfig);
  firestore = getFirestore(this.firebaseApp);
  functions = getFunctions(this.firebaseApp);

  triggerText: string = "";
  messageText: string = "";

  async triggerMe(triggerText: string) {
    try {
      console.log("Triggering Cloud Function: " + triggerText);
      await setDoc(doc(this.firestore, "Messages", triggerText), {
        original: triggerText,
        createdAt: new Date()
      });
    } catch(error) {
      console.error("Error adding document: ", error);
    }
  };

  callMe(messageText: string | null) {
    console.log("Calling Cloud Function: " + messageText);
    // const addMessage = httpsCallable(this.functions, 'addMessage'); // throws CORS error
    const addMessage = httpsCallableFromURL(this.functions, 'http://localhost:5001/demo-test/us-central1/addMessage');
    addMessage({ text: messageText })
      .then((result) => {
        console.log(result.data)
      });
  };
}

index.js has two Firebase Cloud Functions. The first triggers, the second is called.

import * as functions from "firebase-functions";

export const MakeUppercase = functions.firestore.document('Messages/{docId}').onCreate((snap, context) => {
  try {
    const original = snap.data().original;
    const uppercase = original.toUpperCase();
    functions.logger.log('Uppercasing', context.params.docId, original);
    return snap.ref.set({ uppercase }, { merge: true });
  } catch (error) {
    console.error(error); // emulator always throws an "unhandled error": "Your function timed out after ~60s."
  }
});

export const addMessage = functions.https.onCall((data, context) => {
  try {
    const original = data.text;
    const uppercase = original.toUpperCase();
    functions.logger.log('addMessage', original, uppercase);
    return uppercase;
  } catch (error) {
    console.error(error); // emulator always throws an "unhandled error": "Your function timed out after ~60s."
  }
});


问:
http-proxy-middleware to IIS timing out after 120s
I have a GET call (long operation)  from my front-end (angular code) to a webapi (hosted on IIS).
To fix some CORS issue, I had to change the routing so that the call goes from browser to node first and then get routed to IIS.

Before: browser -> iis web api

After: browser -> node express (http-proxy-middleware) -> iis web api

The problem now is that the second call above times out exactly at 120s and IIS returns a 502.3 bad gateway (The operation has timed out) error.
I tried changing the proxy options property (timeout and proxyTimeout) to different values, they kick in only if the value is below 120s. If I specify something greater than 120s, some invisible timeout kicks in at 120s.

My node is v12 and it has a default timeout of 120s, but changing it with server.timeout isn't helping. The http-proxy-middleware version is 2.0.6.
I haven't made any changes to angular code or the iis hosted webapi code.


问:
Licensing - How do I protect Python code using a password or other form of authentication?
I am in a similar position as the individual who asked this question.

I am creating a small utility application that will be shared with 3rd parties as well as used internally and my employer would like us to be able to "maintain control" over the application by preventing unauthorized use.

The protection scheme could be as simple as me distributing a password to those using the application that they then enter into the GUI of the program for authentication. Obviously I cannot hard code the password check in the applications code since they could just edit the code and remove the check.

It is also preferred that the main application code is not easily accessed by those using the application. I understand there are methods to obfuscate and compile the code so that it is difficult to reverse engineer.

Instead of going that route, my thoughts were that I could have the have the application contact a webserver running a flask API that checks the password provided by the user during application run. If it is valid, return code instructions in the response that the client application executes.

I understand that executing code returned from a remote webserver is potentially dangerous, but I am not concerned about it.

Here is the simple scheme I was thinking:

FLASK API ON REMOTE SERVER

```<code>from flask import Flask

PASSWORD = 'demo'

# could maybe read the script file as text and return string instead
def secret_script_code():

    codestring = """
    import math

    x = 1
    y = 5

    def try_this(x, y):
        return math.sqrt((y-x))

    if __name__ == "__main__":

        result = try_this(x, y)
    """
    return codestring

app = Flask(__name__)

@app.route('/', methods = ['GET','POST'])
def index():
    if request.method == 'POST':
        #read the password from the request
        password = request.form['password']
        if password == PASSWORD:
            #send python script as string for client to execute
            return secret_script_code()
    else:
        return "print('Invalid!')'"

if __name__ == '__main__':
    app.run()
</code>```

CLIENT APPLICATION

```<code>import requests

payload = {'password': 'demo'}

def run_program(payload):
    # send post request to flask endpoint
    r = requests.post("https://xxx.xx.xx.x/", data=payload)
    # execute the text returned from post request as code
    exec(r.text)

if __name__ == "__main__":

    run_program(payload)
</code>```

I understand that if the application user wanted to see the "secret code" that could just add a print() statement to print the string that exec() is executing. Perhaps compiling the code string into bytecode and sending that would be better?

I know all code can be decompiled and there's no real way to protect code from those with the motivation to reverse engineer it. No one is going to waste their time doing that here. But there is a genuine need to try to retain control over application use and prevent it from being easily copied.

Body:
I am in a similar position as the individual who asked this question.

I am creating a small utility application that will be shared with 3rd parties as well as used internally and my employer would like us to be able to "maintain control" over the application by preventing unauthorized use.

The protection scheme could be as simple as me distributing a password to those using the application that they then enter into the GUI of the program for authentication. Obviously I cannot hard code the password check in the applications code since they could just edit the code and remove the check.

It is also preferred that the main application code is not easily accessed by those using the application. I understand there are methods to obfuscate and compile the code so that it is difficult to reverse engineer.

Instead of going that route, my thoughts were that I could have the have the application contact a webserver running a flask API that checks the password provided by the user during application run. If it is valid, return code instructions in the response that the client application executes.

I understand that executing code returned from a remote webserver is potentially dangerous, but I am not concerned about it.

Here is the simple scheme I was thinking:

FLASK API ON REMOTE SERVER

from flask import Flask

PASSWORD = 'demo'

# could maybe read the script file as text and return string instead
def secret_script_code():

    codestring = """
    import math

    x = 1
    y = 5

    def try_this(x, y):
        return math.sqrt((y-x))

    if __name__ == "__main__":

        result = try_this(x, y)
    """
    return codestring

app = Flask(__name__)

@app.route('/', methods = ['GET','POST'])
def index():
    if request.method == 'POST':
        #read the password from the request
        password = request.form['password']
        if password == PASSWORD:
            #send python script as string for client to execute
            return secret_script_code()
    else:
        return "print('Invalid!')'"

if __name__ == '__main__':
    app.run()

CLIENT APPLICATION

import requests

payload = {'password': 'demo'}

def run_program(payload):
    # send post request to flask endpoint
    r = requests.post("https://xxx.xx.xx.x/", data=payload)
    # execute the text returned from post request as code
    exec(r.text)

if __name__ == "__main__":

    run_program(payload)

I understand that if the application user wanted to see the "secret code" that could just add a print() statement to print the string that exec() is executing. Perhaps compiling the code string into bytecode and sending that would be better?

I know all code can be decompiled and there's no real way to protect code from those with the motivation to reverse engineer it. No one is going to waste their time doing that here. But there is a genuine need to try to retain control over application use and prevent it from being easily copied.


问:
App check showing Unverified: outdated client requests for all requests with latest firebase 9.15.0
This is what i got from deployed app on firebase. Description for unverified is saying that i have to update Firebase SDK but i have the latest version.

In index.js:

```<code>import { initializeApp } from "firebase/app";
import { initializeAppCheck, ReCaptchaV3Provider } from "firebase/app-check";

const firebaseConfig = {
  apiKey: "...",
  authDomain: "...",
  projectId: "...",
  storageBucket: "...",
  messagingSenderId: "...",
  appId: "...",
  measurementId: "...",
};

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

const appCheck = initializeAppCheck(app, {
  provider: new ReCaptchaV3Provider("KEY"),
  isTokenAutoRefreshEnabled: true,
});
</code>```

What is the problem and why my all request get unverified? Because of this i cant turn on enforce mode

Body:
This is what i got from deployed app on firebase. Description for unverified is saying that i have to update Firebase SDK but i have the latest version.

In index.js:

import { initializeApp } from "firebase/app";
import { initializeAppCheck, ReCaptchaV3Provider } from "firebase/app-check";

const firebaseConfig = {
  apiKey: "...",
  authDomain: "...",
  projectId: "...",
  storageBucket: "...",
  messagingSenderId: "...",
  appId: "...",
  measurementId: "...",
};

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

const appCheck = initializeAppCheck(app, {
  provider: new ReCaptchaV3Provider("KEY"),
  isTokenAutoRefreshEnabled: true,
});

What is the problem and why my all request get unverified? Because of this i cant turn on enforce mode


问:
How to create similar models using rust, rocket.rs and diesel without duplicating code
I am building a restful api using rocket.rs. I am a Rust beginner and learning rocket.rs. I have two database tables: chair and table. I use Rust Diesel ORM. The chair is represented by the Chair struct and table by the Table struct. A chair can refer to a table having Some(table_id) or to no table if None.

I am trying to create a POST endpoint that uses a chair id as parameter and transforms it into a Chair struct. Also, I want to validate that this chair is associated to a table. If the provided chair id is not associated to a table, then an error is sent. I have an implementation working already, but I feel that this is not a clean solution.

```<code>#[derive(Queryable, Serialize)]
pub struct Chair {
    pub id: i32,
    pub color: String,
    pub table_id: Option<i32>
}

#[derive(Queryable, Serialize)]
pub struct ChairWithTable {
    pub id: i32,
    pub color: String,
    pub table: i32
}

impl TryFrom<Chair> for ChairWithTable {
    type Error = ChairError;
    fn try_from(chair: Chair) -> Result<Self, Self::Error> {
        if chair.table_id.is_none() {
            Err(ChairError::WithoutTable)
        } else {
            Ok(ChairWithTable {
                id: chair.id,
                color: chair.color,
                table_id: chair.table_id.unwrap()
            })
        }
    }
}

pub struct Table {
    pub id: i32,
    // ... whatever other fields. this is not important in the example
}

impl<'a> FromParam<'a> for ChairWithTable {
    // implemention details omitted
}

impl<'a> FromParam<'a> for Chair {
    // implemention details omitted
}
</code>```

Here we pretend we can add pieces (could be anything else, not very relevant to the case anyhow) to a chair but only if the chair is bound to a table. Does not make a lot of sense, but I changed the table names so bear with me.

```<code>#[post("/chairs/<chair>/pieces", rank = 1)]
async fn pieces(chair: ChairWithTable, conn: DatabaseConnection) -> Result<Json<[/*irrelevent*/]>, Forbidden<Option<String>>> {
    // implementation details omitted
}
</code>```

So what I feel is wrong about my solution, is that there is a lot of duplication between Chair and ChairWithTable. Actually I copied all the fields and removed the Option wrapping the i32. I also had to impl TryFrom<Chair> for ChairWithTable. This is already verbose and it would get much more complicated if I had even just two Option fields on the same model. I could also omit the ChairWithTable struct and only keep Chair struct. But then when I get in my controller method, I have to check if table_id is Some or None every time and throw an error mid way in the controller code instead of using the param guards as validation.

Coming from web dev background in php and TypeScript, my brain would try to solve this with TypeScript's utility types. I would do something like take the Chair struct and make the field required with something that looks like this type ChairWithTabl = Pick<Chair, 'id'|'color'> & Required<Pick<Chair, 'table_id'>>. Another way of solving it would for me to go with a library like Zod that creates types on the fly with type inference.

Think that one solution in pure Rust would be to aim for struct composition like this answer for this question. But as far as I know, it is not possible to use composition on diesel models

How would you recommend to tackle this kind problem in the context of Rust, Rocket.rs and Diesel?

Body:
I am building a restful api using rocket.rs. I am a Rust beginner and learning rocket.rs. I have two database tables: chair and table. I use Rust Diesel ORM. The chair is represented by the Chair struct and table by the Table struct. A chair can refer to a table having Some(table_id) or to no table if None.

I am trying to create a POST endpoint that uses a chair id as parameter and transforms it into a Chair struct. Also, I want to validate that this chair is associated to a table. If the provided chair id is not associated to a table, then an error is sent. I have an implementation working already, but I feel that this is not a clean solution.

#[derive(Queryable, Serialize)]
pub struct Chair {
    pub id: i32,
    pub color: String,
    pub table_id: Option<i32>
}

#[derive(Queryable, Serialize)]
pub struct ChairWithTable {
    pub id: i32,
    pub color: String,
    pub table: i32
}

impl TryFrom<Chair> for ChairWithTable {
    type Error = ChairError;
    fn try_from(chair: Chair) -> Result<Self, Self::Error> {
        if chair.table_id.is_none() {
            Err(ChairError::WithoutTable)
        } else {
            Ok(ChairWithTable {
                id: chair.id,
                color: chair.color,
                table_id: chair.table_id.unwrap()
            })
        }
    }
}

pub struct Table {
    pub id: i32,
    // ... whatever other fields. this is not important in the example
}

impl<'a> FromParam<'a> for ChairWithTable {
    // implemention details omitted
}

impl<'a> FromParam<'a> for Chair {
    // implemention details omitted
}

Here we pretend we can add pieces (could be anything else, not very relevant to the case anyhow) to a chair but only if the chair is bound to a table. Does not make a lot of sense, but I changed the table names so bear with me.

#[post("/chairs/<chair>/pieces", rank = 1)]
async fn pieces(chair: ChairWithTable, conn: DatabaseConnection) -> Result<Json<[/*irrelevent*/]>, Forbidden<Option<String>>> {
    // implementation details omitted
}

So what I feel is wrong about my solution, is that there is a lot of duplication between Chair and ChairWithTable. Actually I copied all the fields and removed the Option wrapping the i32. I also had to impl TryFrom<Chair> for ChairWithTable. This is already verbose and it would get much more complicated if I had even just two Option fields on the same model. I could also omit the ChairWithTable struct and only keep Chair struct. But then when I get in my controller method, I have to check if table_id is Some or None every time and throw an error mid way in the controller code instead of using the param guards as validation.

Coming from web dev background in php and TypeScript, my brain would try to solve this with TypeScript's utility types. I would do something like take the Chair struct and make the field required with something that looks like this type ChairWithTabl = Pick<Chair, 'id'|'color'> & Required<Pick<Chair, 'table_id'>>. Another way of solving it would for me to go with a library like Zod that creates types on the fly with type inference.

Think that one solution in pure Rust would be to aim for struct composition like this answer for this question. But as far as I know, it is not possible to use composition on diesel models

How would you recommend to tackle this kind problem in the context of Rust, Rocket.rs and Diesel?


问:
TS2322: Type 'Redis' is not assignable to type 'RedisClient'. issue on Docker
I try to build an node.js app but I have an error like ;

```<code> => ERROR [build 7/7] RUN npx nx build driver-api --prod                                                                                53.9s
------
 > [build 7/7] RUN npx nx build driver-api --prod:

nx run driver-api:build:production

chunk (runtime: main) main.js (main) 348 KiB [entry] [rendered]

ERROR in /app/libs/database/src/lib/redis-pub-sub.provider.ts
./libs/database/src/lib/redis-pub-sub.provider.ts 16:10-19
[tsl] ERROR in /app/libs/database/src/lib/redis-pub-sub.provider.ts(16,11)
TS2322: Type 'Redis' is not assignable to type 'RedisClient'.
Type 'Redis' is missing the following properties from type 'Redis': stream, isCluster, connector, reconnectTimeout, and 140 more.

ERROR in /app/libs/database/src/lib/redis-pub-sub.provider.ts
./libs/database/src/lib/redis-pub-sub.provider.ts 17:10-20
[tsl] ERROR in /app/libs/database/src/lib/redis-pub-sub.provider.ts(17,11)
TS2322: Type 'Redis' is not assignable to type 'RedisClient'.

ERROR in libs/database/src/lib/redis-pub-sub.provider.ts:16:11
TS2322: Type 'Redis' is not assignable to type 'RedisClient'.
Type 'Redis' is missing the following properties from type 'Redis': stream, isCluster, connector, reconnectTimeout, and 140 more.
#12 53.66     14 |         };
#12 53.66     15 |         return new RedisPubSub({
#12 53.66   > 16 |           publisher: new Redis(options),
#12 53.66        |           ^^^^^^^^^
#12 53.66     17 |           subscriber: new Redis(options),
#12 53.66     18 |         })
#12 53.66     19 |       } ,
#12 53.66
#12 53.66 ERROR in libs/database/src/lib/redis-pub-sub.provider.ts:17:11
#12 53.66 TS2322: Type 'Redis' is not assignable to type 'RedisClient'.
#12 53.66     15 |         return new RedisPubSub({
#12 53.66     16 |           publisher: new Redis(options),
#12 53.66   > 17 |           subscriber: new Redis(options),
#12 53.66        |           ^^^^^^^^^^
#12 53.66     18 |         })
#12 53.66     19 |       } ,
#12 53.66     20 |     };
#12 53.66
#12 53.66 webpack compiled with 4 errors (b984ccb820b8363c)

</code>```

my redis-pub-sub.provider.ts file like ;

```<code>import { pubSubToken } from '@nestjs-query/query-graphql';
import { RedisPubSub } from 'graphql-redis-subscriptions';
import Redis from 'ioredis';
import { Provider } from '@nestjs/common';

export class RedisPubSubProvider {
  static provider(): Provider {
    return {
      provide: pubSubToken(),
      useFactory: () => {
        const options = {
          host: process.env.REDIS_HOST || 'localhost',
          port: 6379
        };
        return new RedisPubSub({
          publisher: new Redis(options),
          subscriber: new Redis(options),
        })
      } ,
    };
  }
}

</code>```

how can I solve the issue ? can some one help me ?

when I try to build an node.js app I get an error like "TS2322: Type 'Redis' is not assignable to type 'RedisClient'. issue"

Body:
I try to build an node.js app but I have an error like ;

 => ERROR [build 7/7] RUN npx nx build driver-api --prod                                                                                53.9s
------
 > [build 7/7] RUN npx nx build driver-api --prod:

nx run driver-api:build:production

chunk (runtime: main) main.js (main) 348 KiB [entry] [rendered]

ERROR in /app/libs/database/src/lib/redis-pub-sub.provider.ts
./libs/database/src/lib/redis-pub-sub.provider.ts 16:10-19
[tsl] ERROR in /app/libs/database/src/lib/redis-pub-sub.provider.ts(16,11)
TS2322: Type 'Redis' is not assignable to type 'RedisClient'.
Type 'Redis' is missing the following properties from type 'Redis': stream, isCluster, connector, reconnectTimeout, and 140 more.

ERROR in /app/libs/database/src/lib/redis-pub-sub.provider.ts
./libs/database/src/lib/redis-pub-sub.provider.ts 17:10-20
[tsl] ERROR in /app/libs/database/src/lib/redis-pub-sub.provider.ts(17,11)
TS2322: Type 'Redis' is not assignable to type 'RedisClient'.

ERROR in libs/database/src/lib/redis-pub-sub.provider.ts:16:11
TS2322: Type 'Redis' is not assignable to type 'RedisClient'.
Type 'Redis' is missing the following properties from type 'Redis': stream, isCluster, connector, reconnectTimeout, and 140 more.
#12 53.66     14 |         };
#12 53.66     15 |         return new RedisPubSub({
#12 53.66   > 16 |           publisher: new Redis(options),
#12 53.66        |           ^^^^^^^^^
#12 53.66     17 |           subscriber: new Redis(options),
#12 53.66     18 |         })
#12 53.66     19 |       } ,
#12 53.66
#12 53.66 ERROR in libs/database/src/lib/redis-pub-sub.provider.ts:17:11
#12 53.66 TS2322: Type 'Redis' is not assignable to type 'RedisClient'.
#12 53.66     15 |         return new RedisPubSub({
#12 53.66     16 |           publisher: new Redis(options),
#12 53.66   > 17 |           subscriber: new Redis(options),
#12 53.66        |           ^^^^^^^^^^
#12 53.66     18 |         })
#12 53.66     19 |       } ,
#12 53.66     20 |     };
#12 53.66
#12 53.66 webpack compiled with 4 errors (b984ccb820b8363c)

my redis-pub-sub.provider.ts file like ;

import { pubSubToken } from '@nestjs-query/query-graphql';
import { RedisPubSub } from 'graphql-redis-subscriptions';
import Redis from 'ioredis';
import { Provider } from '@nestjs/common';

export class RedisPubSubProvider {
  static provider(): Provider {
    return {
      provide: pubSubToken(),
      useFactory: () => {
        const options = {
          host: process.env.REDIS_HOST || 'localhost',
          port: 6379
        };
        return new RedisPubSub({
          publisher: new Redis(options),
          subscriber: new Redis(options),
        })
      } ,
    };
  }
}

how can I solve the issue ? can some one help me ?

when I try to build an node.js app I get an error like "TS2322: Type 'Redis' is not assignable to type 'RedisClient'. issue"


问:
Bug between navigation screens and modal
So my problem is kind of weird,when i navigate between screens it seems to let the modal open but invisible.Lets say that i have a modal on my home page and pressing the menu button it opens the modal and i start navigate ,when i press the button again to open the modal and navigate to another screen it navigates but it lets open an invisible modal.

Anyone knows what kind of bug this is?

Code below :

```<code>export default function Header() {

  //Use of navigation Hook
  const navigation = useNavigation();

  //Modal Constructor
  const [modalVisible,setModalVisible] = useState(false);

    return (

    // Container
    <View style = {styles.Header}>

      {/* Modal    */}
      <Modal
        animationType="slide"
        transparent={true}
        visible={modalVisible}
        onRequestClose={() => {
          setModalVisible(!modalVisible);
        }}>

        <View style = {styles.modalStyle}>

          {/* Pressable and Text for each functionality  */}
          <Pressable  style = {styles.pressable} onPress = { () => navigation.navigate('Home')}>
            <Text style = {styles. textInsideModalPressables}>Home</Text>
          </Pressable>

          <Pressable  style = {styles.pressable} onPress = { () => navigation.navigate('Profile')}>
            <Text style = {styles. textInsideModalPressables}>Profile</Text>
          </Pressable>

          <Pressable style = {styles.pressable} onPress = { () => navigation.navigate('Settings')}>
            <Text style = {styles. textInsideModalPressables}>Settings</Text>
          </Pressable>

          <Pressable style = {styles.pressable} onPress = { () => navigation.navigate('LogInPage')}>
            <Text style = {styles. textInsideModalPressables}>Log Out</Text>
          </Pressable>

          <Pressable onPress={ () => {setModalVisible(!modalVisible)}} style = {styles.pressable}>
            <Text style = {styles. textInsideModalPressables}>Close modal</Text>
          </Pressable>

        </View>

      </Modal>

      {/* Pressable Mechanism in order to open the Modal */}
      <Pressable onPress={ () => {setModalVisible(!modalVisible)}} style = {styles.pressableMenu}>
        <SimpleLineIcons style = {styles.iconMenu} name="menu" size={Dimensions.get('window').width > 800 ? 40 : 24 } color="white" />
        <Text style = {styles.menuText}>Menu</Text>
      </Pressable>

      <Text style = {styles.nameText}> E-Library</Text>

    </View>
</code>```

Body:
So my problem is kind of weird,when i navigate between screens it seems to let the modal open but invisible.Lets say that i have a modal on my home page and pressing the menu button it opens the modal and i start navigate ,when i press the button again to open the modal and navigate to another screen it navigates but it lets open an invisible modal.

Anyone knows what kind of bug this is?

Code below :

export default function Header() {

  //Use of navigation Hook
  const navigation = useNavigation();

  //Modal Constructor
  const [modalVisible,setModalVisible] = useState(false);

    return (

    // Container
    <View style = {styles.Header}>

      {/* Modal    */}
      <Modal
        animationType="slide"
        transparent={true}
        visible={modalVisible}
        onRequestClose={() => {
          setModalVisible(!modalVisible);
        }}>

        <View style = {styles.modalStyle}>

          {/* Pressable and Text for each functionality  */}
          <Pressable  style = {styles.pressable} onPress = { () => navigation.navigate('Home')}>
            <Text style = {styles. textInsideModalPressables}>Home</Text>
          </Pressable>

          <Pressable  style = {styles.pressable} onPress = { () => navigation.navigate('Profile')}>
            <Text style = {styles. textInsideModalPressables}>Profile</Text>
          </Pressable>

          <Pressable style = {styles.pressable} onPress = { () => navigation.navigate('Settings')}>
            <Text style = {styles. textInsideModalPressables}>Settings</Text>
          </Pressable>

          <Pressable style = {styles.pressable} onPress = { () => navigation.navigate('LogInPage')}>
            <Text style = {styles. textInsideModalPressables}>Log Out</Text>
          </Pressable>

          <Pressable onPress={ () => {setModalVisible(!modalVisible)}} style = {styles.pressable}>
            <Text style = {styles. textInsideModalPressables}>Close modal</Text>
          </Pressable>

        </View>

      </Modal>

      {/* Pressable Mechanism in order to open the Modal */}
      <Pressable onPress={ () => {setModalVisible(!modalVisible)}} style = {styles.pressableMenu}>
        <SimpleLineIcons style = {styles.iconMenu} name="menu" size={Dimensions.get('window').width > 800 ? 40 : 24 } color="white" />
        <Text style = {styles.menuText}>Menu</Text>
      </Pressable>

      <Text style = {styles.nameText}> E-Library</Text>

    </View>


问:
Design patterns for chaining dependency objects
I have a design problem and I can't find the right way to deal with that. In my problem there are 4 classes:

class G

class T depending on the G

class F depending on T

class P depending on G, T and F

Additionally each concrete implementation of P should use exact implementation of T and when F is used then T is not needed. However F and T are different concepts (I would say F is some transformation or different interpretation of T) and it is hard to design common interface for them (otherwise I would think about decorator pattern). I was thinking about approach like below:

```<code>class PImpl extends P {
     G g;
     T t;
     F f;

     PImpl(G g) {
        this.g = g;
        this.t = new TImpl(g);
        this.f = new FImpl(t);
     }
}
</code>```

But isn't it breaking the Dependency Inversion Principle from SOLID? Another idea which is an extenstion of above is additional introduction of initialization method for TImpl and FImpl. Then I would provide implementation classes in the constructor and then do exact construction in the constructor body.

```<code>class Test {
    main() {
       P p = new PImpl(new GImpl(), new FImpl());
    }
}

abstract class P {
    G g;
    T t;
    F f;

    P(G g, T t, F f) {
        this.g = g;
        this.t = t.create(g);
        this.f = f.create(t);
    }
}

class PImpl extends P {

     PImpl(G g, F f) {
        super(g, new TImpl(), f);
     }
}
</code>```

But I'm not sure if this brings any additional value and only makes the code more complex.

Body:
I have a design problem and I can't find the right way to deal with that. In my problem there are 4 classes:

class G

class T depending on the G

class F depending on T

class P depending on G, T and F

Additionally each concrete implementation of P should use exact implementation of T and when F is used then T is not needed. However F and T are different concepts (I would say F is some transformation or different interpretation of T) and it is hard to design common interface for them (otherwise I would think about decorator pattern). I was thinking about approach like below:

class PImpl extends P {
     G g;
     T t;
     F f;

     PImpl(G g) {
        this.g = g;
        this.t = new TImpl(g);
        this.f = new FImpl(t);
     }
}

But isn't it breaking the Dependency Inversion Principle from SOLID? Another idea which is an extenstion of above is additional introduction of initialization method for TImpl and FImpl. Then I would provide implementation classes in the constructor and then do exact construction in the constructor body.

class Test {
    main() {
       P p = new PImpl(new GImpl(), new FImpl());
    }
}

abstract class P {
    G g;
    T t;
    F f;

    P(G g, T t, F f) {
        this.g = g;
        this.t = t.create(g);
        this.f = f.create(t);
    }
}

class PImpl extends P {

     PImpl(G g, F f) {
        super(g, new TImpl(), f);
     }
}

But I'm not sure if this brings any additional value and only makes the code more complex.