问:
How to create a simple dashboard from Azure Storage and Fileshare

I have an azure storage account.

Inside the container, with a client-specific folder structure, every morning, some files get pushed.

I have a function app which processes and converts these files and calls some external service to work upon on these processed files.

I have got a file-share as well, which is basically mounted on a vm.

The external service, after processing the files (#3), generates the resultant success/failure files inside this file-share(#4).

Now the ask is:

Create a simple dashboard which will monitor the storage account(and in effect the container and the file-shares),it should capture & show basic information's, and should look like below table structure(with 3 simple variations of data):

FileName|ReceivedDateTime|NumberOfRecords

```<code>Original_file.csv20221011 5:21 AM|10
Original_file_Success.csv20221011 5:31 AM|9
Original_file_Failure.csv20221011 5:32 AM|1
</code>```

In here the first record is captured from the Container and the second and third - both are generated in the  file-share.

Also, whenever a new failure file is generated, i.e., Original file_Failure, it should send email with a predefines template adding the file name to a predefined recipient list.

Any guidance on the azure service to use?
I have seen Azure Monitor,workbook and other stuffs, but I feel that would be an overkill for such simple requirement.

Thanks in advance.

Body:
I have an azure storage account.

Inside the container, with a client-specific folder structure, every morning, some files get pushed.

I have a function app which processes and converts these files and calls some external service to work upon on these processed files.

I have got a file-share as well, which is basically mounted on a vm.

The external service, after processing the files (#3), generates the resultant success/failure files inside this file-share(#4).

Now the ask is:

Create a simple dashboard which will monitor the storage account(and in effect the container and the file-shares),it should capture & show basic information's, and should look like below table structure(with 3 simple variations of data):

FileName|ReceivedDateTime|NumberOfRecords

Original_file.csv20221011 5:21 AM|10
Original_file_Success.csv20221011 5:31 AM|9
Original_file_Failure.csv20221011 5:32 AM|1

In here the first record is captured from the Container and the second and third - both are generated in the  file-share.

Also, whenever a new failure file is generated, i.e., Original file_Failure, it should send email with a predefines template adding the file name to a predefined recipient list.

Any guidance on the azure service to use?
I have seen Azure Monitor,workbook and other stuffs, but I feel that would be an overkill for such simple requirement.

Thanks in advance.


来源: stackexchange

问:
Binary subset rank with maximum k consecutive 0
Consider N = 6 bits

We have a set S = 2^6 = 64 binary combinations.

We want to consider a subset T of the set S based on the following criteria -

There must be <= k consecutive 0s in the subset T.

Accordingly,

If the binary number is present in subset T, calculate its rank (in binary format)

If the binary number is not present in subset T, return 0 (in binary format)

Note: We want to calculate the rank only by iterating the N bits of the given binary number, and NOT by iterating 2^N numbers.

Here is the pseudo-code -

```<code>string GetBinaryRank(string strBinaryNumber, int max_k_0s)
{
    string strRankBinary = "";

    if(strBinaryNumber.Contains(<= max_k_0s))
    {
       //calculate strRankBinary by iterating over the N bits of strBinaryNumber
       for(int i = 0; i < strBinaryNumber.Length; i++)
       {
           if(max_k_0s == 1)
           {
               //calculate rank
               //binary rank will be 5 bits
               strRankBinary = "xxxxx";
           }
           else if(max_k_0s == 2)
           {
               //calculate rank
               //binary rank will be 6 bits
               strRankBinary = "yyyyyy";
           }
       }
    }
    else
    {
        strRankBinary = "000000";
    }

    return strRankBinary;
}
</code>```

We want to do the rank and unrank operations for the binary number, and determine the maximum number of bits required for "strRankBinary"

Also, we want to generalize the code for "N"-bit numbers and maximum "k" consecutive 0s.

Depending on the maximum rank value, the strRankBinary must contain only the required number of maximum bits.

In the examples given below,

If max_k_0s = 1, maximum rank will be 21, which is 10101 (5 bits) in
binary.

If max_k_0s = 2, maximum rank will be 44, which is 101100 (6 bits) in
binary.

Example 1 (max 1 consecutive 0s in 6-digit binary value):

```<code>Number      Rank    Binary rank
-------------------------------
000000       0      00000
000001       0      00000
000010       0      00000
000011       0      00000
000100       0      00000
000101       0      00000
000110       0      00000
000111       0      00000
001000       0      00000
001001       0      00000
001010       0      00000
001011       0      00000
001100       0      00000
001101       0      00000
001110       0      00000
001111       0      00000
010000       0      00000
010001       0      00000
010010       0      00000
010011       0      00000
010100       0      00000
010101       1      00001
010110       2      00010
010111       3      00011
011000       0      00000
011001       0      00000
011010       4      00100
011011       5      00101
011100       0      00000
011101       6      00110
011110       7      00111
011111       8      01000
100000       0      00000
100001       0      00000
100010       0      00000
100011       0      00000
100100       0      00000
100101       0      00000
100110       0      00000
100111       0      00000
101000       0      00000
101001       0      00000
101010       9      01001
101011      10      01010
101100       0      00000
101101      11      01011
101110      12      01100
101111      13      01101
110000       0      00000
110001       0      00000
110010       0      00000
110011       0      00000
110100       0      00000
110101      14      01110
110110      15      01111
110111      16      10000
111000       0      00000
111001       0      00000
111010      17      10001
111011      18      10010
111100       0      00000
111101      19      10011
111110      20      10100
111111      21      10101
</code>```

Example 2 (max 2 consecutive 0s in 6-digit binary value):

```<code>Number      Rank    Binary rank
-------------------------------
000000       0      000000
000001       0      000000
000010       0      000000
000011       0      000000
000100       0      000000
000101       0      000000
000110       0      000000
000111       0      000000
001000       0      000000
001001       1      000001
001010       2      000010
001011       3      000011
001100       4      000100
001101       5      000101
001110       6      000110
001111       7      000111
010000       0      000000
010001       0      000000
010010       8      001000
010011       9      001001
010100      10      001010
010101      11      001011
010110      12      001100
010111      13      001101
011000       0      000000
011001      14      001110
011010      15      001111
011011      16      010000
011100      17      010001
011101      18      010010
011110      19      010011
011111      20      010100
100000       0      000000
100001       0      000000
100010       0      000000
100011       0      000000
100100      21      010101
100101      22      010110
100110      23      010111
100111      24      011000
101000       0      000000
101001      25      011001
101010      26      011010
101011      27      011011
101100      28      011100
101101      29      011101
101110      30      011110
101111      31      011111
110000       0      000000
110001       0      000000
110010      32      100000
110011      33      100001
110100      34      100010
110101      35      100011
110110      36      100100
110111      37      100101
111000       0      000000
111001      38      100110
111010      39      100111
111011      40      101000
111100      41      101001
111101      42      101010
111110      43      101011
111111      44      101100
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Consider N = 6 bits

We have a set S = 2^6 = 64 binary combinations.

We want to consider a subset T of the set S based on the following criteria -

There must be <= k consecutive 0s in the subset T.

Accordingly,

If the binary number is present in subset T, calculate its rank (in binary format)

If the binary number is not present in subset T, return 0 (in binary format)

Note: We want to calculate the rank only by iterating the N bits of the given binary number, and NOT by iterating 2^N numbers.

Here is the pseudo-code -

string GetBinaryRank(string strBinaryNumber, int max_k_0s)
{
    string strRankBinary = "";

    if(strBinaryNumber.Contains(<= max_k_0s))
    {
       //calculate strRankBinary by iterating over the N bits of strBinaryNumber
       for(int i = 0; i < strBinaryNumber.Length; i++)
       {
           if(max_k_0s == 1)
           {
               //calculate rank
               //binary rank will be 5 bits
               strRankBinary = "xxxxx";
           }
           else if(max_k_0s == 2)
           {
               //calculate rank
               //binary rank will be 6 bits
               strRankBinary = "yyyyyy";
           }
       }
    }
    else
    {
        strRankBinary = "000000";
    }

    return strRankBinary;
}

We want to do the rank and unrank operations for the binary number, and determine the maximum number of bits required for "strRankBinary"

Also, we want to generalize the code for "N"-bit numbers and maximum "k" consecutive 0s.

Depending on the maximum rank value, the strRankBinary must contain only the required number of maximum bits.

In the examples given below,

If max_k_0s = 1, maximum rank will be 21, which is 10101 (5 bits) in
binary.

If max_k_0s = 2, maximum rank will be 44, which is 101100 (6 bits) in
binary.

Example 1 (max 1 consecutive 0s in 6-digit binary value):

Number      Rank    Binary rank
-------------------------------
000000       0      00000
000001       0      00000
000010       0      00000
000011       0      00000
000100       0      00000
000101       0      00000
000110       0      00000
000111       0      00000
001000       0      00000
001001       0      00000
001010       0      00000
001011       0      00000
001100       0      00000
001101       0      00000
001110       0      00000
001111       0      00000
010000       0      00000
010001       0      00000
010010       0      00000
010011       0      00000
010100       0      00000
010101       1      00001
010110       2      00010
010111       3      00011
011000       0      00000
011001       0      00000
011010       4      00100
011011       5      00101
011100       0      00000
011101       6      00110
011110       7      00111
011111       8      01000
100000       0      00000
100001       0      00000
100010       0      00000
100011       0      00000
100100       0      00000
100101       0      00000
100110       0      00000
100111       0      00000
101000       0      00000
101001       0      00000
101010       9      01001
101011      10      01010
101100       0      00000
101101      11      01011
101110      12      01100
101111      13      01101
110000       0      00000
110001       0      00000
110010       0      00000
110011       0      00000
110100       0      00000
110101      14      01110
110110      15      01111
110111      16      10000
111000       0      00000
111001       0      00000
111010      17      10001
111011      18      10010
111100       0      00000
111101      19      10011
111110      20      10100
111111      21      10101

Example 2 (max 2 consecutive 0s in 6-digit binary value):

Number      Rank    Binary rank
-------------------------------
000000       0      000000
000001       0      000000
000010       0      000000
000011       0      000000
000100       0      000000
000101       0      000000
000110       0      000000
000111       0      000000
001000       0      000000
001001       1      000001
001010       2      000010
001011       3      000011
001100       4      000100
001101       5      000101
001110       6      000110
001111       7      000111
010000       0      000000
010001       0      000000
010010       8      001000
010011       9      001001
010100      10      001010
010101      11      001011
010110      12      001100
010111      13      001101
011000       0      000000
011001      14      001110
011010      15      001111
011011      16      010000
011100      17      010001
011101      18      010010
011110      19      010011
011111      20      010100
100000       0      000000
100001       0      000000
100010       0      000000
100011       0      000000
100100      21      010101
100101      22      010110
100110      23      010111
100111      24      011000
101000       0      000000
101001      25      011001
101010      26      011010
101011      27      011011
101100      28      011100
101101      29      011101
101110      30      011110
101111      31      011111
110000       0      000000
110001       0      000000
110010      32      100000
110011      33      100001
110100      34      100010
110101      35      100011
110110      36      100100
110111      37      100101
111000       0      000000
111001      38      100110
111010      39      100111
111011      40      101000
111100      41      101001
111101      42      101010
111110      43      101011
111111      44      101100


问:
oauth-2.0: can i create my own oauth-2.0 provider
My problem is:

I have my authenticate server in my own running in app_1 with some user's account.

I create another application app_2 and i want to help my user's account in app_1 can login in app_2(app_1 like Open authenticate provider, ex: Facebook, google,..... and app_2 can login with app_1 account)

I try to find how to config or architecture of OAuth provider what i can apply in application.
Where i can find the way to do it?
Appreciate if anyone can help me.


问:
Need help getting Nuxt 3 form to post emails to my Strapi 4 Subscriber collection
I have the following code but it does not post to my Subscriber collection. When I put in an email address it does not post to my subscriber collection type. Also it does not console.log
Using Nuxt3/Strapi4

```<code><template>
    <div class="relative flex justify-center w-full h-64 pb-16 mt-14 subscribe-bg">
      <Container>
        <div class="w-full mx-auto lg:w-3/6">
          <div class="px-10 -mt-12 text-center bg-white rounded-lg shadow-xl py-9 subscribe-box">
            <Heading tag="h3" font-style="h3">Subscribe</Heading>
            <Heading tag="h2" font-style="h2">Never miss a planner</Heading>
            <p
              class="w-full px-2 mx-auto text-center pb-7 text-brand-grey-400"
            >Subscribe to receice the worlds most cutting edge planner news direct to your inbox. Our newsletter is on fire.</p>
            <div class="flex items-center">
              <form @submit.prevent="handleSuscribe">
                <input-field
                  id="email"
                  v-model="email.email"
                  type="email"
                  name="email"
                  placeholder="Your email"
                  class="w-3/4 mr-8"
                />
              <Btn class="h-full" type="submit">Subscribe</Btn>
              </form>
             </div>
          </div>
        </div>
      </Container>
    </div>
  </template>

<script setup>
import { useToast } from 'vue-toastification';
const toast = useToast();

const email = ref({ email: "" })
const handleSuscribe = async () => {
  await $fetch("http://localhost:1337/api/subscribers", {
    method: "POST",
    body: {
      data: {
        email: email.value,
      }
    }
  })
  console.log(email.value)
  console.log(handleSuscribe)
}

</script>
</code>```

Tried to convert from the following code from Nuxt 2. It looked pretty simple at first but now I am running into issues.

```<code><template>
      <div
        class="sm:flex mx-auto items-center m-10 justify-center space-x-6 sm:space-x-20 m-3 sm:m-6 mx-6"
      >
        <div>
          <h1 class="text-lg m-7">Sign Up For NewsLetter</h1>
        </div>
        <div>
          <form @submit="handleSuscribe">
            <input
              id=""
              v-model="email"
              class="p-2 m-3 sm:m-0 border border-solid border-t-0 border-l-0 border-r-0 border-b-1 outline-none border-black"
              type="email"
              name=""
              placeholder="email"
            />
            <button type="submit" class="button--grey">Subscribe</button>
          </form>
        </div>
      </div>
    </template>

    <script>
    export default {
      name: 'NewsLetter',
      data() {
        return {
          email: '',
        }
      },
      methods: {
        async handleSuscribe(e) {
          e.preventDefault()
          this.$swal({
            title: 'Successful!',
            text: 'Thanks for Subscribing',
            icon: 'success',
            button: 'Ok',
          })
          await this.$strapi.$subscribers.create({ Email: this.email })
          this.email = '' // clear email input
        },
      },
    }
    </script>
</code>```

Body:
I have the following code but it does not post to my Subscriber collection. When I put in an email address it does not post to my subscriber collection type. Also it does not console.log
Using Nuxt3/Strapi4

<template>

      <Container>

            <Heading tag="h3" font-style="h3">Subscribe</Heading>
            <Heading tag="h2" font-style="h2">Never miss a planner</Heading>

Subscribe to receice the worlds most cutting edge planner news direct to your inbox. Our newsletter is on fire.

              <form @submit.prevent="handleSuscribe">
                <input-field
                  id="email"
                  v-model="email.email"
                  type="email"
                  name="email"
                  placeholder="Your email"
                  class="w-3/4 mr-8"
                />
              <Btn class="h-full" type="submit">Subscribe</Btn>
              </form>

      </Container>

  </template>

Tried to convert from the following code from Nuxt 2. It looked pretty simple at first but now I am running into issues.

<template>

Sign Up For NewsLetter

          <form @submit="handleSuscribe">
            <input
              id=""
              v-model="email"
              class="p-2 m-3 sm:m-0 border border-solid border-t-0 border-l-0 border-r-0 border-b-1 outline-none border-black"
              type="email"
              name=""
              placeholder="email"
            />
            <button type="submit" class="button--grey">Subscribe</button>
          </form>

    </template>


问:
TypeError: Cannot read properties of undefined (reading 'insertOne')
I had this error when I try to add a review using the curl command:

```<code>curl -X POST http://localhost:4444/api/v1/reviews/new -H “Content-Type:application/json” -d ‘{“movieId”:12,”user”:”sara”,”review”:”good”}’
</code>```

reviews.controller.js

```<code>import reviewsDAO from "../dao/reviewsDAO.js";

export default class ReviewsController{

  static async apiPostReview(req, res, next) {
    try {
      const movieId = parseInt(req.body.movieId)
      const review = req.body.review
      const user = req.body.user
      console.log('movieId', movieId)
      const reviewResponse = await reviewsDAO.addReview(
        movieId,
        user,
        review
      )
      res.json({ status: "success" })
    } catch (e) {
      res.status(500).json({ error: e.message })
    }
  }

  static async apiGetReview(req, res, next) {
    try {
      let id = req.params.id || {}
      let review = await reviewsDAO.getReview(id)
      if (!review) {
        res.status(404).json({ error: "Not found" })
        return
      }
      res.json(review)
    } catch (e) {
      console.log(`api, ${e}`)
      res.status(500).json({ error: e })
    }
  }

  static async apiUpdateReview(req, res, next) {
    try {
      const reviewId = req.params.id
      const review = req.body.review
      const user = req.body.user

      const reviewResponse = await reviewsDAO.updateReview(
        reviewId,
        user,
        review
      )

      var { error } = reviewResponse
      if (error) {
        res.status(400).json({ error })
      }

      if (reviewResponse.modifiedCount === 0) {
        throw new Error(
          "unable to update review",
        )
      }

      res.json({ status: "success" })
    } catch (e) {
      res.status(500).json({ error: e.message })
    }
  }

  static async apiDeleteReview(req, res, next) {
    try {
      const reviewId = req.params.id
      const reviewResponse = await reviewsDAO.deleteReview(reviewId)
      res.json({ status: "success" })
    } catch (e) {
      res.status(500).json({ error: e.message })
    }
  }

  static async apiGetReviews(req, res, next) {
    try {
      let id = req.params.id || {}
      let reviews = await reviewsDAO.getReviewsByMovieId(id)
      if (!reviews) {
        res.status(404).json({ error: "Not found" })
        return
      }
      res.json(reviews)
    } catch (e) {
      console.log(`api, ${e}`)
      res.status(500).json({ error: e })
    }
  }
}
</code>```

I have tried several solutions but I didn't resolve the issue

reviewsDAO.js:

```<code>

import mongodb from 'mongodb';
const ObjectID=mongodb.ObjectID;

let reviews;

export default class ReviewsDAO{
    static async injectDB(conn){
        if(reviews){
            return
        }
        try{
            reviews = await conn.db("reviews").collection("reviews");
        } catch(e){
            console.error(`Unable to establish collection handles in userDAO: ${e}..`);
        };
    };

    static async addReview(movieId,user,review){
        try{
            const reviewDoc={
                movieId:movieId,
                user:user,
                review:review
            }
            return await reviews.insertOne(reviewDoc);
        }catch(e){
            console.error(`Unable to post review: ${e}`);
            return{error:e};
        };
    };

    static async getReview(reviewId){
        try{
            return await reviews.findOne({_id:ObjectID(reviewId)})
        }catch(e){
            console.error(`Unable to get review: ${e}`);
            return{error:e};
        };
    };

    static async updateReview(reviewId,user,review){
        try{
            const updateResponse=await review.updateOne({_id:ObjectID(reviewId)},
            {$set:{user:user,review:review}});
            return updateResponse;
        }catch(e){
            console.error(`Unable to update review: ${e}`);
            return{error:e};
        };

    };

    static async getReviewByMovieId(movieId){
        try{
            const cursor=await reviews.find({movieId: parseInt(movieId)});
            return cursor.toArray();

        }catch(e){
            console.error(`Unable to get review: ${e}`);
            return{error:e};
        };
    };

};

</code>```

reviews.route.js:

```<code>import express from 'express';
import ReviewsCtrl from "./reviews.controller.js";

const router=express.Router();

router.route("/movie/:id").get(ReviewsCtrl.apiGetReviews);
router.route("/new").post(ReviewsCtrl.apiPostReview);
router.route("/:id")
    .get(ReviewsCtrl.apiGetReviews)
    .put(ReviewsCtrl.apiUpdateReview)
    .delete(ReviewsCtrl.apiDeleteReview)

export default router;
</code>```

moviedb.js:

```<code>import app from './server.js';
import ReviewsDAO from "./dao/reviewsDAO.js";
import mongodb from 'mongodb';
import dotenv from 'dotenv';

const MongoClient=mongodb.MongoClient

dotenv.config();
const mongo_username = process.env.MONGO_USERNAME;
const mongo_password = process.env.MONGO_PASSWORD;

const port=4444;

MongoClient.connect(`mongodb+srv://${mongo_username}:${mongo_password}@cluster0.b5f7prn.mongodb.net/test`,
{
  maxPoolSize: 50,
  wtimeoutMS: 2500,
  useNewUrlParser: true
})
.catch(err => {
    console.error(err.stack)
    console.error("Error connecting to the database:", err.message)
    process.exit(1)
  })
.then(async client => {
    await ReviewsDAO.injectDB(client)
    app.listen(port, () => {
      console.log(`listening on port ${port}`)
    })
  })

</code>```

Body:
I had this error when I try to add a review using the curl command:

curl -X POST http://localhost:4444/api/v1/reviews/new -H “Content-Type:application/json” -d ‘{“movieId”:12,”user”:”sara”,”review”:”good”}’

reviews.controller.js

import reviewsDAO from "../dao/reviewsDAO.js";

export default class ReviewsController{

  static async apiPostReview(req, res, next) {
    try {
      const movieId = parseInt(req.body.movieId)
      const review = req.body.review
      const user = req.body.user
      console.log('movieId', movieId)
      const reviewResponse = await reviewsDAO.addReview(
        movieId,
        user,
        review
      )
      res.json({ status: "success" })
    } catch (e) {
      res.status(500).json({ error: e.message })
    }
  }

  static async apiGetReview(req, res, next) {
    try {
      let id = req.params.id || {}
      let review = await reviewsDAO.getReview(id)
      if (!review) {
        res.status(404).json({ error: "Not found" })
        return
      }
      res.json(review)
    } catch (e) {
      console.log(`api, ${e}`)
      res.status(500).json({ error: e })
    }
  }

  static async apiUpdateReview(req, res, next) {
    try {
      const reviewId = req.params.id
      const review = req.body.review
      const user = req.body.user

      const reviewResponse = await reviewsDAO.updateReview(
        reviewId,
        user,
        review
      )

      var { error } = reviewResponse
      if (error) {
        res.status(400).json({ error })
      }

      if (reviewResponse.modifiedCount === 0) {
        throw new Error(
          "unable to update review",
        )
      }

      res.json({ status: "success" })
    } catch (e) {
      res.status(500).json({ error: e.message })
    }
  }

  static async apiDeleteReview(req, res, next) {
    try {
      const reviewId = req.params.id
      const reviewResponse = await reviewsDAO.deleteReview(reviewId)
      res.json({ status: "success" })
    } catch (e) {
      res.status(500).json({ error: e.message })
    }
  }

  static async apiGetReviews(req, res, next) {
    try {
      let id = req.params.id || {}
      let reviews = await reviewsDAO.getReviewsByMovieId(id)
      if (!reviews) {
        res.status(404).json({ error: "Not found" })
        return
      }
      res.json(reviews)
    } catch (e) {
      console.log(`api, ${e}`)
      res.status(500).json({ error: e })
    }
  }
}

I have tried several solutions but I didn't resolve the issue

reviewsDAO.js:

import mongodb from 'mongodb';
const ObjectID=mongodb.ObjectID;

let reviews;

export default class ReviewsDAO{
    static async injectDB(conn){
        if(reviews){
            return
        }
        try{
            reviews = await conn.db("reviews").collection("reviews");
        } catch(e){
            console.error(`Unable to establish collection handles in userDAO: ${e}..`);
        };
    };

    static async addReview(movieId,user,review){
        try{
            const reviewDoc={
                movieId:movieId,
                user:user,
                review:review
            }
            return await reviews.insertOne(reviewDoc);
        }catch(e){
            console.error(`Unable to post review: ${e}`);
            return{error:e};
        };
    };

    static async getReview(reviewId){
        try{
            return await reviews.findOne({_id:ObjectID(reviewId)})
        }catch(e){
            console.error(`Unable to get review: ${e}`);
            return{error:e};
        };
    };

    static async updateReview(reviewId,user,review){
        try{
            const updateResponse=await review.updateOne({_id:ObjectID(reviewId)},
            {$set:{user:user,review:review}});
            return updateResponse;
        }catch(e){
            console.error(`Unable to update review: ${e}`);
            return{error:e};
        };

    };

    static async getReviewByMovieId(movieId){
        try{
            const cursor=await reviews.find({movieId: parseInt(movieId)});
            return cursor.toArray();

        }catch(e){
            console.error(`Unable to get review: ${e}`);
            return{error:e};
        };
    };

};

reviews.route.js:

import express from 'express';
import ReviewsCtrl from "./reviews.controller.js";

const router=express.Router();

router.route("/movie/:id").get(ReviewsCtrl.apiGetReviews);
router.route("/new").post(ReviewsCtrl.apiPostReview);
router.route("/:id")
    .get(ReviewsCtrl.apiGetReviews)
    .put(ReviewsCtrl.apiUpdateReview)
    .delete(ReviewsCtrl.apiDeleteReview)

export default router;

moviedb.js:

import app from './server.js';
import ReviewsDAO from "./dao/reviewsDAO.js";
import mongodb from 'mongodb';
import dotenv from 'dotenv';

const MongoClient=mongodb.MongoClient

dotenv.config();
const mongo_username = process.env.MONGO_USERNAME;
const mongo_password = process.env.MONGO_PASSWORD;

const port=4444;

MongoClient.connect(`mongodb+srv://${mongo_username}:${mongo_password}@cluster0.b5f7prn.mongodb.net/test`,
{
  maxPoolSize: 50,
  wtimeoutMS: 2500,
  useNewUrlParser: true
})
.catch(err => {
    console.error(err.stack)
    console.error("Error connecting to the database:", err.message)
    process.exit(1)
  })
.then(async client => {
    await ReviewsDAO.injectDB(client)
    app.listen(port, () => {
      console.log(`listening on port ${port}`)
    })
  })


问:
Automation for WhatsApp group
I'm trying to automate WhatsApp to send messages to my company's WhatsApp groups, which are provided in an excel file. But unfortunately it doesn't work, it's giving an error.

AttributeError: 'WebDriver' object has no attribute 'find_elements_by_id'

I want it to always run every week on the scheduled day and time. I tried several methods and failed.

contatos_df = pd.read_excel("Enviar.xlsx")
display(contatos_df)
```
<hr />
```from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
import urllib

navegador = webdriver.Chrome()
navegador.get("https://web.whatsapp.com/")

while len(navegador.find_elements_by_id("side")) < 1:
    time.sleep(1)

# já estamos com o login feito no whatsapp web
for i, mensagem in enumerate(contatos_df['Mensagem']):
    grupo = contatos_df.loc[i, "grupo"]
    texto = urllib.parse.quote(f"Oi {grupo}! {mensagem}")
    link = f"https://web.whatsapp.com/send?phone={numero}&text={texto}"
    navegador.get(link)
    while len(navegador.find_elements_by_id("side")) < 1:
        time.sleep(1)
    navegador.find_element_by_xpath('//*[@id="main"]/footer/div[1]/div[2]/div/div[2]').send_keys(Keys.ENTER)
    time.sleep(10)
```

Title: Automation for WhatsApp group

Body:
I'm trying to automate WhatsApp to send messages to my company's WhatsApp groups, which are provided in an excel file. But unfortunately it doesn't work, it's giving an error.

AttributeError: 'WebDriver' object has no attribute 'find_elements_by_id'

I want it to always run every week on the scheduled day and time. I tried several methods and failed.

contatos_df = pd.read_excel("Enviar.xlsx")
display(contatos_df)

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
import urllib

navegador = webdriver.Chrome()
navegador.get("https://web.whatsapp.com/")

while len(navegador.find_elements_by_id("side")) < 1:
    time.sleep(1)

# já estamos com o login feito no whatsapp web
for i, mensagem in enumerate(contatos_df['Mensagem']):
    grupo = contatos_df.loc[i, "grupo"]
    texto = urllib.parse.quote(f"Oi {grupo}! {mensagem}")
    link = f"https://web.whatsapp.com/send?phone={numero}&text={texto}"
    navegador.get(link)
    while len(navegador.find_elements_by_id("side")) < 1:
        time.sleep(1)
    navegador.find_element_by_xpath('//*[@id="main"]/footer/div[1]/div[2]/div/div[2]').send_keys(Keys.ENTER)
    time.sleep(10)


问:
"Failed to load resource: the server responded with a status of 415 (Unsupported Media Type)". How to fix Error
I'm trying to submit post form data to an my api using react and I'm passing through JSON data like so.

`

```<code>function AddSong() {
    const [title, setTitle] = useState("");
    const [artist, setArtist] = useState("");
    const [release_date, setReleaseDate] = useState("");
    const [album, setAlbum] = useState("");
    const [genre, setGenre] = useState("");

    let handleSubmit = async (e) => {
      e.preventDefault();
      try {
        let res = await fetch("http://127.0.0.1:8000/api/music_library/?format=json", {
          method: "POST",
          body: JSON.stringify({
            title: title,
            artist: artist,
            album: album,
            release_date: release_date,
            genre: genre,
          }),
        });
        let resJson = await res.json();
        if (res.status === 200) {
          setTitle("");
          setArtist("");
          setReleaseDate("");
          setAlbum("");
          setGenre("");
        }
      } catch (err) {
        console.log(err);
      }
    };
</code>```

`

Here is my submit form.
`

```<code>return (
      <div className="App">
        <form onSubmit={handleSubmit}>
          <input
            type="text"
            value={title}
            placeholder="Title"
            onChange={(e) => setTitle(e.target.value)}
          />
          <input
            type="text"
            value={artist}
            placeholder="Artist"
            onChange={(e) => setArtist(e.target.value)}
          />
          <input
            type="text"
            value={release_date}
            placeholder="Year"
            onChange={(e) => setReleaseDate(e.target.value)}
          />
          <input
            type="text"
            value={album}
            placeholder="Album"
            onChange={(e) => setAlbum(e.target.value)}
          />
          <input
            type="text"
            value={genre}
            placeholder="Genre"
            onChange={(e) => setGenre(e.target.value)}
          />

          <button type="submit">Create</button>

        </form>
      </div>
    );
  }

  export default AddSong;
</code>```

`

When I click submit on the form, Chrome gives me an error saying "Failed to load resource: the server responded with a status of 415 (Unsupported Media Type)". I know it has something to do with the HandleSubmit function and the url im giving it. Im just not sure how to structure it correctly.

I tried going to the django api website and changing the get request url to JSON. I was expecting that accept the JSON data im passing through however it did not and instead gave me the same error I got when using the regular url.

Body:
I'm trying to submit post form data to an my api using react and I'm passing through JSON data like so.

`

function AddSong() {
    const [title, setTitle] = useState("");
    const [artist, setArtist] = useState("");
    const [release_date, setReleaseDate] = useState("");
    const [album, setAlbum] = useState("");
    const [genre, setGenre] = useState("");

    let handleSubmit = async (e) => {
      e.preventDefault();
      try {
        let res = await fetch("http://127.0.0.1:8000/api/music_library/?format=json", {
          method: "POST",
          body: JSON.stringify({
            title: title,
            artist: artist,
            album: album,
            release_date: release_date,
            genre: genre,
          }),
        });
        let resJson = await res.json();
        if (res.status === 200) {
          setTitle("");
          setArtist("");
          setReleaseDate("");
          setAlbum("");
          setGenre("");
        }
      } catch (err) {
        console.log(err);
      }
    };

`

Here is my submit form.
`

return (

        <form onSubmit={handleSubmit}>
          <input
            type="text"
            value={title}
            placeholder="Title"
            onChange={(e) => setTitle(e.target.value)}
          />
          <input
            type="text"
            value={artist}
            placeholder="Artist"
            onChange={(e) => setArtist(e.target.value)}
          />
          <input
            type="text"
            value={release_date}
            placeholder="Year"
            onChange={(e) => setReleaseDate(e.target.value)}
          />
          <input
            type="text"
            value={album}
            placeholder="Album"
            onChange={(e) => setAlbum(e.target.value)}
          />
          <input
            type="text"
            value={genre}
            placeholder="Genre"
            onChange={(e) => setGenre(e.target.value)}
          />

          <button type="submit">Create</button>

        </form>

    );
  }

  export default AddSong;

`

When I click submit on the form, Chrome gives me an error saying "Failed to load resource: the server responded with a status of 415 (Unsupported Media Type)". I know it has something to do with the HandleSubmit function and the url im giving it. Im just not sure how to structure it correctly.

I tried going to the django api website and changing the get request url to JSON. I was expecting that accept the JSON data im passing through however it did not and instead gave me the same error I got when using the regular url.


问:
what circumstances does javascript catch an empty error object?
in my web project, i try to catch all web error and send error to server;

my code like this:

```<code>window.onerror = (message, url, lineNo, columnNo, errorObj) => {
    var originErrorCloned = Object.getOwnPropertyNames((errorObj || {})).reduce(function(result, key){
       result[key] = error[key];
       return result;
    }, {});
    // do send originErrorCloned object to server;
    fetch('xxx', {body: JSON.stringify({error: originErrorCloned})})
};

</code>```

in server, i get some error look like empty object

```<code>{}
</code>```

normal error be like

```<code>{
   "error": "{\"stack\":\"xxx\\n xxx \\n xxx \\n",\"message\":\"Cannot read property 'xxxx' of undefined\"}"
}
</code>```

in my previous version code, i try report error like this

```<code>
window.onerror = (message, url, lineNo, columnNo, errorObj) => {
    fetch('xxx', {body: JSON.stringify({
       message: errorObj.message,
       stack: errorObj.stack,
       name: errorObj.name
    })});

};

</code>```

if errorObj's properties not all undefine, the server will get report like {"message":"", stack:"",name: ""} ,but server get report like "{}",
so i guess errorObj's properties(message,stack,name) are all undefine(void 0),because JSON.stringify will ignore undefine properties name and keep null(eg: empty string) properties name

so my question is how to create a javascript Empty Error ?

and i found most part of empty error object report from applewebkit(safari) or gecko(firefox) webengine and device is Windows PC;

i try to use safrai devtools to create a Error like

```<code>new Error('');  // get {message: '', ...others}
new Error(void 0); // get {stack: 'xxxx', ...others}
new Error({});  // get {message: '[Object Object]'}

</code>```

Body:
in my web project, i try to catch all web error and send error to server;

my code like this:

window.onerror = (message, url, lineNo, columnNo, errorObj) => {
    var originErrorCloned = Object.getOwnPropertyNames((errorObj || {})).reduce(function(result, key){
       result[key] = error[key];
       return result;
    }, {});
    // do send originErrorCloned object to server;
    fetch('xxx', {body: JSON.stringify({error: originErrorCloned})})
};

in server, i get some error look like empty object

{}

normal error be like

{
   "error": "{\"stack\":\"xxx\\n xxx \\n xxx \\n",\"message\":\"Cannot read property 'xxxx' of undefined\"}"
}

in my previous version code, i try report error like this

window.onerror = (message, url, lineNo, columnNo, errorObj) => {
    fetch('xxx', {body: JSON.stringify({
       message: errorObj.message,
       stack: errorObj.stack,
       name: errorObj.name
    })});

};

if errorObj's properties not all undefine, the server will get report like {"message":"", stack:"",name: ""} ,but server get report like "{}",
so i guess errorObj's properties(message,stack,name) are all undefine(void 0),because JSON.stringify will ignore undefine properties name and keep null(eg: empty string) properties name

so my question is how to create a javascript Empty Error ?

and i found most part of empty error object report from applewebkit(safari) or gecko(firefox) webengine and device is Windows PC;

i try to use safrai devtools to create a Error like

new Error('');  // get {message: '', ...others}
new Error(void 0); // get {stack: 'xxxx', ...others}
new Error({});  // get {message: '[Object Object]'}


问:
`flutter run -d chrome` always closes the chrome after render
I'm trying to see / develop the flutter app in Web.

However, when I run:

flutter run -d chrome
```
<p>It can start a chrome browser, and render the page properly; then it would just close, and the process just exit.</p>
<p>I'm also trying:</p>
<pre class="lang-bash prettyprint-override"><code>➜  slide_puzzle git:(release) ✗ webdev serve
webdev could not run for this project.
Could not find a file named "pubspec.yaml" in "$HOME/.pub-cache/hosted/pub.dartlang.org/_fe_analyzer_shared-47.0.0".
</code>```

Here's the project I'm trying to run: <github.com/VGVentures/slide_puzzle>

I'm on Mac, running with latest flutter:

```<code>➜  slide_puzzle git:(release) ✗ flutter --version
Flutter 3.3.10 • channel stable • https://github.com/flutter/flutter.git
Framework • revision 135454af32 (2 weeks ago) • 2022-12-15 07:36:55 -0800
Engine • revision 3316dd8728
Tools • Dart 2.18.6 • DevTools 2.15.0
</code>```

Body:
I'm trying to see / develop the flutter app in Web.

However, when I run:

flutter run -d chrome

It can start a chrome browser, and render the page properly; then it would just close, and the process just exit.

I'm also trying:

➜  slide_puzzle git:(release) ✗ webdev serve
webdev could not run for this project.
Could not find a file named "pubspec.yaml" in "$HOME/.pub-cache/hosted/pub.dartlang.org/_fe_analyzer_shared-47.0.0".

Here's the project I'm trying to run: <github.com/VGVentures/slide_puzzle>

I'm on Mac, running with latest flutter:

➜  slide_puzzle git:(release) ✗ flutter --version
Flutter 3.3.10 • channel stable • https://github.com/flutter/flutter.git
Framework • revision 135454af32 (2 weeks ago) • 2022-12-15 07:36:55 -0800
Engine • revision 3316dd8728
Tools • Dart 2.18.6 • DevTools 2.15.0


问:
psql: error: connection to server on socket "/tmp/.s.PGSQL.5432" failed:
NOTE: I have a MacOS Monterey M1 chip.

After I put in the command line - psql postgres - I get the response state below.

```<code>psql: error: connection to server on socket "/tmp/.s.PGSQL.5432" failed: Connection refused
    Is the server running locally and accepting connections on that socket?
</code>```

I have done the following already:

Restarting PostgreSQL using homebrew brew services restart  postgresql

Re-installing PostgreSQL using Homebrew

```<code>brew uninstall postgresql
</code>```

Updating PostgreSQL using Homebrew

```<code>brew install postgresql@14
brew services start postgresql@14
brew link postgresql@14 --force
</code>```

Body:
NOTE: I have a MacOS Monterey M1 chip.

After I put in the command line - psql postgres - I get the response state below.

psql: error: connection to server on socket "/tmp/.s.PGSQL.5432" failed: Connection refused
    Is the server running locally and accepting connections on that socket?

I have done the following already:

Restarting PostgreSQL using homebrew brew services restart  postgresql

Re-installing PostgreSQL using Homebrew

brew uninstall postgresql

Updating PostgreSQL using Homebrew

brew install postgresql@14
brew services start postgresql@14
brew link postgresql@14 --force


问:
Error: Channel closed by server: 406 (PRECONDITION-FAILED) with message "PRECONDITION_FAILED
i was use RabbitMQ to consume data.
But, sometime in my Consumer its returning error

Error: Channel closed by server: 406 (PRECONDITION-FAILED) with message "PRECONDITION_FAILED - delivery acknowledgement on channel 2 timed out. Timeout value used: 1800000 ms. This timeout value can be configured, see consumers doc guide to learn more"

How can i handle that error?

Here my code

```<code>const services: Service[] = [
  {
    channel: "post-now",
    controller: PostNowController,
  },
  {
    channel: "post-queue",
    controller: PostQueueController,
  },
];

async function boostrap(services: Service[]) {
  try {
    const app = await NestFactory.createApplicationContext(AppModule);

    amqp
      .connect(process.env.RABBITMQ_URL)
      .then((connection) => {
        services.forEach(async (service: Service) => {
          const channel = await connection.createChannel();
          const channelService = channel.assertQueue(service.channel, {
            durable: false,
          });

          if (channelService) {
            try {
              const appController = app.get(service.controller);

              channel.prefetch(30);
              channel
                .consume(
                  service.channel,
                  async (message: any) => {
                    try {
                      const data = JSON.parse(message.content.toString());
                      await appController.exec(data);

                      channel.ack(message);
                    } catch (error) {
                      channel.ack(message);
                      console.log("error consume", service.channel, error);
                    }
                  },
                  { noAck: false }
                )
                .catch((error) => {
                  logger.error(`error consume catch channel consume, ${error}`);
                });
            } catch (error) {
              logger.error(`error consume try catch, ${error}`);
            }
          }

          logger.log(`Watching channel ${service.channel} ...`);
        });
      })
      .catch((error: any) => logger.error(`error connection, ${error}`));
  } catch (error) {
    console.log(`error boostrap, ${error}`);
  }
}

boostrap(services);
</code>```

i was try to catch in every statement, but still not handled

I was expecting, handle that error so that the node does not restart

Body:
i was use RabbitMQ to consume data.
But, sometime in my Consumer its returning error

Error: Channel closed by server: 406 (PRECONDITION-FAILED) with message "PRECONDITION_FAILED - delivery acknowledgement on channel 2 timed out. Timeout value used: 1800000 ms. This timeout value can be configured, see consumers doc guide to learn more"

How can i handle that error?

Here my code

const services: Service[] = [
  {
    channel: "post-now",
    controller: PostNowController,
  },
  {
    channel: "post-queue",
    controller: PostQueueController,
  },
];

async function boostrap(services: Service[]) {
  try {
    const app = await NestFactory.createApplicationContext(AppModule);

    amqp
      .connect(process.env.RABBITMQ_URL)
      .then((connection) => {
        services.forEach(async (service: Service) => {
          const channel = await connection.createChannel();
          const channelService = channel.assertQueue(service.channel, {
            durable: false,
          });

          if (channelService) {
            try {
              const appController = app.get(service.controller);

              channel.prefetch(30);
              channel
                .consume(
                  service.channel,
                  async (message: any) => {
                    try {
                      const data = JSON.parse(message.content.toString());
                      await appController.exec(data);

                      channel.ack(message);
                    } catch (error) {
                      channel.ack(message);
                      console.log("error consume", service.channel, error);
                    }
                  },
                  { noAck: false }
                )
                .catch((error) => {
                  logger.error(`error consume catch channel consume, ${error}`);
                });
            } catch (error) {
              logger.error(`error consume try catch, ${error}`);
            }
          }

          logger.log(`Watching channel ${service.channel} ...`);
        });
      })
      .catch((error: any) => logger.error(`error connection, ${error}`));
  } catch (error) {
    console.log(`error boostrap, ${error}`);
  }
}

boostrap(services);

i was try to catch in every statement, but still not handled

I was expecting, handle that error so that the node does not restart


问:
The keyboard pushed my page up when open and didn't update when closed
I got a problem with Firefox on iOS devices. I have created the modal component and it has a footer. When the Virtual keyboard opened, It pushed the footer to the top of the keyboard. After I closed the keyboard, the footer didn't stick to the bottom as I expected. The footer lay in the middle of the screen and pushed all the content to the top of the screen.

I tried everything I can but the problem still appear. Your idea will help me a lot.

Thank you so much.

enter image description here

I expect the footer will stick to bottom like this when the Keyboard closed
enter image description here


问:
change the login which originally used the email, password, role_id from the users table to use the UserID, password, level from the Visuser table?
I want to change the authentication, which initially uses data from the users table (default), to use the visuser table.

When I try to log in, no error messages appear, but only endless loading.

loading while login

users table

visuser table

visuser table

I've tried changing some of the code from the files App\Http\Controllers\AuthController, resources\views\auth\login.blade.php, config\auth.php, app\Models\Visuser.php, app\Models\User.php, app\Http\Requests\LoginRequests\LoginRequest.php. I expect it will go to the specified page. In fact, it even loads endlessly.

routes\web.php

```<code><?php

use App\Http\Controllers\AttendanceController;
use App\Http\Controllers\AuthController;
use App\Http\Controllers\DashboardController;
use App\Http\Controllers\EmployeeController;
use App\Http\Controllers\HolidayController;
use App\Http\Controllers\HomeController;
use App\Http\Controllers\PositionController;
use App\Http\Controllers\PresenceController;
use Illuminate\Support\Facades\Route;
use SebastianBergmann\CodeCoverage\Report\Html\Dashboard;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::middleware('auth')->group(function () {
    Route::middleware('role:admin,operator')->group(function () {
        // Route::get('/dashboard', [DashboardController::class, 'index'])->name('dashboard.index');
        // positions
        Route::resource('/positions', PositionController::class)->only(['index', 'create']);
        Route::get('/positions/edit', [PositionController::class, 'edit'])->name('positions.edit');
        // employees
        Route::resource('/employees', EmployeeController::class)->only(['index', 'create']);
        Route::get('/employees/edit', [EmployeeController::class, 'edit'])->name('employees.edit');
        // holidays (hari libur)
        Route::resource('/holidays', HolidayController::class)->only(['index', 'create']);
        Route::get('/holidays/edit', [HolidayController::class, 'edit'])->name('holidays.edit');
        // attendances (absensi)
        Route::resource('/attendances', AttendanceController::class)->only(['index', 'create']);

        Route::get('/attendances/edit', [AttendanceController::class, 'edit'])->name('attendances.edit');

        // presences (kehadiran)
        Route::resource('/presences', PresenceController::class)->only(['index']);
        // Route::get('/presences/qrcode', [PresenceController::class, 'showQrcode'])->name('presences.qrcode');
        Route::get('/presences/qrcode/{attendance}', [PresenceController::class, 'showQrcode'])->name('presences.qrcode');
        Route::get('/presences/qrcode/download-pdf', [PresenceController::class, 'downloadQrCodePDF'])->name('presences.qrcode.download-pdf');
        Route::get('/presences/{attendance}', [PresenceController::class, 'show'])->name('presences.show');
        // not present data
        Route::get('/presences/{attendance}/not-present', [PresenceController::class, 'notPresent'])->name('presences.not-present');
        Route::post('/presences/{attendance}/not-present', [PresenceController::class, 'notPresent']);
        // present (url untuk menambahkan/mengubah user yang tidak hadir menjadi hadir)
        Route::post('/presences/{attendance}/present', [PresenceController::class, 'presentUser'])->name('presences.present');
        Route::post('/presences/{attendance}/acceptPermission', [PresenceController::class, 'acceptPermission'])->name('presences.acceptPermission');
        // employees permissions

        Route::get('/presences/{attendance}/permissions', [PresenceController::class, 'permissions'])->name('presences.permissions');
    });

    Route::middleware('role:user')->name('home.')->group(function () {
        Route::get('/', [HomeController::class, 'start'])->name('index');
        Route::get('/home', [HomeController::class, 'index'])->name('home');
        // desctination after scan qrcode
        Route::post('/absensi/qrcode', [HomeController::class, 'sendEnterPresenceUsingQRCode'])->name('sendEnterPresenceUsingQRCode');
        Route::post('/absensi/qrcode/out', [HomeController::class, 'sendOutPresenceUsingQRCode'])->name('sendOutPresenceUsingQRCode');

        Route::get('/absensi/{attendance}', [HomeController::class, 'show'])->name('show');
        Route::get('/absensi/{attendance}/permission', [HomeController::class, 'permission'])->name('permission');
    });

    Route::delete('/logout', [AuthController::class, 'logout'])->name('auth.logout');
});

Route::middleware('guest')->group(function () {
    // auth
    Route::get('/login', [AuthController::class, 'index'])->name('auth.login');
    Route::post('/login', [AuthController::class, 'authenticate']);
});
</code>```

App\Http\Controllers\AuthController

```<code><?php

namespace App\Http\Controllers;

use App\Http\Requests\LoginRequests\LoginRequest;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class AuthController extends Controller
{
    public function index()
    {
        return view('auth.login', [
            "title" => "Masuk"
        ]);
    }

    public function username()
    {
        return 'UserID'; // this string is column of accounts table which we are going use for login
    }

    public function authenticate(LoginRequest $request)
    {
        // $remember = $request->boolean('remember');
        $credentials = $request->only(['UserID', 'password']);

        if (Auth::attempt($credentials)) { // login gagal
            request()->session()->regenerate();
            $data = [
                "success" => true,
                // "redirect_to" => auth()->user()->isUser() ? route('home.index') : route('dashboard.index'),
                "redirect_to" => auth()->user()->isUser() ? route('home.index') : route('attendances.index'),
                "message" => "Login berhasil, silahkan tunggu!"
            ];
            return response()->json($data);
        }

        $data = [
            "success" => false,
            "message" => "Login gagal, silahkan coba lagi!"
        ];
        return response()->json($data)->setStatusCode(400);
    }

    public function logout()
    {
        auth()->logout();

        request()->session()->regenerate();
        request()->session()->regenerateToken();

        return redirect()->route('auth.login')->with('success', 'Anda berhasil keluar.');
    }
}
</code>```

resources\views\auth\login.blade.php

```<code>@extends('layouts.auth')

@push('style')
<link rel="stylesheet" href="{{ asset('css/auth/login.css') }}">
@endpush

@section('content')

<div class="w-100">

    <main class="form-signin w-100 m-auto">
        <form method="POST" action="{{ route('auth.login') }}" id="login-form">
            <h1 class="h3 mb-3 fw-normal">Silahkan masuk untuk absensi</h1>

            <div class="form-floating">
                <input type="text" class="form-control" id="floatingInputEmail" name="UserID"
                    placeholder="User ID">
                <label for="floatingInputEmail">User ID</label>
            </div>
            <div class="form-floating">
                <input type="password" class="form-control" id="floatingPassword" name="password"
                    placeholder="Password">
                <label for="floatingPassword">Password</label>
            </div>

            <div class="form-check mb-3">
                <input class="form-check-input" type="checkbox" name="remember" id="flexCheckRemember">
                <label class="form-check-label" for="flexCheckRemember">
                    Ingatkan Saya di Perangkat ini
                </label>
            </div>

            <button class="w-100 btn btn-primary" type="submit" id="login-form-button">Masuk</button>
            <p class="mt-5 mb-3 text-muted">© 2022</p>
        </form>
    </main>

</div>
@endsection

@push('script')
<script type="module" src="{{ asset('js/auth/login.js') }}"></script>
@endpush
</code>```

config\auth.php

```<code><?php

return [

    /*
    |--------------------------------------------------------------------------
    | Authentication Defaults
    |--------------------------------------------------------------------------
    |
    | This option controls the default authentication "guard" and password
    | reset options for your application. You may change these defaults
    | as required, but they're a perfect start for most applications.
    |
    */

    'defaults' => [
        'guard' => 'web',
        'passwords' => 'users',
    ],

    /*
    |--------------------------------------------------------------------------
    | Authentication Guards
    |--------------------------------------------------------------------------
    |
    | Next, you may define every authentication guard for your application.
    | Of course, a great default configuration has been defined for you
    | here which uses session storage and the Eloquent user provider.
    |
    | All authentication drivers have a user provider. This defines how the
    | users are actually retrieved out of your database or other storage
    | mechanisms used by this application to persist your user's data.
    |
    | Supported: "session"
    |
    */

    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],
    ],

    /*
    |--------------------------------------------------------------------------
    | User Providers
    |--------------------------------------------------------------------------
    |
    | All authentication drivers have a user provider. This defines how the
    | users are actually retrieved out of your database or other storage
    | mechanisms used by this application to persist your user's data.
    |
    | If you have multiple user tables or models you may configure multiple
    | sources which represent each model / table. These sources may then
    | be assigned to any extra authentication guards you have defined.
    |
    | Supported: "database", "eloquent"
    |
    */

    'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\Models\Visuser::class,
        ],

        // 'users' => [
        //     'driver' => 'database',
        //     'table' => 'users',
        // ],
    ],

    /*
    |--------------------------------------------------------------------------
    | Resetting Passwords
    |--------------------------------------------------------------------------
    |
    | You may specify multiple password reset configurations if you have more
    | than one user table or model in the application and you want to have
    | separate password reset settings based on the specific user types.
    |
    | The expire time is the number of minutes that each reset token will be
    | considered valid. This security feature keeps tokens short-lived so
    | they have less time to be guessed. You may change this as needed.
    |
    */

    'passwords' => [
        'users' => [
            'provider' => 'users',
            'table' => 'password_resets',
            'expire' => 60,
            'throttle' => 60,
        ],
    ],

    /*
    |--------------------------------------------------------------------------
    | Password Confirmation Timeout
    |--------------------------------------------------------------------------
    |
    | Here you may define the amount of seconds before a password confirmation
    | times out and the user is prompted to re-enter their password via the
    | confirmation screen. By default, the timeout lasts for three hours.
    |
    */

    'password_timeout' => 10800,

];
</code>```

app\Models\Visuser.php

```<code><?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Database\Eloquent\Model;

