问:
Testing errors, unit and staging
I got two problems, 1) I am not being able to test the it("picks a winner , resest the lottery , and sends money" test. It wont run, it passes the time limit on the chain no matter how much I set it

```<code>const { inputToConfig } = require("@ethereum-waffle/compiler")
const { assert, expect } = require("chai")
const { network, getNamedAccounts, deployments, ethers } = require("hardhat")
const { developmentChains, networkConfig } = require("../../helper-hardhat-config")

!developmentChains.includes(network.name)
    ? describe.skip
    : describe("Raffle Unit Tests", function () {
          let raffle, vrfCoordinatorV2Mock, raffleEntranceFee, deployer, interval
          const chainId = network.config.chainId

          beforeEach(async function () {
              deployer = (await getNamedAccounts()).deployer
              await deployments.fixture(["all"])
              raffle = await ethers.getContract("Raffle", deployer)
              vrfCoordinatorV2Mock = await ethers.getContract("VRFCoordinatorV2Mock", deployer)
              raffleEntranceFee = await raffle.getEntranceFee()
              interval = await raffle.getInterval()
          })

          describe("constructor", function () {
              it("initializes the raffle correctly", async function () {
                  // ideally we make our tests have 1 assert per "it"
                  const raffleState = await raffle.getRaffleState()
                  assert.equal(raffleState.toString(), "0")
                  assert.equal(interval.toString(), networkConfig[chainId]["interval"])
              })
          })
          describe("enterRaffle", function () {
              it("reverts when you dont pay enough", async function () {
                  await expect(raffle.enterRaffle()).to.be.revertedWith(
                      "Raffle__NotEnoughETHEntered"
                  )
              })
              it("records players when they enter", async function () {
                  await raffle.enterRaffle({ value: raffleEntranceFee })
                  const playerFromContract = await raffle.getPlayer(0)
                  assert.equal(playerFromContract, deployer)
              })
              it("emits event on enter", async function () {
                  await expect(raffle.enterRaffle({ value: raffleEntranceFee })).to.emit(
                      raffle,
                      "RaffleEnter"
                  )
              })
              it("doesnt allow entrance when raffle is calculating", async function () {
                  await raffle.enterRaffle({ value: raffleEntranceFee })
                  await network.provider.send("evm_increaseTime", [interval.toNumber() + 1])
                  await network.provider.send("evm_mine", [])
                  // we pretend to be chainlink keeper
                  await raffle.performUpkeep([])
                  await expect(raffle.enterRaffle({ value: raffleEntranceFee })).to.be.revertedWith(
                      "Raffle__NotOpen"
                  )
              })
          })
          describe("checkUpkeep", function () {
              it("returns falseif people havent send any ETH", async function () {
                  await network.provider.send("evm_increaseTime", [interval.toNumber() + 1])
                  await network.provider.send("evm_mine", [])
                  const { upkeepNeeded } = await raffle.callStatic.checkUpkeep([])
                  assert(!upkeepNeeded)
              })
              it("returns false if raffle isn't open", async () => {
                  await raffle.enterRaffle({ value: raffleEntranceFee })
                  await network.provider.send("evm_increaseTime", [interval.toNumber() + 1])
                  await network.provider.send("evm_mine", [])
                  await raffle.performUpkeep([]) // changes the state to calculating
                  const raffleState = await raffle.getRaffleState() // stores the new state
                  const { upkeepNeeded } = await raffle.callStatic.checkUpkeep("0x") // upkeepNeeded = (timePassed && isOpen && hasBalance && hasPlayers)
                  assert.equal(raffleState.toString() == "0", upkeepNeeded == false)
              })
              it("returns false if enough time hasn't passed", async () => {
                  await raffle.enterRaffle({ value: raffleEntranceFee })
                  await network.provider.send("evm_increaseTime", [interval.toNumber() - 5]) // use a higher number here if this test fails
                  await network.provider.request({ method: "evm_mine", params: [] })
                  const { upkeepNeeded } = await raffle.callStatic.checkUpkeep("0x") // upkeepNeeded = (timePassed && isOpen && hasBalance && hasPlayers)
                  assert(!upkeepNeeded)
              })
              it("returns true if enough time has passed, has players, eth, and is open", async () => {
                  await raffle.enterRaffle({ value: raffleEntranceFee })
                  await network.provider.send("evm_increaseTime", [interval.toNumber() + 1])
                  await network.provider.request({ method: "evm_mine", params: [] })
                  const { upkeepNeeded } = await raffle.callStatic.checkUpkeep("0x") // upkeepNeeded = (timePassed && isOpen && hasBalance && hasPlayers)
                  assert(!upkeepNeeded)
              })
          })
          describe("performUpkeep", function () {
              it("it casn only run if checkUpkeep is true", async function () {
                  await raffle.enterRaffle({ value: raffleEntranceFee })
                  await network.provider.send("evm_increaseTime", [interval.toNumber() + 1])
                  await network.provider.send("evm_mine", [])
                  const tx = await raffle.performUpkeep([])
                  assert(tx)
              })
              it("reverts when checkUpkeep is false", async function () {
                  await expect(raffle.performUpkeep("0x")).to.be.revertedWith(
                      "Raffle_UpkeepNotNeeded"
                  )
              })
              it("updates the raffle state and emits a requestId", async () => {
                  // Too many asserts in this test!
                  await raffle.enterRaffle({ value: raffleEntranceFee })
                  await network.provider.send("evm_increaseTime", [interval.toNumber() + 1])
                  await network.provider.send("evm_mine", [])
                  const txResponse = await raffle.performUpkeep("0x") // emits requestId
                  const txReceipt = await txResponse.wait(1) // waits 1 block
                  const raffleState = await raffle.getRaffleState() // updates state
                  const requestId = txReceipt.events[1].args.requestId
                  assert(requestId.toNumber() > 0)
                  assert(raffleState == 1) // 0 = open, 1 = calculating
              })
          })

          beforeEach(async function () {
              await raffle.enterRaffle({ value: raffleEntranceFee })
              await network.provider.send("evm_increaseTime", [interval.toNumber() + 1])
              await network.provider.send("evm_mine", [])
          })
          it("can only be called after performUpkeep", async function () {
              await expect(
                  vrfCoordinatorV2Mock.fulfillRandomWords(0, raffle.address)
              ).to.be.revertedWith("nonexistent request")
              await expect(
                  vrfCoordinatorV2Mock.fulfillRandomWords(1, raffle.address)
              ).to.be.revertedWith("nonexistent request")
          })
          // WAY TOO BIG
          it("picks a winner , resest the lottery , and sends money", async () => {
              const additonalEnternace = 3
              const startingAccountIndex = 2 // deployer = 0
              const accounts = await ethers.getSigners()

              // connecting 3 extra people to the rafffle , not including the deployer which makes it 4
              for (
                  let i = startingAccountIndex;
                  i < startingAccountIndex + additonalEnternace;
                  i++
              ) {
                  const accountConnectedRaffle = raffle.connect(accounts[i])
                  await accountConnectedRaffle.enterRaffle({ value: raffleEntranceFee })
              }
              const startingTimeStamp = await raffle.getLatestTimeStamp()

              // performUpKeep {mock being chainLink keepers}
              // fullfillRandomWords {mock being the chainLink VRF}
              // IF WE ON TESTNET : we have to wait for the fullfillRandomWords
              await new Promise(async (resolve, reject) => {
                  // Listening for the winnerPicked Event
                  raffle.once("WinnerPicked", async () => {
                      console.log("Found the event")

                      try {
                          const recentWinner = await raffle.getRecentWinner()
                          console.log(`the Last winner was : ${recentWinner}`)

                          console.log(
                              "------------------------All Accounts------------------------"
                          )
                          console.log(accounts[0].address)
                          console.log(accounts[1].address)
                          console.log(accounts[2].address)
                          console.log(accounts[3].address)

                          const raffleState = await raffle.getRaffleState()
                          const endingTimeStamp = await raffle.getLatestTimeStamp()
                          const numPlayers = await raffle.getNumberOfPlayer()
                          const winnerEndingBalance = await accounts[2].getBalance()

                          // asserts
                          assert.equal(numPlayers.toString(), "0")
                          assert.equal(raffleState.toString(), "0")
                          assert(endingTimeStamp > startingTimeStamp)

                          // doing the math to make sure the winner gets the right amount

                          assert.equal(
                              winnerEndingBalance.toString(),
                              winnerStartingBalace
                                  .add(
                                      raffleEntranceFee
                                          .mul(additonalEnternace)
                                          .add(raffleEntranceFee)
                                  )
                                  .toString()
                          )
                      } catch (error) {
                          reject(error)
                      }
                      resolve()
                  })
                  // setting up a listener

                  // below , we will fire the event , and the listner will pick it up , and resolve
                  const tx = await raffle.performUpkeep([])
                  const txReceipt = await tx.wait(1)
                  const winnerStartingBalace = await accounts[2].getBalance()
                  await vrfCoordinatorV2Mock.fulfillRandomWords(
                      txReceipt.events[1].args.requestId,
                      raffle.address
                  )
              })
          })
      })
</code>```

The second problem is that when I test my tests on GOERLI network, it shows an Error that reads: 1) Raffle Unit Tests
"before each" hook for "works with live Chainlink Keepers and Chainlink VRF, we get a random winner":
Error: No Contract deployed with name VRFCoordinatorV2Mock
at Object.getContract (node_modules/@nomiclabs/hardhat-ethers/src/internal/helpers.ts:447:11)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at Context. (test/staging/Raffle.staging.test.js:15:38)

```<code>const { inputToConfig } = require("@ethereum-waffle/compiler")
const { assert, expect } = require("chai")
const { network, getNamedAccounts, deployments, ethers } = require("hardhat")
const { developmentChains, networkConfig } = require("../../helper-hardhat-config")

developmentChains.includes(network.name)
    ? describe.skip
    : describe("Raffle Unit Tests", function () {
          let raffle, raffleEntranceFee, deployer

          beforeEach(async function () {
              deployer = (await getNamedAccounts()).deployer
              await deployments.fixture(["all"])
              raffle = await ethers.getContract("Raffle", deployer)
              vrfCoordinatorV2Mock = await ethers.getContract("VRFCoordinatorV2Mock", deployer)
              raffleEntranceFee = await raffle.getEntranceFee()
          })
          describe("fulfillRandomWords", function () {
              it("works with live Chainlink Keepers and Chainlink VRF, we get a random winner", async function () {
                  // enter the raffle
                  console.log("Setting up test...")
                  await deployments.fixture(["mocks"])
                  const startingTimeStamp = await raffle.getLastTimeStamp()
                  const accounts = await ethers.getSigners()

                  console.log("Setting up Listener...")
                  await new Promise(async (resolve, reject) => {
                      // setup listener before we enter the raffle
                      // Just in case the blockchain moves REALLY fast
                      raffle.once("WinnerPicked", async () => {
                          console.log("WinnerPicked event fired!")
                          try {

                              const recentWinner = await raffle.getRecentWinner()
                              const raffleState = await raffle.getRaffleState()
                              const winnerEndingBalance = await accounts[0].getBalance()
                              const endingTimeStamp = await raffle.getLastTimeStamp()

                              await expect(raffle.getPlayer(0)).to.be.reverted
                              assert.equal(recentWinner.toString(), accounts[0].address)
                              assert.equal(raffleState, 0)
                              assert.equal(
                                  winnerEndingBalance.toString(),
                                  winnerStartingBalance.add(raffleEntranceFee).toString()
                              )
                              assert(endingTimeStamp > startingTimeStamp)
                              resolve()
                          } catch (error) {
                              console.log(error)
                              reject(error)
                          }
                      })
                      // Then entering the raffle
                      console.log("Entering Raffle...")
                      const tx = await raffle.enterRaffle({ value: raffleEntranceFee })
                      await tx.wait(1)
                      console.log("Ok, time to wait...")
                      const winnerStartingBalance = await accounts[0].getBalance()

                      // and this code WONT complete until our listener has finished listening!
                  })
              })
          })
      })
</code>```

