问:
Error: ENOENT with correct file path when using node:fs
I am trying to read data from a json file but I get Error: ENOENT even though from what I can see, the file path has been written correctly.

The code I am running:

```<code>const fs = require("fs");

const testing = require("./test.json")
console.log("yes") // works

const testData = fs.readFileSync("./test.json");
console.log(testData); // returns Error: ENOENT
</code>```

I have tried writing different file paths, testing in another project, deleting and reinstalling package-lock.json, reinstalling node, still getting Error: ENOENT: no such file or directory, open './test.json'. How can I prevent this error, or, is there a node module that I can install that would let me read and write to a json file?

Body:
I am trying to read data from a json file but I get Error: ENOENT even though from what I can see, the file path has been written correctly.

The code I am running:

const fs = require("fs");

const testing = require("./test.json")
console.log("yes") // works

const testData = fs.readFileSync("./test.json");
console.log(testData); // returns Error: ENOENT

I have tried writing different file paths, testing in another project, deleting and reinstalling package-lock.json, reinstalling node, still getting Error: ENOENT: no such file or directory, open './test.json'. How can I prevent this error, or, is there a node module that I can install that would let me read and write to a json file?


来源: stackexchange

问:
Why getting thid error: g++ is not recognized as the name of a cmdlet, function, script file?
I have installed g++ compiler for Windows 10 (64 bit) using this guide provided in official VS Code docs:https://code.visualstudio.com/docs/cpp/config-mingw

I have also added the Path in the Environment variables as:

Still I'm getting this error:

```<code>The term 'g++' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the
spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1
+ g++ --version
+ ~~~
</code>```

while checking the version of g++ on Powershell using:

```<code>g++ --version
gcc --version
gmd --version
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have installed g++ compiler for Windows 10 (64 bit) using this guide provided in official VS Code docs:https://code.visualstudio.com/docs/cpp/config-mingw

I have also added the Path in the Environment variables as:

Still I'm getting this error:

The term 'g++' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the
spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1
+ g++ --version
+ ~~~

while checking the version of g++ on Powershell using:

g++ --version
gcc --version
gmd --version


问:
Displaying Relationship SQLAlchemy paths in HTML (Pyhon Flask)
Essentially, I want to get the notes part displayed in my html card

This is what my flask route looks like

```<code>def home():
    from .models import User
    users = User.query.all() #the user note is what I need on the HTML

    if request.method=='POST':
        note = request.form.get('note')

        if len(note)<1:
            flash('Description is too short! Add something please', category="error")
        elif len(note)>500:
            flash('Description is too long! use a smaller tag...', category='error')
        else:
            new_note = Note(data=note, user_id=current_user.id)
            db.session.add(new_note)
            db.session.commit()
            flash('Updated Successfully', category='success')
    return render_template("home.html", user=current_user, users=users)
</code>```

My model looks like this

```<code>class Note(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    data = db.Column(db.String(10000))
    date = db.Column(db.DateTime(timezone=True), default=func.now())
    user_id = db.Column(db.Integer,db.ForeignKey('user.id'))

class User(db.Model, UserMixin):
    id=db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(150), unique=True)
    password = db.Column(db.String(150))
    first_name = db.Column(db.String(150))
    notes = db.relationship('Note') #relationship
</code>```

My HTML

```<code>{% for e in users %}
{% if e.notes %}
<div class="card" style="width: 18rem;">
  <div class="card-body">
    <h5 class="card-title">{{e.first_name}}</h5>
    <p class="card-text">{{e.notes}}</p>
     <!-- Need it displayed here ^^^ --!>
    <a href="#" class="btn btn-primary">Contact Me</a>
  </div>
</div>
{% endif %}
{% endfor %}
</code>```

I wanted the returned value to be a actual string but...

Instead of giving the string value of the note, it returned something like this:
[<Note 1>]

Note: Yeah, the code looks like the Tech with Tim video. I'm new to flask and needed somewhere to start off of.

Thanks!

Body:
Essentially, I want to get the notes part displayed in my html card

This is what my flask route looks like

def home():
    from .models import User
    users = User.query.all() #the user note is what I need on the HTML

    if request.method=='POST':
        note = request.form.get('note')

        if len(note)<1:
            flash('Description is too short! Add something please', category="error")
        elif len(note)>500:
            flash('Description is too long! use a smaller tag...', category='error')
        else:
            new_note = Note(data=note, user_id=current_user.id)
            db.session.add(new_note)
            db.session.commit()
            flash('Updated Successfully', category='success')
    return render_template("home.html", user=current_user, users=users)

My model looks like this

class Note(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    data = db.Column(db.String(10000))
    date = db.Column(db.DateTime(timezone=True), default=func.now())
    user_id = db.Column(db.Integer,db.ForeignKey('user.id'))

class User(db.Model, UserMixin):
    id=db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(150), unique=True)
    password = db.Column(db.String(150))
    first_name = db.Column(db.String(150))
    notes = db.relationship('Note') #relationship

My HTML

{% for e in users %}
{% if e.notes %}

{{e.first_name}}

{{e.notes}}


问:
Acessing Rest API through R with Authorization Header
I am trying to access the trademe API but for some reason I keep getting thrown a 400 error code,so I think there must be something wrong with my code. My current code is below:
There is no documentation I can find online for the OAuth 1.0 and how to use it in R, so I am pretty stuck. Any help would be greatly appreciated. Thank you</p>
```<code>library(httr)
library(jsonlite)

headers <-
  c("Authorization: " = "OAuth",
    "oauth_consumer_key" = Consumer_Key,
    "oauth_signature_method"="PLAINTEXT",
    "oauth_signature"= Consumer_Signature)

test <- POST(url = 'https://secure.tmsandbox.co.nz/Oauth/RequestToken?scope=MyTradeMeRead,MyTradeMeWrite',
             config(add_headers(headers))
)

test$status_code
</code>```

Body:
I am trying to access the trademe API but for some reason I keep getting thrown a 400 error code,so I think there must be something wrong with my code. My current code is below:
There is no documentation I can find online for the OAuth 1.0 and how to use it in R, so I am pretty stuck. Any help would be greatly appreciated. Thank you

library(httr)
library(jsonlite)

headers <-
  c("Authorization: " = "OAuth",
    "oauth_consumer_key" = Consumer_Key,
    "oauth_signature_method"="PLAINTEXT",
    "oauth_signature"= Consumer_Signature)

test <- POST(url = 'https://secure.tmsandbox.co.nz/Oauth/RequestToken?scope=MyTradeMeRead,MyTradeMeWrite',
             config(add_headers(headers))
)

test$status_code


问:
How can I set OV certs for my website on Firebase Hosting?
Since we had wildcard SSL certificate(OV) for our company, I wanted to set this cert to our new website on Firebase Hosting, but I couldn't find the way to set it.

Does anyone know how, or have any ideas to use both OV certs and Firebase Hosting at the same time?

There was nothing much I could do on Firebase settings page.


问:
Is it feasible to use 32 characters (128 bits) of a sha256 digest as a UUID?
I am using the following code in python to generate a deterministic UUID. I found this solution here.

```<code>import hashlib
import uuid

hash = hashlib.sha256('foobar'.encode('utf-8'))

uuid.UUID(hash.hexdigest()[::2])
</code>```

I can see that it is using a slice operator to get every other hexadecimal nibble. This is done because UUID() expects a 32 character long string. Effectively, this would produce 2^128 unique hashes rather than 2^256.

For my purposes, there would be at most 1 billion unique records.

Using the following approximate formula for accidental collision probability:

```<code>k^2/2n where:
k is the number of records (1 billion)
n is the number of total possible hashes (2^128).
</code>```

The probability of collision is: 1.47 x 10^-21. It is low enough that I feel safe that a collision would not occur.

Anyways, I just wanted to see if anyone could confirm my above logic/intuition. Am I safe to assume that the above probability of collision for the above code is correct? Thank you.

Also, does taking every other hex nibble, instead of truncating the first/last 32 characters affect collision probability?

Note:
Apparently UUIDv5 uses a very similar technique, instead using SHA-1 as the hashing algorithm and digest() instead of hexdigest(). That leads me to believe that the above code is safe to use, but I would still like to make sure just in case source.

```<code>def uuid5(namespace, name):
     """Generate a UUID from the SHA-1 hash of a namespace UUID and a name."""
     from hashlib import sha1
     hash = sha1(namespace.bytes + bytes(name, "utf-8")).digest()
     return UUID(bytes=hash[:16], version=5)
</code>```

Body:
I am using the following code in python to generate a deterministic UUID. I found this solution here.

import hashlib
import uuid

hash = hashlib.sha256('foobar'.encode('utf-8'))

uuid.UUID(hash.hexdigest()[::2])

I can see that it is using a slice operator to get every other hexadecimal nibble. This is done because UUID() expects a 32 character long string. Effectively, this would produce 2^128 unique hashes rather than 2^256.

For my purposes, there would be at most 1 billion unique records.

Using the following approximate formula for accidental collision probability:

k^2/2n where:
k is the number of records (1 billion)
n is the number of total possible hashes (2^128).

The probability of collision is: 1.47 x 10^-21. It is low enough that I feel safe that a collision would not occur.

Anyways, I just wanted to see if anyone could confirm my above logic/intuition. Am I safe to assume that the above probability of collision for the above code is correct? Thank you.

Also, does taking every other hex nibble, instead of truncating the first/last 32 characters affect collision probability?

Note:
Apparently UUIDv5 uses a very similar technique, instead using SHA-1 as the hashing algorithm and digest() instead of hexdigest(). That leads me to believe that the above code is safe to use, but I would still like to make sure just in case source.

def uuid5(namespace, name):
     """Generate a UUID from the SHA-1 hash of a namespace UUID and a name."""
     from hashlib import sha1
     hash = sha1(namespace.bytes + bytes(name, "utf-8")).digest()
     return UUID(bytes=hash[:16], version=5)


问:
Scriptable Trigger After Line Level Landed Cost Entry on Item Receipt
I have a scenario where I want to capture data entered on an Item Receipt immediately after the user keys line level Landed Costs into the sub-record via the inventory detail popup or Landed Cost popup. The scenario is to display real-time actual landed costs.

Thus far there does not appear to be a fieldChanged or postSourcing client-script trigger occurring after the user adds costs in the popup.


问:
Error: invalid address or ENS name with Chainlink VRF
Smart Contract:

```<code>// SPDX-License-Identifier: MIT

pragma solidity 0.8.17;

import "erc721a/contracts/ERC721A.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "@chainlink/contracts/src/v0.8/interfaces/VRFCoordinatorV2Interface.sol";
import "@chainlink/contracts/src/v0.8/VRFConsumerBaseV2.sol";