class Visuser extends Authenticatable
{
    use HasFactory;

    const USER_ROLE_ID = 5;

    protected $fillable = [
        'UserID',
        'password',
        'level',
    ];

    protected $hidden = [
        'password',
    ];

    public function isUser()
    {
        return $this->role_id === self::USER_ROLE_ID;
    }
}
</code>```

app\Models\User.php

```<code><?php

// namespace App\Models;

// use Illuminate\Contracts\Auth\MustVerifyEmail;
// use Illuminate\Database\Eloquent\Factories\HasFactory;
// use Illuminate\Foundation\Auth\User as Authenticatable;
// use Illuminate\Notifications\Notifiable;
// use Laravel\Sanctum\HasApiTokens;

// class User extends Authenticatable
// {
//     use HasApiTokens, HasFactory, Notifiable;

//     const ADMIN_ROLE_ID = 1;
//     const OPERATOR_ROLE_ID = 2;
//     const USER_ROLE_ID = 3;

//     /**
//      * The attributes that are mass assignable.
//      *
//      * @var array<int, string>
//      */
//     protected $fillable = [
//         'name',
//         'department',
//         'email',
//         'password',
//         'role_id',
//         'position_id',
//         'phone',
//     ];

//     /**
//      * The attributes that should be hidden for serialization.
//      *
//      * @var array<int, string>
//      */
//     protected $hidden = [
//         'password',
//         'remember_token',
//     ];