Can anyone help me out with these, here's the link to my repo: https://github.com/anooj1/hardhat-raffle

Title: Testing errors, unit and staging

Body:
I got two problems, 1) I am not being able to test the it("picks a winner , resest the lottery , and sends money" test. It wont run, it passes the time limit on the chain no matter how much I set it

const { inputToConfig } = require("@ethereum-waffle/compiler")
const { assert, expect } = require("chai")
const { network, getNamedAccounts, deployments, ethers } = require("hardhat")
const { developmentChains, networkConfig } = require("../../helper-hardhat-config")

!developmentChains.includes(network.name)
    ? describe.skip
    : describe("Raffle Unit Tests", function () {
          let raffle, vrfCoordinatorV2Mock, raffleEntranceFee, deployer, interval
          const chainId = network.config.chainId

          beforeEach(async function () {
              deployer = (await getNamedAccounts()).deployer
              await deployments.fixture(["all"])
              raffle = await ethers.getContract("Raffle", deployer)
              vrfCoordinatorV2Mock = await ethers.getContract("VRFCoordinatorV2Mock", deployer)
              raffleEntranceFee = await raffle.getEntranceFee()
              interval = await raffle.getInterval()
          })

          describe("constructor", function () {
              it("initializes the raffle correctly", async function () {
                  // ideally we make our tests have 1 assert per "it"
                  const raffleState = await raffle.getRaffleState()
                  assert.equal(raffleState.toString(), "0")
                  assert.equal(interval.toString(), networkConfig[chainId]["interval"])
              })
          })
          describe("enterRaffle", function () {
              it("reverts when you dont pay enough", async function () {
                  await expect(raffle.enterRaffle()).to.be.revertedWith(
                      "Raffle__NotEnoughETHEntered"
                  )
              })
              it("records players when they enter", async function () {
                  await raffle.enterRaffle({ value: raffleEntranceFee })
                  const playerFromContract = await raffle.getPlayer(0)
                  assert.equal(playerFromContract, deployer)
              })
              it("emits event on enter", async function () {
                  await expect(raffle.enterRaffle({ value: raffleEntranceFee })).to.emit(
                      raffle,
                      "RaffleEnter"
                  )
              })
              it("doesnt allow entrance when raffle is calculating", async function () {
                  await raffle.enterRaffle({ value: raffleEntranceFee })
                  await network.provider.send("evm_increaseTime", [interval.toNumber() + 1])
                  await network.provider.send("evm_mine", [])
                  // we pretend to be chainlink keeper
                  await raffle.performUpkeep([])
                  await expect(raffle.enterRaffle({ value: raffleEntranceFee })).to.be.revertedWith(
                      "Raffle__NotOpen"
                  )
              })
          })
          describe("checkUpkeep", function () {
              it("returns falseif people havent send any ETH", async function () {
                  await network.provider.send("evm_increaseTime", [interval.toNumber() + 1])
                  await network.provider.send("evm_mine", [])
                  const { upkeepNeeded } = await raffle.callStatic.checkUpkeep([])
                  assert(!upkeepNeeded)
              })
              it("returns false if raffle isn't open", async () => {
                  await raffle.enterRaffle({ value: raffleEntranceFee })
                  await network.provider.send("evm_increaseTime", [interval.toNumber() + 1])
                  await network.provider.send("evm_mine", [])
                  await raffle.performUpkeep([]) // changes the state to calculating
                  const raffleState = await raffle.getRaffleState() // stores the new state
                  const { upkeepNeeded } = await raffle.callStatic.checkUpkeep("0x") // upkeepNeeded = (timePassed && isOpen && hasBalance && hasPlayers)
                  assert.equal(raffleState.toString() == "0", upkeepNeeded == false)
              })
              it("returns false if enough time hasn't passed", async () => {
                  await raffle.enterRaffle({ value: raffleEntranceFee })
                  await network.provider.send("evm_increaseTime", [interval.toNumber() - 5]) // use a higher number here if this test fails
                  await network.provider.request({ method: "evm_mine", params: [] })
                  const { upkeepNeeded } = await raffle.callStatic.checkUpkeep("0x") // upkeepNeeded = (timePassed && isOpen && hasBalance && hasPlayers)
                  assert(!upkeepNeeded)
              })
              it("returns true if enough time has passed, has players, eth, and is open", async () => {
                  await raffle.enterRaffle({ value: raffleEntranceFee })
                  await network.provider.send("evm_increaseTime", [interval.toNumber() + 1])
                  await network.provider.request({ method: "evm_mine", params: [] })
                  const { upkeepNeeded } = await raffle.callStatic.checkUpkeep("0x") // upkeepNeeded = (timePassed && isOpen && hasBalance && hasPlayers)
                  assert(!upkeepNeeded)
              })
          })
          describe("performUpkeep", function () {
              it("it casn only run if checkUpkeep is true", async function () {
                  await raffle.enterRaffle({ value: raffleEntranceFee })
                  await network.provider.send("evm_increaseTime", [interval.toNumber() + 1])
                  await network.provider.send("evm_mine", [])
                  const tx = await raffle.performUpkeep([])
                  assert(tx)
              })
              it("reverts when checkUpkeep is false", async function () {
                  await expect(raffle.performUpkeep("0x")).to.be.revertedWith(
                      "Raffle_UpkeepNotNeeded"
                  )
              })
              it("updates the raffle state and emits a requestId", async () => {
                  // Too many asserts in this test!
                  await raffle.enterRaffle({ value: raffleEntranceFee })
                  await network.provider.send("evm_increaseTime", [interval.toNumber() + 1])
                  await network.provider.send("evm_mine", [])
                  const txResponse = await raffle.performUpkeep("0x") // emits requestId
                  const txReceipt = await txResponse.wait(1) // waits 1 block
                  const raffleState = await raffle.getRaffleState() // updates state
                  const requestId = txReceipt.events[1].args.requestId
                  assert(requestId.toNumber() > 0)
                  assert(raffleState == 1) // 0 = open, 1 = calculating
              })
          })

          beforeEach(async function () {
              await raffle.enterRaffle({ value: raffleEntranceFee })
              await network.provider.send("evm_increaseTime", [interval.toNumber() + 1])
              await network.provider.send("evm_mine", [])
          })
          it("can only be called after performUpkeep", async function () {
              await expect(
                  vrfCoordinatorV2Mock.fulfillRandomWords(0, raffle.address)
              ).to.be.revertedWith("nonexistent request")
              await expect(
                  vrfCoordinatorV2Mock.fulfillRandomWords(1, raffle.address)
              ).to.be.revertedWith("nonexistent request")
          })
          // WAY TOO BIG
          it("picks a winner , resest the lottery , and sends money", async () => {
              const additonalEnternace = 3
              const startingAccountIndex = 2 // deployer = 0
              const accounts = await ethers.getSigners()

              // connecting 3 extra people to the rafffle , not including the deployer which makes it 4
              for (
                  let i = startingAccountIndex;
                  i < startingAccountIndex + additonalEnternace;
                  i++
              ) {
                  const accountConnectedRaffle = raffle.connect(accounts[i])
                  await accountConnectedRaffle.enterRaffle({ value: raffleEntranceFee })
              }
              const startingTimeStamp = await raffle.getLatestTimeStamp()

              // performUpKeep {mock being chainLink keepers}
              // fullfillRandomWords {mock being the chainLink VRF}
              // IF WE ON TESTNET : we have to wait for the fullfillRandomWords
              await new Promise(async (resolve, reject) => {
                  // Listening for the winnerPicked Event
                  raffle.once("WinnerPicked", async () => {
                      console.log("Found the event")

                      try {
                          const recentWinner = await raffle.getRecentWinner()
                          console.log(`the Last winner was : ${recentWinner}`)

                          console.log(
                              "------------------------All Accounts------------------------"
                          )
                          console.log(accounts[0].address)
                          console.log(accounts[1].address)
                          console.log(accounts[2].address)
                          console.log(accounts[3].address)

                          const raffleState = await raffle.getRaffleState()
                          const endingTimeStamp = await raffle.getLatestTimeStamp()
                          const numPlayers = await raffle.getNumberOfPlayer()
                          const winnerEndingBalance = await accounts[2].getBalance()

                          // asserts
                          assert.equal(numPlayers.toString(), "0")
                          assert.equal(raffleState.toString(), "0")
                          assert(endingTimeStamp > startingTimeStamp)

                          // doing the math to make sure the winner gets the right amount

                          assert.equal(
                              winnerEndingBalance.toString(),
                              winnerStartingBalace
                                  .add(
                                      raffleEntranceFee
                                          .mul(additonalEnternace)
                                          .add(raffleEntranceFee)
                                  )
                                  .toString()
                          )
                      } catch (error) {
                          reject(error)
                      }
                      resolve()
                  })
                  // setting up a listener

                  // below , we will fire the event , and the listner will pick it up , and resolve
                  const tx = await raffle.performUpkeep([])
                  const txReceipt = await tx.wait(1)
                  const winnerStartingBalace = await accounts[2].getBalance()
                  await vrfCoordinatorV2Mock.fulfillRandomWords(
                      txReceipt.events[1].args.requestId,
                      raffle.address
                  )
              })
          })
      })

The second problem is that when I test my tests on GOERLI network, it shows an Error that reads: 1) Raffle Unit Tests
"before each" hook for "works with live Chainlink Keepers and Chainlink VRF, we get a random winner":
Error: No Contract deployed with name VRFCoordinatorV2Mock
at Object.getContract (node_modules/@nomiclabs/hardhat-ethers/src/internal/helpers.ts:447:11)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at Context. (test/staging/Raffle.staging.test.js:15:38)

const { inputToConfig } = require("@ethereum-waffle/compiler")
const { assert, expect } = require("chai")
const { network, getNamedAccounts, deployments, ethers } = require("hardhat")
const { developmentChains, networkConfig } = require("../../helper-hardhat-config")