contract KartoCarsNFT is ERC721A, Ownable, VRFConsumerBaseV2 {

    event RequestSent(uint256 requestID, uint32 numWords);
    event RequestFulfilled(uint256 requestID, uint256[] randomWords, uint256 payment);

    struct RequestStatus {
      uint256 paid;
      bool fulfilled;
      uint256[] randomWords;
    }

    enum SaleStatus {
      PAUSED,
      WHITELIST,
      PUBLIC
    }

    using Strings for uint256;

    // ~~~~~~~~~~~~~~~~~~ Set Sale as PAUSED on DEPLOY ~~~~~~~~~~~~~~~~~~
    SaleStatus public saleStatus = SaleStatus.PAUSED;

    string private preRevealURI;
    string private postRevealBaseURI;

    // ~~~~~~~~~~~~~~~~~~ Sale Settings ~~~~~~~~~~~~~~~~~~
    uint256 public PRICE_KC = 0.07 ether;
    uint256 private constant MAX_KC = 10000;
    uint256 public publicPerWallet = 3;
    uint256 public wlPerWallet = 3;

    //~~~~~~~~~~~~~~~~~~ Chainlink Settings ~~~~~~~~~~~~~~~~~~
    uint256[] public requestIds;
    uint256 public lastRequestId;
    uint32 callbackGasLimit = 100000;
    uint16 requestConfirmations = 3;
    uint32 numWords = 2;
    VRFCoordinatorV2Interface COORDINATOR;

    address[] private teamAddress;
    uint[] private teamSplit;

    // ~~~~~~~~~~~~~~~~~~ Chainlink Sub ID ~~~~~~~~~~~~~~~~~~
    uint64 s_subscriptionId;

    bytes32 public whitelistMerkleRoot;

    mapping(address => uint256) public wlMintedAmt;
    mapping (address => uint256) public publicMintAmt;
    mapping(uint256 => RequestStatus) public s_requests;

    // ~~~~~~~~~~~~~~~~~~ Reveal ~~~~~~~~~~~~~~~~~~
    bool public revealed;
    uint256 public tokenOffset;

    // ~~~~~~~~~~~~~~~~~~ Chainlink VRF ~~~~~~~~~~~~~~~~~~
    bytes32 public chainlinkKeyHash;

    constructor(
      address[] memory _team,
      uint[] memory _split,
      string memory _preRevealURI,
      address _vrfCoordinator,
      bytes32 _chainlinkKeyHash,
      uint64 _subscriptionId
    )
      ERC721A("Karto Cars NFT", "KARTOCARS")
      VRFConsumerBaseV2(0x271682DEB8C4E0901D1a1550aD2e64D568E69909) {
        addTeam(_team, _split);
        preRevealURI = _preRevealURI;
        chainlinkKeyHash = _chainlinkKeyHash;
        COORDINATOR = VRFCoordinatorV2Interface(_vrfCoordinator);
        s_subscriptionId = _subscriptionId;
    }

    // ~~~~~~~~~~~~~~~~~~ Prevent Bots ~~~~~~~~~~~~~~~~~~
    modifier callerIsUser() {
      require(tx.origin == msg.sender, "The caller is another contract");
      _;
    }

    // ~~~~~~~~~~~~~~~~~~ Metadata Functions ~~~~~~~~~~~~~~~~~~
    function setPreRevealURI(string memory _URI) external onlyOwner {
      preRevealURI = _URI;
    }

    function setPostRevealBaseURI(string memory _URI) external onlyOwner {
      postRevealBaseURI = _URI;
    }

    // ~~~~~~~~~~~~~~~~~~ Token URI ~~~~~~~~~~~~~~~~~~
    // Before reveal, return same pre-reveal URI
    // After reveal, return post-reveal URI with random token offset from Chainlink
    function tokenURI(uint256 _tokenId) public view override returns (string memory) {
      require(_exists(_tokenId), "ERC721Metadata: URI query for nonexistent token");
      if (!revealed) return preRevealURI;
      uint256 shiftedTokenId = (_tokenId + tokenOffset) % totalSupply();
      return string(abi.encodePacked(postRevealBaseURI, shiftedTokenId.toString()));
    }

    // ~~~~~~~~~~~~~~~~~~ Sale State Function ~~~~~~~~~~~~~~~~~~

    function setSaleStatus(SaleStatus _status) external onlyOwner {
      saleStatus = _status;
    }

    // ~~~~~~~~~~~~~~~~~~ Setting Merkle Root Function ~~~~~~~~~~~~~~~~~~
    function setMerkleRoots(bytes32 _whitelistMerkleRoot) external onlyOwner {
      whitelistMerkleRoot = _whitelistMerkleRoot;
    }

    function processMint(uint256 _quantity) internal {
      require(msg.value == PRICE_KC * _quantity, "INCORRECT ETH SENT");
      require(totalSupply() + _quantity <= MAX_KC, "MAX CAP OF KC EXCEEDED");
      _mint(msg.sender, _quantity);
    }

    // ~~~~~~~~~~~~~~~~~~ Whitelist Sale Function ~~~~~~~~~~~~~~~~~~
    function whitelistSale(uint256 _quantity, bytes32[] memory _proof) external payable callerIsUser {
      require(saleStatus == SaleStatus.WHITELIST, "WL SALE NOT ACTIVE");
      require(
        MerkleProof.verify(_proof, whitelistMerkleRoot, keccak256(abi.encodePacked(msg.sender))),
        "MINTER IS NOT ON WHITELIST"
      );
      require(_quantity <= wlPerWallet, "SURPASSED WL TX LIMIT");
      require(_quantity + wlMintedAmt[msg.sender] <= wlPerWallet , "MAX WL MINTED");
      wlMintedAmt[msg.sender]+= _quantity;

      processMint(_quantity);
    }

    // ~~~~~~~~~~~~~~~~~~ Public Sale Function ~~~~~~~~~~~~~~~~~~
    function publicSale(
      uint256 _quantity
    ) external payable callerIsUser {
      require(saleStatus == SaleStatus.PUBLIC, "PUBLIC SALE NOT LIVE");
      require(_quantity <= publicPerWallet, "QUANTITY SURPASSES PER-TXN LIMIT");
      require(_quantity + publicMintAmt[msg.sender] <= publicPerWallet, "MAX PUBLIC MINTED");
      publicMintAmt[msg.sender]+= _quantity;
      processMint(_quantity);
    }

  // ~~~~~~~~~~~~~~~~~~ Airdrop Function ~~~~~~~~~~~~~~~~~~
  function airDrop(
    uint256 _quantity, address _receiver
  ) public onlyOwner {
    _mint(_receiver, _quantity);
  }

    // ~~~~~~~~~~~~~~~~~~ Edit Chainlink Configuration ~~~~~~~~~~~~~~~~~~
    function setChainlinkConfig(bytes32 _keyhash) external onlyOwner {
      chainlinkKeyHash = _keyhash;
    }

    // ~~~~~~~~~~~~~~~~~~ Request Token Offset ~~~~~~~~~~~~~~~~~~
    // NOTE: contract must be approved for and own LINK before calling this function
    function startReveal(string memory _newURI) external onlyOwner returns (uint256 requestId) {
      require(!revealed, "ALREADY REVEALED");
      postRevealBaseURI = _newURI;
      requestId = COORDINATOR.requestRandomWords(
              chainlinkKeyHash,
              s_subscriptionId,
              requestConfirmations,
              callbackGasLimit,
              numWords
          );
      return requestId;
    }

    // ~~~~~~~~~~~~~~~~~~ CHAINLINK CALLBACK FOR TOKEN OFFSET ~~~~~~~~~~~~~~~~~~
    function fulfillRandomWords(uint256 _requestId, uint256[] memory randomWords) internal override {
      require(!revealed, "ALREADY REVEALED");
      revealed = true;

    }

    // ~~~~~~~~~~~~~~~~~~ onlyOwner Functions ~~~~~~~~~~~~~~~~~~
    function changePrice(uint256 _price) public onlyOwner {
        PRICE_KC = _price;
    }

    function changePublicAmt(uint256 _amt) public onlyOwner {
        publicPerWallet = _amt;
    }

    function changeWhitelistAmt(uint256 _wlAmt) public onlyOwner {
        wlPerWallet = _wlAmt;
    }

    function numberMinted(address _owner) public view returns (uint256) {
      return _numberMinted(_owner);
    }

    function getOwnershipData(uint256 _tokenId) external view returns (TokenOwnership memory) {
      return _ownershipOf(_tokenId);
    }

    function addTeam(address[] memory _team, uint[] memory _split) public onlyOwner {
        require(_team.length == _split.length, "Address and Shares must equal");
        teamAddress = _team;
        teamSplit = _split;
    }

    //~~~~~~~~~~~~~~~~~~ Withdraw Functions ~~~~~~~~~~~~~~~~~~
    function internalWithdrawal(uint _amount) internal onlyOwner {
        for(uint i = 0; i < teamAddress.length; i++) {
            uint split = teamSplit[i];
            (bool os, ) = payable(teamAddress[i]).call{value: _amount * split / 100}('');
            require(os);
        }
    }

    function teamWithdraw() public onlyOwner {
        internalWithdrawal(address(this).balance);
    }

    function emergencyWithdraw() public onlyOwner {
        (bool os, ) = payable(owner()).call{value: address(this).balance}('');
        require(os);
    }
}
</code>```

Deploy Script:

```<code>async function main() {
    const [deployer] = await ethers.getSigners();
    vrfCoordinator = 0x271682deb8c4e0901d1a1550ad2e64d568e69909; // SET FOR MAINNET, WILL NEED TO CHANGE TO TESTNET IF WANTED TO TEST FOR ALL 3.
    chainlinkKeyHash = 0x8af398995b04c28e9951adb9721ef74c74f93e6a478f39e7e0777be13527e7ef;
    subID = 0x67388e9228301fce52e39196537fa6a6ee0a1f91;

    console.log("Deploying contract with the account: ", deployer.address);

    console.log("Account Balance: ", (await deployer.getBalance()).toString());

    const Token = await ethers.getContractFactory("KartoCarsNFT");

    console.log("Deploying Contract...Stand by....");

    const token = await Token.deploy([0x8faA2802aACa47AEe59f02A96E29225436eEF9A8,0x012D8E2cE2716B260718abE39062A76be15570B3],[98,2],"test",vrfCoordinator, chainlinkKeyHash, subID);

    console.log("Contract deployed to: ", token.address);
}