//     /**
//      * The attributes that should be cast.
//      *
//      * @var array<string, string>
//      */
//     protected $casts = [
//         'email_verified_at' => 'datetime',
//     ];

//     public function role()
//     {
//         return $this->belongsTo(Role::class);
//     }

//     public function position()
//     {
//         return $this->belongsTo(Position::class);
//     }

//     public function scopeOnlyEmployees($query)
//     {
//         return $query->where('role_id', self::USER_ROLE_ID);
//     }

//     public function isAdmin()
//     {
//         return $this->role_id === self::ADMIN_ROLE_ID;
//     }

//     public function isOperator()
//     {
//         return $this->role_id === self::OPERATOR_ROLE_ID;
//     }

//     public function isUser()
//     {
//         return $this->role_id === self::USER_ROLE_ID;
//     }
// }
</code>```

app\Http\Requests\LoginRequests\LoginRequest.php

```<code><?php

namespace App\Http\Requests\LoginRequests;

use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Exceptions\HttpResponseException;

class LoginRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, mixed>
     */
    public function rules()
    {
        return [
            'UserID' => 'required',
            'password' => 'required',
        ];
    }

    public function failedValidation(Validator $validator)
    {
        throw new HttpResponseException(response()->json([
            'success'   => false,
            'erorr' => true,
            'message'   => 'Validation errors',
            'errors'      => $validator->errors()
        ])->setStatusCode(422));
    }
}
</code>```

app\Http\Middleware\Authenticate.php

```<code><?php