developmentChains.includes(network.name)
    ? describe.skip
    : describe("Raffle Unit Tests", function () {
          let raffle, raffleEntranceFee, deployer

          beforeEach(async function () {
              deployer = (await getNamedAccounts()).deployer
              await deployments.fixture(["all"])
              raffle = await ethers.getContract("Raffle", deployer)
              vrfCoordinatorV2Mock = await ethers.getContract("VRFCoordinatorV2Mock", deployer)
              raffleEntranceFee = await raffle.getEntranceFee()
          })
          describe("fulfillRandomWords", function () {
              it("works with live Chainlink Keepers and Chainlink VRF, we get a random winner", async function () {
                  // enter the raffle
                  console.log("Setting up test...")
                  await deployments.fixture(["mocks"])
                  const startingTimeStamp = await raffle.getLastTimeStamp()
                  const accounts = await ethers.getSigners()

                  console.log("Setting up Listener...")
                  await new Promise(async (resolve, reject) => {
                      // setup listener before we enter the raffle
                      // Just in case the blockchain moves REALLY fast
                      raffle.once("WinnerPicked", async () => {
                          console.log("WinnerPicked event fired!")
                          try {

                              const recentWinner = await raffle.getRecentWinner()
                              const raffleState = await raffle.getRaffleState()
                              const winnerEndingBalance = await accounts[0].getBalance()
                              const endingTimeStamp = await raffle.getLastTimeStamp()

                              await expect(raffle.getPlayer(0)).to.be.reverted
                              assert.equal(recentWinner.toString(), accounts[0].address)
                              assert.equal(raffleState, 0)
                              assert.equal(
                                  winnerEndingBalance.toString(),
                                  winnerStartingBalance.add(raffleEntranceFee).toString()
                              )
                              assert(endingTimeStamp > startingTimeStamp)
                              resolve()
                          } catch (error) {
                              console.log(error)
                              reject(error)
                          }
                      })
                      // Then entering the raffle
                      console.log("Entering Raffle...")
                      const tx = await raffle.enterRaffle({ value: raffleEntranceFee })
                      await tx.wait(1)
                      console.log("Ok, time to wait...")
                      const winnerStartingBalance = await accounts[0].getBalance()

                      // and this code WONT complete until our listener has finished listening!
                  })
              })
          })
      })

Can anyone help me out with these, here's the link to my repo: https://github.com/anooj1/hardhat-raffle


来源: stackexchange

问:
React Redux state returning incorrect value and then the correct value
Im currently trying to code login functionality using React and Redux however, for some reason when user is logged in, redux extension shows the state correctly as isAuthenticated = true however, when I pass the state into props it firstly renders as false and then secondly renders as true.

Here is the code I use for login page.

```<code>import { FunctionComponent, useState } from "react";
import { Navigate } from 'react-router-dom'
import { connect } from "react-redux";
import { login } from "../actions/auth";
import { IAuth } from "../reducers/auth";

interface ILogin {
    login: (username: string, password: string) => void;
    isAuthenticated: boolean;
}

const Login: FunctionComponent<ILogin> = ({ login, isAuthenticated }) => {
    const [formData, setFormData] = useState({
        username: "",
        password: "",
    });

    const { username, password } = formData;
    console.log(isAuthenticated)
    if (isAuthenticated){
        return <Navigate to="/"/>
    }

    const onChange = (e: React.ChangeEvent<HTMLInputElement>) => setFormData({
        ...formData,
        [e.target.name]: e.target.value,
    })

    const onSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
        e.preventDefault();
        login(username, password)
    }

    return (
        <div className='bg-accent w-full overflow-hidden'>
            <div className="min-h-screen flex justify-center items-center">
                <div className="p-8 flex-1">
                <div className="w-80 bg-white rounded-3xl mx-auto overflow-hidden shadow-xl">
                    <div className="absolute z-[0] w-[20%] h-[15%] pink__gradient" />
                    <div className="absolute z-[1] w-[20%] h-[30%] rounded-full white__gradient bottom-40" />
                    <div className="absolute z-[0] w-[20%] h-[20%] bottom-20 blue__gradient" />
                    <div className="px-10 pt-4 pb-8 rounded-tr-4xl z-[2]">
                        <h1 className="text-2xl font-semibold text-gray-900">Welcome back!</h1>
                        <form className="mt-12" onSubmit={e => onSubmit(e)}>
                            <div className="relative">
                            <input
                                id="username"
                                name="username"
                                type="text"
                                className="peer h-10 w-full border-b-2 border-gray-300 text-gray-900 placeholder-transparent focus:outline-none
                                focus:border-rose-600" placeholder=" "
                                value={username}
                                onChange={e => onChange(e)}
                                required />
                            <label htmlFor="username" className="cursor-text absolute left-0 -top-3.5 text-gray-600 text-sm transition-all peer-placeholder-shown:text-base peer-placeholder-shown:text-gray-400 peer-placeholder-shown:top-2 peer-focus:-top-3.5 peer-focus:text-gray-600 peer-focus:text-sm">A Account</label>
                            </div>
                            <div className="mt-10 relative">
                            <input
                                id="password"
                                type="password"
                                name="password"
                                className="peer h-10 w-full border-b-2 border-gray-300 text-gray-900 placeholder-transparent focus:outline-none
                                focus:border-rose-600" placeholder="Password"
                                value={password}
                                onChange={e => onChange(e)}
                                minLength={6}
                                required />
                            <label htmlFor="password" className="cursor-text absolute left-0 -top-3.5 text-gray-600 text-sm transition-all peer-placeholder-shown:text-base peer-placeholder-shown:text-gray-400 peer-placeholder-shown:top-2 peer-focus:-top-3.5 peer-focus:text-gray-600 peer-focus:text-sm">Password</label>
                            </div>

                            <button className="mt-10 px-4 py-2 font-semibold text-center block w-full bg-rose-600 text-slate-100">Login</button>
                        </form>
                    </div>
                </div>
                </div>
            </div>
        </div>
    )
}

interface IState {
    auth: IAuth
}

const mapStateToProps = (state: IState) => ({
    isAuthenticated: state.auth.isAuthenticated
})

export default connect(mapStateToProps, { login })(Login);
</code>```

Here is screenshot of redux extension.

However, console.log(isAuthenticated) firsly shows as false and then as true.

Screenshot is from login page.

This causes my PrivateRoutes to always redirect to login page even though the user is already logged in.

Code for PrivateRoutes:

```<code>import { FunctionComponent } from 'react'
import { Outlet, Navigate } from 'react-router-dom'
import { connect } from "react-redux";
import { IAuth } from "../reducers/auth";

interface IPrivate {
  isAuthenticated: boolean;
}

const PrivateRoutes: FunctionComponent<IPrivate> = ({ isAuthenticated }) => {
  console.log(isAuthenticated)
  return (
    isAuthenticated ? <Outlet/> : <Navigate to='/login'/>
  )
};

interface IState {
    auth: IAuth
}

const mapStateToProps = (state: IState) => ({
    isAuthenticated: state.auth.isAuthenticated
})

export default connect(mapStateToProps)(PrivateRoutes);
</code>```

Here is my store:

```<code>import { configureStore } from '@reduxjs/toolkit'
import rootReducer from './reducers';

const store = configureStore({ reducer: rootReducer })

export default store;
</code>```

Reducer:

```<code>import {
    LOGIN_SUCCESS,
    LOGIN_FAIL,
    AUTHENTICATED_SUCCESS,
    AUTHENTICATED_FAIL,
    LOGOUT
} from '../actions/types';

export interface IAuth {
    access: string | null;
    refresh: string | null;
    isAuthenticated: boolean;
}

const initialState: IAuth = {
    access: localStorage.getItem('access'),
    refresh: localStorage.getItem('refresh'),
    isAuthenticated: false,
}

export interface IAuthNonNull {
    access: string;
    refresh: string;
    isAuthenticated: boolean;
}

interface IAction {
    type: string,
    payload: IAuthNonNull
}

export default function(state: IAuth = initialState, action: IAction) {
    const { type, payload } = action;

    switch(type) {
        case AUTHENTICATED_SUCCESS:
            return {
                ...state,
                isAuthenticated: true
            }
        case AUTHENTICATED_FAIL:
            return {
                ...state,
                isAuthenticated: false
            }
        case LOGIN_SUCCESS:
            localStorage.setItem('access', payload.access);
            localStorage.setItem('refresh', payload.refresh);
            return {
                ...state,
                isAuthenticated: true,
                access: payload.access,
                refresh: payload.refresh,
            }
        case LOGIN_FAIL:
        case LOGOUT:
            localStorage.removeItem('access');
            localStorage.removeItem('refresh');
            return {
                ...state,
                access: null,
                refresh: null,
                isAuthenticated: false,
            }
        default:
            return state;
    }
}
</code>```

and actions

```<code>import {
    LOGIN_SUCCESS,
    LOGIN_FAIL,
    AUTHENTICATED_SUCCESS,
    AUTHENTICATED_FAIL,
    LOGOUT
} from './types';

import axios from 'axios';

export const checkAuthenticated = () => async (dispatch: any) => {
    if (localStorage.getItem('access')) {
        const config = {
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json',
            }
        }

        const body = JSON.stringify({ token: localStorage.getItem('access') });

        try {
            const res = await axios.post(`${process.env.REACT_APP_API_URL}/api/token/verify/`, body, config);
            if (res.data.code !== 'token_not_valid') {
                dispatch({
                    type: AUTHENTICATED_SUCCESS
                });
            } else {
                dispatch({
                    type: AUTHENTICATED_FAIL
                });
            }
        } catch (err) {
            dispatch({
                type: AUTHENTICATED_FAIL
            });
        }
    } else {
        dispatch({
            type: AUTHENTICATED_FAIL
        });
    }
}

export const login = (username: string, password: string) => async (dispatch: any) => {
    const config = {
        headers: {
            'Content-Type': 'application/json'
        }
    }

    const body = JSON.stringify({ username, password });

    try {
        const res = await axios.post(`${process.env.REACT_APP_API_URL}/api/token/`, body, config);

        dispatch({
            type: LOGIN_SUCCESS,
            payload: res.data
        });
    } catch (err) {
        dispatch({
            type: LOGIN_FAIL
        });
    }
}

export const logout = () => (dispatch: any) => {
    dispatch({
        type: LOGOUT
    });
}
</code>```

Any idea what might be causing this issue?

Thanks in advance :)

ContentLicense: CC BY-SA 4.0

Body:
Im currently trying to code login functionality using React and Redux however, for some reason when user is logged in, redux extension shows the state correctly as isAuthenticated = true however, when I pass the state into props it firstly renders as false and then secondly renders as true.

Here is the code I use for login page.

import { FunctionComponent, useState } from "react";
import { Navigate } from 'react-router-dom'
import { connect } from "react-redux";
import { login } from "../actions/auth";
import { IAuth } from "../reducers/auth";

interface ILogin {
    login: (username: string, password: string) => void;
    isAuthenticated: boolean;
}