main()
.then(() => process.exit(0))
.catch((error) => {
    console.error(error);
    process.exit(1);
});
</code>```

We aren't sure if we are doing something wrong in our deploy script or if the contract needs to be setup different.

We have tried changing the addresses by putting them in quotes or wording the deploy script differently, but still nothing. The constructor at the top is where we are setting everything and our deploy script is setting the values for the constructor.

Body:
Smart Contract:

// SPDX-License-Identifier: MIT

pragma solidity 0.8.17;

import "erc721a/contracts/ERC721A.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "@chainlink/contracts/src/v0.8/interfaces/VRFCoordinatorV2Interface.sol";
import "@chainlink/contracts/src/v0.8/VRFConsumerBaseV2.sol";

contract KartoCarsNFT is ERC721A, Ownable, VRFConsumerBaseV2 {

    event RequestSent(uint256 requestID, uint32 numWords);
    event RequestFulfilled(uint256 requestID, uint256[] randomWords, uint256 payment);

    struct RequestStatus {
      uint256 paid;
      bool fulfilled;
      uint256[] randomWords;
    }

    enum SaleStatus {
      PAUSED,
      WHITELIST,
      PUBLIC
    }

    using Strings for uint256;

    // ~~~~~~~~~~~~~~~~~~ Set Sale as PAUSED on DEPLOY ~~~~~~~~~~~~~~~~~~
    SaleStatus public saleStatus = SaleStatus.PAUSED;

    string private preRevealURI;
    string private postRevealBaseURI;

    // ~~~~~~~~~~~~~~~~~~ Sale Settings ~~~~~~~~~~~~~~~~~~
    uint256 public PRICE_KC = 0.07 ether;
    uint256 private constant MAX_KC = 10000;
    uint256 public publicPerWallet = 3;
    uint256 public wlPerWallet = 3;

    //~~~~~~~~~~~~~~~~~~ Chainlink Settings ~~~~~~~~~~~~~~~~~~
    uint256[] public requestIds;
    uint256 public lastRequestId;
    uint32 callbackGasLimit = 100000;
    uint16 requestConfirmations = 3;
    uint32 numWords = 2;
    VRFCoordinatorV2Interface COORDINATOR;

    address[] private teamAddress;
    uint[] private teamSplit;

    // ~~~~~~~~~~~~~~~~~~ Chainlink Sub ID ~~~~~~~~~~~~~~~~~~
    uint64 s_subscriptionId;

    bytes32 public whitelistMerkleRoot;

    mapping(address => uint256) public wlMintedAmt;
    mapping (address => uint256) public publicMintAmt;
    mapping(uint256 => RequestStatus) public s_requests;

    // ~~~~~~~~~~~~~~~~~~ Reveal ~~~~~~~~~~~~~~~~~~
    bool public revealed;
    uint256 public tokenOffset;

    // ~~~~~~~~~~~~~~~~~~ Chainlink VRF ~~~~~~~~~~~~~~~~~~
    bytes32 public chainlinkKeyHash;

    constructor(
      address[] memory _team,
      uint[] memory _split,
      string memory _preRevealURI,
      address _vrfCoordinator,
      bytes32 _chainlinkKeyHash,
      uint64 _subscriptionId
    )
      ERC721A("Karto Cars NFT", "KARTOCARS")
      VRFConsumerBaseV2(0x271682DEB8C4E0901D1a1550aD2e64D568E69909) {
        addTeam(_team, _split);
        preRevealURI = _preRevealURI;
        chainlinkKeyHash = _chainlinkKeyHash;
        COORDINATOR = VRFCoordinatorV2Interface(_vrfCoordinator);
        s_subscriptionId = _subscriptionId;
    }

    // ~~~~~~~~~~~~~~~~~~ Prevent Bots ~~~~~~~~~~~~~~~~~~
    modifier callerIsUser() {
      require(tx.origin == msg.sender, "The caller is another contract");
      _;
    }

    // ~~~~~~~~~~~~~~~~~~ Metadata Functions ~~~~~~~~~~~~~~~~~~
    function setPreRevealURI(string memory _URI) external onlyOwner {
      preRevealURI = _URI;
    }

    function setPostRevealBaseURI(string memory _URI) external onlyOwner {
      postRevealBaseURI = _URI;
    }

    // ~~~~~~~~~~~~~~~~~~ Token URI ~~~~~~~~~~~~~~~~~~
    // Before reveal, return same pre-reveal URI
    // After reveal, return post-reveal URI with random token offset from Chainlink
    function tokenURI(uint256 _tokenId) public view override returns (string memory) {
      require(_exists(_tokenId), "ERC721Metadata: URI query for nonexistent token");
      if (!revealed) return preRevealURI;
      uint256 shiftedTokenId = (_tokenId + tokenOffset) % totalSupply();
      return string(abi.encodePacked(postRevealBaseURI, shiftedTokenId.toString()));
    }

    // ~~~~~~~~~~~~~~~~~~ Sale State Function ~~~~~~~~~~~~~~~~~~

    function setSaleStatus(SaleStatus _status) external onlyOwner {
      saleStatus = _status;
    }

    // ~~~~~~~~~~~~~~~~~~ Setting Merkle Root Function ~~~~~~~~~~~~~~~~~~
    function setMerkleRoots(bytes32 _whitelistMerkleRoot) external onlyOwner {
      whitelistMerkleRoot = _whitelistMerkleRoot;
    }

    function processMint(uint256 _quantity) internal {
      require(msg.value == PRICE_KC * _quantity, "INCORRECT ETH SENT");
      require(totalSupply() + _quantity <= MAX_KC, "MAX CAP OF KC EXCEEDED");
      _mint(msg.sender, _quantity);
    }

    // ~~~~~~~~~~~~~~~~~~ Whitelist Sale Function ~~~~~~~~~~~~~~~~~~
    function whitelistSale(uint256 _quantity, bytes32[] memory _proof) external payable callerIsUser {
      require(saleStatus == SaleStatus.WHITELIST, "WL SALE NOT ACTIVE");
      require(
        MerkleProof.verify(_proof, whitelistMerkleRoot, keccak256(abi.encodePacked(msg.sender))),
        "MINTER IS NOT ON WHITELIST"
      );
      require(_quantity <= wlPerWallet, "SURPASSED WL TX LIMIT");
      require(_quantity + wlMintedAmt[msg.sender] <= wlPerWallet , "MAX WL MINTED");
      wlMintedAmt[msg.sender]+= _quantity;

      processMint(_quantity);
    }

    // ~~~~~~~~~~~~~~~~~~ Public Sale Function ~~~~~~~~~~~~~~~~~~
    function publicSale(
      uint256 _quantity
    ) external payable callerIsUser {
      require(saleStatus == SaleStatus.PUBLIC, "PUBLIC SALE NOT LIVE");
      require(_quantity <= publicPerWallet, "QUANTITY SURPASSES PER-TXN LIMIT");
      require(_quantity + publicMintAmt[msg.sender] <= publicPerWallet, "MAX PUBLIC MINTED");
      publicMintAmt[msg.sender]+= _quantity;
      processMint(_quantity);
    }

  // ~~~~~~~~~~~~~~~~~~ Airdrop Function ~~~~~~~~~~~~~~~~~~
  function airDrop(
    uint256 _quantity, address _receiver
  ) public onlyOwner {
    _mint(_receiver, _quantity);
  }

    // ~~~~~~~~~~~~~~~~~~ Edit Chainlink Configuration ~~~~~~~~~~~~~~~~~~
    function setChainlinkConfig(bytes32 _keyhash) external onlyOwner {
      chainlinkKeyHash = _keyhash;
    }

    // ~~~~~~~~~~~~~~~~~~ Request Token Offset ~~~~~~~~~~~~~~~~~~
    // NOTE: contract must be approved for and own LINK before calling this function
    function startReveal(string memory _newURI) external onlyOwner returns (uint256 requestId) {
      require(!revealed, "ALREADY REVEALED");
      postRevealBaseURI = _newURI;
      requestId = COORDINATOR.requestRandomWords(
              chainlinkKeyHash,
              s_subscriptionId,
              requestConfirmations,
              callbackGasLimit,
              numWords
          );
      return requestId;
    }

    // ~~~~~~~~~~~~~~~~~~ CHAINLINK CALLBACK FOR TOKEN OFFSET ~~~~~~~~~~~~~~~~~~
    function fulfillRandomWords(uint256 _requestId, uint256[] memory randomWords) internal override {
      require(!revealed, "ALREADY REVEALED");
      revealed = true;

    }

    // ~~~~~~~~~~~~~~~~~~ onlyOwner Functions ~~~~~~~~~~~~~~~~~~
    function changePrice(uint256 _price) public onlyOwner {
        PRICE_KC = _price;
    }

    function changePublicAmt(uint256 _amt) public onlyOwner {
        publicPerWallet = _amt;
    }

    function changeWhitelistAmt(uint256 _wlAmt) public onlyOwner {
        wlPerWallet = _wlAmt;
    }

    function numberMinted(address _owner) public view returns (uint256) {
      return _numberMinted(_owner);
    }

    function getOwnershipData(uint256 _tokenId) external view returns (TokenOwnership memory) {
      return _ownershipOf(_tokenId);
    }

    function addTeam(address[] memory _team, uint[] memory _split) public onlyOwner {
        require(_team.length == _split.length, "Address and Shares must equal");
        teamAddress = _team;
        teamSplit = _split;
    }

    //~~~~~~~~~~~~~~~~~~ Withdraw Functions ~~~~~~~~~~~~~~~~~~
    function internalWithdrawal(uint _amount) internal onlyOwner {
        for(uint i = 0; i < teamAddress.length; i++) {
            uint split = teamSplit[i];
            (bool os, ) = payable(teamAddress[i]).call{value: _amount * split / 100}('');
            require(os);
        }
    }

    function teamWithdraw() public onlyOwner {
        internalWithdrawal(address(this).balance);
    }

    function emergencyWithdraw() public onlyOwner {
        (bool os, ) = payable(owner()).call{value: address(this).balance}('');
        require(os);
    }
}

Deploy Script:

async function main() {
    const [deployer] = await ethers.getSigners();
    vrfCoordinator = 0x271682deb8c4e0901d1a1550ad2e64d568e69909; // SET FOR MAINNET, WILL NEED TO CHANGE TO TESTNET IF WANTED TO TEST FOR ALL 3.
    chainlinkKeyHash = 0x8af398995b04c28e9951adb9721ef74c74f93e6a478f39e7e0777be13527e7ef;
    subID = 0x67388e9228301fce52e39196537fa6a6ee0a1f91;

    console.log("Deploying contract with the account: ", deployer.address);

    console.log("Account Balance: ", (await deployer.getBalance()).toString());

    const Token = await ethers.getContractFactory("KartoCarsNFT");

    console.log("Deploying Contract...Stand by....");

    const token = await Token.deploy([0x8faA2802aACa47AEe59f02A96E29225436eEF9A8,0x012D8E2cE2716B260718abE39062A76be15570B3],[98,2],"test",vrfCoordinator, chainlinkKeyHash, subID);

    console.log("Contract deployed to: ", token.address);
}

main()
.then(() => process.exit(0))
.catch((error) => {
    console.error(error);
    process.exit(1);
});

We aren't sure if we are doing something wrong in our deploy script or if the contract needs to be setup different.

We have tried changing the addresses by putting them in quotes or wording the deploy script differently, but still nothing. The constructor at the top is where we are setting everything and our deploy script is setting the values for the constructor.


问:
Getting eslint missing in props validation error after upgrading to latest eslint
I recently upgraded my eslint package (and all plugins) from 7.16.0 to 8.30.0 and now in a couple of my components I'm getting the error ESLint: 'propertyName' is missing in props validation(react/prop-types). Before the upgrade these components were not getting any linter errors. This is only happening in a couple of components making this even more difficult to determine why only these properties are having errors. In one component it is a prop type used within a function, but when the same prop is used outside that function no error is thrown. In this image if you look at the templateProps object just above the error it also contains onRowClicked but does not have a linter error.

On the other component the props having the issue are coming from an inherited interface; however not all of the inherited props are having the issue. Here label and inputRef are also coming from the inherited interface, but they don't seem to have an issue.

This library contains a number of components that are inheriting from the same base interface as this component here but none of them are throwing errors. I have checked the eslint-plugin-react repo on GitHub and no one has reported this issue yet. On other posts I have seen the advice to disable this rule, but I really don't want to do that unless absolutely necessary (although I may change it to a warning for the time being). Before I log this as a potential issue I was wondering if anyone else has seen a similar problem. Thanks in advance.


问:
webpack express config build succesfully but gives errow when run the build "ERROR in index Module not found:" some path issue
I wanted to use express server with webpack so tried with follow steps

Repo Link

webpack.dev.config.js

```<code>const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ESLintPlugin = require('eslint-webpack-plugin');

const APP_DIR = path.join(__dirname, 'src');
const BUILD_DIR = path.join(__dirname, 'dist');

const options = {
  extensions: [`js`],
  exclude: [`/node_modules/`],
  emitWarning: true,
  failOnError: false,
};

const config = {
  entry: {
    index: path.join(__dirname, '/src/index.js'),
  },
  output: {
    path: BUILD_DIR,
    publicPath: '.',
    filename: '[name].js',
  },
  mode: 'development',
  target: 'web',
  //devtool: 'eval-source-map',
  resolve: {
    extensions: ['.html', '.js', '.json', '.css'],
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['@babel/preset-env'],
          },
        },
      },
      { test: /\.html$/i, loader: 'html-loader' },
      {
        test: /\.css$/,
        use: ['style-loader', 'css-loader'],
      },
      {
        test: /\.(png|svg|jpg|gif)$/,
        use: ['file-loader'],
      },
    ],
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: './src/html/index.html',
      filename: './index.html',
      excludeChunks: ['server'],
    }),
    //new webpack.HotModuleReplacementPlugin(),
    new ESLintPlugin(options),
    new webpack.NoEmitOnErrorsPlugin(),
  ],
};

module.exports = config;

</code>```

webpack.server-config.js

```<code>const path = require('path');
const webpack = require('webpack');
const nodeExternals = require('webpack-node-externals');