namespace App\Http\Middleware;

use Illuminate\Auth\Middleware\Authenticate as Middleware;

class Authenticate extends Middleware
{
    /**
     * Get the path the user should be redirected to when they are not authenticated.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return string|null
     */
    protected function redirectTo($request)
    {
        if (!$request->expectsJson()) {
            return route('auth.login');
        }
    }
}
</code>```

Body:
I want to change the authentication, which initially uses data from the users table (default), to use the visuser table.

When I try to log in, no error messages appear, but only endless loading.

loading while login

users table

visuser table

visuser table

I've tried changing some of the code from the files App\Http\Controllers\AuthController, resources\views\auth\login.blade.php, config\auth.php, app\Models\Visuser.php, app\Models\User.php, app\Http\Requests\LoginRequests\LoginRequest.php. I expect it will go to the specified page. In fact, it even loads endlessly.

routes\web.php

<?php

use App\Http\Controllers\AttendanceController;
use App\Http\Controllers\AuthController;
use App\Http\Controllers\DashboardController;
use App\Http\Controllers\EmployeeController;
use App\Http\Controllers\HolidayController;
use App\Http\Controllers\HomeController;
use App\Http\Controllers\PositionController;
use App\Http\Controllers\PresenceController;
use Illuminate\Support\Facades\Route;
use SebastianBergmann\CodeCoverage\Report\Html\Dashboard;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::middleware('auth')->group(function () {
    Route::middleware('role:admin,operator')->group(function () {
        // Route::get('/dashboard', [DashboardController::class, 'index'])->name('dashboard.index');
        // positions
        Route::resource('/positions', PositionController::class)->only(['index', 'create']);
        Route::get('/positions/edit', [PositionController::class, 'edit'])->name('positions.edit');
        // employees
        Route::resource('/employees', EmployeeController::class)->only(['index', 'create']);
        Route::get('/employees/edit', [EmployeeController::class, 'edit'])->name('employees.edit');
        // holidays (hari libur)
        Route::resource('/holidays', HolidayController::class)->only(['index', 'create']);
        Route::get('/holidays/edit', [HolidayController::class, 'edit'])->name('holidays.edit');
        // attendances (absensi)
        Route::resource('/attendances', AttendanceController::class)->only(['index', 'create']);

        Route::get('/attendances/edit', [AttendanceController::class, 'edit'])->name('attendances.edit');

        // presences (kehadiran)
        Route::resource('/presences', PresenceController::class)->only(['index']);
        // Route::get('/presences/qrcode', [PresenceController::class, 'showQrcode'])->name('presences.qrcode');
        Route::get('/presences/qrcode/{attendance}', [PresenceController::class, 'showQrcode'])->name('presences.qrcode');
        Route::get('/presences/qrcode/download-pdf', [PresenceController::class, 'downloadQrCodePDF'])->name('presences.qrcode.download-pdf');
        Route::get('/presences/{attendance}', [PresenceController::class, 'show'])->name('presences.show');
        // not present data
        Route::get('/presences/{attendance}/not-present', [PresenceController::class, 'notPresent'])->name('presences.not-present');
        Route::post('/presences/{attendance}/not-present', [PresenceController::class, 'notPresent']);
        // present (url untuk menambahkan/mengubah user yang tidak hadir menjadi hadir)
        Route::post('/presences/{attendance}/present', [PresenceController::class, 'presentUser'])->name('presences.present');
        Route::post('/presences/{attendance}/acceptPermission', [PresenceController::class, 'acceptPermission'])->name('presences.acceptPermission');
        // employees permissions

        Route::get('/presences/{attendance}/permissions', [PresenceController::class, 'permissions'])->name('presences.permissions');
    });

    Route::middleware('role:user')->name('home.')->group(function () {
        Route::get('/', [HomeController::class, 'start'])->name('index');
        Route::get('/home', [HomeController::class, 'index'])->name('home');
        // desctination after scan qrcode
        Route::post('/absensi/qrcode', [HomeController::class, 'sendEnterPresenceUsingQRCode'])->name('sendEnterPresenceUsingQRCode');
        Route::post('/absensi/qrcode/out', [HomeController::class, 'sendOutPresenceUsingQRCode'])->name('sendOutPresenceUsingQRCode');

        Route::get('/absensi/{attendance}', [HomeController::class, 'show'])->name('show');
        Route::get('/absensi/{attendance}/permission', [HomeController::class, 'permission'])->name('permission');
    });

    Route::delete('/logout', [AuthController::class, 'logout'])->name('auth.logout');
});

Route::middleware('guest')->group(function () {
    // auth
    Route::get('/login', [AuthController::class, 'index'])->name('auth.login');
    Route::post('/login', [AuthController::class, 'authenticate']);
});

App\Http\Controllers\AuthController

<?php

namespace App\Http\Controllers;

use App\Http\Requests\LoginRequests\LoginRequest;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class AuthController extends Controller
{
    public function index()
    {
        return view('auth.login', [
            "title" => "Masuk"
        ]);
    }

    public function username()
    {
        return 'UserID'; // this string is column of accounts table which we are going use for login
    }

    public function authenticate(LoginRequest $request)
    {
        // $remember = $request->boolean('remember');
        $credentials = $request->only(['UserID', 'password']);

        if (Auth::attempt($credentials)) { // login gagal
            request()->session()->regenerate();
            $data = [
                "success" => true,
                // "redirect_to" => auth()->user()->isUser() ? route('home.index') : route('dashboard.index'),
                "redirect_to" => auth()->user()->isUser() ? route('home.index') : route('attendances.index'),
                "message" => "Login berhasil, silahkan tunggu!"
            ];
            return response()->json($data);
        }

        $data = [
            "success" => false,
            "message" => "Login gagal, silahkan coba lagi!"
        ];
        return response()->json($data)->setStatusCode(400);
    }

    public function logout()
    {
        auth()->logout();

        request()->session()->regenerate();
        request()->session()->regenerateToken();

        return redirect()->route('auth.login')->with('success', 'Anda berhasil keluar.');
    }
}

resources\views\auth\login.blade.php

@extends('layouts.auth')

@push('style')
<link rel="stylesheet" href="{{ asset('css/auth/login.css') }}">
@endpush

@section('content')

        <form method="POST" action="{{ route('auth.login') }}" id="login-form">

Silahkan masuk untuk absensi

                <input type="text" class="form-control" id="floatingInputEmail" name="UserID"
                    placeholder="User ID">
                User ID

                <input type="password" class="form-control" id="floatingPassword" name="password"
                    placeholder="Password">
                Password

                <input class="form-check-input" type="checkbox" name="remember" id="flexCheckRemember">

                    Ingatkan Saya di Perangkat ini

            <button class="w-100 btn btn-primary" type="submit" id="login-form-button">Masuk</button>

© 2022

        </form>

@endsection

@push('script')

@endpush

config\auth.php

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Authentication Defaults
    |--------------------------------------------------------------------------
    |
    | This option controls the default authentication "guard" and password
    | reset options for your application. You may change these defaults
    | as required, but they're a perfect start for most applications.
    |
    */

    'defaults' => [
        'guard' => 'web',
        'passwords' => 'users',
    ],

    /*
    |--------------------------------------------------------------------------
    | Authentication Guards
    |--------------------------------------------------------------------------
    |
    | Next, you may define every authentication guard for your application.
    | Of course, a great default configuration has been defined for you
    | here which uses session storage and the Eloquent user provider.
    |
    | All authentication drivers have a user provider. This defines how the
    | users are actually retrieved out of your database or other storage
    | mechanisms used by this application to persist your user's data.
    |
    | Supported: "session"
    |
    */

    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],
    ],

    /*
    |--------------------------------------------------------------------------
    | User Providers
    |--------------------------------------------------------------------------
    |
    | All authentication drivers have a user provider. This defines how the
    | users are actually retrieved out of your database or other storage
    | mechanisms used by this application to persist your user's data.
    |
    | If you have multiple user tables or models you may configure multiple
    | sources which represent each model / table. These sources may then
    | be assigned to any extra authentication guards you have defined.
    |
    | Supported: "database", "eloquent"
    |
    */

    'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\Models\Visuser::class,
        ],

        // 'users' => [
        //     'driver' => 'database',
        //     'table' => 'users',
        // ],
    ],

    /*
    |--------------------------------------------------------------------------
    | Resetting Passwords
    |--------------------------------------------------------------------------
    |
    | You may specify multiple password reset configurations if you have more
    | than one user table or model in the application and you want to have
    | separate password reset settings based on the specific user types.
    |
    | The expire time is the number of minutes that each reset token will be
    | considered valid. This security feature keeps tokens short-lived so
    | they have less time to be guessed. You may change this as needed.
    |
    */

    'passwords' => [
        'users' => [
            'provider' => 'users',
            'table' => 'password_resets',
            'expire' => 60,
            'throttle' => 60,
        ],
    ],

    /*
    |--------------------------------------------------------------------------
    | Password Confirmation Timeout
    |--------------------------------------------------------------------------
    |
    | Here you may define the amount of seconds before a password confirmation
    | times out and the user is prompted to re-enter their password via the
    | confirmation screen. By default, the timeout lasts for three hours.
    |
    */

    'password_timeout' => 10800,

];

app\Models\Visuser.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Database\Eloquent\Model;

class Visuser extends Authenticatable
{
    use HasFactory;

    const USER_ROLE_ID = 5;

    protected $fillable = [
        'UserID',
        'password',
        'level',
    ];

    protected $hidden = [
        'password',
    ];

    public function isUser()
    {
        return $this->role_id === self::USER_ROLE_ID;
    }
}

app\Models\User.php

<?php

// namespace App\Models;

// use Illuminate\Contracts\Auth\MustVerifyEmail;
// use Illuminate\Database\Eloquent\Factories\HasFactory;
// use Illuminate\Foundation\Auth\User as Authenticatable;
// use Illuminate\Notifications\Notifiable;
// use Laravel\Sanctum\HasApiTokens;

// class User extends Authenticatable
// {
//     use HasApiTokens, HasFactory, Notifiable;

//     const ADMIN_ROLE_ID = 1;
//     const OPERATOR_ROLE_ID = 2;
//     const USER_ROLE_ID = 3;

//     /**
//      * The attributes that are mass assignable.
//      *
//      * @var array<int, string>
//      */
//     protected $fillable = [
//         'name',
//         'department',
//         'email',
//         'password',
//         'role_id',
//         'position_id',
//         'phone',
//     ];

//     /**
//      * The attributes that should be hidden for serialization.
//      *
//      * @var array<int, string>
//      */
//     protected $hidden = [
//         'password',
//         'remember_token',
//     ];

//     /**
//      * The attributes that should be cast.
//      *
//      * @var array<string, string>
//      */
//     protected $casts = [
//         'email_verified_at' => 'datetime',
//     ];

//     public function role()
//     {
//         return $this->belongsTo(Role::class);
//     }

//     public function position()
//     {
//         return $this->belongsTo(Position::class);
//     }

//     public function scopeOnlyEmployees($query)
//     {
//         return $query->where('role_id', self::USER_ROLE_ID);
//     }

//     public function isAdmin()
//     {
//         return $this->role_id === self::ADMIN_ROLE_ID;
//     }

//     public function isOperator()
//     {
//         return $this->role_id === self::OPERATOR_ROLE_ID;
//     }

//     public function isUser()
//     {
//         return $this->role_id === self::USER_ROLE_ID;
//     }
// }

app\Http\Requests\LoginRequests\LoginRequest.php

<?php

namespace App\Http\Requests\LoginRequests;

use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Exceptions\HttpResponseException;

class LoginRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, mixed>
     */
    public function rules()
    {
        return [
            'UserID' => 'required',
            'password' => 'required',
        ];
    }

    public function failedValidation(Validator $validator)
    {
        throw new HttpResponseException(response()->json([
            'success'   => false,
            'erorr' => true,
            'message'   => 'Validation errors',
            'errors'      => $validator->errors()
        ])->setStatusCode(422));
    }
}

app\Http\Middleware\Authenticate.php

<?php

namespace App\Http\Middleware;

use Illuminate\Auth\Middleware\Authenticate as Middleware;

class Authenticate extends Middleware
{
    /**
     * Get the path the user should be redirected to when they are not authenticated.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return string|null
     */
    protected function redirectTo($request)
    {
        if (!$request->expectsJson()) {
            return route('auth.login');
        }
    }
}


问:
A better solution to validate JSON unmarshal to nested structs
There appears to be few options to validate the source JSON used when unmarshalling to a struct. By validate I mean 3 main things:

a required field exists in the JSON

the field is the correct type (e.g. don't force a string into an integer)

the field contains a valid value (value range / enum)

For nested structs, I simply mean where an attribute in one struct has the type of another struct:

type Example struct {
    Attr1 int        `json:"attr1"`
    Attr2 ExampleToo `json:"attr2"`
}

type ExampleToo struct {
    Attr3 int `json:"attr3"`
}
```
<p>And this JSON would be valid:</p>
<pre class="lang-json prettyprint-override"><code>{"attr1": 5, "attr2": {"attr3": 0}}
</code>```

To keep this simple, I'll focus simply on integers. The concept of "zero values" is the first issue. I could create an UnmarshalJSON method, which is detected by JSON packages, including the standard encoding/json package. The problem with this approach is that is that is does not support nested structs. If ExampleToo has an UnmarshalJSON method, the ExampleToo.UnmarshalJSON() method is never called if unmarshalling to an Example object. It would be possible to write a method Example.UnmarshalJSON() that recursively handled validation, but that seems extremely complex, especially if ExampleToo is reused in many places.

So there appears to be some packages like the go-playground/validator where validation can be specified both as functions and tags. However, this works on the struct created, and not the JSON itself. So if a field is tagged as validation:"required" on an integer, and the integer value is 0, this will return an error because 0 is both a valid value and the "zero value" for integers.

An example of the latter here: https://go.dev/play/p/zqSUksPzUiq

I could also use pointers for everything, checking for nil as missing values. The main problem with that is that it requires dereferencing on each use and is a pretty uncommon practice for things like integers and strings.

One thing that I have also considered is a "sister struct" that uses pointers to do validation for required fields. The process would basically be to write a validation method for each struct, then validate that sister struct. If it works, then deserialize the main struct (without pointers). I haven't started on this, just a concept I've thought about, but I'm hoping there are better validation options.

So... is there a better way to do JSON/YAML input validation on nested structs? I'm happy to mix methods where say UnmarshalJSON is used for doing some work like verifying fields exist, but I'd like to pass that back to the library to let it continue to call UnmarshalJSON on subsequent nested structs. I'd also rather defer to the JSON library for casting values into the struct, etc.

Body:
There appears to be few options to validate the source JSON used when unmarshalling to a struct. By validate I mean 3 main things:

a required field exists in the JSON

the field is the correct type (e.g. don't force a string into an integer)

the field contains a valid value (value range / enum)

For nested structs, I simply mean where an attribute in one struct has the type of another struct:

type Example struct {
    Attr1 int        `json:"attr1"`
    Attr2 ExampleToo `json:"attr2"`
}

type ExampleToo struct {
    Attr3 int `json:"attr3"`
}

And this JSON would be valid:

{"attr1": 5, "attr2": {"attr3": 0}}

To keep this simple, I'll focus simply on integers. The concept of "zero values" is the first issue. I could create an UnmarshalJSON method, which is detected by JSON packages, including the standard encoding/json package. The problem with this approach is that is that is does not support nested structs. If ExampleToo has an UnmarshalJSON method, the ExampleToo.UnmarshalJSON() method is never called if unmarshalling to an Example object. It would be possible to write a method Example.UnmarshalJSON() that recursively handled validation, but that seems extremely complex, especially if ExampleToo is reused in many places.

So there appears to be some packages like the go-playground/validator where validation can be specified both as functions and tags. However, this works on the struct created, and not the JSON itself. So if a field is tagged as validation:"required" on an integer, and the integer value is 0, this will return an error because 0 is both a valid value and the "zero value" for integers.

An example of the latter here: https://go.dev/play/p/zqSUksPzUiq

I could also use pointers for everything, checking for nil as missing values. The main problem with that is that it requires dereferencing on each use and is a pretty uncommon practice for things like integers and strings.

One thing that I have also considered is a "sister struct" that uses pointers to do validation for required fields. The process would basically be to write a validation method for each struct, then validate that sister struct. If it works, then deserialize the main struct (without pointers). I haven't started on this, just a concept I've thought about, but I'm hoping there are better validation options.

So... is there a better way to do JSON/YAML input validation on nested structs? I'm happy to mix methods where say UnmarshalJSON is used for doing some work like verifying fields exist, but I'd like to pass that back to the library to let it continue to call UnmarshalJSON on subsequent nested structs. I'd also rather defer to the JSON library for casting values into the struct, etc.


问:
Retry python command in powershell
I am not very familiar with command line nor python, but I'm trying to run a line in Windows PowerShell that does work some of the time, but it takes 30-40 different attempts to get it to work. I'm wondering if there's a way to automate it easily to retry if (when) it fails until I get a success, or for a certain number of attempts, just so I can step away from the computer.

This is what I input in Windows Powershell:

py Mystery.py --create_spoiler --multi 2 --names Player1,Player2,Player3 --outputpath ./output/ --p1 mystery_example.yml --p2 mystery_example2.yml --p3 mystery_example3.yml

Title: Retry python command in powershell


问:
set the notification for Slack's notion app
notion page image
slack apps image

like the image above, I connected Slack and Notion.
I'm getting a notifications for all the changes on the linked Notion page.

but I only want the notification to come when I'm on a mention.
how can I do?


问:
Why does the file name where tensorflow profiler saves logs change slightly each time?
I am currently profiling using tensorflow profiler in aws, gcp, and alibaba clouds. However, the location and file name of the log file are slightly different each time. "Plugin" files sometimes become "plugins", and the file name or location changes little by little every time. Why? All Ubuntu, tensorflow, tensorboard, etc. environments are all proceeding the same.</p>


问:
Blazor - Apply strikethrough to the list every time the end user click the list itself
```<code>