const Login: FunctionComponent<ILogin> = ({ login, isAuthenticated }) => {
    const [formData, setFormData] = useState({
        username: "",
        password: "",
    });

    const { username, password } = formData;
    console.log(isAuthenticated)
    if (isAuthenticated){
        return <Navigate to="/"/>
    }

    const onChange = (e: React.ChangeEvent<HTMLInputElement>) => setFormData({
        ...formData,
        [e.target.name]: e.target.value,
    })

    const onSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
        e.preventDefault();
        login(username, password)
    }

    return (

Welcome back!

                        <form className="mt-12" onSubmit={e => onSubmit(e)}>

                            <input
                                id="username"
                                name="username"
                                type="text"
                                className="peer h-10 w-full border-b-2 border-gray-300 text-gray-900 placeholder-transparent focus:outline-none
                                focus:border-rose-600" placeholder=" "
                                value={username}
                                onChange={e => onChange(e)}
                                required />
                            A Account

                            <input
                                id="password"
                                type="password"
                                name="password"
                                className="peer h-10 w-full border-b-2 border-gray-300 text-gray-900 placeholder-transparent focus:outline-none
                                focus:border-rose-600" placeholder="Password"
                                value={password}
                                onChange={e => onChange(e)}
                                minLength={6}
                                required />
                            Password

                            <button className="mt-10 px-4 py-2 font-semibold text-center block w-full bg-rose-600 text-slate-100">Login</button>
                        </form>

    )
}

interface IState {
    auth: IAuth
}

const mapStateToProps = (state: IState) => ({
    isAuthenticated: state.auth.isAuthenticated
})

export default connect(mapStateToProps, { login })(Login);

Here is screenshot of redux extension.

However, console.log(isAuthenticated) firsly shows as false and then as true.

Screenshot is from login page.

This causes my PrivateRoutes to always redirect to login page even though the user is already logged in.

Code for PrivateRoutes:

import { FunctionComponent } from 'react'
import { Outlet, Navigate } from 'react-router-dom'
import { connect } from "react-redux";
import { IAuth } from "../reducers/auth";

interface IPrivate {
  isAuthenticated: boolean;
}

const PrivateRoutes: FunctionComponent<IPrivate> = ({ isAuthenticated }) => {
  console.log(isAuthenticated)
  return (
    isAuthenticated ? <Outlet/> : <Navigate to='/login'/>
  )
};

interface IState {
    auth: IAuth
}

const mapStateToProps = (state: IState) => ({
    isAuthenticated: state.auth.isAuthenticated
})

export default connect(mapStateToProps)(PrivateRoutes);

Here is my store:

import { configureStore } from '@reduxjs/toolkit'
import rootReducer from './reducers';

const store = configureStore({ reducer: rootReducer })

export default store;

Reducer:

import {
    LOGIN_SUCCESS,
    LOGIN_FAIL,
    AUTHENTICATED_SUCCESS,
    AUTHENTICATED_FAIL,
    LOGOUT
} from '../actions/types';

export interface IAuth {
    access: string | null;
    refresh: string | null;
    isAuthenticated: boolean;
}

const initialState: IAuth = {
    access: localStorage.getItem('access'),
    refresh: localStorage.getItem('refresh'),
    isAuthenticated: false,
}

export interface IAuthNonNull {
    access: string;
    refresh: string;
    isAuthenticated: boolean;
}

interface IAction {
    type: string,
    payload: IAuthNonNull
}

export default function(state: IAuth = initialState, action: IAction) {
    const { type, payload } = action;

    switch(type) {
        case AUTHENTICATED_SUCCESS:
            return {
                ...state,
                isAuthenticated: true
            }
        case AUTHENTICATED_FAIL:
            return {
                ...state,
                isAuthenticated: false
            }
        case LOGIN_SUCCESS:
            localStorage.setItem('access', payload.access);
            localStorage.setItem('refresh', payload.refresh);
            return {
                ...state,
                isAuthenticated: true,
                access: payload.access,
                refresh: payload.refresh,
            }
        case LOGIN_FAIL:
        case LOGOUT:
            localStorage.removeItem('access');
            localStorage.removeItem('refresh');
            return {
                ...state,
                access: null,
                refresh: null,
                isAuthenticated: false,
            }
        default:
            return state;
    }
}

and actions

import {
    LOGIN_SUCCESS,
    LOGIN_FAIL,
    AUTHENTICATED_SUCCESS,
    AUTHENTICATED_FAIL,
    LOGOUT
} from './types';

import axios from 'axios';

export const checkAuthenticated = () => async (dispatch: any) => {
    if (localStorage.getItem('access')) {
        const config = {
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json',
            }
        }

        const body = JSON.stringify({ token: localStorage.getItem('access') });

        try {
            const res = await axios.post(`${process.env.REACT_APP_API_URL}/api/token/verify/`, body, config);
            if (res.data.code !== 'token_not_valid') {
                dispatch({
                    type: AUTHENTICATED_SUCCESS
                });
            } else {
                dispatch({
                    type: AUTHENTICATED_FAIL
                });
            }
        } catch (err) {
            dispatch({
                type: AUTHENTICATED_FAIL
            });
        }
    } else {
        dispatch({
            type: AUTHENTICATED_FAIL
        });
    }
}

export const login = (username: string, password: string) => async (dispatch: any) => {
    const config = {
        headers: {
            'Content-Type': 'application/json'
        }
    }

    const body = JSON.stringify({ username, password });

    try {
        const res = await axios.post(`${process.env.REACT_APP_API_URL}/api/token/`, body, config);

        dispatch({
            type: LOGIN_SUCCESS,
            payload: res.data
        });
    } catch (err) {
        dispatch({
            type: LOGIN_FAIL
        });
    }
}

export const logout = () => (dispatch: any) => {
    dispatch({
        type: LOGOUT
    });
}

Any idea what might be causing this issue?

Thanks in advance :)


问:
How to adjust the overlay card same size and position as its bottom card in React?
I want to make a hover animation effect in scss. The idea is when cursor hover on the card, another hidden card appear on top of the hovered card.

But now I got stuck on making the hidden card scss: I am not sure how to make the card the same size and the same position as the bottom card(dark blue card). It is for the className "card-hover"

Below is the code for js:

```<code><div className="gallery">

            {data.map((item)=>
              <div className="card-holder" key={item.id}>
                <div className="card-head">
                  <img className="card-img" src={item.image} alt="project item" />

                </div>
                  <div className="card-body">
                    <h2 className="item-name">{item.title}</h2>
                    <div className="item-date">{item.year}</div>
                  </div>

                <div className="card-hover">
                  <div className="item-role">{item.role}</div>
                  <div className="item-type">{item.type}</div>
                  <div className="item-decs">{item.desc}</div>
                </div>
              </div>

            )}

 </div>
</code>```

Code for scss:

```<code>.gallery{
    margin-left: 10rem;
    margin-right: 10rem;
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    grid-gap: 8px;
    justify-content: center;
}

.card-holder{
    border-radius: 4px;
    margin-top: 1rem;
    background-color: $darkBlue;
    box-shadow: 0px 8px 56px rgb(15 80 100 / 16%);

}

.card-hover {
    position: absolute;
    background-color: #D62839;
    display: inline;
    width: 100%;
    height: 100%;
}

</code>```

The current result:
enter image description here

I have looked through tutorial videos of how to make this kind of hover effect, but all solutions so far were to set

```<code>width:100%;
height:100%
</code>```

or

```<code>top:0;
bottom:0;
left:0;
right:0;
</code>```

However, when I tried them the result is like the screenshot above. Can someone help me with this? Thank you

Body:
I want to make a hover animation effect in scss. The idea is when cursor hover on the card, another hidden card appear on top of the hovered card.

But now I got stuck on making the hidden card scss: I am not sure how to make the card the same size and the same position as the bottom card(dark blue card). It is for the className "card-hover"

Below is the code for js:

            {data.map((item)=>

{item.title}

{item.year}

{item.role}

{item.type}

{item.desc}

            )}

Code for scss:

.gallery{
    margin-left: 10rem;
    margin-right: 10rem;
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    grid-gap: 8px;
    justify-content: center;
}

.card-holder{
    border-radius: 4px;
    margin-top: 1rem;
    background-color: $darkBlue;
    box-shadow: 0px 8px 56px rgb(15 80 100 / 16%);

}

.card-hover {
    position: absolute;
    background-color: #D62839;
    display: inline;
    width: 100%;
    height: 100%;
}

The current result:
enter image description here

I have looked through tutorial videos of how to make this kind of hover effect, but all solutions so far were to set

width:100%;
height:100%

or

top:0;
bottom:0;
left:0;
right:0;

However, when I tried them the result is like the screenshot above. Can someone help me with this? Thank you