const config = (_, argv) => {
  const SERVER_PATH = argv.mode === 'production' ? './src/server/server-prod.js' : './src/server/server-dev.js';
  return {
    entry: {
      server: path.join(__dirname, 'src', '/server/server-dev.js'),
    },
    output: {
      path: path.join(__dirname, 'dist'),
      publicPath: '/',
      filename: '[name].js',
      clean: true,
    },
    mode: argv.mode,
    target: 'node',
    node: {
      // Need this when working with express, otherwise the build fails
      __dirname: false, // if you don't put this is, __dirname
      __filename: false, // and __filename return blank or /
    },
    externals: [nodeExternals()], // Need this to avoid error when working with Express
    module: {
      rules: [
        {
          // Transpile ES6-8 into ES5
          test: /\.js$/,
          exclude: /node_modules/,
          use: {
            loader: 'babel-loader',
          },
        },
      ],
    },
  };
};
module.exports = config;

</code>```

package.json

```<code>  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack --mode development --config webpack.dev.config.js",
    "clean": "rd /s /q dist >nul 2>&1|echo.>null",
    "start": "node ./dist/server.js",
    "server": "webpack --mode development --config webpack.server.config.js",
    "buildDev": "npm run server && npm run build"
  },
  "main": "index.js"

</code>```

server/server-dev.js

```<code>import express from 'express';
import path from 'path';
import { webpack } from 'webpack';
import webpackDevMiddleware from 'webpack-dev-middleware';
//import webpackHotMiddleware from 'webpack-hot-middleware';
import config from '../../webpack.dev.config.js';

const app = express();
const DIST_DIR = __dirname;
const HTML_FILE = path.join(DIST_DIR, 'index.html');
const compiler = webpack(config);

console.log(HTML_FILE);

app.use(
  webpackDevMiddleware(compiler, {
    publicPath: config.output.publicPath,
  })
);

//app.use(webpackHotMiddleware(compiler));

app.use(express.static(DIST_DIR));
app.get('*', (req, res) => {
  res.sendFile(HTML_FILE);
});

const PORT = process.env.PORT || 8070;

app.listen(PORT, () => {
  console.log(`App123 listening to ${PORT}....`);
  console.log('Press Ctrl+C to quit.');
});
</code>```

npm run buildDev

executed successfully

but when run

npm run server

it has below output

App123 listening to 8070....
Press Ctrl+C to quit.
assets by status 971 bytes [cached] 2 assets

ERROR in index
Module not found: Error: Can't resolve 'D:\Developer\canvas\dist\src\index.js' in 'D:\Developer\canvas'
resolve 'D:\Developer\canvas\dist\src\index.js' in 'D:\Developer\canvas'
  using description file: D:\Developer\canvas\package.json (relative path: .)
    Field 'browser' doesn't contain a valid alias configuration
    using description file: D:\Developer\canvas\package.json (relative path: ./dist/src/index.js)
      no extension
        Field 'browser' doesn't contain a valid alias configuration
        D:\Developer\canvas\dist\src\index.js doesn't exist
      .html
        Field 'browser' doesn't contain a valid alias configuration
        D:\Developer\canvas\dist\src\index.js.html doesn't exist
      .js
        Field 'browser' doesn't contain a valid alias configuration
        D:\Developer\canvas\dist\src\index.js.js doesn't exist
      .json
        Field 'browser' doesn't contain a valid alias configuration
        D:\Developer\canvas\dist\src\index.js.json doesn't exist
      .css
        Field 'browser' doesn't contain a valid alias configuration
        D:\Developer\canvas\dist\src\index.js.css doesn't exist
      as directory
        D:\Developer\canvas\dist\src\index.js doesn't exist

webpack 5.75.0 compiled with 1 error in 537 ms

```

although when I open localhost:8070 it loaded successfully.

someone please help

is this right approach?

how to fix this issue.

Body:
I wanted to use express server with webpack so tried with follow steps

Repo Link

webpack.dev.config.js

const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ESLintPlugin = require('eslint-webpack-plugin');

const APP_DIR = path.join(__dirname, 'src');
const BUILD_DIR = path.join(__dirname, 'dist');

const options = {
  extensions: [`js`],
  exclude: [`/node_modules/`],
  emitWarning: true,
  failOnError: false,
};

const config = {
  entry: {
    index: path.join(__dirname, '/src/index.js'),
  },
  output: {
    path: BUILD_DIR,
    publicPath: '.',
    filename: '[name].js',
  },
  mode: 'development',
  target: 'web',
  //devtool: 'eval-source-map',
  resolve: {
    extensions: ['.html', '.js', '.json', '.css'],
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['@babel/preset-env'],
          },
        },
      },
      { test: /\.html$/i, loader: 'html-loader' },
      {
        test: /\.css$/,
        use: ['style-loader', 'css-loader'],
      },
      {
        test: /\.(png|svg|jpg|gif)$/,
        use: ['file-loader'],
      },
    ],
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: './src/html/index.html',
      filename: './index.html',
      excludeChunks: ['server'],
    }),
    //new webpack.HotModuleReplacementPlugin(),
    new ESLintPlugin(options),
    new webpack.NoEmitOnErrorsPlugin(),
  ],
};

module.exports = config;

webpack.server-config.js

const path = require('path');
const webpack = require('webpack');
const nodeExternals = require('webpack-node-externals');

const config = (_, argv) => {
  const SERVER_PATH = argv.mode === 'production' ? './src/server/server-prod.js' : './src/server/server-dev.js';
  return {
    entry: {
      server: path.join(__dirname, 'src', '/server/server-dev.js'),
    },
    output: {
      path: path.join(__dirname, 'dist'),
      publicPath: '/',
      filename: '[name].js',
      clean: true,
    },
    mode: argv.mode,
    target: 'node',
    node: {
      // Need this when working with express, otherwise the build fails
      __dirname: false, // if you don't put this is, __dirname
      __filename: false, // and __filename return blank or /
    },
    externals: [nodeExternals()], // Need this to avoid error when working with Express
    module: {
      rules: [
        {
          // Transpile ES6-8 into ES5
          test: /\.js$/,
          exclude: /node_modules/,
          use: {
            loader: 'babel-loader',
          },
        },
      ],
    },
  };
};
module.exports = config;

package.json

  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack --mode development --config webpack.dev.config.js",
    "clean": "rd /s /q dist >nul 2>&1|echo.>null",
    "start": "node ./dist/server.js",
    "server": "webpack --mode development --config webpack.server.config.js",
    "buildDev": "npm run server && npm run build"
  },
  "main": "index.js"

server/server-dev.js

import express from 'express';
import path from 'path';
import { webpack } from 'webpack';
import webpackDevMiddleware from 'webpack-dev-middleware';
//import webpackHotMiddleware from 'webpack-hot-middleware';
import config from '../../webpack.dev.config.js';

const app = express();
const DIST_DIR = __dirname;
const HTML_FILE = path.join(DIST_DIR, 'index.html');
const compiler = webpack(config);

console.log(HTML_FILE);

app.use(
  webpackDevMiddleware(compiler, {
    publicPath: config.output.publicPath,
  })
);

//app.use(webpackHotMiddleware(compiler));

app.use(express.static(DIST_DIR));
app.get('*', (req, res) => {
  res.sendFile(HTML_FILE);
});

const PORT = process.env.PORT || 8070;

app.listen(PORT, () => {
  console.log(`App123 listening to ${PORT}....`);
  console.log('Press Ctrl+C to quit.');
});

npm run buildDev

executed successfully

but when run

npm run server

it has below output

App123 listening to 8070....
Press Ctrl+C to quit.
assets by status 971 bytes [cached] 2 assets

ERROR in index
Module not found: Error: Can't resolve 'D:\Developer\canvas\dist\src\index.js' in 'D:\Developer\canvas'
resolve 'D:\Developer\canvas\dist\src\index.js' in 'D:\Developer\canvas'
  using description file: D:\Developer\canvas\package.json (relative path: .)
    Field 'browser' doesn't contain a valid alias configuration
    using description file: D:\Developer\canvas\package.json (relative path: ./dist/src/index.js)
      no extension
        Field 'browser' doesn't contain a valid alias configuration
        D:\Developer\canvas\dist\src\index.js doesn't exist
      .html
        Field 'browser' doesn't contain a valid alias configuration
        D:\Developer\canvas\dist\src\index.js.html doesn't exist
      .js
        Field 'browser' doesn't contain a valid alias configuration
        D:\Developer\canvas\dist\src\index.js.js doesn't exist
      .json
        Field 'browser' doesn't contain a valid alias configuration
        D:\Developer\canvas\dist\src\index.js.json doesn't exist
      .css
        Field 'browser' doesn't contain a valid alias configuration
        D:\Developer\canvas\dist\src\index.js.css doesn't exist
      as directory
        D:\Developer\canvas\dist\src\index.js doesn't exist

webpack 5.75.0 compiled with 1 error in 537 ms

although when I open localhost:8070 it loaded successfully.

someone please help

is this right approach?

how to fix this issue.


问:
502 gateway on successful deployment from docker container throws 502 gateways error
He Heroku community,

I'm facing 502 gateway error on my domain https://secure-dawn-68418.herokuapp.com/ after successful deployment.

Need your help on this

Want app successfully run with 200 status code


问:
Spring boot JPA Hibernate - Old generation memory not being freed up
We are using Spring boot 2.6.6 (Java8) which internally pulls in hibernate version 5.6.7.Final. Database used is Oracle 19c.

We are using "saveAll" method of JPA repository to do batch insert/updates for entities but observing that the old generation memory keeps increasing without getting freed up. We are using "ParNew" for Young generation GC and "CMS" for old generation GC.

Below is what we saw in one of the recent heap dumps generated on OOM -

```<code>Problem Suspect 1   One instance of "org.hibernate.engine.internal.StatefulPersistenceContext" loaded by
 "sun.misc.Launcher$AppClassLoader @ 0x700000000" occupies 3,845,753,568 (82.42%) bytes.
 The memory is accumulated in one instance of "org.hibernate.engine.internal.EntityEntryContext" loaded by
 "sun.misc.Launcher$AppClassLoader @ 0x700000000".
</code>```

Below is the configuration class

```<code>@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef = "entityManagerFactory", basePackages = { "com.xxx.yyy.persistence.repository" })
public class BootDatasourceConfig {

    @ConfigurationProperties(prefix = "yyy.persistence.datasource")
    @Bean(name = "yyyDS")
    @Primary
    public DataSource primaryDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Primary
    @Bean(name = "entityManagerFactory")
    public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder, @Qualifier("yyyDS") DataSource dataSource) {
        LocalContainerEntityManagerFactoryBean em = builder.dataSource(dataSource).packages("com.xxx.yyy.persistence.entity").persistenceUnit("persistence").build();
        em.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
        return em;
    }

    @Primary
    @Bean(name = "transactionManager")
    public PlatformTransactionManager transactionManager(@Qualifier("entityManagerFactory") EntityManagerFactory entityManagerFactory) {
        return new JpaTransactionManager(entityManagerFactory);
    }

}
</code>```

Below is the service class

```<code>@Service
@Transactional
public class PersistenceServiceImpl implements PersistenceService {

@Autowired
private Entity1Repository entity1repo;

@Autowired
private Entity2Repository entity2repo;

@Override
public PersistenceResponse process (PersistenceReqMsg reqMsg) {
    List<PersistenceRequest> reqLst = reqMsg.getReqList();

    List<Entity2> entity2Lst = new ArrayList<>();
    List<Entity1> entity1Lst = new ArrayList<>();

    for (PersistenceRequest req : reqLst) {
         for (PersistenceEvt evt : req.getBdy().getEvents()) {
             entity1Lst(...);
         }
         entity2Lst(...)
    }

    if (CollectionUtils.isNotEmpty(entity1Lst)) {
         entity1repo.saveAll(entity1Lst);
    }
    if (CollectionUtils.isNotEmpty(entity2Lst)) {
         entity2repo.saveAll(entity2Lst);
    }

    return AAAPersistenceResponse;
}

}
</code>```