<ul>
    <li @onclick="Strike_Click_List" >@CssClassStrike Apple with Mango</li>
</ul>
<br />

@code {
    protected string CssClassStrike { get; set; }
    protected int a;

    protected void Strike_Click_List()
    {
        if (a == 1)
        {
            CssClassStrike = "";// What is the syntax that would strike the Apple Mango?
            a = 0;
        }
        else
        {
            CssClassStrike = null;
            a = 1;
        }
    }
}
</code>```

I'd like to apply a strikethrough to list Apple with Mango every click by end user. At the moment I'm struggling to find any simple way of achieving this.

Any ideas? Thanks!

Body:
@CssClassStrike Apple with Mango

@code {
    protected string CssClassStrike { get; set; }
    protected int a;

    protected void Strike_Click_List()
    {
        if (a == 1)
        {
            CssClassStrike = "";// What is the syntax that would strike the Apple Mango?
            a = 0;
        }
        else
        {
            CssClassStrike = null;
            a = 1;
        }
    }
}

I'd like to apply a strikethrough to list Apple with Mango every click by end user. At the moment I'm struggling to find any simple way of achieving this.

Any ideas? Thanks!


问:
How to get range slider step to change after a certain number in js
I want this slider to be a step of 1 when below 36 and a step of 3 when over 36. It seems to work when I drag the slider, however when using the buttons or the left and right arrow keys the step seems to stay at 1? I want it to work totally whether using buttons or the keydown not just when dragging the slider.

var finalSubstringModel = 'nam12k'
// Get the buttons and range slider elements
var prevButton = document.getElementById('prev-button');
var nextButton = document.getElementById('next-button');
var rangeSlider = document.getElementById('range-slider');
var step = rangeSlider.step;
// Add event listeners to the buttons
if (finalSubstringModel.includes("nam12k")) {
  // If the value of the slider is greater than 36, set the step size to 3
  if (rangeSlider.value > 36) {
    var step = 3;
  } else {
    var step = 1;
  }
  // Update the step attribute of the slider
  rangeSlider.setAttribute("step", step);
};
prevButton.addEventListener('click', function() {
  event.preventDefault();
  // Decrement the value of the range slider by the step value
  rangeSlider.value -= step;
});
rangeSlider.addEventListener('input', function() {});

nextButton.addEventListener('click', function() {
  event.preventDefault();
  // Increment the value of the range slider by the step value
  val = parseInt(rangeSlider.value);
  val += step;
  rangeSlider.value = val;
});

document.addEventListener('keydown', function(e) {
  if (e.keyCode == 39) { //right
    rangeSlider.value = +rangeSlider.value + +step;
  } else if (e.keyCode == 37) { //left
    rangeSlider.value = +rangeSlider.value - +step;
  }
})

const slider = document.querySelector('.slider');
const playPauseButton = document.querySelector('.play-pause-button');

// Set up an interval to update the slider value every 50 milliseconds
let interval = null;
// Function to start the interval and change the play/pause button text to 'Pause'
function play() {
  interval = setInterval(() => {
    // Increment the current value of the range slider by the step value
    let newValue = parseInt(slider.value) + parseInt(step);
    // Set the new value to 0 if it is greater than the maximum value
    if (newValue > parseInt(slider.max)) {
      newValue = 0;
    }
    // Set the new value of the range slider
    slider.value = newValue;
  }, 600);
  playPauseButton.innerText = 'Pause';
  console.log(slider.value)
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type='range' min='0' max='84' value='0' step='6' id='range-slider' class='slider' />
<button id='prev-button' class='prev'></button>
<button class='play-pause-button'>Play</button>
<button id='next-button' class='next'></button></code>```