问:
Unexpected any value in conditional. An explicit comparison or type cast
The code runs and works fine, but ESLint is screaming at me for an unexpected value in conditional mode. How can I get rid of this problem (I don't want to disable eslint rules)?

This code is responsible for handling the database service and for creating an ADMIN user with the given credentials but first it checks if such an ADMIN already exists in the database.

error:
src/lib/data.service.ts   28:11  error  Unexpected any value in
conditional. An explicit comparison or type cast is required
@typescript-eslint/strict-boolean-expressions

```<code>data.service.ts:

@Injectable()
export class DataService extends PrismaClient {
  constructor (readonly config: ConfigService) {
    super({
      datasources: {
        db: {
          url: config.get('DATABASE_URL')
        }
      }
    })
    this.createAdminUser(this).catch(console.error)
  }

  async createAdminUser (dataService: DataService): Promise<void> {
    try {
      const adminUser: User | null = await dataService.user.findUnique({
        where: {
          email: 'admin@gmail.com'
        }
      })
      if (adminUser != null) {
        const password =
          dataService.config.get('ADMIN_PASSWORD') || 'NotSafePassword1!'
        const hashedPassword = await argon2.hash(password)

        const user = await dataService.user.create({
          data: {
            email: 'admin@gmail.com',
            password: hashedPassword,
            firstName: 'Admin',
            lastName: 'User',
            role: 'ADMIN'
          }
        })

        console.log(`Created admin user with email: ${user.email}`)
      }
    } catch (error) {
      console.error(error)
    }
  }
}
</code>```

The problem is probably in

```<code>if (adminUser != null)
</code>```

I tried using the conditions

```<code>if (adminUser !== null && Boolean(adminUser))
</code>```

and

```<code>if (!!adminUser)
</code>```

but ESlint keeps throwing the same error.

Body:
The code runs and works fine, but ESLint is screaming at me for an unexpected value in conditional mode. How can I get rid of this problem (I don't want to disable eslint rules)?

This code is responsible for handling the database service and for creating an ADMIN user with the given credentials but first it checks if such an ADMIN already exists in the database.

error:
src/lib/data.service.ts   28:11  error  Unexpected any value in
conditional. An explicit comparison or type cast is required
@typescript-eslint/strict-boolean-expressions

data.service.ts:

@Injectable()
export class DataService extends PrismaClient {
  constructor (readonly config: ConfigService) {
    super({
      datasources: {
        db: {
          url: config.get('DATABASE_URL')
        }
      }
    })
    this.createAdminUser(this).catch(console.error)
  }

  async createAdminUser (dataService: DataService): Promise<void> {
    try {
      const adminUser: User | null = await dataService.user.findUnique({
        where: {
          email: 'admin@gmail.com'
        }
      })
      if (adminUser != null) {
        const password =
          dataService.config.get('ADMIN_PASSWORD') || 'NotSafePassword1!'
        const hashedPassword = await argon2.hash(password)

        const user = await dataService.user.create({
          data: {
            email: 'admin@gmail.com',
            password: hashedPassword,
            firstName: 'Admin',
            lastName: 'User',
            role: 'ADMIN'
          }
        })

        console.log(`Created admin user with email: ${user.email}`)
      }
    } catch (error) {
      console.error(error)
    }
  }
}

The problem is probably in

if (adminUser != null)

I tried using the conditions

if (adminUser !== null && Boolean(adminUser))

and

if (!!adminUser)

but ESlint keeps throwing the same error.


问:
MongoDB with PHP - Fatal error: Uncaught Error: Call to undefined method MongoDB\Driver\Cursor::limit()
Am trying to fetch data from MongoDB using PHP.
I have implemented the following code:

```<code>    $all_items = $collection
        ->find( $where_search, array('_id', 'name', 'email', 'bod', 'mobile') )
        ->limit( $per_page )
        ->skip( $start )
        ->sort( array(
            $Allele => $sort == 'ASC' ? 1 : -1
        ));
</code>```

I am getting the following error:

```<code>Fatal error: Uncaught Error: Call to undefined method MongoDB\Driver\Cursor::limit() in /var/www/
</code>```

The used MongoDB version is v4.2, PHP 7.4 and Composer version 2.5.1

I also included the Composer’s autoloader

```<code> require 'vendor/autoload.php';
</code>```

and installed the below MongoDB extension and included the

Body:
Am trying to fetch data from MongoDB using PHP.
I have implemented the following code:

    $all_items = $collection
        ->find( $where_search, array('_id', 'name', 'email', 'bod', 'mobile') )
        ->limit( $per_page )
        ->skip( $start )
        ->sort( array(
            $Allele => $sort == 'ASC' ? 1 : -1
        ));

I am getting the following error:

Fatal error: Uncaught Error: Call to undefined method MongoDB\Driver\Cursor::limit() in /var/www/

The used MongoDB version is v4.2, PHP 7.4 and Composer version 2.5.1

I also included the Composer’s autoloader

 require 'vendor/autoload.php';

and installed the below MongoDB extension and included the


问:
INVALID_ARGUMENT: expected compatible input types, but input 1: What does this TF error mean and how do I resolve this?
I have been working on a neural network and want to train it through tensorflow's FastAPI and when I trigger training, this error shows up; that I cannot comprehend-

```<code>2023-01-05 19:17:57.881722: W tensorflow/core/common_runtime/forward_type_inference.cc:231] Type inference failed. This indicates an invalid graph that escaped type checking. Error message: INVALID_ARGUMENT: expected compatible input types, but input 1:
type_id: TFT_OPTIONAL
args {
  type_id: TFT_PRODUCT
  args {
    type_id: TFT_TENSOR
    args {
      type_id: TFT_BOOL
    }
  }
}
 is neither a subtype nor a supertype of the combined inputs preceding it:
type_id: TFT_OPTIONAL
args {
  type_id: TFT_PRODUCT
  args {
    type_id: TFT_TENSOR
    args {
      type_id: TFT_LEGACY_VARIANT
    }
  }
}

        while inferring type of node 'binary_crossentropy/cond/output/_10'
2023-01-05 19:18:16.532189: I tensorflow/core/kernels/data/shuffle_dataset_op.cc:390] Filling up shuffle buffer (this may take a while): 361 of 5000
2023-01-05 19:18:26.305368: I tensorflow/core/kernels/data/shuffle_dataset_op.cc:390] Filling up shuffle buffer (this may take a while): 635 of 5000
2023-01-05 19:18:36.170004: I tensorflow/core/kernels/data/shuffle_dataset_op.cc:390] Filling up shuffle buffer (this may take a while): 1017 of 5000
2023-01-05 19:18:46.177664: I tensorflow/core/kernels/data/shuffle_dataset_op.cc:390] Filling up shuffle buffer (this may take a while): 1263 of 5000
2023-01-05 19:18:56.154804: I tensorflow/core/kernels/data/shuffle_dataset_op.cc:390] Filling up shuffle buffer (this may take a while): 1559 of 5000
2023-01-05 19:19:06.208777: I tensorflow/core/kernels/data/shuffle_dataset_op.cc:390] Filling up shuffle buffer (this may take a while): 1949 of 5000
2023-01-05 19:19:16.177522: I tensorflow/core/kernels/data/shuffle_dataset_op.cc:390] Filling up shuffle buffer (this may take a while): 2147 of 5000
2023-01-05 19:19:26.192117: I tensorflow/core/kernels/data/shuffle_dataset_op.cc:390] Filling up shuffle buffer (this may take a while): 2282 of 5000
2023-01-05 19:19:36.637720: I tensorflow/core/kernels/data/shuffle_dataset_op.cc:390] Filling up shuffle buffer (this may take a while): 2448 of 5000
2023-01-05 19:19:46.256679: I tensorflow/core/kernels/data/shuffle_dataset_op.cc:390] Filling up shuffle buffer (this may take a while): 2621 of 5000
2023-01-05 19:19:56.203889: I tensorflow/core/kernels/data/shuffle_dataset_op.cc:390] Filling up shuffle buffer (this may take a while): 2829 of 5000
2023-01-05 19:20:06.300115: I tensorflow/core/kernels/data/shuffle_dataset_op.cc:390] Filling up shuffle buffer (this may take a while): 3083 of 5000
2023-01-05 19:20:16.191704: I tensorflow/core/kernels/data/shuffle_dataset_op.cc:390] Filling up shuffle buffer (this may take a while): 3338 of 5000
2023-01-05 19:20:26.192851: I tensorflow/core/kernels/data/shuffle_dataset_op.cc:390] Filling up shuffle buffer (this may take a while): 3669 of 5000
2023-01-05 19:20:36.212527: I tensorflow/core/kernels/data/shuffle_dataset_op.cc:390] Filling up shuffle buffer (this may take a while): 4049 of 5000
2023-01-05 19:20:46.401018: I tensorflow/core/kernels/data/shuffle_dataset_op.cc:390] Filling up shuffle buffer (this may take a while): 4398 of 5000
2023-01-05 19:20:56.168909: I tensorflow/core/kernels/data/shuffle_dataset_op.cc:390] Filling up shuffle buffer (this may take a while): 4596 of 5000
2023-01-05 19:21:06.164738: I tensorflow/core/kernels/data/shuffle_dataset_op.cc:390] Filling up shuffle buffer (this may take a while): 4821 of 5000
2023-01-05 19:21:07.181289: I tensorflow/core/kernels/data/shuffle_dataset_op.cc:415] Shuffle buffer filled.
Traceback (most recent call last):
  File "C:\Users\Radhe Krishna\OneDrive\Documents\MarkATT\main.py", line 527, in <module>
    training_history = model.fit(train,epochs=10, validation_data = val)
  File "C:\Users\Radhe Krishna\OneDrive\Documents\MarkATT\MarkATT\lib\site-packages\keras\utils\traceback_utils.py", line 67, in error_handler
    raise e.with_traceback(filtered_tb) from None
  File "C:\Users\Radhe Krishna\OneDrive\Documents\MarkATT\MarkATT\lib\site-packages\tensorflow\python\eager\execute.py", line 54, in quick_execute
    tensors = pywrap_tfe.TFE_Py_Execute(ctx._handle, device_name, op_name,
tensorflow.python.framework.errors_impl.InvalidArgumentError: Graph execution error:

Detected at node 'gradient_tape/sub_2/BroadcastGradientArgs' defined at (most recent call last):
    File "C:\Users\Radhe Krishna\OneDrive\Documents\MarkATT\main.py", line 527, in <module>
      training_history = model.fit(train,epochs=10, validation_data = val)
    File "C:\Users\Radhe Krishna\OneDrive\Documents\MarkATT\MarkATT\lib\site-packages\keras\utils\traceback_utils.py", line 64, in error_handler
      return fn(*args, **kwargs)
    File "C:\Users\Radhe Krishna\OneDrive\Documents\MarkATT\MarkATT\lib\site-packages\keras\engine\training.py", line 1409, in fit
      tmp_logs = self.train_function(iterator)
    File "C:\Users\Radhe Krishna\OneDrive\Documents\MarkATT\MarkATT\lib\site-packages\keras\engine\training.py", line 1051, in train_function
      return step_function(self, iterator)
    File "C:\Users\Radhe Krishna\OneDrive\Documents\MarkATT\MarkATT\lib\site-packages\keras\engine\training.py", line 1040, in step_function
      outputs = model.distribute_strategy.run(run_step, args=(data,))
    File "C:\Users\Radhe Krishna\OneDrive\Documents\MarkATT\MarkATT\lib\site-packages\keras\engine\training.py", line 1030, in run_step
      outputs = model.train_step(data)
    File "C:\Users\Radhe Krishna\OneDrive\Documents\MarkATT\main.py", line 500, in train_step
      grad = tape.gradient(total_loss, self.model.trainable_variables)
Node: 'gradient_tape/sub_2/BroadcastGradientArgs'
Incompatible shapes: [2,4] vs. [8]
         [[{{node gradient_tape/sub_2/BroadcastGradientArgs}}]] [Op:__inference_train_function_22025]

</code>```

For your reference, this is the training class that I intent to use-

```<code>class FaceTracker(Model):
    # Making the initialization function to instantiate our model fro training
    def __init__(self,facetracker,**kwargs):
        super().__init__(**kwargs)
        self.model = facetracker
    # Making the compile method to compile all the losses and optimizers needed to train the model
    def compile(self, optimizer,classloss,localization_loss,**kwargs):
        super().compile(**kwargs)
        self.classloss = class_loss
        self.localization_loss = regress_loss
        self.optimizer = optimizer
    # Defining the training step where the backprop shall be applied to our data
    def train_step(self,batch,**kwargs):

        X,y = batch
        with tf.GradientTape() as tape:
            classes,coords = self.model(X,training=True)
            batch_classloss = self.classloss(y[0],classes)
            batch_localloss = self.localization_loss(y[1],coords)

            total_loss = batch_localloss+0.5*batch_classloss
            grad = tape.gradient(total_loss, self.model.trainable_variables)
            optimizer.apply_gradients(zip(grad,self.model.trainable_variables))
            return{
                "total_loss":total_loss,
                "class_loss":batch_classloss,
                "localization_loss":batch_localloss
            }
        # Definging the testing step for the model, which is similar to the train_step but without backprop
        def test_step(self,batch,**kwargs):
            X,y = batch
            classes,coords = self.model(X,training=True)
            batch_classloss = self.classloss(y[0],classes)
            batch_localloss = self.localization_loss(tf.cast(y[1],tf.float32),coords)
            total_loss = batch_localloss+0.5%batch_classloss
            return{
                "total_loss":total_loss,
                "classloss":batch_classloss,
                "localization_loss":batch_localloss
            }
        #Defining a lambda function that should act as a call function.Lambda is used so as to prevent us from having to subclass the method to make a child class
        lambda self,X,**kwargs: self.model(X,**kwargs)

</code>```

It would be a great help if someone could give me insights on how do I resolve this issue.
For more clarity, I also raised a related query earlier that you could visit and dive deeper into
My query

Thanks in advance!!

Trying to initiate training of a Neural Network, but getting this eerror that I cannot understand myselfyour text

Body:
I have been working on a neural network and want to train it through tensorflow's FastAPI and when I trigger training, this error shows up; that I cannot comprehend-

2023-01-05 19:17:57.881722: W tensorflow/core/common_runtime/forward_type_inference.cc:231] Type inference failed. This indicates an invalid graph that escaped type checking. Error message: INVALID_ARGUMENT: expected compatible input types, but input 1:
type_id: TFT_OPTIONAL
args {
  type_id: TFT_PRODUCT
  args {
    type_id: TFT_TENSOR
    args {
      type_id: TFT_BOOL
    }
  }
}
 is neither a subtype nor a supertype of the combined inputs preceding it:
type_id: TFT_OPTIONAL
args {
  type_id: TFT_PRODUCT
  args {
    type_id: TFT_TENSOR
    args {
      type_id: TFT_LEGACY_VARIANT
    }
  }
}

        while inferring type of node 'binary_crossentropy/cond/output/_10'
2023-01-05 19:18:16.532189: I tensorflow/core/kernels/data/shuffle_dataset_op.cc:390] Filling up shuffle buffer (this may take a while): 361 of 5000
2023-01-05 19:18:26.305368: I tensorflow/core/kernels/data/shuffle_dataset_op.cc:390] Filling up shuffle buffer (this may take a while): 635 of 5000
2023-01-05 19:18:36.170004: I tensorflow/core/kernels/data/shuffle_dataset_op.cc:390] Filling up shuffle buffer (this may take a while): 1017 of 5000
2023-01-05 19:18:46.177664: I tensorflow/core/kernels/data/shuffle_dataset_op.cc:390] Filling up shuffle buffer (this may take a while): 1263 of 5000
2023-01-05 19:18:56.154804: I tensorflow/core/kernels/data/shuffle_dataset_op.cc:390] Filling up shuffle buffer (this may take a while): 1559 of 5000
2023-01-05 19:19:06.208777: I tensorflow/core/kernels/data/shuffle_dataset_op.cc:390] Filling up shuffle buffer (this may take a while): 1949 of 5000
2023-01-05 19:19:16.177522: I tensorflow/core/kernels/data/shuffle_dataset_op.cc:390] Filling up shuffle buffer (this may take a while): 2147 of 5000
2023-01-05 19:19:26.192117: I tensorflow/core/kernels/data/shuffle_dataset_op.cc:390] Filling up shuffle buffer (this may take a while): 2282 of 5000
2023-01-05 19:19:36.637720: I tensorflow/core/kernels/data/shuffle_dataset_op.cc:390] Filling up shuffle buffer (this may take a while): 2448 of 5000
2023-01-05 19:19:46.256679: I tensorflow/core/kernels/data/shuffle_dataset_op.cc:390] Filling up shuffle buffer (this may take a while): 2621 of 5000
2023-01-05 19:19:56.203889: I tensorflow/core/kernels/data/shuffle_dataset_op.cc:390] Filling up shuffle buffer (this may take a while): 2829 of 5000
2023-01-05 19:20:06.300115: I tensorflow/core/kernels/data/shuffle_dataset_op.cc:390] Filling up shuffle buffer (this may take a while): 3083 of 5000
2023-01-05 19:20:16.191704: I tensorflow/core/kernels/data/shuffle_dataset_op.cc:390] Filling up shuffle buffer (this may take a while): 3338 of 5000
2023-01-05 19:20:26.192851: I tensorflow/core/kernels/data/shuffle_dataset_op.cc:390] Filling up shuffle buffer (this may take a while): 3669 of 5000
2023-01-05 19:20:36.212527: I tensorflow/core/kernels/data/shuffle_dataset_op.cc:390] Filling up shuffle buffer (this may take a while): 4049 of 5000
2023-01-05 19:20:46.401018: I tensorflow/core/kernels/data/shuffle_dataset_op.cc:390] Filling up shuffle buffer (this may take a while): 4398 of 5000
2023-01-05 19:20:56.168909: I tensorflow/core/kernels/data/shuffle_dataset_op.cc:390] Filling up shuffle buffer (this may take a while): 4596 of 5000
2023-01-05 19:21:06.164738: I tensorflow/core/kernels/data/shuffle_dataset_op.cc:390] Filling up shuffle buffer (this may take a while): 4821 of 5000
2023-01-05 19:21:07.181289: I tensorflow/core/kernels/data/shuffle_dataset_op.cc:415] Shuffle buffer filled.
Traceback (most recent call last):
  File "C:\Users\Radhe Krishna\OneDrive\Documents\MarkATT\main.py", line 527, in <module>
    training_history = model.fit(train,epochs=10, validation_data = val)
  File "C:\Users\Radhe Krishna\OneDrive\Documents\MarkATT\MarkATT\lib\site-packages\keras\utils\traceback_utils.py", line 67, in error_handler
    raise e.with_traceback(filtered_tb) from None
  File "C:\Users\Radhe Krishna\OneDrive\Documents\MarkATT\MarkATT\lib\site-packages\tensorflow\python\eager\execute.py", line 54, in quick_execute
    tensors = pywrap_tfe.TFE_Py_Execute(ctx._handle, device_name, op_name,
tensorflow.python.framework.errors_impl.InvalidArgumentError: Graph execution error:

Detected at node 'gradient_tape/sub_2/BroadcastGradientArgs' defined at (most recent call last):
    File "C:\Users\Radhe Krishna\OneDrive\Documents\MarkATT\main.py", line 527, in <module>
      training_history = model.fit(train,epochs=10, validation_data = val)
    File "C:\Users\Radhe Krishna\OneDrive\Documents\MarkATT\MarkATT\lib\site-packages\keras\utils\traceback_utils.py", line 64, in error_handler
      return fn(*args, **kwargs)
    File "C:\Users\Radhe Krishna\OneDrive\Documents\MarkATT\MarkATT\lib\site-packages\keras\engine\training.py", line 1409, in fit
      tmp_logs = self.train_function(iterator)
    File "C:\Users\Radhe Krishna\OneDrive\Documents\MarkATT\MarkATT\lib\site-packages\keras\engine\training.py", line 1051, in train_function
      return step_function(self, iterator)
    File "C:\Users\Radhe Krishna\OneDrive\Documents\MarkATT\MarkATT\lib\site-packages\keras\engine\training.py", line 1040, in step_function
      outputs = model.distribute_strategy.run(run_step, args=(data,))
    File "C:\Users\Radhe Krishna\OneDrive\Documents\MarkATT\MarkATT\lib\site-packages\keras\engine\training.py", line 1030, in run_step
      outputs = model.train_step(data)
    File "C:\Users\Radhe Krishna\OneDrive\Documents\MarkATT\main.py", line 500, in train_step
      grad = tape.gradient(total_loss, self.model.trainable_variables)
Node: 'gradient_tape/sub_2/BroadcastGradientArgs'
Incompatible shapes: [2,4] vs. [8]
         [[{{node gradient_tape/sub_2/BroadcastGradientArgs}}]] [Op:__inference_train_function_22025]

For your reference, this is the training class that I intent to use-

class FaceTracker(Model):
    # Making the initialization function to instantiate our model fro training
    def __init__(self,facetracker,**kwargs):
        super().__init__(**kwargs)
        self.model = facetracker
    # Making the compile method to compile all the losses and optimizers needed to train the model
    def compile(self, optimizer,classloss,localization_loss,**kwargs):
        super().compile(**kwargs)
        self.classloss = class_loss
        self.localization_loss = regress_loss
        self.optimizer = optimizer
    # Defining the training step where the backprop shall be applied to our data
    def train_step(self,batch,**kwargs):

        X,y = batch
        with tf.GradientTape() as tape:
            classes,coords = self.model(X,training=True)
            batch_classloss = self.classloss(y[0],classes)
            batch_localloss = self.localization_loss(y[1],coords)

            total_loss = batch_localloss+0.5*batch_classloss
            grad = tape.gradient(total_loss, self.model.trainable_variables)
            optimizer.apply_gradients(zip(grad,self.model.trainable_variables))
            return{
                "total_loss":total_loss,
                "class_loss":batch_classloss,
                "localization_loss":batch_localloss
            }
        # Definging the testing step for the model, which is similar to the train_step but without backprop
        def test_step(self,batch,**kwargs):
            X,y = batch
            classes,coords = self.model(X,training=True)
            batch_classloss = self.classloss(y[0],classes)
            batch_localloss = self.localization_loss(tf.cast(y[1],tf.float32),coords)
            total_loss = batch_localloss+0.5%batch_classloss
            return{
                "total_loss":total_loss,
                "classloss":batch_classloss,
                "localization_loss":batch_localloss
            }
        #Defining a lambda function that should act as a call function.Lambda is used so as to prevent us from having to subclass the method to make a child class
        lambda self,X,**kwargs: self.model(X,**kwargs)

It would be a great help if someone could give me insights on how do I resolve this issue.
For more clarity, I also raised a related query earlier that you could visit and dive deeper into
My query

Thanks in advance!!

Trying to initiate training of a Neural Network, but getting this eerror that I cannot understand myselfyour text


问:
GC issues compiling a large scala monorepo
Scala version=2.12.15
SBT version=1.4.9
JVM=1.8
GC=ParallelGC ( marksweep/scavenge )
Heap size=14GB
Monorepo is full of spark code

Files to compile 34013 over 3-4 subprojects

What we've noticed is the gradual increase on old-gen space that doesn't clear out even though GC's are constantly happening which suggests there are a lot of live objects

A heap dump was taken

jmap -histo ( 3rd column is size in megabytes )

```<code>13: 1209208 181.843 [Ljava.lang.Object;
12: 8881966 203.292 xsbti.api.NameHash
11: 9080251 207.83 scala.collection.immutable.HashSet$HashSet1
10: 7052557 215.227 scala.reflect.internal.Trees$Literal
9: 6539689 249.469 scala.reflect.internal.Trees$TypeTree
8: 10487573 320.055 scala.reflect.internal.Symbols$TypeHistory
7: 4839129 332.277 scala.reflect.internal.Symbols$TermSymbol
6: 10500404 400.559 scala.reflect.internal.Trees$Apply
5: 10728133 409.246 scala.reflect.internal.Trees$Ident
4: 30407384 695.97 java.lang.String
3: 18842332 718.778 scala.reflect.internal.Trees$Select
2: 35977908 823.469 scala.collection.immutable.$colon$colon
1: 30412139 1942.91 [C
</code>```

When we analyzed the retained sizes of various classes, scala.collection.immutable.$colon$colon was retaining around 5G of heap

I'm curious to understand how scalac works to get to the bottom of this. Worst case perhaps we do need 14G of heap to compile our monorepo

Body:
Scala version=2.12.15
SBT version=1.4.9
JVM=1.8
GC=ParallelGC ( marksweep/scavenge )
Heap size=14GB
Monorepo is full of spark code

Files to compile 34013 over 3-4 subprojects

What we've noticed is the gradual increase on old-gen space that doesn't clear out even though GC's are constantly happening which suggests there are a lot of live objects

A heap dump was taken

jmap -histo ( 3rd column is size in megabytes )

13: 1209208 181.843 [Ljava.lang.Object;
12: 8881966 203.292 xsbti.api.NameHash
11: 9080251 207.83 scala.collection.immutable.HashSet$HashSet1
10: 7052557 215.227 scala.reflect.internal.Trees$Literal
9: 6539689 249.469 scala.reflect.internal.Trees$TypeTree
8: 10487573 320.055 scala.reflect.internal.Symbols$TypeHistory
7: 4839129 332.277 scala.reflect.internal.Symbols$TermSymbol
6: 10500404 400.559 scala.reflect.internal.Trees$Apply
5: 10728133 409.246 scala.reflect.internal.Trees$Ident
4: 30407384 695.97 java.lang.String
3: 18842332 718.778 scala.reflect.internal.Trees$Select
2: 35977908 823.469 scala.collection.immutable.$colon$colon
1: 30412139 1942.91 [C

When we analyzed the retained sizes of various classes, scala.collection.immutable.$colon$colon was retaining around 5G of heap

I'm curious to understand how scalac works to get to the bottom of this. Worst case perhaps we do need 14G of heap to compile our monorepo


问:
Spring boot integration test Authentication
Hello everyone in my application im using oauth2.0 for authentication in my controller methods im always checking if Authentication argument is always set.

```<code>public ResponseEntity<?> getFarm(Authentication authentication) {
        if (authentication == null) {
            return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
        }
}
</code>```

everything works fine but im trying to write integration test for this and I have problem with mocking the authentication i was trying many solutions there like : Spring Test & Security: How to mock authentication? but still im getting null.

this is my integration test

```<code>@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment= SpringBootTest.WebEnvironment.RANDOM_PORT)
public class TestRest {

    @Autowired
    private TestRestTemplate restTemplate;

    @Test
    public void findAllCustomers() {
        var farmInfoDto = new FarmInfoDto("big farm", "warsaw", "strett", "123", "15a");

        var test = restTemplate.withBasicAuth("test","test").postForEntity("/farm", farmInfoDto, Farm.class);
        var farm = test.getBody();

        assert farm.getFarmName().equals(farmInfoDto.farmName());
    }
}
</code>```

Body:
Hello everyone in my application im using oauth2.0 for authentication in my controller methods im always checking if Authentication argument is always set.

public ResponseEntity<?> getFarm(Authentication authentication) {
        if (authentication == null) {
            return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
        }
}

everything works fine but im trying to write integration test for this and I have problem with mocking the authentication i was trying many solutions there like : Spring Test & Security: How to mock authentication? but still im getting null.

this is my integration test

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment= SpringBootTest.WebEnvironment.RANDOM_PORT)
public class TestRest {

    @Autowired
    private TestRestTemplate restTemplate;

    @Test
    public void findAllCustomers() {
        var farmInfoDto = new FarmInfoDto("big farm", "warsaw", "strett", "123", "15a");

        var test = restTemplate.withBasicAuth("test","test").postForEntity("/farm", farmInfoDto, Farm.class);
        var farm = test.getBody();

        assert farm.getFarmName().equals(farmInfoDto.farmName());
    }
}


问:
Use Optimization to minimize a output dependent function (python)
Consider a simple code running inside a while loop:

```<code>while m_diff >= convergence_lim and paramC <= M_lim:
 paramC = temp_M
 try:
     paramB, M, P = some_function(paramA, paramB, paramC)
 except:
     temp_M+= 0.001
     continue
 totalM0 = paramB['Mo']
 totalM1 = sum(M)    # Sum of all M
 m_diff  = abs(totalM0 - totalM1)
 temp_M+= 0.001
</code>```

This would run forever and iterate each 0.001 sample until m_diff is acceptable. I would like to use scipy.optimize to arrive at the numbers faster.

The issue is with the paramB as the function some_function regenerates a different value of paramB. The optimizer should look for best paramC that minimizes m_diff.

I tried:

```<code>import scipy.optimize

def mass_diff_func(paramC, paramB):
   paramA = 10  #Constant
   try:
       paramB, M, P = some_function(paramA, paramB, paramC)
   except:
       return float('inf'), paramB

   totalM0 = paramB['Mo']
   totalM1 = sum(M)
   m_diff = abs(totalM0 - totalM1)
   return m_diff, paramB

  result = scipy.optimize.minimize(mass_diff_func, paramC, args=(paramB,), bounds=[(convergence_lim, M_lim)])
  optimal_paramC = result.x
</code>```

But changes to paramB doesn't seem to be carried to minimize function. Or minimize function doesn't register changes to paramB, either way any idea how to fix this?

Open to other optimizers as well.

Body:
Consider a simple code running inside a while loop:

while m_diff >= convergence_lim and paramC <= M_lim:
 paramC = temp_M
 try:
     paramB, M, P = some_function(paramA, paramB, paramC)
 except:
     temp_M+= 0.001
     continue
 totalM0 = paramB['Mo']
 totalM1 = sum(M)    # Sum of all M
 m_diff  = abs(totalM0 - totalM1)
 temp_M+= 0.001

This would run forever and iterate each 0.001 sample until m_diff is acceptable. I would like to use scipy.optimize to arrive at the numbers faster.

The issue is with the paramB as the function some_function regenerates a different value of paramB. The optimizer should look for best paramC that minimizes m_diff.

I tried:

import scipy.optimize

def mass_diff_func(paramC, paramB):
   paramA = 10  #Constant
   try:
       paramB, M, P = some_function(paramA, paramB, paramC)
   except:
       return float('inf'), paramB

   totalM0 = paramB['Mo']
   totalM1 = sum(M)
   m_diff = abs(totalM0 - totalM1)
   return m_diff, paramB

  result = scipy.optimize.minimize(mass_diff_func, paramC, args=(paramB,), bounds=[(convergence_lim, M_lim)])
  optimal_paramC = result.x

But changes to paramB doesn't seem to be carried to minimize function. Or minimize function doesn't register changes to paramB, either way any idea how to fix this?

Open to other optimizers as well.


问:
ft4222 1.7.0 does not raise exception on error
I am performing I2C master read/write using UMFT4222 ftdi module. I am using python lib ft4222(https://msrelectronics.gitlab.io/python-ft4222/api.html#ft4222.FT2XXDeviceError)

Now sometime in my system I2C slave is not powered on so ftdi chip should generates an error. But even device is not powered on, READ API does not raises and exception and it reads 0x00. Code snippet is attached below.

Is exception support is not added in ft4222?
Is there a way I can get error in python when device is not present?

```<code>import ft4222
import ft4222.I2CMaster
from ft4222.GPIO import Dir, Port, Output
import time

# list devices
nbDev = ft4222.createDeviceInfoList()
for i in range(nbDev):
    print(ft4222.getDeviceInfoDetail(i, False))

# open device with default description 'FT4222 A'
dev = ft4222.openByDescription('FT4222 A')

# init i2c master, clock speed 100kHz
dev.i2cMaster_Init(100000)

# do a i2c transfers where full control is required
slave = 24# address
send_data = b'\x02\x01\x07'
# read one byte, don't stop
dev.gpio_Init(gpio0 = Dir.OUTPUT)
dev.gpio_Init(gpio1 = Dir.OUTPUT)
int_data = dev.i2cMaster_Write(slave, send_data)
time.sleep(0.5)
print(int_data)
data = dev.i2cMaster_Read(slave,10) #This should raise an exception
print(data.hex())
</code>```

Output:
{'index': 0, 'flags': 2, 'type': 10, 'id': 67330076, 'location': 5169, 'serial': b'A', 'description': b'FT4222 A', 'handle': 0}
{'index': 1, 'flags': 2, 'type': 10, 'id': 67330076, 'location': 5170, 'serial': b'B', 'description': b'FT4222 B', 'handle': 0}
3
00000000000000000000

I have looked into python source of module but I dont see any development regarding I2C. It looks like it is somehow connected to dll but I am not sure how to go ahead for fixing this issue as I have not worked with C development in python.

Body:
I am performing I2C master read/write using UMFT4222 ftdi module. I am using python lib ft4222(https://msrelectronics.gitlab.io/python-ft4222/api.html#ft4222.FT2XXDeviceError)

Now sometime in my system I2C slave is not powered on so ftdi chip should generates an error. But even device is not powered on, READ API does not raises and exception and it reads 0x00. Code snippet is attached below.

Is exception support is not added in ft4222?
Is there a way I can get error in python when device is not present?

import ft4222
import ft4222.I2CMaster
from ft4222.GPIO import Dir, Port, Output
import time

# list devices
nbDev = ft4222.createDeviceInfoList()
for i in range(nbDev):
    print(ft4222.getDeviceInfoDetail(i, False))

# open device with default description 'FT4222 A'
dev = ft4222.openByDescription('FT4222 A')

# init i2c master, clock speed 100kHz
dev.i2cMaster_Init(100000)

# do a i2c transfers where full control is required
slave = 24# address
send_data = b'\x02\x01\x07'
# read one byte, don't stop
dev.gpio_Init(gpio0 = Dir.OUTPUT)
dev.gpio_Init(gpio1 = Dir.OUTPUT)
int_data = dev.i2cMaster_Write(slave, send_data)
time.sleep(0.5)
print(int_data)
data = dev.i2cMaster_Read(slave,10) #This should raise an exception
print(data.hex())

Output:
{'index': 0, 'flags': 2, 'type': 10, 'id': 67330076, 'location': 5169, 'serial': b'A', 'description': b'FT4222 A', 'handle': 0}
{'index': 1, 'flags': 2, 'type': 10, 'id': 67330076, 'location': 5170, 'serial': b'B', 'description': b'FT4222 B', 'handle': 0}
3
00000000000000000000

I have looked into python source of module but I dont see any development regarding I2C. It looks like it is somehow connected to dll but I am not sure how to go ahead for fixing this issue as I have not worked with C development in python.


问:
ClassCastException depending on which gradle module holds the code?
I have a gradle project with two modules, library and app. library is a java-library that can be published as maven artifact. It contains some util methods that are used by app, hence app depends on library.

Now, I'd like to add two util methods for serialization as shown below. Depending on where the util methods are placed and whether or not the serialized string of MyClass (which is also located in app) is written to a csv file in between (serialize -> export -> import -> deserialize).

Case 1 / No Problem: As long as my util methods are part of app, I can serialize and deserialize MyClass without any problems, even if I export the serialized string to a csv-file in between.

Case 2 / No Problem: When my utils methods are part of library, I can only serialize and deserialize MyClass, if the serialized string is not written to a csv-file in between.

Case 3 / PROBLEM: If my utils are placed in library and the serialized string is written to a csv-file in between, then I get a java.lang.ClassCastException: Cannot cast my.package.MyClass to my.package.MyClass at java.base/java.lang.Class.cast(Class.java:3605).

When I run the debugger up until ois.readObject(), I can even see the properly deserialized object. However, it is not possible to cast it correctly.

Could anyone help me to find the reason for the situation described above? Any ideas why this error could occur? Any ideas why it might not be allowed to have my util methods in library?

```<code>@Nonnull
public static <T> String serialize(T object) throws IllegalStateException {
    try (
        final ByteArrayOutputStream bos = new ByteArrayOutputStream();
        final ObjectOutputStream oos = new ObjectOutputStream(bos)
    ) {
        oos.writeObject(object);
        return Base64.getEncoder().encodeToString(bos.toByteArray());
    } catch (final IOException e) {
        throw new IllegalStateException("serialization failed", e);
    }
}

@Nonnull
public static <T> T deserialize(String objectAsString, Class<T> tClass) throws IllegalStateException {
    final byte[] data = Base64.getDecoder().decode(objectAsString);
    try (
        final ByteArrayInputStream bis = new ByteArrayInputStream(data);
        final ObjectInputStream ois = new ObjectInputStream(bis)
    ) {
        return tClass.cast(ois.readObject());
    } catch (Exception e) {
        throw new IllegalStateException("deserialization failed", e);
    }
}
</code>```

Body:
I have a gradle project with two modules, library and app. library is a java-library that can be published as maven artifact. It contains some util methods that are used by app, hence app depends on library.

Now, I'd like to add two util methods for serialization as shown below. Depending on where the util methods are placed and whether or not the serialized string of MyClass (which is also located in app) is written to a csv file in between (serialize -> export -> import -> deserialize).

Case 1 / No Problem: As long as my util methods are part of app, I can serialize and deserialize MyClass without any problems, even if I export the serialized string to a csv-file in between.

Case 2 / No Problem: When my utils methods are part of library, I can only serialize and deserialize MyClass, if the serialized string is not written to a csv-file in between.

Case 3 / PROBLEM: If my utils are placed in library and the serialized string is written to a csv-file in between, then I get a java.lang.ClassCastException: Cannot cast my.package.MyClass to my.package.MyClass at java.base/java.lang.Class.cast(Class.java:3605).

When I run the debugger up until ois.readObject(), I can even see the properly deserialized object. However, it is not possible to cast it correctly.

Could anyone help me to find the reason for the situation described above? Any ideas why this error could occur? Any ideas why it might not be allowed to have my util methods in library?

@Nonnull
public static <T> String serialize(T object) throws IllegalStateException {
    try (
        final ByteArrayOutputStream bos = new ByteArrayOutputStream();
        final ObjectOutputStream oos = new ObjectOutputStream(bos)
    ) {
        oos.writeObject(object);
        return Base64.getEncoder().encodeToString(bos.toByteArray());
    } catch (final IOException e) {
        throw new IllegalStateException("serialization failed", e);
    }
}

@Nonnull
public static <T> T deserialize(String objectAsString, Class<T> tClass) throws IllegalStateException {
    final byte[] data = Base64.getDecoder().decode(objectAsString);
    try (
        final ByteArrayInputStream bis = new ByteArrayInputStream(data);
        final ObjectInputStream ois = new ObjectInputStream(bis)
    ) {
        return tClass.cast(ois.readObject());
    } catch (Exception e) {
        throw new IllegalStateException("deserialization failed", e);
    }
}


问:
How to store a thread on a Web Application
I'm working on a legacy code made in .Net Framework 4.7, very old, I don't know too much about it as I started programming on .Net Core onwards. There is a mix of vb.net and c#, classes with 40k lines of code (90% of the code was program as structured programming, even seeing the same piece of code repeated below) and methods with 3.5k lines of code, so big refactoring's is a no no, it is already in prod.

Problem:
Someone created a Thread to finish a method and don't block the GUI when clicking a button, is a new(ed) up instance of Thread in the middle of a class. This Thread needs to finish before reaching a certain point in the GUI, the idea is to check if the thread finished when someone clicks a button, the other button is on another page and it postback.

Question:
How can I add a reference to an IEnumerable of these particular managed threads and ask if the last one finished?

What I tried:
Because I have never used Threads and never 'newed' up something this important in the middle of a 40k lines of code class, the only thing I tried that they are doing is to try and store some sort of flag on Session, problem is, how do you update the flag?.


问:
Can I use a Mongo query to query a List of objects in c#?
I would like to use a Mongo query to query a List of objects in c#.

I tried using FilterDefinition.Inject() as in the following example

```<code>List<Student> students = new List<Student>
{
    new Student {LastName="Omelchenko", Scores= new List<int> {97, 72, 81, 60}},
    new Student {LastName="O'Donnell", Scores= new List<int> {75, 84, 91, 39}},
    new Student {LastName="Mortensen", Scores= new List<int> {88, 94, 65, 85}},
    new Student {LastName="Garcia", Scores= new List<int> {97, 89, 85, 82}},
    new Student {LastName="Beebe", Scores= new List<int> {35, 72, 91, 70}}
};

FilterDefinition<BsonDocument> filter = "{ LastName: Omelchenko }";
var filterQuery = students.Where(x => filter.Inject()).ToList();

</code>```

but I get an exception

```<code>System.InvalidOperationException: 'The LinqExtensions.Inject method is only intended to be used in LINQ Where clauses.'
</code>```

Is there any way to use a Mongo query to query a List of objects?

Body:
I would like to use a Mongo query to query a List of objects in c#.

I tried using FilterDefinition.Inject() as in the following example

List<Student> students = new List<Student>
{
    new Student {LastName="Omelchenko", Scores= new List<int> {97, 72, 81, 60}},
    new Student {LastName="O'Donnell", Scores= new List<int> {75, 84, 91, 39}},
    new Student {LastName="Mortensen", Scores= new List<int> {88, 94, 65, 85}},
    new Student {LastName="Garcia", Scores= new List<int> {97, 89, 85, 82}},
    new Student {LastName="Beebe", Scores= new List<int> {35, 72, 91, 70}}
};

FilterDefinition<BsonDocument> filter = "{ LastName: Omelchenko }";
var filterQuery = students.Where(x => filter.Inject()).ToList();

but I get an exception

System.InvalidOperationException: 'The LinqExtensions.Inject method is only intended to be used in LINQ Where clauses.'

Is there any way to use a Mongo query to query a List of objects?


问:
Assert downloading Pytorch models (model.pth does not exist)
I am having this problem trying to use LayoutParser but I believe it is actually an issue with Pytorch checkpoint.  I get the following assert

The directory contains model.pth?dl=1 and model.pth.lock

It looks like the downloading creates a file called model.pth?dl=1 and and a .lock file.  But it fails to finish by renaming it to model.pth.  It seems to happen with all LayoutParser pretrained models.

Anyone seen this?

Thank you
Peter

The assert is thrown from this call with any of the pretrained models

The full code to reproduce this is:

```<code>import layoutparser as lp

if __name__ == "__main__":
    model = lp.Detectron2LayoutModel(
        config_path="lp://PubLayNet/faster_rcnn_R_50_FPN_3x/config",
        label_map={0:"Text",1:"Title",2:"List",3:"Table",4:"Figure"},
        extra_config=["MODEL.ROI_HEADS.SCORE_THRESH_TEST",0.1]
)
</code>```

Body:
I am having this problem trying to use LayoutParser but I believe it is actually an issue with Pytorch checkpoint.  I get the following assert

The directory contains model.pth?dl=1 and model.pth.lock

It looks like the downloading creates a file called model.pth?dl=1 and and a .lock file.  But it fails to finish by renaming it to model.pth.  It seems to happen with all LayoutParser pretrained models.

Anyone seen this?

Thank you
Peter

The assert is thrown from this call with any of the pretrained models

The full code to reproduce this is:

import layoutparser as lp

if __name__ == "__main__":
    model = lp.Detectron2LayoutModel(
        config_path="lp://PubLayNet/faster_rcnn_R_50_FPN_3x/config",
        label_map={0:"Text",1:"Title",2:"List",3:"Table",4:"Figure"},
        extra_config=["MODEL.ROI_HEADS.SCORE_THRESH_TEST",0.1]
)


问:
JQuery trigger click does not return target id
I have the following jquery code to trigger a click event:

```<code> $(document).on('click','#button1, #button2',function(e){
     console.log(e.target.id);

     if (e.target.id == 'button1') {
         $( "#widgetA .closeresults" ).trigger( "click" );
     }
     else {
         $( "#widgetB .closeresults" ).trigger( "click" );
     }
 });
</code>```

The trigger event should fire the following code however e.target.id is always empty:

```<code> $(document).on('click','#widgetA .closeresults, #widgetB .closeresults',function(e){
      console.log(e.target.id)
      if (e.target.id == 'widgetA') {
          //do something
      }
      else {
         // do something else
      }

 });
</code>```

How do i get the id of the element that initiated the trigger event?

*** UPDATE ***

If button1 is clicked then I want the trigger click event which calls the second snippet of code to return widgetA as the target.id as that is what I'm using to trigger the event. How can I achieve this.

Body:
I have the following jquery code to trigger a click event:

 $(document).on('click','#button1, #button2',function(e){
     console.log(e.target.id);

     if (e.target.id == 'button1') {
         $( "#widgetA .closeresults" ).trigger( "click" );
     }
     else {
         $( "#widgetB .closeresults" ).trigger( "click" );
     }
 });

The trigger event should fire the following code however e.target.id is always empty:

 $(document).on('click','#widgetA .closeresults, #widgetB .closeresults',function(e){
      console.log(e.target.id)
      if (e.target.id == 'widgetA') {
          //do something
      }
      else {
         // do something else
      }

 });

How do i get the id of the element that initiated the trigger event?

*** UPDATE ***

If button1 is clicked then I want the trigger click event which calls the second snippet of code to return widgetA as the target.id as that is what I'm using to trigger the event. How can I achieve this.


问:
oddness with http to https through .htaccess
So I put these commands in my .htaccess file

```<code>RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</code>```

and something peculiar happened. In my HostGator access logs, I never saw reportage of download success (as in Apache code 200). I seemed to get mainly 301 redirect notifications. That is, people were downloading stuff fine, but I never saw any indication of that in my access logs. Can someone explain to me why that is? I am an Apache novice, so pardon my misunderstanding.

I removed those lines and, yep, all my expected code 200 notifications returned.

Body:
So I put these commands in my .htaccess file

RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

and something peculiar happened. In my HostGator access logs, I never saw reportage of download success (as in Apache code 200). I seemed to get mainly 301 redirect notifications. That is, people were downloading stuff fine, but I never saw any indication of that in my access logs. Can someone explain to me why that is? I am an Apache novice, so pardon my misunderstanding.

I removed those lines and, yep, all my expected code 200 notifications returned.