Below are the repo definitions -

```<code>@Repository
public interface Entity1Repository extends JpaRepository<Entity1, Long>, JpaSpecificationExecutor<Entity1>, CustomRepository  {}

@Repository
public interface Entity2Repository extends JpaRepository<Entity2, Long>, JpaSpecificationExecutor<Entity2>, CustomRepository  {}
</code>```

Below are the application prop entries -

```<code>yyy.persistence.datasource.type=com.zaxxer.hikari.HikariDataSource
yyy.persistence.datasource.driverClassName=oracle.jdbc.OracleDriver
yyy.persistence.datasource.jdbcUrl=jdbc:oracle:thin:@ddd:1521:ccc
yyy.persistence.datasource.maximumPoolSize=20
yyy.persistence.datasource.idleTimeout=5
yyy.persistence.datasource.minimumIdle=5
yyy.persistence.datasource.connectionTimeout=60000

spring.jpa.database-platform= org.hibernate.dialect.Oracle12cDialect
spring.jpa.show-sql=false
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.Oracle12cDialect
spring.jpa.properties.hibernate.id.new_generator_mappings = false
spring.jpa.properties.hibernate.format_sql = true
spring.jpa.properties.hibernate.current_session_context_class=org.springframework.orm.hibernate5.SpringSessionContext
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
spring.jpa.properties.hibernate.jdbc.batch_size=50
spring.jpa.properties.hibernate.order_inserts=true
spring.jpa.properties.hibernate.order_updates=true
</code>```

Below is minimal entity definition -

```<code>@Entity
@Table(name = "entity1table", uniqueConstraints = @UniqueConstraint(columnNames = { "ref1", "ref2" })) {

@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "entity1_id", unique = true, nullable = false)
public Long getEntity1Id() {
    return this.entity1Id;
}

}
</code>```

From the heap dump it looks like entities are not being cleared from memory and building up over time. The incoming request object "PersistenceReqMsg" will not have an appreciably high number of records (max 250). Since the @Service method is executed in a @Transaction, my understanding is that JPA internally will issue "commit"/"rollback" based on batch size but not sure if JPA is also clearing the entities from persistence context. Could this be the reason for memory not being released?

Besides above JPA repo based code, we have few other service classes where "EntityManager" is being injected via @PersistenceContext and used to execute look up queries and some inserts/updates. Below is the sample -

```<code>@PersistenceContext
    private EntityManager em;

public getDetails () {
   em.createNativeQuery(....);
}
</code>```

Not sure if these could also contribute to the memory building up.
Is it better to inject "EntityManagerFactory" instead of "EntityManager" and create a new instance of EM for every execution?

Body:
We are using Spring boot 2.6.6 (Java8) which internally pulls in hibernate version 5.6.7.Final. Database used is Oracle 19c.

We are using "saveAll" method of JPA repository to do batch insert/updates for entities but observing that the old generation memory keeps increasing without getting freed up. We are using "ParNew" for Young generation GC and "CMS" for old generation GC.

Below is what we saw in one of the recent heap dumps generated on OOM -

Problem Suspect 1   One instance of "org.hibernate.engine.internal.StatefulPersistenceContext" loaded by
 "sun.misc.Launcher$AppClassLoader @ 0x700000000" occupies 3,845,753,568 (82.42%) bytes.
 The memory is accumulated in one instance of "org.hibernate.engine.internal.EntityEntryContext" loaded by
 "sun.misc.Launcher$AppClassLoader @ 0x700000000".

Below is the configuration class

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef = "entityManagerFactory", basePackages = { "com.xxx.yyy.persistence.repository" })
public class BootDatasourceConfig {

    @ConfigurationProperties(prefix = "yyy.persistence.datasource")
    @Bean(name = "yyyDS")
    @Primary
    public DataSource primaryDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Primary
    @Bean(name = "entityManagerFactory")
    public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder, @Qualifier("yyyDS") DataSource dataSource) {
        LocalContainerEntityManagerFactoryBean em = builder.dataSource(dataSource).packages("com.xxx.yyy.persistence.entity").persistenceUnit("persistence").build();
        em.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
        return em;
    }

    @Primary
    @Bean(name = "transactionManager")
    public PlatformTransactionManager transactionManager(@Qualifier("entityManagerFactory") EntityManagerFactory entityManagerFactory) {
        return new JpaTransactionManager(entityManagerFactory);
    }

}

Below is the service class

@Service
@Transactional
public class PersistenceServiceImpl implements PersistenceService {

@Autowired
private Entity1Repository entity1repo;

@Autowired
private Entity2Repository entity2repo;

@Override
public PersistenceResponse process (PersistenceReqMsg reqMsg) {
    List<PersistenceRequest> reqLst = reqMsg.getReqList();

    List<Entity2> entity2Lst = new ArrayList<>();
    List<Entity1> entity1Lst = new ArrayList<>();

    for (PersistenceRequest req : reqLst) {
         for (PersistenceEvt evt : req.getBdy().getEvents()) {
             entity1Lst(...);
         }
         entity2Lst(...)
    }

    if (CollectionUtils.isNotEmpty(entity1Lst)) {
         entity1repo.saveAll(entity1Lst);
    }
    if (CollectionUtils.isNotEmpty(entity2Lst)) {
         entity2repo.saveAll(entity2Lst);
    }

    return AAAPersistenceResponse;
}

}

Below are the repo definitions -

@Repository
public interface Entity1Repository extends JpaRepository<Entity1, Long>, JpaSpecificationExecutor<Entity1>, CustomRepository  {}

@Repository
public interface Entity2Repository extends JpaRepository<Entity2, Long>, JpaSpecificationExecutor<Entity2>, CustomRepository  {}

Below are the application prop entries -

yyy.persistence.datasource.type=com.zaxxer.hikari.HikariDataSource
yyy.persistence.datasource.driverClassName=oracle.jdbc.OracleDriver
yyy.persistence.datasource.jdbcUrl=jdbc:oracle:thin:@ddd:1521:ccc
yyy.persistence.datasource.maximumPoolSize=20
yyy.persistence.datasource.idleTimeout=5
yyy.persistence.datasource.minimumIdle=5
yyy.persistence.datasource.connectionTimeout=60000

spring.jpa.database-platform= org.hibernate.dialect.Oracle12cDialect
spring.jpa.show-sql=false
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.Oracle12cDialect
spring.jpa.properties.hibernate.id.new_generator_mappings = false
spring.jpa.properties.hibernate.format_sql = true
spring.jpa.properties.hibernate.current_session_context_class=org.springframework.orm.hibernate5.SpringSessionContext
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
spring.jpa.properties.hibernate.jdbc.batch_size=50
spring.jpa.properties.hibernate.order_inserts=true
spring.jpa.properties.hibernate.order_updates=true

Below is minimal entity definition -

@Entity
@Table(name = "entity1table", uniqueConstraints = @UniqueConstraint(columnNames = { "ref1", "ref2" })) {

@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "entity1_id", unique = true, nullable = false)
public Long getEntity1Id() {
    return this.entity1Id;
}

}

From the heap dump it looks like entities are not being cleared from memory and building up over time. The incoming request object "PersistenceReqMsg" will not have an appreciably high number of records (max 250). Since the @Service method is executed in a @Transaction, my understanding is that JPA internally will issue "commit"/"rollback" based on batch size but not sure if JPA is also clearing the entities from persistence context. Could this be the reason for memory not being released?

Besides above JPA repo based code, we have few other service classes where "EntityManager" is being injected via @PersistenceContext and used to execute look up queries and some inserts/updates. Below is the sample -

@PersistenceContext
    private EntityManager em;

public getDetails () {
   em.createNativeQuery(....);
}

Not sure if these could also contribute to the memory building up.
Is it better to inject "EntityManagerFactory" instead of "EntityManager" and create a new instance of EM for every execution?


问:
Uncaught Error: "$.fn.modal" is not defined; please double check you have included the Bootstrap JavaScript library
Getting this error after calling JavaScript function with Bootbox from code behind after I upgraded to bootstrap 5. But works fine if I call the same function from my aspx page.

```<code>Error: Uncaught Error: "$.fn.modal" is not defined; please double check you have included the Bootstrap JavaScript library. See https://getbootstrap.com/docs/5.1/getting-started/introduction/ for more details.
</code>```

I've included all the dependencies.

My aspx code:

```<code><html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>

    <script src="include/js/jquery-1.12.4.js"></script>
    <script src="include/js/jquery.min.js" type="text/javascript"></script>
    <script src="include/js/jquery-ui.min.js" type="text/javascript"></script>

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous" />
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.min.js" integrity="sha384-cuYeSxntonz0PPNlHhBs68uyIAVpIIOZZ5JqeqvYYIcEL727kskC66kF92t6Xl2V" crossorigin="anonymous"></script>

    <script src="include/js/part/bootbox.min.js"></script>

    <script type="text/javascript">
        function AlertMessage() {
            bootbox.alert({
                title: "My title",
                message: "My Custom Message.....!!!",

            });
            return false;
        }

        $(document).ready(function () {
            /*AlertMessage();*/
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
        </div>
    </form>
</body>
</html>
</code>```

My Code behind :

```<code>protected void Page_Load(object sender, EventArgs e)
{
    Page.RegisterStartupScript("Getdata", "<script type=text/javascript>AlertMessage();</script>");
}
</code>```

Works fine when I call it from document ready. But shows error when called from code behind.
Already tried Page.ClientScript.

Body:
Getting this error after calling JavaScript function with Bootbox from code behind after I upgraded to bootstrap 5. But works fine if I call the same function from my aspx page.

Error: Uncaught Error: "$.fn.modal" is not defined; please double check you have included the Bootstrap JavaScript library. See https://getbootstrap.com/docs/5.1/getting-started/introduction/ for more details.

I've included all the dependencies.

My aspx code:

    <title></title>

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous" />

    <form id="form1" runat="server">

    </form>

My Code behind :

protected void Page_Load(object sender, EventArgs e)
{
    Page.RegisterStartupScript("Getdata", "");
}

Works fine when I call it from document ready. But shows error when called from code behind.
Already tried Page.ClientScript.


问:
Low latency live streaming ubuntu server
Is there any alternative to apple's mediastreamsegmenter and mediafilesegmenter to build low latency http live streaming linux server

I have tried to find alternative to apple's hls tools but have found anything for linux machine.


问:
HTTP fetch in react native gives 304 error on fetch and does not show database data
My backend REST api is written in Node.Js and MongoDB

So i am trying to make the request from a React native application and I am getting Http 304, for some reasons i do not seem to understand and hence, I decided to come on here to see if there was a possibility of a resolve. Sought the internet, it seems its a known problem, but no viable solution.

My source code is looking like this