Body:
I want this slider to be a step of 1 when below 36 and a step of 3 when over 36. It seems to work when I drag the slider, however when using the buttons or the left and right arrow keys the step seems to stay at 1? I want it to work totally whether using buttons or the keydown not just when dragging the slider.

var finalSubstringModel = 'nam12k'
// Get the buttons and range slider elements
var prevButton = document.getElementById('prev-button');
var nextButton = document.getElementById('next-button');
var rangeSlider = document.getElementById('range-slider');
var step = rangeSlider.step;
// Add event listeners to the buttons
if (finalSubstringModel.includes("nam12k")) {
  // If the value of the slider is greater than 36, set the step size to 3
  if (rangeSlider.value > 36) {
    var step = 3;
  } else {
    var step = 1;
  }
  // Update the step attribute of the slider
  rangeSlider.setAttribute("step", step);
};
prevButton.addEventListener('click', function() {
  event.preventDefault();
  // Decrement the value of the range slider by the step value
  rangeSlider.value -= step;
});
rangeSlider.addEventListener('input', function() {});

nextButton.addEventListener('click', function() {
  event.preventDefault();
  // Increment the value of the range slider by the step value
  val = parseInt(rangeSlider.value);
  val += step;
  rangeSlider.value = val;
});

document.addEventListener('keydown', function(e) {
  if (e.keyCode == 39) { //right
    rangeSlider.value = +rangeSlider.value + +step;
  } else if (e.keyCode == 37) { //left
    rangeSlider.value = +rangeSlider.value - +step;
  }
})