```<code>import React, {useEffect, useState} from 'react';
import {
  ActivityIndicator,
  Button,
  Image,
  ImageBackground,
  SafeAreaView,
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
} from 'react-native';
import {Header, Avatar, Icon, Card} from '@rneui/themed';
import {FlatList, ScrollView} from 'react-native-gesture-handler';
import {useNavigation} from '@react-navigation/native';
import {Tab} from '@rneui/base';
import AsyncStorage from '@react-native-async-storage/async-storage';

const HomePage = () => {
  const [transaction_details, setTransaction_details] = useState([]);
  const [isLoading, setLoading] = useState(true);

  const navigation = useNavigation();

  const Item = ({title}) => (
    <View style={styles.item}>
      <Text style={styles.title}>{title}</Text>
    </View>
  );

  FlatListItemSeparator = () => {
    return (
      <View
        style={{
          height: 1,
          width: 350,
          backgroundColor: '#D3D3D3',
        }}
      />
    );
  };

  showdata = async () => {
    let token = await AsyncStorage.getItem('token');
    alert(token);
  };

  getTransactionsList = async () => {
    let token = await AsyncStorage.getItem('token');
    let email = await AsyncStorage.getItem('email');

    fetch('https://***********/api/user-data/get-transactionby-email/' + email, {
      method: 'GET',
      headers: {
        'Accept': 'application/json',
        'Content-type': 'application/json',
        'Authorization': `Bearer ${token}`,
      },
    })
      .then(response => response.json())
      .then(responseJson => {
        setTransaction_details(responseJson.results);
        setLoading(false);
      });
  };

  useEffect(() => {
    //showdata();
    getTransactionsList();
  });

  /*useEffect(() => {
    fetch('https://brotherlike-navies.000webhostapp.com/people/people.php', {
      method: 'GET',
      headers: {
        Accept: 'application/json',
        'Content-type': 'application/json',
      },
    })
      .then(response => response.json())
      .then(responseJson => {
        setTransaction_details(responseJson);
        setLoading(false);
      });
  }, []);
  */

  return (
    <View style={{flex: 1}}>
      <Header
        containerStyle={{
          backgroundColor: 'transparent',
          justifyContent: 'space-around',
        }}
        leftComponent={
          <Avatar
            small
            rounded
            source={{
              uri: 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSiRne6FGeaSVKarmINpum5kCuJ-pwRiA9ZT6D4_TTnUVACpNbzwJKBMNdiicFDChdFuYA&usqp=CAU',
            }}
            onPress={() => console.log('Left Clicked!')}
            activeOpacity={0.7}
          />
        }
        rightComponent={
          <Icon
            name={'mail-outline'}
            color={'#00BB23'}
            size={32}
            onPress={() => navigation.navigate('Accounts')}
          />
        }></Header>

      <ImageBackground
        source={{
          uri: 'asset:/logo/bg.JPG',
        }}
        imageStyle={{borderRadius: 6}}
        style={{
          top: 15,
          paddingTop: 95,
          alignSelf: 'center',
          width: 328,
          height: 145,
          borderadius: 9,
          justifyContent: 'center',
          alignSelf: 'center',
          alignItems: 'center',
        }}>
        <View>
          <Text style={styles.accText}>Wallet Balance</Text>
          <Text style={styles.text}> 250,000 </Text>
        </View>
      </ImageBackground>
      <View>
        <Text
          style={{
            fontFamily: 'Poppins-Bold',
            flexDirection: 'row',
            paddingTop: 55,
            fontSize: 15,
            left: 18,
            color: 'gray',
          }}>
          Recent Transactions
        </Text>
      </View>
      <View style={{flex: 1, marginTop: 35}}>
        {isLoading ? (
          <ActivityIndicator />
        ) : (
<FlatList
    data={transaction_details}
    ItemSeparatorComponent={this.FlatListItemSeparator}
    renderItem={({ item }) => {
      return (
        <View>
          <View style={{ flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center' }}>
            <Text>{item.narration}</Text>
            <Text>{item.amount}</Text>
          </View>
          <Text>{item.date}</Text>
        </View>
      )
    }}
    keyExtractor={(item) => item.id.toString()}
 />
        )}
      </View>
    </View>
  );
};

export default HomePage;

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    padding: 20,
  },

  paragraph: {
    fontSize: 18,
    fontWeight: 'bold',
    textAlign: 'center',
    padding: 20,
  },
  text: {
    top: -85,
    fontSize: 30,
    color: 'white',
    textAlign: 'center',
    fontFamily: 'Poppins-Bold',
  },
  mainContainer: {
    paddingTop: 90,
    justifyContent: 'center',
    alignItems: 'center',
  },
  accText: {
    top: -85,
    paddingTop: 10,
    justifyContent: 'center',
    alignItems: 'center',
    fontFamily: 'Poppins-Medium',
    color: 'white',
    textAlign: 'center',
  },
  PayeeName: {
    justifyContent: 'flex-start',
    flexWrap :'wrap',
    fontFamily: 'Poppins-Medium',
    size: 800,
    fontWeight: 'bold',
  },
  amountValue: {
    textAlign:'right',
    fontFamily: 'Poppins-Medium',
    size: 800,
    fontWeight: 'bold',
  },
});
</code>```

I do not seem to understand why this is not working as expected. Someone should please give a guide as to what is going on.

Body:
My backend REST api is written in Node.Js and MongoDB

So i am trying to make the request from a React native application and I am getting Http 304, for some reasons i do not seem to understand and hence, I decided to come on here to see if there was a possibility of a resolve. Sought the internet, it seems its a known problem, but no viable solution.

My source code is looking like this

import React, {useEffect, useState} from 'react';
import {
  ActivityIndicator,
  Button,
  Image,
  ImageBackground,
  SafeAreaView,
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
} from 'react-native';
import {Header, Avatar, Icon, Card} from '@rneui/themed';
import {FlatList, ScrollView} from 'react-native-gesture-handler';
import {useNavigation} from '@react-navigation/native';
import {Tab} from '@rneui/base';
import AsyncStorage from '@react-native-async-storage/async-storage';

const HomePage = () => {
  const [transaction_details, setTransaction_details] = useState([]);
  const [isLoading, setLoading] = useState(true);

  const navigation = useNavigation();

  const Item = ({title}) => (
    <View style={styles.item}>
      <Text style={styles.title}>{title}</Text>
    </View>
  );

  FlatListItemSeparator = () => {
    return (
      <View
        style={{
          height: 1,
          width: 350,
          backgroundColor: '#D3D3D3',
        }}
      />
    );
  };

  showdata = async () => {
    let token = await AsyncStorage.getItem('token');
    alert(token);
  };

  getTransactionsList = async () => {
    let token = await AsyncStorage.getItem('token');
    let email = await AsyncStorage.getItem('email');

    fetch('https://***********/api/user-data/get-transactionby-email/' + email, {
      method: 'GET',
      headers: {
        'Accept': 'application/json',
        'Content-type': 'application/json',
        'Authorization': `Bearer ${token}`,
      },
    })
      .then(response => response.json())
      .then(responseJson => {
        setTransaction_details(responseJson.results);
        setLoading(false);
      });
  };

  useEffect(() => {
    //showdata();
    getTransactionsList();
  });

  /*useEffect(() => {
    fetch('https://brotherlike-navies.000webhostapp.com/people/people.php', {
      method: 'GET',
      headers: {
        Accept: 'application/json',
        'Content-type': 'application/json',
      },
    })
      .then(response => response.json())
      .then(responseJson => {
        setTransaction_details(responseJson);
        setLoading(false);
      });
  }, []);
  */

  return (
    <View style={{flex: 1}}>
      <Header
        containerStyle={{
          backgroundColor: 'transparent',
          justifyContent: 'space-around',
        }}
        leftComponent={
          <Avatar
            small
            rounded
            source={{
              uri: 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSiRne6FGeaSVKarmINpum5kCuJ-pwRiA9ZT6D4_TTnUVACpNbzwJKBMNdiicFDChdFuYA&usqp=CAU',
            }}
            onPress={() => console.log('Left Clicked!')}
            activeOpacity={0.7}
          />
        }
        rightComponent={
          <Icon
            name={'mail-outline'}
            color={'#00BB23'}
            size={32}
            onPress={() => navigation.navigate('Accounts')}
          />
        }>

      <ImageBackground
        source={{
          uri: 'asset:/logo/bg.JPG',
        }}
        imageStyle={{borderRadius: 6}}
        style={{
          top: 15,
          paddingTop: 95,
          alignSelf: 'center',
          width: 328,
          height: 145,
          borderadius: 9,
          justifyContent: 'center',
          alignSelf: 'center',
          alignItems: 'center',
        }}>
        <View>
          <Text style={styles.accText}>Wallet Balance</Text>
          <Text style={styles.text}> 250,000 </Text>
        </View>
      </ImageBackground>
      <View>
        <Text
          style={{
            fontFamily: 'Poppins-Bold',
            flexDirection: 'row',
            paddingTop: 55,
            fontSize: 15,
            left: 18,
            color: 'gray',
          }}>
          Recent Transactions
        </Text>
      </View>
      <View style={{flex: 1, marginTop: 35}}>
        {isLoading ? (
          <ActivityIndicator />
        ) : (
<FlatList
    data={transaction_details}
    ItemSeparatorComponent={this.FlatListItemSeparator}
    renderItem={({ item }) => {
      return (
        <View>
          <View style={{ flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center' }}>
            <Text>{item.narration}</Text>
            <Text>{item.amount}</Text>
          </View>
          <Text>{item.date}</Text>
        </View>
      )
    }}
    keyExtractor={(item) => item.id.toString()}
 />
        )}
      </View>
    </View>
  );
};

export default HomePage;

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    padding: 20,
  },

  paragraph: {
    fontSize: 18,
    fontWeight: 'bold',
    textAlign: 'center',
    padding: 20,
  },
  text: {
    top: -85,
    fontSize: 30,
    color: 'white',
    textAlign: 'center',
    fontFamily: 'Poppins-Bold',
  },
  mainContainer: {
    paddingTop: 90,
    justifyContent: 'center',
    alignItems: 'center',
  },
  accText: {
    top: -85,
    paddingTop: 10,
    justifyContent: 'center',
    alignItems: 'center',
    fontFamily: 'Poppins-Medium',
    color: 'white',
    textAlign: 'center',
  },
  PayeeName: {
    justifyContent: 'flex-start',
    flexWrap :'wrap',
    fontFamily: 'Poppins-Medium',
    size: 800,
    fontWeight: 'bold',
  },
  amountValue: {
    textAlign:'right',
    fontFamily: 'Poppins-Medium',
    size: 800,
    fontWeight: 'bold',
  },
});

I do not seem to understand why this is not working as expected. Someone should please give a guide as to what is going on.


问:
Caching GET method of @RepositoryRestResource
I have a @RespositoryRestResource class. Only the GET operation is being used which returns all the data. This is taking some time. So I want to cache this call. However I'm not sure how to achieve caching for RepositoryRestResource. Any help is much appreciated. Thanks

```<code>@RepositoryRestResource(collectionResourceRel = "employees", path = "employees", excerptProjection = EmployeeProjection.class)
public interface EmployeeRepository extends BaseRepository<Employee, QEmployee> {

}
</code>```

Tried to add caching in the project but somehow I'm not sure which method is being used for getting all the data through GET operation.

Body:
I have a @RespositoryRestResource class. Only the GET operation is being used which returns all the data. This is taking some time. So I want to cache this call. However I'm not sure how to achieve caching for RepositoryRestResource. Any help is much appreciated. Thanks

@RepositoryRestResource(collectionResourceRel = "employees", path = "employees", excerptProjection = EmployeeProjection.class)
public interface EmployeeRepository extends BaseRepository<Employee, QEmployee> {

}

Tried to add caching in the project but somehow I'm not sure which method is being used for getting all the data through GET operation.