const slider = document.querySelector('.slider');
const playPauseButton = document.querySelector('.play-pause-button');

// Set up an interval to update the slider value every 50 milliseconds
let interval = null;
// Function to start the interval and change the play/pause button text to 'Pause'
function play() {
  interval = setInterval(() => {
    // Increment the current value of the range slider by the step value
    let newValue = parseInt(slider.value) + parseInt(step);
    // Set the new value to 0 if it is greater than the maximum value
    if (newValue > parseInt(slider.max)) {
      newValue = 0;
    }
    // Set the new value of the range slider
    slider.value = newValue;
  }, 600);
  playPauseButton.innerText = 'Pause';
  console.log(slider.value)
}

<input type='range' min='0' max='84' value='0' step='6' id='range-slider' class='slider' />
<button id='prev-button' class='prev'></button>
<button class='play-pause-button'>Play</button>
<button id='next-button' class='next'></button>


问:
When I run the command 'ls' in a Linux system, nothing happened
I was trying to re-implement a simple linux file system. I implemented the function iterate_dir(), while I was testing if it could work successfully, I ran the command ls and nothing happened, no errors reported either.(I had created some files before running the command).
It will be really helpful if you could help me figure that out. Thanks in advance.

Ubuntu 22.04 & Linux 5.15.0-56-generic x86_64 is used.