问:
How can I return a value from a Sub-Class JFrame to the Parent JFrame?
Im trying to just Use 2 JFrames to return a username value back to its calling method on the parent class. Im puzzled. It works without using the gui and I understand it that way but this. Theres seems to be something simple im missing. I only posted the main parts of the program thats relevant by the way the second class at the bottom is a seperate class on a another tab. Im using it as another window.</p>
```<code>   public class LoginWn extends JFrame implements ActionListener {

   JButton loginBtn = new JButton( );

   JTextField usrNmFld = new JTextField( );
   JPasswordField pswdFld = new JPasswordField( );

   public static  String cnfrmdUsrNm;

  public LoginWn( )
    { //Frame header
            setBounds(100, 100, 727, 482);
            setVisible(true);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //Set Listener for Window
            addWindowListener(new WindowAdapter( ) {
                public void windowClosing(WindowEvent e) {
                    exitForm(e);
                }
            });

    newUsrBtn.setIcon(new ImageIcon("C:\\Users\\Etienne Shelton\\Desktop\\Java IDE Files\\Glossy Blue JButton.png"));
             layeredPane.setLayer(newUsrBtn, 3);
             newUsrBtn.setBounds(550, 412, 89, 23);
             newUsrBtn.addActionListener(new ActionListener( ) {
                 public void actionPerformed(ActionEvent e) {
                     //Send To JPanel
                    newUsrBtnActionPerformed( );
               }
           });
            layeredPane.add(newUsrBtn);

   public void loginBtnActionPerformed(ActionEvent e) throws IOException {

       getUsrData( );
   }

   public void getUsrData( )  {

      cnfrmdUsrNm = NewUsrWn.getUsrData( );
   }

        public NewUsrWn extends LoginWn( ) { //Inherited Class On Seperate ab

    JLayeredPane layeredPane = new JLayeredPane( );
    JFrame frame = new JFrame( );
    frame.setVisible(true);
    frame.setBounds(100, 100, 512, 499);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

      layeredPane.setLayer(setBtn, 3);
    setBtn.setBounds(193, 222, 89, 23);
    setBtn.addActionListener(new ActionListener( ) {
        public void actionPerformed(ActionEvent e) {
            setBtnActionPerformed(e);
        }
    });
    layeredPane.add(setBtn);

    layeredPane.setLayer(pswdTxtFld, 3);
    pswdTxtFld.setColumns(10);
    pswdTxtFld.setBounds(152, 188, 184, 23);
    layeredPane.add(pswdTxtFld);

    layeredPane.setLayer(bckBtn, 3);
    bckBtn.setBounds(193, 256, 89, 23);
    layeredPane.add(bckBtn);

frame.getContentPane().setLayout(groupLayout);
   }

    public void setBtnActionPerformed(ActionEvent e) {
    getUsrData();
    }

    //Set UserName and Password
     public static String getUsrData( ) {
     String entrdUsrNm;

     // String entrdPswd;
     //Get Username from user & InhX from NewUsrWn Class
    entrdUsrNm = usrTxtFld.getText( );
    //entrdPswd = pswdTxtFld.getText( );
    //Confirm entered passwords as final Passwords
    cnfrmdUsrNm = entrdUsrNm;
    //cnfrmdPswd = entrdPswd;
    return (cnfrmdUsrNm);
     }
</code>```