code:

```<code>struct dir_entry {
    char filename[MAXLEN];
    uint8_t idx;
};

struct file_blk {
    uint8_t busy;
    mode_t mode;
    uint8_t idx;

    union {
        uint8_t file_size;
        uint8_t dir_children;
    };
    char data[0];
};

static int evanfs_iterate(struct file *filp, struct dir_context *ctx)
{
    loff_t pos;
    struct file_blk *blk;
    struct dir_entry *entry;
    int i;

    pos = ctx->pos;
    if (pos)
        return 0;

    blk = (struct file_blk *)file_inode(filp)->i_private;

    if (!S_ISDIR(blk->mode)) {
        return -ENOTDIR;
    }

    entry = (struct dir_entry *)&blk->data[0];
    for (i = 0; i < blk->dir_children; i++) {
        dir_emit(ctx, entry[i].filename, MAXLEN, pos, entry[i].idx);
        pos += sizeof(struct dir_entry);
    }

    return 0;
}
</code>```

and here are what it looked like when I ran the command:

commands in text format:

```<code>root@evan-virtual-machine:/home/evan/src/evanfs# make
make -C /lib/modules/5.4.0-135-generic/build/ M=home/evan/src/evanfs modules
make[1]: Entering directory '/usr/src/linux-headers-5.4.0-135-generic'
  Building modules, stage 2.
  MODPOST 1 modules
make[1]: Leaving directory '/usr/src/linux-headers-5.4.0-135-generic'
root@evan-virtual-machine:/home/evan/src/evanfs# insmod ./evanfs.ko
root@evan-virtual-machine:/home/evan/src/evanfs# insmod mount -t evanfs none /mnt
root@evan-virtual-machine:/home/evan/src/evanfs# cd /mnt/
root@evan-virtual-machine:/mnt# mkdir dir1
root@evan-virtual-machine:/mnt# echo 111 > ./dir1/a
root@evan-virtual-machine:/mnt# cat ./dir1/a
111
root@evan-virtual-machine:/mnt# ls

</code>```

Body:
I was trying to re-implement a simple linux file system. I implemented the function iterate_dir(), while I was testing if it could work successfully, I ran the command ls and nothing happened, no errors reported either.(I had created some files before running the command).
It will be really helpful if you could help me figure that out. Thanks in advance.

Ubuntu 22.04 & Linux 5.15.0-56-generic x86_64 is used.

code:

struct dir_entry {
    char filename[MAXLEN];
    uint8_t idx;
};

struct file_blk {
    uint8_t busy;
    mode_t mode;
    uint8_t idx;

    union {
        uint8_t file_size;
        uint8_t dir_children;
    };
    char data[0];
};

static int evanfs_iterate(struct file *filp, struct dir_context *ctx)
{
    loff_t pos;
    struct file_blk *blk;
    struct dir_entry *entry;
    int i;

    pos = ctx->pos;
    if (pos)
        return 0;

    blk = (struct file_blk *)file_inode(filp)->i_private;

    if (!S_ISDIR(blk->mode)) {
        return -ENOTDIR;
    }

    entry = (struct dir_entry *)&blk->data[0];
    for (i = 0; i < blk->dir_children; i++) {
        dir_emit(ctx, entry[i].filename, MAXLEN, pos, entry[i].idx);
        pos += sizeof(struct dir_entry);
    }

    return 0;
}

and here are what it looked like when I ran the command:

commands in text format:

root@evan-virtual-machine:/home/evan/src/evanfs# make
make -C /lib/modules/5.4.0-135-generic/build/ M=home/evan/src/evanfs modules
make[1]: Entering directory '/usr/src/linux-headers-5.4.0-135-generic'
  Building modules, stage 2.
  MODPOST 1 modules
make[1]: Leaving directory '/usr/src/linux-headers-5.4.0-135-generic'
root@evan-virtual-machine:/home/evan/src/evanfs# insmod ./evanfs.ko
root@evan-virtual-machine:/home/evan/src/evanfs# insmod mount -t evanfs none /mnt
root@evan-virtual-machine:/home/evan/src/evanfs# cd /mnt/
root@evan-virtual-machine:/mnt# mkdir dir1
root@evan-virtual-machine:/mnt# echo 111 > ./dir1/a
root@evan-virtual-machine:/mnt# cat ./dir1/a
111
root@evan-virtual-machine:/mnt# ls