Body:
Im trying to just Use 2 JFrames to return a username value back to its calling method on the parent class. Im puzzled. It works without using the gui and I understand it that way but this. Theres seems to be something simple im missing. I only posted the main parts of the program thats relevant by the way the second class at the bottom is a seperate class on a another tab. Im using it as another window.

   public class LoginWn extends JFrame implements ActionListener {

   JButton loginBtn = new JButton( );

   JTextField usrNmFld = new JTextField( );
   JPasswordField pswdFld = new JPasswordField( );

   public static  String cnfrmdUsrNm;

  public LoginWn( )
    { //Frame header
            setBounds(100, 100, 727, 482);
            setVisible(true);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //Set Listener for Window
            addWindowListener(new WindowAdapter( ) {
                public void windowClosing(WindowEvent e) {
                    exitForm(e);
                }
            });

    newUsrBtn.setIcon(new ImageIcon("C:\\Users\\Etienne Shelton\\Desktop\\Java IDE Files\\Glossy Blue JButton.png"));
             layeredPane.setLayer(newUsrBtn, 3);
             newUsrBtn.setBounds(550, 412, 89, 23);
             newUsrBtn.addActionListener(new ActionListener( ) {
                 public void actionPerformed(ActionEvent e) {
                     //Send To JPanel
                    newUsrBtnActionPerformed( );
               }
           });
            layeredPane.add(newUsrBtn);

   public void loginBtnActionPerformed(ActionEvent e) throws IOException {

       getUsrData( );
   }

   public void getUsrData( )  {

      cnfrmdUsrNm = NewUsrWn.getUsrData( );
   }

        public NewUsrWn extends LoginWn( ) { //Inherited Class On Seperate ab

    JLayeredPane layeredPane = new JLayeredPane( );
    JFrame frame = new JFrame( );
    frame.setVisible(true);
    frame.setBounds(100, 100, 512, 499);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

      layeredPane.setLayer(setBtn, 3);
    setBtn.setBounds(193, 222, 89, 23);
    setBtn.addActionListener(new ActionListener( ) {
        public void actionPerformed(ActionEvent e) {
            setBtnActionPerformed(e);
        }
    });
    layeredPane.add(setBtn);

    layeredPane.setLayer(pswdTxtFld, 3);
    pswdTxtFld.setColumns(10);
    pswdTxtFld.setBounds(152, 188, 184, 23);
    layeredPane.add(pswdTxtFld);

    layeredPane.setLayer(bckBtn, 3);
    bckBtn.setBounds(193, 256, 89, 23);
    layeredPane.add(bckBtn);

frame.getContentPane().setLayout(groupLayout);
   }

    public void setBtnActionPerformed(ActionEvent e) {
    getUsrData();
    }

    //Set UserName and Password
     public static String getUsrData( ) {
     String entrdUsrNm;

     // String entrdPswd;
     //Get Username from user & InhX from NewUsrWn Class
    entrdUsrNm = usrTxtFld.getText( );
    //entrdPswd = pswdTxtFld.getText( );
    //Confirm entered passwords as final Passwords
    cnfrmdUsrNm = entrdUsrNm;
    //cnfrmdPswd = entrdPswd;
    return (cnfrmdUsrNm);
     }


问:
I am building a VOD service. The videos have been stored on S3 buckets. How do I decrease the latency while fetching the videos?
The backend is in node and front end is built using react. I used getObject to fetch the video from the bucket and then used createReadStream() on it and then pipe the response.

```<code>s3
    .getObject({
      Bucket: bucket,
      Key: filename,
      Range: 'bytes=0-20582912',
    })
    .createReadStream()
    .pipe(res);
</code>```

Can someone tell me how do I introduce byte range fetches in it? I want the video to be divided into chunks and then send it to the video player in the front end. I am also using mp4, would using HLS help in this case? Or would creating a presigned-url and then sending that to the video-player help?

I tried the above the code but I am hoping less latency and immediate buffering.

Body:
The backend is in node and front end is built using react. I used getObject to fetch the video from the bucket and then used createReadStream() on it and then pipe the response.

s3
    .getObject({
      Bucket: bucket,
      Key: filename,
      Range: 'bytes=0-20582912',
    })
    .createReadStream()
    .pipe(res);

Can someone tell me how do I introduce byte range fetches in it? I want the video to be divided into chunks and then send it to the video player in the front end. I am also using mp4, would using HLS help in this case? Or would creating a presigned-url and then sending that to the video-player help?

I tried the above the code but I am hoping less latency and immediate buffering.


问:
Change Int Value Inside the While Loop
I try to make snake game and I want increase score when snake eat the food I have a int score upper the game loop and I want the increase in the while loop to the score and I get a error Segmentation fault (core dumped).

#include <iostream>

#include <SFML/Graphics.hpp>
#include <SFML/System.hpp>
#include <SFML/Window.hpp>
#include <SFML/Audio.hpp>
#include <SFML/Network.hpp>

#include <list>

int main()
{

    sf::RenderWindow window(sf::VideoMode(400, 400), "omega");
    sf::Event ev;

// tail

    std::list<int> tail;

//shape

    sf::RectangleShape rectangle(sf::Vector2f(18.f, 18.f));
    sf::RectangleShape tailRectangle(sf::Vector2f(18.f, 18.f));
    sf::RectangleShape foodRectangle(sf::Vector2(18.f, 18.f));

    rectangle.setFillColor(sf::Color(250, 250, 250));
    tailRectangle.setFillColor(sf::Color(250, 250, 250));
    foodRectangle.setFillColor(sf::Color(255, 0, 0));

// variable

    int x = 80.f;
    int y = 80.f;

    int speed = 4;
    int FLAG = 0;

    std::string direction = "down";

//Time

    sf::Clock clock;
    window.setFramerateLimit(60);

// Food

    int foodChoice_x;
    int foodChoice_y;
    int score = 3;

    bool foodFlag = true;

//Game loop

    while (window.isOpen())

    {

        // FPS
        float currentTime = clock.restart().asSeconds();
        float fps = 1.0f / (currentTime);

        //Event polling
        while (window.pollEvent(ev))
        {
            switch (ev.type)
            {
                case sf::Event::Closed:
                    window.close();
                    break;
                case sf::Event::KeyPressed:
                    if (ev.key.code == sf::Keyboard::Escape)
                        window.close();

                    if (ev.key.code == sf::Keyboard::W)
                        FLAG = 0;
                    if (ev.key.code == sf::Keyboard::S)
                        FLAG = 1;
                    if (ev.key.code == sf::Keyboard::A)
                        FLAG = 2;
                    if (ev.key.code == sf::Keyboard::D)
                        FLAG = 3;
                default:
                    break;
            }
        }

// Eat Food
        if (foodChoice_x * 20 == x && foodChoice_y * 20 == y)
        {
            score++;
            foodFlag = true;
        }
// Food maker
        if (foodFlag)
        {
            foodChoice_x = rand() % 17 + 2;
            foodChoice_y = rand() % 17 + 2;

            foodRectangle.setPosition(foodChoice_x * 20, foodChoice_y * 20);
            foodFlag = false;
        }

// Tail maker

        int count = 0;

        if (x % 20 == 0 && y % 20 == 0)
        {
            tail.push_front(x);
            tail.push_front(y);
        }

        if (tail.size() > score * 2)
            for (int n : tail)
            {
                tail.pop_back();
            }

        if (FLAG == 0)
            if (x % 20 == 0 && y % 20 == 0)
                direction = "up";
        if (FLAG == 1)
            if (x % 20 == 0 && y % 20 == 0)
                direction = "down";
        if (FLAG == 2)
            if (x % 20 == 0 && y % 20 == 0)
                direction = "left";
        if (FLAG == 3)
            if (x % 20 == 0 && y % 20 == 0)
                direction = "right";

        if (direction == "up")
            y -= speed;
        if (direction == "down")
            y += speed;
        if (direction == "right")
            x += speed;
        if (direction == "left")
            x -= speed;

//Update

        rectangle.setPosition(x, y);
        std::list<int>::iterator it = tail.begin();

//Render

        window.clear(); // Clear old frame

//Draw your game

        window.draw(rectangle);
        window.draw(foodRectangle);

// Draw tail

        count = 0;
        int X;
        int Y;

        for (int n : tail)
        {

            if (count % 2 == 1)
                X = n;
            if (count % 2 == 0)
                Y = n;

            count++;

            if (count % 2 == 0)
                tailRectangle.setPosition(X, Y);
            window.draw(tailRectangle);
        }

//FPS

        window.display(); // Tek app that window is done drawing

//End of application

// Food eat

    }

    return 0;
}
```

I except the value increase and not get a error but that's not working but when I put the declaration score in the while loop that s working but useless because value is same every time.

Title: Change Int Value Inside the While Loop

Body:
I try to make snake game and I want increase score when snake eat the food I have a int score upper the game loop and I want the increase in the while loop to the score and I get a error Segmentation fault (core dumped).

#include <iostream>

#include <SFML/Graphics.hpp>
#include <SFML/System.hpp>
#include <SFML/Window.hpp>
#include <SFML/Audio.hpp>
#include <SFML/Network.hpp>

#include <list>

int main()
{

    sf::RenderWindow window(sf::VideoMode(400, 400), "omega");
    sf::Event ev;

// tail

    std::list<int> tail;

//shape

    sf::RectangleShape rectangle(sf::Vector2f(18.f, 18.f));
    sf::RectangleShape tailRectangle(sf::Vector2f(18.f, 18.f));
    sf::RectangleShape foodRectangle(sf::Vector2(18.f, 18.f));

    rectangle.setFillColor(sf::Color(250, 250, 250));
    tailRectangle.setFillColor(sf::Color(250, 250, 250));
    foodRectangle.setFillColor(sf::Color(255, 0, 0));

// variable

    int x = 80.f;
    int y = 80.f;

    int speed = 4;
    int FLAG = 0;

    std::string direction = "down";

//Time

    sf::Clock clock;
    window.setFramerateLimit(60);

// Food

    int foodChoice_x;
    int foodChoice_y;
    int score = 3;

    bool foodFlag = true;

//Game loop

    while (window.isOpen())

    {

        // FPS
        float currentTime = clock.restart().asSeconds();
        float fps = 1.0f / (currentTime);

        //Event polling
        while (window.pollEvent(ev))
        {
            switch (ev.type)
            {
                case sf::Event::Closed:
                    window.close();
                    break;
                case sf::Event::KeyPressed:
                    if (ev.key.code == sf::Keyboard::Escape)
                        window.close();

                    if (ev.key.code == sf::Keyboard::W)
                        FLAG = 0;
                    if (ev.key.code == sf::Keyboard::S)
                        FLAG = 1;
                    if (ev.key.code == sf::Keyboard::A)
                        FLAG = 2;
                    if (ev.key.code == sf::Keyboard::D)
                        FLAG = 3;
                default:
                    break;
            }
        }

// Eat Food
        if (foodChoice_x * 20 == x && foodChoice_y * 20 == y)
        {
            score++;
            foodFlag = true;
        }
// Food maker
        if (foodFlag)
        {
            foodChoice_x = rand() % 17 + 2;
            foodChoice_y = rand() % 17 + 2;

            foodRectangle.setPosition(foodChoice_x * 20, foodChoice_y * 20);
            foodFlag = false;
        }

// Tail maker

        int count = 0;

        if (x % 20 == 0 && y % 20 == 0)
        {
            tail.push_front(x);
            tail.push_front(y);
        }

        if (tail.size() > score * 2)
            for (int n : tail)
            {
                tail.pop_back();
            }

        if (FLAG == 0)
            if (x % 20 == 0 && y % 20 == 0)
                direction = "up";
        if (FLAG == 1)
            if (x % 20 == 0 && y % 20 == 0)
                direction = "down";
        if (FLAG == 2)
            if (x % 20 == 0 && y % 20 == 0)
                direction = "left";
        if (FLAG == 3)
            if (x % 20 == 0 && y % 20 == 0)
                direction = "right";

        if (direction == "up")
            y -= speed;
        if (direction == "down")
            y += speed;
        if (direction == "right")
            x += speed;
        if (direction == "left")
            x -= speed;

//Update

        rectangle.setPosition(x, y);
        std::list<int>::iterator it = tail.begin();

//Render

        window.clear(); // Clear old frame

//Draw your game

        window.draw(rectangle);
        window.draw(foodRectangle);

// Draw tail

        count = 0;
        int X;
        int Y;

        for (int n : tail)
        {

            if (count % 2 == 1)
                X = n;
            if (count % 2 == 0)
                Y = n;

            count++;

            if (count % 2 == 0)
                tailRectangle.setPosition(X, Y);
            window.draw(tailRectangle);
        }

//FPS

        window.display(); // Tek app that window is done drawing

//End of application

// Food eat

    }

    return 0;
}

I except the value increase and not get a error but that's not working but when I put the declaration score in the while loop that s working but useless because value is same every time.


问:
Create Firebase Dynamic Link using JAVA
In my firebase account, I create dynamic link manually and I got that dynamic link in my application, but the issue is that I need to create dynamic link randomly using JAVA.

I am able to create manually, but not able to create using JAVA.

Title: Create Firebase Dynamic Link using JAVA


问:
Calculating Date for Comparison Power BI
I use this measure to calculate a past date in PBI for comparison purposes.

```<code>Old_Date = calculate([Total sales], DATEADD(Dates[Date],-1099,DAY))
</code>```

As I am new to PBI I am having trouble with writing a measure that allows me to have a possible of 2 previous dates based on criteria.  What I am looking for is something like this:

```<code>old_date = if(month(Dates[Date])>=10,
calculate([Total sales], DATEADD(Dates[Date],-1099,DAY)),
calculate([Total sales], DATEADD(Dates[Date],-1463,DAY)))
</code>```

Firstly, is this possible?  Secondly by using the if statement PBI does not let me select Date[Date].

I should add that these are tables stored on a server.

Appreciate any help.

Thanks

I have tried various versions of the measure above.

Body:
I use this measure to calculate a past date in PBI for comparison purposes.

Old_Date = calculate([Total sales], DATEADD(Dates[Date],-1099,DAY))

As I am new to PBI I am having trouble with writing a measure that allows me to have a possible of 2 previous dates based on criteria.  What I am looking for is something like this:

old_date = if(month(Dates[Date])>=10,
calculate([Total sales], DATEADD(Dates[Date],-1099,DAY)),
calculate([Total sales], DATEADD(Dates[Date],-1463,DAY)))

Firstly, is this possible?  Secondly by using the if statement PBI does not let me select Date[Date].

I should add that these are tables stored on a server.

Appreciate any help.

Thanks

I have tried various versions of the measure above.


问:
Uncaught TypeError: lineTotal is not a function When using <form> tag / JAVASCRIPT

var renumber = 0;

function calculateDueAmount() {
  var tblRows = document.getElementById("addItems").getElementsByTagName("tr");
  let total = 0;
  for (var i = 0; i < tblRows.length; i++) {
    let lineTotal = tblRows[i]
      .getElementsByTagName("td")[4]
      .getElementsByTagName("input")[0].value;
    total += Number(lineTotal);
  }
  document.getElementById("amountDue").innerText = total.toFixed(2);
}

function addItem() {
  renumber++;
  var html = "
";
  html += "" + renumber + "	";
  html += "<input name='itemName[]'>	";

  html +=
    "$<input  onblur='lineTotal(this);' value='0' name='amount[]'>	";
  html +=
    "<input  onblur='lineTotal(this);' value='0' name='qty[]'>	";
  html +=
    "$<input onblur='lineTotal(this);' value='0' name='lineTotal[]'>	";
  html +=
    "<button type='button' id='remove_button' onclick='removeItem(this);'> X </button>	";
  html += "
";
  document.getElementById("addItems").insertRow().innerHTML = html;
}

function removeItem(elem) {
  let rowToDelete = elem.parentElement.parentElement;
  let rowNumber = rowToDelete.getElementsByTagName("td")[0].innerText;
  document.getElementById("addItems").deleteRow(rowNumber - 1);
  let tblRows = document.getElementById("addItems").getElementsByTagName("tr");
  let j = 0;
  for (; j < tblRows.length; j++) {
    tblRows[j].getElementsByTagName("td")[0].innerText = j + 1;
  }
  calculateDueAmount();
  renumber = j;
}

function lineTotal(elem) {
  var mainRow = elem.parentElement.parentElement;
  var amt = mainRow
    .getElementsByTagName("td")[2]
    .getElementsByTagName("input")[0].value;
  var qty = mainRow
    .getElementsByTagName("td")[3]
    .getElementsByTagName("input")[0].value;
  var total = mainRow
    .getElementsByTagName("td")[4]
    .getElementsByTagName("input")[0];
  var myResult = Number(amt) * Number(qty);
  total.value = myResult;
  calculateDueAmount();
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="home-section">
  <div class="sign-up-box">
    <h1>Payment details</h1>

    <div class="signup-container">
      <label>Service Ticket Number : </label>
      <br />

      <form action="" method="post">
        <table>
          <tr>
            <th>#</th>
            <th>Item Name</th>

            <th>Amount per unit</th>
            <th>Quantity</th>
            <th>Line Total</th>
          </tr>

          <tbody id="addItems"></tbody>
        </table>

        <p>
          <button type="button" onclick="addItem();">Add Item</button>
        </p>

        <p>
          Amount Due: $<span id="amountDue">0.00</span>
          <script src="includes/javascript.js"></script>
        </p>

        <p>
          <input id="invoice_submit" type="submit" name="submit" />
        </p>
      </form>
    </div>
  </div>
</div></code>```

This my first time posting. Code is working perfectly. It is able to run its function like add rows, auto calculate amount and qty column and display it on the linetotal column.

The only problem here is that when I add <form> tag into the the code, the auto calculation stops working because of this error

Uncaught TypeError: lineTotal is not a function

where is doesn't recognise lineTotal as a function.

I have already tried console.log(lineTotal) and it displayed the lineTotal function.

Body:
var renumber = 0;

function calculateDueAmount() {
  var tblRows = document.getElementById("addItems").getElementsByTagName("tr");
  let total = 0;
  for (var i = 0; i < tblRows.length; i++) {
    let lineTotal = tblRows[i]
      .getElementsByTagName("td")[4]
      .getElementsByTagName("input")[0].value;
    total += Number(lineTotal);
  }
  document.getElementById("amountDue").innerText = total.toFixed(2);
}

function addItem() {
  renumber++;
  var html = "
";
  html += "" + renumber + "	";
  html += "<input name='itemName[]'>	";

  html +=
    "$<input  onblur='lineTotal(this);' value='0' name='amount[]'>	";
  html +=
    "<input  onblur='lineTotal(this);' value='0' name='qty[]'>	";
  html +=
    "$<input onblur='lineTotal(this);' value='0' name='lineTotal[]'>	";
  html +=
    "<button type='button' id='remove_button' onclick='removeItem(this);'> X </button>	";
  html += "
";
  document.getElementById("addItems").insertRow().innerHTML = html;
}

function removeItem(elem) {
  let rowToDelete = elem.parentElement.parentElement;
  let rowNumber = rowToDelete.getElementsByTagName("td")[0].innerText;
  document.getElementById("addItems").deleteRow(rowNumber - 1);
  let tblRows = document.getElementById("addItems").getElementsByTagName("tr");
  let j = 0;
  for (; j < tblRows.length; j++) {
    tblRows[j].getElementsByTagName("td")[0].innerText = j + 1;
  }
  calculateDueAmount();
  renumber = j;
}

function lineTotal(elem) {
  var mainRow = elem.parentElement.parentElement;
  var amt = mainRow
    .getElementsByTagName("td")[2]
    .getElementsByTagName("input")[0].value;
  var qty = mainRow
    .getElementsByTagName("td")[3]
    .getElementsByTagName("input")[0].value;
  var total = mainRow
    .getElementsByTagName("td")[4]
    .getElementsByTagName("input")[0];
  var myResult = Number(amt) * Number(qty);
  total.value = myResult;
  calculateDueAmount();
}

Payment details

      Service Ticket Number :

      <form action="" method="post">

            #
            Item Name

            Amount per unit
            Quantity
            Line Total

          <button type="button" onclick="addItem();">Add Item</button>

          Amount Due: $0.00

          <input id="invoice_submit" type="submit" name="submit" />

      </form>

This my first time posting. Code is working perfectly. It is able to run its function like add rows, auto calculate amount and qty column and display it on the linetotal column.

The only problem here is that when I add <form> tag into the the code, the auto calculation stops working because of this error

Uncaught TypeError: lineTotal is not a function

where is doesn't recognise lineTotal as a function.

I have already tried console.log(lineTotal) and it displayed the lineTotal function.


问:
Pycharm autocompletion error occurred in opencv 4.6 or higher version

Pycharm

VSC

```<code>virtual environment contents

1.windows os
2.python 3.8 ver.
3. opencv 4.6.0.66
</code>```

Both pycharm and vsc autocompletion does not work.

searching the google. but there is not solving skills

Body:
Pycharm

VSC

virtual environment contents

1.windows os
2.python 3.8 ver.
3. opencv 4.6.0.66

Both pycharm and vsc autocompletion does not work.

searching the google. but there is not solving skills