问:
How to present Settings view on button click macOS SwiftUI
I have this app which is a menu bar app, hence the app is never really 'in focus' so it's not immediately obvious that the user can use the CMD + , shortcut to open the app's settings, hence why I'd like to add a button option so they can open settings via the menubar too:

```<code>@main
struct macOSApp: App {
@NSApplicationDelegateAdaptor(AppDelegate.self) var delegate

var body: some Scene {
    WindowGroup {
        MenuView()
            .environmentObject(Authentication())
    }
    WindowGroup("LoginView") {
        LoginView()
            .environmentObject(Authentication())
    }.handlesExternalEvents(matching: Set(arrayLiteral: "macOSApp://LoginView"))
    Settings {
        SettingsView()
            .environmentObject(Authentication())
    }.handlesExternalEvents(matching: Set(arrayLiteral: "macOSApp://SettingsView"))
  }
}
</code>```

I have the:

```<code>Settings {
        SettingsView()
            .environmentObject(Authentication())
    }.handlesExternalEvents(matching: Set(arrayLiteral: "macOSApp://SettingsView"))
}
</code>```

for my settings page, which works perfectly if the user opens it up via the CMD + , shortcut, I've added a .handlesExternalEvents(matching: Set(arrayLiteral: "macOSApp://SettingsView")) modifier onto it so upon button click I can run:

```<code>if let url = URL(string: "UpSend://SettingsView") {
   openURL(url)
}
</code>```

Which works for my Login screen, but when it runs, it just takes the main view of the app and puts it in its own window, not showing the Settings screen.

I appreciate I'm not using a WindowGroup I'm using Settings so opening up the window might need something entirely different, I just do not know what?

答:
Don’t include the “macOSApp://“ part in handlesExternalEvents. Try this:</p>
```<code>Settings {
        SettingsView()
            .environmentObject(Authentication())
    }.handlesExternalEvents(matching: Set(arrayLiteral: "SettingsView"))
}
</code>```

Body:
I have this app which is a menu bar app, hence the app is never really 'in focus' so it's not immediately obvious that the user can use the CMD + , shortcut to open the app's settings, hence why I'd like to add a button option so they can open settings via the menubar too:

@main
struct macOSApp: App {
@NSApplicationDelegateAdaptor(AppDelegate.self) var delegate

var body: some Scene {
    WindowGroup {
        MenuView()
            .environmentObject(Authentication())
    }
    WindowGroup("LoginView") {
        LoginView()
            .environmentObject(Authentication())
    }.handlesExternalEvents(matching: Set(arrayLiteral: "macOSApp://LoginView"))
    Settings {
        SettingsView()
            .environmentObject(Authentication())
    }.handlesExternalEvents(matching: Set(arrayLiteral: "macOSApp://SettingsView"))
  }
}

I have the:

Settings {
        SettingsView()
            .environmentObject(Authentication())
    }.handlesExternalEvents(matching: Set(arrayLiteral: "macOSApp://SettingsView"))
}

for my settings page, which works perfectly if the user opens it up via the CMD + , shortcut, I've added a .handlesExternalEvents(matching: Set(arrayLiteral: "macOSApp://SettingsView")) modifier onto it so upon button click I can run:

if let url = URL(string: "UpSend://SettingsView") {
   openURL(url)
}

Which works for my Login screen, but when it runs, it just takes the main view of the app and puts it in its own window, not showing the Settings screen.

I appreciate I'm not using a WindowGroup I'm using Settings so opening up the window might need something entirely different, I just do not know what?

Body:
Don’t include the “macOSApp://“ part in handlesExternalEvents. Try this:

Settings {
        SettingsView()
            .environmentObject(Authentication())
    }.handlesExternalEvents(matching: Set(arrayLiteral: "SettingsView"))
}


来源: stackexchange

问:
Parse through "USE" column of my ASB server list
I am working with a server list and I need to know how to create a string to parse through the "USE" column of the server list.</p>

答:
Here are some ideas:

1) If it's a one-time manipulation of data

Import the data into Excel, then use the CONCATENATE function (link) or the & operator to combine text values into the appropriate format.

```<code>=CONCATENATE("USE ", A1, " BLAH BLAH BLAH", B1)
</code>```

or

```<code>="USE "&A1&" BLAH BLAH BLAH"&B1
</code>```

2) If it's a recurring need

Use the Power Query CSV connector to ingest the CSV file and add a concatenation formula in Power Query (Text.Combine) or the resulting table (same formulas as above).

If the filename changes with each extract, use the Import Data from a folder feature.

Drop the new files in the same folder then just refresh the data and the list will be updated automatically.

ContentLicense: CC BY-SA 4.0

Body:
Here are some ideas:

1) If it's a one-time manipulation of data

Import the data into Excel, then use the CONCATENATE function (link) or the & operator to combine text values into the appropriate format.

=CONCATENATE("USE ", A1, " BLAH BLAH BLAH", B1)

or

="USE "&A1&" BLAH BLAH BLAH"&B1

2) If it's a recurring need

Use the Power Query CSV connector to ingest the CSV file and add a concatenation formula in Power Query (Text.Combine) or the resulting table (same formulas as above).

If the filename changes with each extract, use the Import Data from a folder feature.

Drop the new files in the same folder then just refresh the data and the list will be updated automatically.


问:
Can I recover from panic, handle the error, then panic again and keep the original stack trace?
Is it possible to "rethrow" an error from recover and keep the original stack trace? The best I know how to do is to panic again, but that does create a new stacktrace.

```<code>func do() {
    defer func() {
        cleanUp()
        if x := recover(); x != nil {
            handleError()
            panic(x)
        }
    }()
    doStuff()
}
</code>```

My motivation for wanting this is that unless my function exits normally or handleError runs, my program deadlocks. And unless I preserve the original strack trace, I do not know where it crashed.

答:
As Daniel Conde Marin questioned here

I do not believe you need to worry about calling panic and passing in a recover()'s response object creating a cryptic or "new" stack trace, at least in go 1.17. It looks like doing so simply adds another "src/runtime/panic.go:<linenum>" frame to the trace.

See this example test:
https://goplay.space/#5i1RCJyiFJr

Go does not treat panics like other languages treat try/catch/throw/finally.

ContentLicense: CC BY-SA 3.0

Body:
Is it possible to "rethrow" an error from recover and keep the original stack trace? The best I know how to do is to panic again, but that does create a new stacktrace.

func do() {
    defer func() {
        cleanUp()
        if x := recover(); x != nil {
            handleError()
            panic(x)
        }
    }()
    doStuff()
}

My motivation for wanting this is that unless my function exits normally or handleError runs, my program deadlocks. And unless I preserve the original strack trace, I do not know where it crashed.


问:
font-size:8px appearance in edge/firefox/chrome not the same
I have a simple a with style font-size:8px, but the result in edge is different from chrome and firefox.
I also tried font-size:50%, the result is the same.

```<code><a style="font-size:8px;display:block;text-align:center;color:#f8e8b8;background-color:#205010">
    雪亚小站旗下
</a>
</code>```

Or you can just visit my website https://snowyyang.com/rfwiki/QandA

font-size:8px in edge

font-size:8px in chrome and firefox

 <--

I want to keep the same appearance in all browsers without using images. What should I do?

答: It's turn out that the minimum font size in Edge is 12px.</p>

Body:
I have a simple a with style font-size:8px, but the result in edge is different from chrome and firefox.
I also tried font-size:50%, the result is the same.

    雪亚小站旗下

Or you can just visit my website https://snowyyang.com/rfwiki/QandA

font-size:8px in edge

font-size:8px in chrome and firefox

 <--

I want to keep the same appearance in all browsers without using images. What should I do?


问:
How do node_modules packages read config files in the project root?
I am creating an npm package that needs to be able to read config files from the project root. I'm not sure how to do this.

For example,

Next.js is able to read ./pages/ and ./next.config.js from the project root

Jest is able to read ./jest.config.js from the project root

ESLint is able to read ./.eslintrc.json from the project root

Prettier is able to read ./.prettierrc.js from the project root

Typescript is able to read ./tsconfig.json from the project root

Babel is able to read ./.babelrc from the project root

I've tried looking at their source code to see how they do it but the projects are so large that I can't find the relevant section.

How do they achieve this?

答:
They start from the directory the file lives in and recursively looks upwards in the file system tree until it finds the file it's looks for.

Something like this:

const FILE_NAME = 'target-file.json';

const fsp = require('fs').promises,
      path = require('path');

let find = async (dir=__dirname) => {
  let ls = await fsp.readdir(dir);
  if(ls.includes(FILE_NAME))
    return path.join(dir,FILE_NAME);
  else if(dir == '/')
    throw new Error(`Could not find ${FILE_NAME}`);
  else
    return find(path.resolve(dir,'..'));
}
```
<p>Or if you were looking for a standard node "project root" you might want to recurse up and find a directory containing a directory names 'node_modules' like this:</p>
<pre class="lang-js prettyprint-override"><code>const fsp = require('fs').promises,
      path = require('path');

let find = async (dir=__dirname) => {
  let ls = await fsp.readdir(dir);
  if(ls.includes('node_modules'))
    return dir;
  else if(dir == '/')
    throw new Error(`Could not find project root`);
  else
    return find(path.resolve(dir,'..'));
}
</code>```

Body:
They start from the directory the file lives in and recursively looks upwards in the file system tree until it finds the file it's looks for.

Something like this:

const FILE_NAME = 'target-file.json';

const fsp = require('fs').promises,
      path = require('path');

let find = async (dir=__dirname) => {
  let ls = await fsp.readdir(dir);
  if(ls.includes(FILE_NAME))
    return path.join(dir,FILE_NAME);
  else if(dir == '/')
    throw new Error(`Could not find ${FILE_NAME}`);
  else
    return find(path.resolve(dir,'..'));
}

Or if you were looking for a standard node "project root" you might want to recurse up and find a directory containing a directory names 'node_modules' like this:

const fsp = require('fs').promises,
      path = require('path');

let find = async (dir=__dirname) => {
  let ls = await fsp.readdir(dir);
  if(ls.includes('node_modules'))
    return dir;
  else if(dir == '/')
    throw new Error(`Could not find project root`);
  else
    return find(path.resolve(dir,'..'));
}


问:
Javascript: Replace a Shown Div with another Hidden Div with Button onclick
i want to replace a div that is already displayed with another Hidden div with just one click. i don't want it to toggle. below is the code.

```<code><html>

<script type="text/javascript">
function show(elementId) {
 document.getElementById("surf").style.display="none";
 document.getElementById(elementId).style.display="block";
}
</script>

<div id="mode" style="display: visible;">Display By Default</div>

<div id="surf" style="display: none;">Display On Click</div>
<br/>
<button type="submit" id="submit" onclick="show('surf');" name="submit">Submit</button>
</html>
</code>```

My desired output should be Display On Click when i click the button.

But right now i'm having both Display By Default and Display On Click showing when i click the button display by default at the top and Display On Click at button. i just want Display By Default to be replaced with Display On Click on same line.

答:
```<code><!DOCTYPE html>
  <html>
  <body>
    <div id="div1" style="display:block">
    <h2>first div</h2>
</div>
<div id="div2" style="display:none">
    <h2>second div</h2>
</div>
<button onclick=show()>click here</button>
</body>
<script>
function show() {
    let div1 = document.querySelector('#div1');
    let div2 = document.querySelector('#div2');

    if (div1.style.display == "block") {
        div1.style.display = "none";
        div2.style.display = "block";
    } else {
        div1.style.display = "block";
        div2.style.display = "none";
    }

  }
</script>
</html>
</code>```

onclick to hide div1 and show div2,
Next click hide div2 and show div1.

Body:
i want to replace a div that is already displayed with another Hidden div with just one click. i don't want it to toggle. below is the code.

Display By Default

Display On Click

<button type="submit" id="submit" onclick="show('surf');" name="submit">Submit</button>

My desired output should be Display On Click when i click the button.

But right now i'm having both Display By Default and Display On Click showing when i click the button display by default at the top and Display On Click at button. i just want Display By Default to be replaced with Display On Click on same line.

Body:
<!DOCTYPE html>
  <html>
  <body>
    <div id="div1" style="display:block">
    <h2>first div</h2>
</div>
<div id="div2" style="display:none">
    <h2>second div</h2>
</div>
<button onclick=show()>click here</button>
</body>
<script>
function show() {
    let div1 = document.querySelector('#div1');
    let div2 = document.querySelector('#div2');

    if (div1.style.display == "block") {
        div1.style.display = "none";
        div2.style.display = "block";
    } else {
        div1.style.display = "block";
        div2.style.display = "none";
    }

  }
</script>
</html>

onclick to hide div1 and show div2,
Next click hide div2 and show div1.


问:
Exception while writing multipart empty csv file from Apache Beam into netApp Storage Grid
Problem Statement

We are consuming multiple csv files into pcollections -> Apply beam SQL to transform data -> write resulted pcollection.
This is working absolutely fine if we have some data in all the source pCollections and beam SQL generates new collection with some data.
When Transform pCollection is generating empty pCollection and when writing that in netApp Storage Grid it is throwing below,

```<code>Exception in thread "main" org.apache.beam.sdk.Pipeline$PipelineExecutionException: java.io.IOException: Failed closing channel to s3://bucket-name/.temp-beam-847f362f-8884-454e-bfbe-baf9a4e32806/0b72948a5fcccb28-174f-426b-a225-ae3d3cbb126f
    at org.apache.beam.runners.direct.DirectRunner$DirectPipelineResult.waitUntilFinish(DirectRunner.java:373)
    at org.apache.beam.runners.direct.DirectRunner$DirectPipelineResult.waitUntilFinish(DirectRunner.java:341)
    at org.apache.beam.runners.direct.DirectRunner.run(DirectRunner.java:218)
    at org.apache.beam.runners.direct.DirectRunner.run(DirectRunner.java:67)
    at org.apache.beam.sdk.Pipeline.run(Pipeline.java:323)
    at org.apache.beam.sdk.Pipeline.run(Pipeline.java:309)
    at ECSOperations.main(ECSOperations.java:53)
Caused by: java.io.IOException: Failed closing channel to s3://bucket-name/.temp-beam-847f362f-8884-454e-bfbe-baf9a4e32806/0b72948a5fcccb28-174f-426b-a225-ae3d3cbb126f
    at org.apache.beam.sdk.io.FileBasedSink$Writer.close(FileBasedSink.java:1076)
    at org.apache.beam.sdk.io.FileBasedSink$WriteOperation.createMissingEmptyShards(FileBasedSink.java:759)
    at org.apache.beam.sdk.io.FileBasedSink$WriteOperation.finalizeDestination(FileBasedSink.java:639)
    at org.apache.beam.sdk.io.WriteFiles$FinalizeTempFileBundles$FinalizeFn.process(WriteFiles.java:1040)
Caused by: java.io.IOException: com.amazonaws.services.s3.model.AmazonS3Exception: Your proposed upload is smaller than the minimum allowed object size. (Service: Amazon S3; Status Code: 400; Error Code: EntityTooSmall; Request ID: 1643869619144605; S3 Extended Request ID: null; Proxy: null), S3 Extended Request ID: null
</code>```

Following is sample code

```<code>ECSOptions options = PipelineOptionsFactory.fromArgs(args).as(ECSOptions.class);
setupConfiguration(options);
Pipeline p = Pipeline.create(options);
PCollection<String> pSource= p.apply(TextIO.read().from("src/main/resources/empty.csv"));
pSource.apply(TextIO.write().to("s3://bucket-name/empty.csv").withoutSharding());
p.run();
</code>```

Observation

It is working fine if we write simple file and not multipart file(simple put object to Storage Grid)

Seems its known issue with Storage Grid but we want to check whether we can handle this from beam pipeline or not.

What I have tried

Tried to see if I can check size of PCollection before writing and put some string into output file but since PCollection is empty it is not going in PTransform at all.

Tried with Count.globally as well but that event didn't help

Ask

Is there anyway we can handle this in Beam like we can check size of the PCollection before writing? and if size is zero i.e. empty pcollection so we can avoid writing file to avoid this issue.

Has anyone faced similar issue and able to sort out?

答: You can't check to see if the PCollection is empty during pipeline construction, as it has not been computed yet. If this filesystem can't support empty files, you could try writing to another filesystem and then copying iff the file is not empty (assuming the file in question is not too large).</p>

Body:
Problem Statement

We are consuming multiple csv files into pcollections -> Apply beam SQL to transform data -> write resulted pcollection.
This is working absolutely fine if we have some data in all the source pCollections and beam SQL generates new collection with some data.
When Transform pCollection is generating empty pCollection and when writing that in netApp Storage Grid it is throwing below,

Exception in thread "main" org.apache.beam.sdk.Pipeline$PipelineExecutionException: java.io.IOException: Failed closing channel to s3://bucket-name/.temp-beam-847f362f-8884-454e-bfbe-baf9a4e32806/0b72948a5fcccb28-174f-426b-a225-ae3d3cbb126f
    at org.apache.beam.runners.direct.DirectRunner$DirectPipelineResult.waitUntilFinish(DirectRunner.java:373)
    at org.apache.beam.runners.direct.DirectRunner$DirectPipelineResult.waitUntilFinish(DirectRunner.java:341)
    at org.apache.beam.runners.direct.DirectRunner.run(DirectRunner.java:218)
    at org.apache.beam.runners.direct.DirectRunner.run(DirectRunner.java:67)
    at org.apache.beam.sdk.Pipeline.run(Pipeline.java:323)
    at org.apache.beam.sdk.Pipeline.run(Pipeline.java:309)
    at ECSOperations.main(ECSOperations.java:53)
Caused by: java.io.IOException: Failed closing channel to s3://bucket-name/.temp-beam-847f362f-8884-454e-bfbe-baf9a4e32806/0b72948a5fcccb28-174f-426b-a225-ae3d3cbb126f
    at org.apache.beam.sdk.io.FileBasedSink$Writer.close(FileBasedSink.java:1076)
    at org.apache.beam.sdk.io.FileBasedSink$WriteOperation.createMissingEmptyShards(FileBasedSink.java:759)
    at org.apache.beam.sdk.io.FileBasedSink$WriteOperation.finalizeDestination(FileBasedSink.java:639)
    at org.apache.beam.sdk.io.WriteFiles$FinalizeTempFileBundles$FinalizeFn.process(WriteFiles.java:1040)
Caused by: java.io.IOException: com.amazonaws.services.s3.model.AmazonS3Exception: Your proposed upload is smaller than the minimum allowed object size. (Service: Amazon S3; Status Code: 400; Error Code: EntityTooSmall; Request ID: 1643869619144605; S3 Extended Request ID: null; Proxy: null), S3 Extended Request ID: null

Following is sample code

ECSOptions options = PipelineOptionsFactory.fromArgs(args).as(ECSOptions.class);
setupConfiguration(options);
Pipeline p = Pipeline.create(options);
PCollection<String> pSource= p.apply(TextIO.read().from("src/main/resources/empty.csv"));
pSource.apply(TextIO.write().to("s3://bucket-name/empty.csv").withoutSharding());
p.run();

Observation

It is working fine if we write simple file and not multipart file(simple put object to Storage Grid)

Seems its known issue with Storage Grid but we want to check whether we can handle this from beam pipeline or not.

What I have tried

Tried to see if I can check size of PCollection before writing and put some string into output file but since PCollection is empty it is not going in PTransform at all.

Tried with Count.globally as well but that event didn't help

Ask

Is there anyway we can handle this in Beam like we can check size of the PCollection before writing? and if size is zero i.e. empty pcollection so we can avoid writing file to avoid this issue.

Has anyone faced similar issue and able to sort out?


问:
How does "apt-get install" work to download a file?
I have recently started using Ubuntu and am confused as to how the Linux package system is run and operated. Does a company (i.e. Canonical or Azure (if you are using WSL)) own and run the package installing servers, or is it community-based like a torrent if you know what I mean? I can imagine the server resources would be very expensive.</p>

答: The servers are called package repositories and some of them are already added to /etc/apt/sources.list or similar file by the creators of your linux distridution (in your case, Ubuntu). You can freely add new repositories hosted by other companies and individuals to your list or remove existing ones.


答:
You are targeting the wrong element here document.getElementById("surf").style.display="none";. The "surf" should be "mode" instead. This worked for me

function show(elementId) {
    document.getElementById("mode").style.display="none";
    document.getElementById(elementId).style.display="block";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="mode" style="display: visible;">Display By Default</div>
<div id="surf" style="display: none;">Display On Click</div>
<br/>
<button type="submit" id="submit" onclick="show('surf');" name="submit">Submit</button></code>```

Title: Javascript: Replace a Shown Div with another Hidden Div with Button onclick

Body:
You are targeting the wrong element here document.getElementById("surf").style.display="none";. The "surf" should be "mode" instead. This worked for me

function show(elementId) {
    document.getElementById("mode").style.display="none";
    document.getElementById(elementId).style.display="block";
}

<div id="mode" style="display: visible;">Display By Default</div>
<div id="surf" style="display: none;">Display On Click</div>
<br/>
<button type="submit" id="submit" onclick="show('surf');" name="submit">Submit</button>


问:
ERC721 Minted NFT not showing on Opensea.io testnet
I run my code on rinkeby etherscan network and it works perfectly. But the image and descriptions are not showing on opensea testnet. I run the /validate/ url it shows Valid: "false".

Here is what I found when I force update on opensea, https://testnets-api.opensea.io/api/v1/asset/0x668D179B933af761e4732B084290D32B3235C22b/0/?force_update=true

Here is my code:

```<code>    // SPDX-License-Identifier: MIT
pragma solidity ^0.8.2;

import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "./ERC2981ContractWideRoyalties.sol";
import "hardhat/console.sol";

contract SmoothApe is ERC721URIStorage, Ownable, ERC2981ContractWideRoyalties {
    using Counters for Counters.Counter;
    using Strings for uint256;

    Counters.Counter private _tokenIdCounter;

    event EmitNFT(address sender, uint256 tokenId);

    uint256 public preSaleTokenPrice = 0.01 ether;
    uint256 public costPrice = 0.02 ether;
    uint256 public maxSupply = 10000;
    uint256 public maxMintNft = 10;

    string public baseURI;
    string public baseExtension = ".json";
    string public notRevealedUri;

    bool public paused = false;
    bool public revealed = true;
    bool public presale = false;

    // set 0x7350243981aB92E2A3646e377EBbFC28e9DE96C1 as payable admn wallet
    address payable public adminWallet = payable(0xAb8483F64d9C6d1EcF9b849Ae677dD3315835cb2);
    address payable public communityWallet = payable(0x4B20993Bc481177ec7E8f571ceCaE8A9e22C02db);
    address payable public t1Wallet = payable(0x78731D3Ca6b7E34aC0F824c42a7cC18A495cabaB);
    address payable public t2Wallet = payable(0x617F2E2fD72FD9D5503197092aC168c91465E7f2);
    address payable public t3Wallet = payable(0x17F6AD8Ef982297579C203069C1DbfFE4348c372);

    // Mapping from token ID to owner address
    mapping(uint256 => address) private _owners;

    constructor(string memory _name, string memory _symbol,string memory _initBaseURI, string memory _initNotRevealedUri) ERC721(_name, _symbol) {
        setBaseURI(_initBaseURI);
        setNotRevealedUri(_initNotRevealedUri);
    }

    // inherit and override erc165
    function supportsInterface(bytes4 interfaceId) public view virtual override (ERC721, ERC2981Base) returns (bool) {
        return super.supportsInterface(interfaceId);
    }

    // set Royalty value (between 0 and 10000)
    function setRoyalties(address recipient, uint256 value) public onlyOwner {
        _setRoyalties(recipient, value);
    }

    function _baseURI() internal view override returns (string memory) {
        return baseURI;
    }

    function mintApe() public payable {
        uint256 tokenId = _tokenIdCounter.current();
        require(!paused, "Minting is paused");
        require(msg.sender != owner(), "You can't mint ape to admin");
        // require(_mintAmount > 0, "Mint amount must be greater than 0");
        // require(_mintAmount <= maxSupply, "Mint amount must be less than or equal to max supply");
        if(presale == true) {
            preSaleTokenPrice = costPrice;

        }
        require(msg.value >= costPrice, string(abi.encodePacked("Must send at least ", costPrice.toString(), " ether to purchase")));
        require(balanceOf(msg.sender) < maxMintNft, "You can only own 11 ape at a time");
        // require(_mintAmount + balanceOf(msg.sender) <= maxMintNft, "You can only own 10 ape at a time");
        // adminWallet.transfer(msg.value);
        payable(owner()).transfer(msg.value);
        emit EmitNFT(msg.sender, tokenId);
        // for(uint256 i = 1; i <= _mintAmount; i++){
        _safeMint(msg.sender, tokenId);
        // _setTokenURI(tokenId, _baseURI());
        _tokenIdCounter.increment();
        // }
    }

    // admin mint ape to wallet
    function mintApeTo(address _to, uint256 _mintAmount) public onlyOwner {
        require(!paused, "Minting is paused");
        require(_mintAmount > 0, "Mint amount must be greater than 0");
        require(_mintAmount <= maxSupply, "Mint amount must be less than or equal to max supply");
        for(uint256 i = 1; i <= _mintAmount; i++){
            uint256 tokenId = _tokenIdCounter.current();
            _safeMint(_to, tokenId);
            // _setTokenURI(tokenId, _baseURI());
            _tokenIdCounter.increment();
        }
    }

    function getCostPrice() public view virtual returns (uint256) {
        return costPrice;
    }
    //  function to set cost of ape
    function setCost(uint256 _preSaleTokenPrice, uint256 _publicTokenPrice) public onlyOwner {
        preSaleTokenPrice = _preSaleTokenPrice;
        costPrice = _publicTokenPrice;
    }
    // set presale to true
    function setPresale(bool _presale) public onlyOwner {
        presale = _presale;
    }
    function reveal(bool _reveal) public onlyOwner {
        revealed = _reveal;
    }
    // pause function
    function pause() public onlyOwner {
        paused = true;
    }
    // set function for setBaseURI and setNotRevealed function
    function setBaseURI(string memory _newBaseURI) public onlyOwner {
        baseURI = _newBaseURI;
    }

    function setTokenURI(uint256 _tokenId, string memory _tokenURI) public onlyOwner {
        _setTokenURI(_tokenId, _tokenURI);
    }

    // override tokenURI function
    function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
        require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
        require(tokenId < _tokenIdCounter.current(), "Token ID must be less than the total supply");
        if(!revealed) {
            return notRevealedUri;
        }
        string memory currentBaseURI = _baseURI();
        return bytes(currentBaseURI).length > 0
            ? string(
                abi.encodePacked(
                    currentBaseURI,
                    tokenId.toString(),
                    baseExtension))
                    : "";
    }
}
</code>```

Here is a sample of NFT i mint:
https://testnets.opensea.io/assets/0x668D179B933af761e4732B084290D32B3235C22b/0

my ipfs CID:
ipfs://QmaoMZ19zhpC6T4id6jdBP1Qz5dQSmRZMkQZU7Zt8hyFNQ/

答:
I had the same problem. Turned out that I wasn't uploading the images to ipfs correctly because it was visible only to me on my machine. So try to see if the ipfs metadata are correctly formated and are accesible from different devices.

Also you shouldn't just paste your entire contract in. Tt is really hard to answer your question then. Just write out the important sections of the code.

Body:
I run my code on rinkeby etherscan network and it works perfectly. But the image and descriptions are not showing on opensea testnet. I run the /validate/ url it shows Valid: "false".

Here is what I found when I force update on opensea, https://testnets-api.opensea.io/api/v1/asset/0x668D179B933af761e4732B084290D32B3235C22b/0/?force_update=true

Here is my code:

    // SPDX-License-Identifier: MIT
pragma solidity ^0.8.2;

import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "./ERC2981ContractWideRoyalties.sol";
import "hardhat/console.sol";

contract SmoothApe is ERC721URIStorage, Ownable, ERC2981ContractWideRoyalties {
    using Counters for Counters.Counter;
    using Strings for uint256;

    Counters.Counter private _tokenIdCounter;

    event EmitNFT(address sender, uint256 tokenId);

    uint256 public preSaleTokenPrice = 0.01 ether;
    uint256 public costPrice = 0.02 ether;
    uint256 public maxSupply = 10000;
    uint256 public maxMintNft = 10;

    string public baseURI;
    string public baseExtension = ".json";
    string public notRevealedUri;

    bool public paused = false;
    bool public revealed = true;
    bool public presale = false;

    // set 0x7350243981aB92E2A3646e377EBbFC28e9DE96C1 as payable admn wallet
    address payable public adminWallet = payable(0xAb8483F64d9C6d1EcF9b849Ae677dD3315835cb2);
    address payable public communityWallet = payable(0x4B20993Bc481177ec7E8f571ceCaE8A9e22C02db);
    address payable public t1Wallet = payable(0x78731D3Ca6b7E34aC0F824c42a7cC18A495cabaB);
    address payable public t2Wallet = payable(0x617F2E2fD72FD9D5503197092aC168c91465E7f2);
    address payable public t3Wallet = payable(0x17F6AD8Ef982297579C203069C1DbfFE4348c372);

    // Mapping from token ID to owner address
    mapping(uint256 => address) private _owners;

    constructor(string memory _name, string memory _symbol,string memory _initBaseURI, string memory _initNotRevealedUri) ERC721(_name, _symbol) {
        setBaseURI(_initBaseURI);
        setNotRevealedUri(_initNotRevealedUri);
    }

    // inherit and override erc165
    function supportsInterface(bytes4 interfaceId) public view virtual override (ERC721, ERC2981Base) returns (bool) {
        return super.supportsInterface(interfaceId);
    }

    // set Royalty value (between 0 and 10000)
    function setRoyalties(address recipient, uint256 value) public onlyOwner {
        _setRoyalties(recipient, value);
    }

    function _baseURI() internal view override returns (string memory) {
        return baseURI;
    }

    function mintApe() public payable {
        uint256 tokenId = _tokenIdCounter.current();
        require(!paused, "Minting is paused");
        require(msg.sender != owner(), "You can't mint ape to admin");
        // require(_mintAmount > 0, "Mint amount must be greater than 0");
        // require(_mintAmount <= maxSupply, "Mint amount must be less than or equal to max supply");
        if(presale == true) {
            preSaleTokenPrice = costPrice;

        }
        require(msg.value >= costPrice, string(abi.encodePacked("Must send at least ", costPrice.toString(), " ether to purchase")));
        require(balanceOf(msg.sender) < maxMintNft, "You can only own 11 ape at a time");
        // require(_mintAmount + balanceOf(msg.sender) <= maxMintNft, "You can only own 10 ape at a time");
        // adminWallet.transfer(msg.value);
        payable(owner()).transfer(msg.value);
        emit EmitNFT(msg.sender, tokenId);
        // for(uint256 i = 1; i <= _mintAmount; i++){
        _safeMint(msg.sender, tokenId);
        // _setTokenURI(tokenId, _baseURI());
        _tokenIdCounter.increment();
        // }
    }

    // admin mint ape to wallet
    function mintApeTo(address _to, uint256 _mintAmount) public onlyOwner {
        require(!paused, "Minting is paused");
        require(_mintAmount > 0, "Mint amount must be greater than 0");
        require(_mintAmount <= maxSupply, "Mint amount must be less than or equal to max supply");
        for(uint256 i = 1; i <= _mintAmount; i++){
            uint256 tokenId = _tokenIdCounter.current();
            _safeMint(_to, tokenId);
            // _setTokenURI(tokenId, _baseURI());
            _tokenIdCounter.increment();
        }
    }

    function getCostPrice() public view virtual returns (uint256) {
        return costPrice;
    }
    //  function to set cost of ape
    function setCost(uint256 _preSaleTokenPrice, uint256 _publicTokenPrice) public onlyOwner {
        preSaleTokenPrice = _preSaleTokenPrice;
        costPrice = _publicTokenPrice;
    }
    // set presale to true
    function setPresale(bool _presale) public onlyOwner {
        presale = _presale;
    }
    function reveal(bool _reveal) public onlyOwner {
        revealed = _reveal;
    }
    // pause function
    function pause() public onlyOwner {
        paused = true;
    }
    // set function for setBaseURI and setNotRevealed function
    function setBaseURI(string memory _newBaseURI) public onlyOwner {
        baseURI = _newBaseURI;
    }

    function setTokenURI(uint256 _tokenId, string memory _tokenURI) public onlyOwner {
        _setTokenURI(_tokenId, _tokenURI);
    }

    // override tokenURI function
    function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
        require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
        require(tokenId < _tokenIdCounter.current(), "Token ID must be less than the total supply");
        if(!revealed) {
            return notRevealedUri;
        }
        string memory currentBaseURI = _baseURI();
        return bytes(currentBaseURI).length > 0
            ? string(
                abi.encodePacked(
                    currentBaseURI,
                    tokenId.toString(),
                    baseExtension))
                    : "";
    }
}

Here is a sample of NFT i mint:
https://testnets.opensea.io/assets/0x668D179B933af761e4732B084290D32B3235C22b/0

my ipfs CID:
ipfs://QmaoMZ19zhpC6T4id6jdBP1Qz5dQSmRZMkQZU7Zt8hyFNQ/


问:
Why do I get a segmentation fault when calling a virtual method in this code?
I'm still learning C++; I was trying out how polymorphism works and I got a segmentation fault when calling a virtual method.

(Note: I didn't mark the destructor as virtual, I was just trying out to see what happens.) Here's the code:

```<code>#include <iostream>

using namespace std;

class Base
{
protected:
  char *name;

public:
  Base(char *name)
  {
    cout << name << ": Base class cons" << endl;
  }

  ~Base()
  {
    cout << name << ": Base class des" << endl;
  }

  virtual void disp();
};

void Base::disp()
{
  cout << name << ": Base disp()" << endl;
}

class Child : public Base
{
public:
  Child(char *name):
    Base(name)
  {
    cout << name << ": Child class cons" << endl;
  }

  ~Child()
  {
    cout << name << ": Child class des" << endl;
  }

  virtual void disp()
  {
    cout << name << ": Child disp()" << endl;
  }
};

int main()
{
  //Base b;
  //b.disp();
  Base c = Child("2");
  c.disp();
}
</code>```

Also, if you've any other tips regarding the usage of inheritance and polymorphism in general for someone who knows these concepts in Java, please let me know. Thank you!

答:
You have a couple of problems with your code.

First, and the reason why your getting a segfault, is the implementation of the Base ctor takes a parameter of the same name as one of the class' member variables:

```<code>class Base
{
protected:
  char *name;

public:
  Base(char ***name**)
  {
    cout << name << ": Base class cons" << endl;
  }
</code>```

The ctor's parameter 'name' hides the class' member variable of the same, erm... name.

Second, you are slicing your object here:

```<code>int main()
{
  //Base b;
  //b.disp();
  Base c = Child("2");
  c.disp();
}
</code>```

'c' is of type Base, and you are trying to assign a Child to it.  All of the stuff that is unique to Child will be sliced off when you assign the ogbject to the base class.

Here is code that fixes both these problems:

```<code>#include <iostream>
#include <string>

using namespace std;

class Base
{
protected:
    std::string name_;

public:
  Base(char *name)
      : name_(name) {
    cout << name_ << ": Base class cons" << endl;
  }

  ~Base()
  {
    cout << name_ << ": Base class des" << endl;
  }

  virtual void disp();
};

void Base::disp()
{
  cout << name_ << ": Base disp()" << endl;
}

class Child : public Base
{
public:
  Child(char *name):
    Base(name)
  {
    cout << name_ << ": Child class cons" << endl;
  }

  ~Child()
  {
    cout << name_ << ": Child class des" << endl;
  }

  virtual void disp()
  {
    cout << name_ << ": Child disp()" << endl;
  }
};

int main()
{
  //Base b;
  //b.disp();
  Base * c = new Child("2");
  c->disp();
  delete c;
}
</code>```

OwnerDisplayName: Srikanth

ContentLicense: CC BY-SA 2.5

Body:
I'm still learning C++; I was trying out how polymorphism works and I got a segmentation fault when calling a virtual method.

(Note: I didn't mark the destructor as virtual, I was just trying out to see what happens.) Here's the code:

#include <iostream>

using namespace std;

class Base
{
protected:
  char *name;

public:
  Base(char *name)
  {
    cout << name << ": Base class cons" << endl;
  }

  ~Base()
  {
    cout << name << ": Base class des" << endl;
  }

  virtual void disp();
};

void Base::disp()
{
  cout << name << ": Base disp()" << endl;
}

class Child : public Base
{
public:
  Child(char *name):
    Base(name)
  {
    cout << name << ": Child class cons" << endl;
  }

  ~Child()
  {
    cout << name << ": Child class des" << endl;
  }

  virtual void disp()
  {
    cout << name << ": Child disp()" << endl;
  }
};

int main()
{
  //Base b;
  //b.disp();
  Base c = Child("2");
  c.disp();
}

Also, if you've any other tips regarding the usage of inheritance and polymorphism in general for someone who knows these concepts in Java, please let me know. Thank you!

Body:
You have a couple of problems with your code.

First, and the reason why your getting a segfault, is the implementation of the Base ctor takes a parameter of the same name as one of the class' member variables:

class Base
{
protected:
  char *name;

public:
  Base(char ***name**)
  {
    cout << name << ": Base class cons" << endl;
  }

The ctor's parameter 'name' hides the class' member variable of the same, erm... name.

Second, you are slicing your object here:

int main()
{
  //Base b;
  //b.disp();
  Base c = Child("2");
  c.disp();
}

'c' is of type Base, and you are trying to assign a Child to it.  All of the stuff that is unique to Child will be sliced off when you assign the ogbject to the base class.

Here is code that fixes both these problems:

#include <iostream>
#include <string>

using namespace std;

class Base
{
protected:
    std::string name_;

public:
  Base(char *name)
      : name_(name) {
    cout << name_ << ": Base class cons" << endl;
  }

  ~Base()
  {
    cout << name_ << ": Base class des" << endl;
  }

  virtual void disp();
};

void Base::disp()
{
  cout << name_ << ": Base disp()" << endl;
}

class Child : public Base
{
public:
  Child(char *name):
    Base(name)
  {
    cout << name_ << ": Child class cons" << endl;
  }

  ~Child()
  {
    cout << name_ << ": Child class des" << endl;
  }

  virtual void disp()
  {
    cout << name_ << ": Child disp()" << endl;
  }
};

int main()
{
  //Base b;
  //b.disp();
  Base * c = new Child("2");
  c->disp();
  delete c;
}

OwnerDisplayName: John Dibling


问:
Distinguish between NULL and not present using JSON Merge Patch with NetCore WebApi and System.Text.Json
I want to support partial updates with JSON Merge Patch. The domain model is based on the always valid concept and has no public setters. Therefore I can't just apply the changes to the class types. I need to translate the changes to the specific commands.

Since classes have nullable properties I need to be able to distinguish between properties set to null and not provided.

I'm aware of JSON Patch. I could use patch.JsonPatchDocument.Operations to go through the list of changes. JSON Patch is just verbose and more difficult for the client. JSON Patch requires to use Newtonsoft.Json (Microsoft states an option to change Startup.ConfigureServices to only use Newtonsoft.Json for JSON Patch (https://learn.microsoft.com/en-us/aspnet/core/web-api/jsonpatch?view=aspnetcore-6.0).

Newtonsoft supports IsSpecified-Properties that can be used as a solution for JSON Merge Patch in the DTO classes (How to make Json.NET set IsSpecified properties for properties with complex values?). This would solve the problem, but again requires Newtonsoft. System.Text.Json does not support this feature. There is an open issue for 2 years (https://github.com/dotnet/runtime/issues/40395), but nothing to expect.

There is a post that describes a solution with a custom JsonConverter for Web API (https://github.com/dotnet/runtime/issues/40395). Would this solution still be usable for NetCore?

I was wondering if there is an option to access the raw json or a json object inside the controller method after the DTO object was filled. Then I could manually check if a property was set. Web Api closes the stream, so I can't access the body anymore. It seems there are ways to change that behavior (https://gunnarpeipman.com/aspnet-core-request-body/#comments). It seems quite complicated and feels like a gun that is too big. I also don't understand what changes were made for NetCore 6.

I'm surpised that such a basic problem needs one to jump through so many loops. Is there an easy way to accomplish my goal with System.Text.Json and NetCore 6? Are there other options? Would using Newtonsoft have any other bad side effects?

答:
With the helpful comments of jhmckimm I found
Custom JSON serializer for optional property with System.Text.Json. DBC shows a fantastic solution using Text.Json and Optional<T>. This should be in the Microsoft docs!

In Startup I added:

```<code>services.AddControllers()
  .AddJsonOptions(o => o.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingDefault)
  .AddJsonOptions(o => o.JsonSerializerOptions.Converters.Add(new OptionalConverter()));
</code>```

Since we use <Nullable>enable</Nullable> and   <WarningsAsErrors>nullable</WarningsAsErrors> I adapted the code for nullables.

```<code>public readonly struct Optional<T>
    {
        public Optional(T? value)
        {
            this.HasValue = true;
            this.Value = value;
        }

        public bool HasValue { get; }
        public T? Value { get; }
        public static implicit operator Optional<T>(T value) => new Optional<T>(value);
        public override string ToString() => this.HasValue ? (this.Value?.ToString() ?? "null") : "unspecified";
    }

public class OptionalConverter : JsonConverterFactory
    {
        public override bool CanConvert(Type typeToConvert)
        {
            if (!typeToConvert.IsGenericType) { return false; }
            if (typeToConvert.GetGenericTypeDefinition() != typeof(Optional<>)) { return false; }
            return true;
        }

        public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options)
        {
            Type valueType = typeToConvert.GetGenericArguments()[0];

            return (JsonConverter)Activator.CreateInstance(
                type: typeof(OptionalConverterInner<>).MakeGenericType(new Type[] { valueType }),
                bindingAttr: BindingFlags.Instance | BindingFlags.Public,
                binder: null,
                args: null,
                culture: null
            )!;
        }

        private class OptionalConverterInner<T> : JsonConverter<Optional<T>>
        {
            public override Optional<T> Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
            {
                T? value = JsonSerializer.Deserialize<T>(ref reader, options);
                return new Optional<T>(value);
            }

            public override void Write(Utf8JsonWriter writer, Optional<T> value, JsonSerializerOptions options) =>
                JsonSerializer.Serialize(writer, value.Value, options);
        }
    }
</code>```

My test DTO looks like this:

```<code>public class PatchGroupDTO
    {
        public Optional<Guid?> SalesGroupId { get; init; }

        public Optional<Guid?> AccountId { get; init; }

        public Optional<string?> Name { get; init; }

        public Optional<DateTime?> Start { get; init; }

        public Optional<DateTime?> End { get; init; }
    }
</code>```

I can now access the fields and check with .HasValue if the value was set. It also works for writing and allows us to stripe fields based on permission.

Body:
With the helpful comments of jhmckimm I found
Custom JSON serializer for optional property with System.Text.Json. DBC shows a fantastic solution using Text.Json and Optional<T>. This should be in the Microsoft docs!

In Startup I added:

services.AddControllers()
  .AddJsonOptions(o => o.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingDefault)
  .AddJsonOptions(o => o.JsonSerializerOptions.Converters.Add(new OptionalConverter()));

Since we use <Nullable>enable</Nullable> and   <WarningsAsErrors>nullable</WarningsAsErrors> I adapted the code for nullables.

public readonly struct Optional<T>
    {
        public Optional(T? value)
        {
            this.HasValue = true;
            this.Value = value;
        }

        public bool HasValue { get; }
        public T? Value { get; }
        public static implicit operator Optional<T>(T value) => new Optional<T>(value);
        public override string ToString() => this.HasValue ? (this.Value?.ToString() ?? "null") : "unspecified";
    }

public class OptionalConverter : JsonConverterFactory
    {
        public override bool CanConvert(Type typeToConvert)
        {
            if (!typeToConvert.IsGenericType) { return false; }
            if (typeToConvert.GetGenericTypeDefinition() != typeof(Optional<>)) { return false; }
            return true;
        }

        public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options)
        {
            Type valueType = typeToConvert.GetGenericArguments()[0];

            return (JsonConverter)Activator.CreateInstance(
                type: typeof(OptionalConverterInner<>).MakeGenericType(new Type[] { valueType }),
                bindingAttr: BindingFlags.Instance | BindingFlags.Public,
                binder: null,
                args: null,
                culture: null
            )!;
        }

        private class OptionalConverterInner<T> : JsonConverter<Optional<T>>
        {
            public override Optional<T> Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
            {
                T? value = JsonSerializer.Deserialize<T>(ref reader, options);
                return new Optional<T>(value);
            }

            public override void Write(Utf8JsonWriter writer, Optional<T> value, JsonSerializerOptions options) =>
                JsonSerializer.Serialize(writer, value.Value, options);
        }
    }

My test DTO looks like this:

public class PatchGroupDTO
    {
        public Optional<Guid?> SalesGroupId { get; init; }

        public Optional<Guid?> AccountId { get; init; }

        public Optional<string?> Name { get; init; }

        public Optional<DateTime?> Start { get; init; }

        public Optional<DateTime?> End { get; init; }
    }

I can now access the fields and check with .HasValue if the value was set. It also works for writing and allows us to stripe fields based on permission.


问:
R Shiny: using a reactive output in UI
I'm building a shiny app that will sum population counts by user-defined cut points. could be any number of cut points from 0-100.

my thought is to have the user define the number of age categories they want and then have them enter in the ranges. To do this I installed the package shinyMatrix.

Ideally, I'd like the number of rows in the matrix to be equal to the number of cuts the user defined but this requires a reactive value in the UI function.

```<code>ui <- shinyUI(fluidPage(
  sidebarLayout(sidebarPanel(
    numericInput("breaks", "Enter number of age groups", 0, min= 1, max= 100),
    matrixInput("grid", value= matrix(NA,6,2, dimnames = list(NULL, c("lower", "upper"))),
                  rows = list(extend = TRUE),
                  cols = list(names = TRUE)),
    actionButton("calc", "Calculate")
  ),
  mainPanel(
    h4("Population Sum by group"),
    dataTableOutput("table")
  )
  )
))
</code>```

so where the 6 is in the matrixInput it should be something like output$breaks

答:
You could use updateMatrixInput on the server side to update the "grid", setting the number of rows equal to input$breaks

```<code>  observeEvent(input$breaks, {
    updateMatrixInput(session,inputId = "grid",
                      value = matrix(NA,input$breaks,2,dimnames =list(NULL,c("lower","upper"))))
  })
</code>```

Title: R Shiny: using a reactive output in UI

Body:
I'm building a shiny app that will sum population counts by user-defined cut points. could be any number of cut points from 0-100.

my thought is to have the user define the number of age categories they want and then have them enter in the ranges. To do this I installed the package shinyMatrix.

Ideally, I'd like the number of rows in the matrix to be equal to the number of cuts the user defined but this requires a reactive value in the UI function.

ui <- shinyUI(fluidPage(
  sidebarLayout(sidebarPanel(
    numericInput("breaks", "Enter number of age groups", 0, min= 1, max= 100),
    matrixInput("grid", value= matrix(NA,6,2, dimnames = list(NULL, c("lower", "upper"))),
                  rows = list(extend = TRUE),
                  cols = list(names = TRUE)),
    actionButton("calc", "Calculate")
  ),
  mainPanel(
    h4("Population Sum by group"),
    dataTableOutput("table")
  )
  )
))

so where the 6 is in the matrixInput it should be something like output$breaks

Body:
You could use updateMatrixInput on the server side to update the "grid", setting the number of rows equal to input$breaks

  observeEvent(input$breaks, {
    updateMatrixInput(session,inputId = "grid",
                      value = matrix(NA,input$breaks,2,dimnames =list(NULL,c("lower","upper"))))
  })


问:
Javascript Countdown Timer Not Pulling Current Date
I've inherited a React project where a jQuery countdown timer is used to hide/display a button. If there is time left on the clock, the button below is unclickable and greyed out, else there is no time left on the clock the button is meant to be clickable and the countdown timer should then be hidden.

The timer counts down, but it is not pulling the correct date to count down to, so it won't expire for another 261 days. I've tried setting the date in the past so that the timer expires and no longer displays, thereby allowing the button to be clickable but that's not working.

I deployed this site as a static build at https://scarebearsnft.com, does that have something to do with it? That it can't get the current date and time from the system?

Handletimer.js

```<code>import $ from 'jquery';

export const HandleTimer = () => {
    var countDownDate = new Date("Oct 30, 2021 15:37:25").getTime();

    var x = setInterval(function() {

    var now = new Date().getTime();
    var distance = countDownDate - now;

    var days = Math.floor(distance / (1000 * 60 * 60 * 24));
    var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
    var seconds = Math.floor((distance % (1000 * 60)) / 1000);

    // If time is left, timer will be displayed and button will be disabled
    if (distance >0) {
        $(".time").show();

        $("#daysTimer").html(days);
        $("#hoursTimer").html(hours);
        $("#minutesTimer").html(minutes);
        $("#secondsTimer").html(seconds);

        $("#mintBtn").prop('disabled',true)
        $("#selectBtn").attr('disabled',true)
        $("#mintBtn").css({'background-color':'gray'})
        $(".mintBtn").hover(function(){
            $(this).css('color','white')
        })
        $("#selectBtn").css({'background-color':'gray'})

    }

    // If time has finished, timer will hide and button will be enabled
    else{
        clearInterval(x);
        $(".time").hide();

        $(".mintBtn").mouseover(function() {
            $(this).css("background-color","white");
            $(this).css("color","#850101");
        }).mouseout(function() {
            $(this).css("background-color","#850101");
            $(this).css("color","white");
        });
    }
    },1000);
}
</code>```

Topsection.js

```<code>import React, { useEffect, useState, useRef } from "react";
import { useDispatch, useSelector } from "react-redux";
import { connect } from "../redux/blockchain/blockchainActions";
import { fetchData } from "../redux/data/dataActions";
import { counter } from "../hooks/counter";
import Background from '../images/cover.jpeg';

const TopSection = () => {
  const [timeLeft, setTimeLeft] = React.useState(counter());
  const [mintvalue, setMintvalue] = React.useState(0);
  const dispatch = useDispatch();
  const blockchain = useSelector((state) => state.blockchain);
  const data = useSelector((state) => state.data);
  const [costOfNFT, setCost] = useState(0.005);

  const [claimingNft, setClaimingNft] = useState(false);

  const claimNFTs = (_amount) => {
    if (_amount <= 0) {
      alert("Enter some amount to mint your Scare Bears")
      return;
    }
    else if (_amount > 20){
      alert(`You cannot mint more than ${_amount} Scare Bears at a time`)
      return;
    }
    setClaimingNft(true);
    blockchain.smartContract.methods
      .mint(_amount)
      .send({
        to: "HIDDEN",
        from: blockchain.account,
        value: blockchain.web3.utils.toWei((22 * _amount).toString(), "ether"),
      })
      .once("error", (err) => {
        console.log(err);
        alert(err['message'])
        setClaimingNft(false);
      })
      .then((receipt) => {
        alert("You now own a Scare Bears. go visit Opensea.io to view it.")
        setClaimingNft(false);
        dispatch(fetchData(blockchain.account));
      });
  };
  const getData = () => {
    if (blockchain.account !== "" && blockchain.smartContract !== null) {
      dispatch(fetchData(blockchain.account));
    }
  };

  useEffect(() => {
    getData();
  }, [blockchain.account]);

  React.useEffect(() => {
    const id = setTimeout(() => {
      setTimeLeft(counter());
    }, 1000);

    return () => {
      clearTimeout(id);
    };
  });

  return (
    <>
      <div
        class="main d-flex align-items-md-center py-5 py-sm-0"
        style={{
          backgroundImage: `linear-gradient(rgba(0, 0, 0, 0.5), rgb(0, 0, 0)), url(${Background})`,
          //backgroundImage: `url(/images/Header.gif)`,
          backgroundRepeat: "no-repeat",
          backgroundSize: "cover",
        }}
      >
        <div className="main-section">

          <div class="row d-flex align-items-center" style={{
            marginTop: '43px'
            , justifyContent: 'center', paddingBottom: '75px'
          }}>
            <div class="col-md-4 col-lg-4 d-flex align-items-center ">
              <div class="col-12 d-flex flex-column">
                {Object.keys(timeLeft).length > 0 && (
                  <div class="row text-center justify-content-around time">
                    <div class="col-2 ">
                      <h3 id="daysTimer">{timeLeft.days}</h3>
                      <h4>Days</h4>
                    </div>
                    <div class="col-2">
                      <h3 id="hoursTimer">{timeLeft.hours}</h3>
                      <h4>Hrs</h4>
                    </div>
                    <div class="col-2">
                      <h3 id="minutesTimer">{timeLeft.minutes}</h3>
                      <h4>Min</h4>
                    </div>
                    <div class="col-2">
                      <h3 id="secondsTimer">{timeLeft.seconds}</h3>
                      <h4>Sec</h4>
                    </div>
                  </div>
                )}
                {blockchain.account === "" ||
                        blockchain.smartContract === null ? (
                <div className="row mint" style={{
                  marginLeft: '0px', marginRight: '0px'
                  , justifyContent: 'center'
                }}>

                  <div className="col-12">
                    <div class="row d-flex align-items-stretch mint-box-title"
                      style={{ borderColor: 'blanchedalmond', marginLeft: '0px', marginRight: '0px' }}>
                      <p class="col-md-12 text-center">
                        0/4444
                      </p>
                    </div>
                  </div>
                  <div>
                    <div class="d-flex align-items-stretch"
                      style={{ borderColor: 'blanchedalmond', marginLeft: '0px', marginRight: '0px' }}>
                      <h2 class="col-md-12 text-center">
                        ScareBears cost 22 MATIC
                      </h2>
                    </div>
                  </div>
                  <div className="col-12">
                    <div class="row right d-flex align-items-stretch"
                      style={{ borderColor: 'blanchedalmond', marginLeft: '0px', marginRight: '0px' }}>
                      <p class="col-md-12 text-center" style={{ fontSize: '12px' }}>
                        CONNECT TO THE POLYGON NETWORK
                      </p>
                    </div>
                    <div className="col-6" style={{ marginLeft: '25%' }}>
                    <button
                      class={"col-12 py-3  mintBtn"}
                      className={`col-12 py-2  mintBtn ${Object.keys(timeLeft).length > 0
                        ? "mint-btn-before"
                        : "mint-btn-after"
                        }`}
                      id="mintBtn"
                      disabled={Object.keys(timeLeft).length > 0}
                      onClick={(e) => {
                        e.preventDefault();
                        dispatch(connect());
                        getData();
                      }}
                    >
                      {!Object.keys(timeLeft).length > 0 ? "CONNECT" : "CONNECT"}
                    </button>
                    </div>
                  </div>

                </div>
                ):(

                  <div className="col-12" >
                    <div class="row d-flex align-items-stretch mint-box-title"
                      style={{ borderColor: 'blanchedalmond', marginLeft: '1px', marginRight: '0px' }}>
                      <p class="col-md-12 text-center">
                      {data.totalSupply}/4444
                      </p>
                    </div>

                    <div className="col-8"  style={{ marginLeft: '16%' }}>
                      <div className="number">
                        <span className="minus" onClick={() => setMintvalue((mintvalue > 0) ? mintvalue - 1 : mintvalue)}>-</span>
                        <input type="number" min="0" max="20" className="number-mint" value={mintvalue} />
                        <span className="plus" onClick={() => setMintvalue((mintvalue < 20) ? mintvalue + 1 : mintvalue)}>+</span>
                      </div>
                    </div>
                    <div className="col-8" style={{ marginLeft: '15%' }}>
                    <button
                      class={"col-12 py-3  mintBtn"}
                      className={`col-12 py-2  mintBtn ${Object.keys(timeLeft).length > 0
                        ? "mint-btn-before"
                        : "mint-btn-after"
                        }`}
                      id="mintBtn"
                      disabled={Object.keys(timeLeft).length > 0}
                      onClick={(e) => {
                        e.preventDefault();
                        claimNFTs(parseInt(mintvalue));
                        getData();
                      }}
                    >
                      {!Object.keys(timeLeft).length > 0 ? "Mint" : "Minted"}
                    </button>
                    </div>
                    <div className="row">
                    <div className="col-12">
                    <div>
                    <div class="row d-flex align-items-stretch mint-box-title"
                      style={{ borderColor: 'blanchedalmond', marginLeft: '0px', marginRight: '0px' }}>
                      <h2 class="col-md-12 text-center">
                        ScareBears cost 22 MATIC
                      </h2>
                    </div>
                  </div>

                  </div>
                </div>
                  </div>
                  )}

              </div>
            </div>
          </div>
        </div>

      </div>
    </>
  );
};
export default TopSection;

</code>```

答:
I created a semi-working example by removing the react parts since that is not really part of the question. I would expect you can build from this example.

remove stle= some places and used classes.

Created an object to hold the values rather than many variables.

Created functions to call to do what it needed to.

Created an array of date part names to cycle to update display of.

Set a "secondsBack" to do a test rather than some days.

Added a few in-line comments and removed/,moved some code to functions

function getDateFragment(framentType, from) {
  switch (framentType) {
    case 'days':
      return Math.floor(from / (1000 * 60 * 60 * 24));
      break;
    case 'hours':
      return Math.floor((from % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
      break;
    case 'minutes':
      return Math.floor((from % (1000 * 60 * 60)) / (1000 * 60));
      break;
    case 'seconds':
      return Math.floor((from % (1000 * 60)) / 1000);
      break;
    default:
      console.log(`Sorry, we are out of ${framentType} time.`);
  }
}
const HandleTimer = () => {
  // this is in the past so "false" will always be the case; make it postive date
  //let countDownDate = new Date("Oct 30, 2021 15:37:25").getTime();

  // hold all our values in one place:
  let timeFragments = {
    interval: 1000, // how long between updates
    daysBack: 2, // go back 2 days on timer
    secondsBack: 16, //for our test
    countDownDate: new Date(),
    now: new Date(),
    distance: 0,
    days: 0,
    hours: 0,
    minutes: 0,
    seconds: 0,
    initTimer: function() {
      this.countDownDate
        //  .setDate(this.countDownDate.getDate() - this.daysBack);
        //for our test seconds not days
        .setSeconds(this.countDownDate.getSeconds() - this.secondsBack);
      this.distance = this.now.getTime() - this.countDownDate.getTime();
    },
    setDistance: function() {
      this.distance = this.distance - this.interval;
    },
    timers: {
      days: $("#daysTimer"),
      hours: $("#hoursTimer"),
      minutes: $("#minutesTimer"),
      seconds: $("#secondsTimer")
    },
    periods: ["days", "hours", "minutes", "seconds"],
    updateTimes: function() {
      this.periods.forEach(function(element, index, array) {
        this[element] = getDateFragment(element, this.distance)
      }, this);
    },
    updateTimer: function() {
      this.timers.days.html(this.days);
      this.timers.hours.html(this.hours);
      this.timers.minutes.html(this.minutes);
      this.timers.seconds.html(this.seconds);
    }
  };
  timeFragments.initTimer();
  timeFragments.setDistance();
  console.log("Date:", timeFragments.countDownDate, timeFragments.distance);
  let x = setInterval(function() {
      timeFragments.setDistance();
      timeFragments.updateTimes();
      // If time is left, timer will be displayed and button will be disabled
      if (timeFragments.distance > 0) { // was false to start with, fixed that
        $(".time").not(":visible").show();
        timeFragments.updateTimer();

        $("#mintMintBtn").prop('disabled', true);
        $("#mintConnectBtn").prop('disabled', true);
        $("#selectBtn").prop('disabled', true);
        /* $("#selectBtn").css({
           'background-color': 'gray'
         })*/

      }
      // If time has finished, timer will hide and button will be enabled
      else {
        console.log("We are here: false");
        clearInterval(x);
        $(".time").hide();
        $("#mintMintBtn").prop('disabled', false);
        $("#mintConnectBtn").prop('disabled', false);
      }
    },
    timeFragments.interval);
  // detect state instead of adding more handlers
  $(".mintBtn").on("mouseenter", function() {
    if ($(this).not(":disabled")) {
      $(this).addClass('over-me').removeClass('not-over-me');
    } else {
      $(this).removeClass('not-over-me over-me');
    }
  }).on("mouseleave", function() {
    if ($(this).not(":disabled")) {
      $(this).addClass('not-over-me').removeClass('over-me');
    } else {
      $(this).removeClass('not-over-me over-me');
    }
  });
  $("#mintMintBtn").on("mouseenter", function() {
    if ($(this).is(":disabled")) {
      $(this).css('color', 'white');
    }
  });
};
HandleTimer();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.main-section>div.row:first-of-type {
  margin-top: 43px!important;
  justify-content: center;
  padding-bottom: 75px;
}

.no-x-margins {
  margin-left: 0px;
  margin-right: 0px;
}

.blanche {
  border-color: blanchedalmond;
  margin-left: 0px;
  margin-right: 0px;
}

#selectBtn,
#mintMintBtn:disabled {
  background-color: #808080!important;
}

.over-me {
  background-color: #ffffff;
  color: #850101;
}

.not-over-me {
  background-color: #850101;
  color: #ffffff;
}</code>```

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

0

Days

0

Hrs

0

Min

0

Sec

                  0/4444

                  ScareBears cost 22 MATIC

                  CONNECT TO THE POLYGON NETWORK

                <button class="col-12 py-3  mintBtn mint-btn-before" id="mintConnectBtn" onClick="(e) => {e.preventDefault(); dispatch(connect()); getData(); }">
                      CONNECT
                    </button>

                4/4444

                setMintvalue((mintvalue > 0) ? mintvalue - 1 : mintvalue)">-
                <input type="number" min="0" max="20" class="number-mint" value="3" />
                setMintvalue((mintvalue < 20) ? mintvalue + 1 : mintvalue)">+

              <button class="col-12 py-3  mintBtn mint-btn-before" id="mintMintBtn" disabled="false" onClick="(e)=> { e.preventDefault();claimNFTs(parseInt(mintvalue)); getData();">Mint</button>

                      ScareBears cost 22 MATIC

```

Body:
I've inherited a React project where a jQuery countdown timer is used to hide/display a button. If there is time left on the clock, the button below is unclickable and greyed out, else there is no time left on the clock the button is meant to be clickable and the countdown timer should then be hidden.

The timer counts down, but it is not pulling the correct date to count down to, so it won't expire for another 261 days. I've tried setting the date in the past so that the timer expires and no longer displays, thereby allowing the button to be clickable but that's not working.

I deployed this site as a static build at https://scarebearsnft.com, does that have something to do with it? That it can't get the current date and time from the system?

Handletimer.js

import $ from 'jquery';

export const HandleTimer = () => {
    var countDownDate = new Date("Oct 30, 2021 15:37:25").getTime();

    var x = setInterval(function() {

    var now = new Date().getTime();
    var distance = countDownDate - now;

    var days = Math.floor(distance / (1000 * 60 * 60 * 24));
    var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
    var seconds = Math.floor((distance % (1000 * 60)) / 1000);

    // If time is left, timer will be displayed and button will be disabled
    if (distance >0) {
        $(".time").show();

        $("#daysTimer").html(days);
        $("#hoursTimer").html(hours);
        $("#minutesTimer").html(minutes);
        $("#secondsTimer").html(seconds);

        $("#mintBtn").prop('disabled',true)
        $("#selectBtn").attr('disabled',true)
        $("#mintBtn").css({'background-color':'gray'})
        $(".mintBtn").hover(function(){
            $(this).css('color','white')
        })
        $("#selectBtn").css({'background-color':'gray'})

    }

    // If time has finished, timer will hide and button will be enabled
    else{
        clearInterval(x);
        $(".time").hide();

        $(".mintBtn").mouseover(function() {
            $(this).css("background-color","white");
            $(this).css("color","#850101");
        }).mouseout(function() {
            $(this).css("background-color","#850101");
            $(this).css("color","white");
        });
    }
    },1000);
}

Topsection.js

import React, { useEffect, useState, useRef } from "react";
import { useDispatch, useSelector } from "react-redux";
import { connect } from "../redux/blockchain/blockchainActions";
import { fetchData } from "../redux/data/dataActions";
import { counter } from "../hooks/counter";
import Background from '../images/cover.jpeg';

const TopSection = () => {
  const [timeLeft, setTimeLeft] = React.useState(counter());
  const [mintvalue, setMintvalue] = React.useState(0);
  const dispatch = useDispatch();
  const blockchain = useSelector((state) => state.blockchain);
  const data = useSelector((state) => state.data);
  const [costOfNFT, setCost] = useState(0.005);

  const [claimingNft, setClaimingNft] = useState(false);

  const claimNFTs = (_amount) => {
    if (_amount <= 0) {
      alert("Enter some amount to mint your Scare Bears")
      return;
    }
    else if (_amount > 20){
      alert(`You cannot mint more than ${_amount} Scare Bears at a time`)
      return;
    }
    setClaimingNft(true);
    blockchain.smartContract.methods
      .mint(_amount)
      .send({
        to: "HIDDEN",
        from: blockchain.account,
        value: blockchain.web3.utils.toWei((22 * _amount).toString(), "ether"),
      })
      .once("error", (err) => {
        console.log(err);
        alert(err['message'])
        setClaimingNft(false);
      })
      .then((receipt) => {
        alert("You now own a Scare Bears. go visit Opensea.io to view it.")
        setClaimingNft(false);
        dispatch(fetchData(blockchain.account));
      });
  };
  const getData = () => {
    if (blockchain.account !== "" && blockchain.smartContract !== null) {
      dispatch(fetchData(blockchain.account));
    }
  };

  useEffect(() => {
    getData();
  }, [blockchain.account]);

  React.useEffect(() => {
    const id = setTimeout(() => {
      setTimeLeft(counter());
    }, 1000);

    return () => {
      clearTimeout(id);
    };
  });

  return (
    <>
      <div
        class="main d-flex align-items-md-center py-5 py-sm-0"
        style={{
          backgroundImage: `linear-gradient(rgba(0, 0, 0, 0.5), rgb(0, 0, 0)), url(${Background})`,
          //backgroundImage: `url(/images/Header.gif)`,
          backgroundRepeat: "no-repeat",
          backgroundSize: "cover",
        }}
      >

                {Object.keys(timeLeft).length > 0 && (

{timeLeft.days}

Days

{timeLeft.hours}

Hrs

{timeLeft.minutes}

Min

{timeLeft.seconds}

Sec

                )}
                {blockchain.account === "" ||
                        blockchain.smartContract === null ? (

                        0/4444

                        ScareBears cost 22 MATIC

                        CONNECT TO THE POLYGON NETWORK

                    <button
                      class={"col-12 py-3  mintBtn"}
                      className={`col-12 py-2  mintBtn ${Object.keys(timeLeft).length > 0
                        ? "mint-btn-before"
                        : "mint-btn-after"
                        }`}
                      id="mintBtn"
                      disabled={Object.keys(timeLeft).length > 0}
                      onClick={(e) => {
                        e.preventDefault();
                        dispatch(connect());
                        getData();
                      }}
                    >
                      {!Object.keys(timeLeft).length > 0 ? "CONNECT" : "CONNECT"}
                    </button>

                ):(

                      {data.totalSupply}/4444

                         setMintvalue((mintvalue > 0) ? mintvalue - 1 : mintvalue)}>-
                        <input type="number" min="0" max="20" className="number-mint" value={mintvalue} />
                         setMintvalue((mintvalue < 20) ? mintvalue + 1 : mintvalue)}>+

                    <button
                      class={"col-12 py-3  mintBtn"}
                      className={`col-12 py-2  mintBtn ${Object.keys(timeLeft).length > 0
                        ? "mint-btn-before"
                        : "mint-btn-after"
                        }`}
                      id="mintBtn"
                      disabled={Object.keys(timeLeft).length > 0}
                      onClick={(e) => {
                        e.preventDefault();
                        claimNFTs(parseInt(mintvalue));
                        getData();
                      }}
                    >
                      {!Object.keys(timeLeft).length > 0 ? "Mint" : "Minted"}
                    </button>

                        ScareBears cost 22 MATIC

                  )}

    </>
  );
};
export default TopSection;

Body:
I created a semi-working example by removing the react parts since that is not really part of the question. I would expect you can build from this example.

remove stle= some places and used classes.

Created an object to hold the values rather than many variables.

Created functions to call to do what it needed to.

Created an array of date part names to cycle to update display of.

Set a "secondsBack" to do a test rather than some days.

Added a few in-line comments and removed/,moved some code to functions

function getDateFragment(framentType, from) {
  switch (framentType) {
    case 'days':
      return Math.floor(from / (1000 * 60 * 60 * 24));
      break;
    case 'hours':
      return Math.floor((from % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
      break;
    case 'minutes':
      return Math.floor((from % (1000 * 60 * 60)) / (1000 * 60));
      break;
    case 'seconds':
      return Math.floor((from % (1000 * 60)) / 1000);
      break;
    default:
      console.log(`Sorry, we are out of ${framentType} time.`);
  }
}
const HandleTimer = () => {
  // this is in the past so "false" will always be the case; make it postive date
  //let countDownDate = new Date("Oct 30, 2021 15:37:25").getTime();

  // hold all our values in one place:
  let timeFragments = {
    interval: 1000, // how long between updates
    daysBack: 2, // go back 2 days on timer
    secondsBack: 16, //for our test
    countDownDate: new Date(),
    now: new Date(),
    distance: 0,
    days: 0,
    hours: 0,
    minutes: 0,
    seconds: 0,
    initTimer: function() {
      this.countDownDate
        //  .setDate(this.countDownDate.getDate() - this.daysBack);
        //for our test seconds not days
        .setSeconds(this.countDownDate.getSeconds() - this.secondsBack);
      this.distance = this.now.getTime() - this.countDownDate.getTime();
    },
    setDistance: function() {
      this.distance = this.distance - this.interval;
    },
    timers: {
      days: $("#daysTimer"),
      hours: $("#hoursTimer"),
      minutes: $("#minutesTimer"),
      seconds: $("#secondsTimer")
    },
    periods: ["days", "hours", "minutes", "seconds"],
    updateTimes: function() {
      this.periods.forEach(function(element, index, array) {
        this[element] = getDateFragment(element, this.distance)
      }, this);
    },
    updateTimer: function() {
      this.timers.days.html(this.days);
      this.timers.hours.html(this.hours);
      this.timers.minutes.html(this.minutes);
      this.timers.seconds.html(this.seconds);
    }
  };
  timeFragments.initTimer();
  timeFragments.setDistance();
  console.log("Date:", timeFragments.countDownDate, timeFragments.distance);
  let x = setInterval(function() {
      timeFragments.setDistance();
      timeFragments.updateTimes();
      // If time is left, timer will be displayed and button will be disabled
      if (timeFragments.distance > 0) { // was false to start with, fixed that
        $(".time").not(":visible").show();
        timeFragments.updateTimer();

        $("#mintMintBtn").prop('disabled', true);
        $("#mintConnectBtn").prop('disabled', true);
        $("#selectBtn").prop('disabled', true);
        /* $("#selectBtn").css({
           'background-color': 'gray'
         })*/

      }
      // If time has finished, timer will hide and button will be enabled
      else {
        console.log("We are here: false");
        clearInterval(x);
        $(".time").hide();
        $("#mintMintBtn").prop('disabled', false);
        $("#mintConnectBtn").prop('disabled', false);
      }
    },
    timeFragments.interval);
  // detect state instead of adding more handlers
  $(".mintBtn").on("mouseenter", function() {
    if ($(this).not(":disabled")) {
      $(this).addClass('over-me').removeClass('not-over-me');
    } else {
      $(this).removeClass('not-over-me over-me');
    }
  }).on("mouseleave", function() {
    if ($(this).not(":disabled")) {
      $(this).addClass('not-over-me').removeClass('over-me');
    } else {
      $(this).removeClass('not-over-me over-me');
    }
  });
  $("#mintMintBtn").on("mouseenter", function() {
    if ($(this).is(":disabled")) {
      $(this).css('color', 'white');
    }
  });
};
HandleTimer();

.main-section>div.row:first-of-type {
  margin-top: 43px!important;
  justify-content: center;
  padding-bottom: 75px;
}

.no-x-margins {
  margin-left: 0px;
  margin-right: 0px;
}

.blanche {
  border-color: blanchedalmond;
  margin-left: 0px;
  margin-right: 0px;
}

#selectBtn,
#mintMintBtn:disabled {
  background-color: #808080!important;
}

.over-me {
  background-color: #ffffff;
  color: #850101;
}

.not-over-me {
  background-color: #850101;
  color: #ffffff;
}

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="main d-flex align-items-md-center py-5 py-sm-0" style='background-image: linear-gradient(rgba(0, 0, 0, 0.5), rgb(0, 0, 0)), url(${Background}) background-repeat:no-repeat; background-size: cover'>
  <div class="main-section">
    <div class="row d-flex align-items-center">
      <div class="col col-4 d-flex align-items-center">
        <div class="col-12 d-flex flex-column">
          <div class="row text-center justify-content-around time">
            <div class="col-2">
              <h3 id="daysTimer">0</h3>
              <h4 class="date-header">Days</h4>
            </div>
            <div class="col-2">
              <h3 id="hoursTimer">0</h3>
              <h4>Hrs</h4>
            </div>
            <div class="col-2">
              <h3 id="minutesTimer">0</h3>
              <h4>Min</h4>
            </div>
            <div class="col-2">
              <h3 id="secondsTimer">0</h3>
              <h4>Sec</h4>
            </div>
          </div>
          <div class="row mint no-x-margins" style="justify-content: center;">
            <div class="col-12">
              <div class="row d-flex align-items-stretch mint-box-title blanche">
                <p class="col-md-12 text-center">
                  0/4444
                </p>
              </div>
            </div>
            <div>
              <div class="d-flex align-items-stretch blanche">
                <h2 class="col-md-12 text-center">
                  ScareBears cost 22 MATIC
                </h2>
              </div>
            </div>
            <div class="col-12">
              <div class="row right d-flex align-items-stretch blanche">
                <p class="col-md-12 text-center" style="font-size: 12px;">
                  CONNECT TO THE POLYGON NETWORK
                </p>
              </div>
              <div class="col-6" style="margin-left: 25%;">
                <button class="col-12 py-3  mintBtn mint-btn-before" id="mintConnectBtn" onClick="(e) => {e.preventDefault(); dispatch(connect()); getData(); }">
                      CONNECT
                    </button>
              </div>
            </div>
          </div>
          <div class="col-12">
            <div class="row d-flex align-items-stretch mint-box-title blanche">
              <p class="col-md-12 text-center">
                4/4444
              </p>
            </div>
            <div class="col-8" style=" margin-left: 16%;">
              <div class="number">
                <span class="minus" onClick="()=>setMintvalue((mintvalue > 0) ? mintvalue - 1 : mintvalue)">-</span>
                <input type="number" min="0" max="20" class="number-mint" value="3" />
                <span class="plus" onClick="()=>setMintvalue((mintvalue < 20) ? mintvalue + 1 : mintvalue)">+</span>
              </div>
            </div>
            <div class="col-8" style="marginLeft: 15%;">
              <button class="col-12 py-3  mintBtn mint-btn-before" id="mintMintBtn" disabled="false" onClick="(e)=> { e.preventDefault();claimNFTs(parseInt(mintvalue)); getData();">Mint</button>
            </div>
            <div class="row">
              <div class="col-12">
                <div>
                  <div class="row d-flex align-items-stretch mint-box-title blanche">
                    <h2 class="col-md-12 text-center">
                      ScareBears cost 22 MATIC
                    </h2>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>


问:
Java Program to sort
I'm trying to implement a code to mergeSort a list. I was told to use getFirst() and addAll() but I don't know how so this is what I came up with:

Also, I can't use a void for mergeSort method - because it gives me an error so I have to return something.

Any suggestions will be very appreciate

答:
You were close in terms of getting your approach working.  Here's what I came up with.  I changed the logic to create new lists to contain the results at each level rather than creating new lists when you break up a list.  There's no reason to copy a list just to keep it in the same order.  It's the list in the new order that needs to be fresh storage.  This limits the number of copies and I think makes the logic easier, since you can then just append onto the end of each result list instead of having to have logic to set the right position in each list.

```<code>import java.util.Arrays;
import java.util.LinkedList;

class Test {

    public static LinkedList<Integer> mergeSort(LinkedList<Integer> list, int start, int count) {

        if (count < 2) {
            LinkedList<Integer> result = new LinkedList<>();
            result.add(list.get(start));
            return result;
        }

        int size1 = count / 2;
        int size2 = count - size1;

        LinkedList<Integer> list_1 = mergeSort(list, start, size1);
        LinkedList<Integer> list_2 = mergeSort(list, start + size1, size2);

        return merge(list_1, list_2);
    }

    public static LinkedList<Integer> merge(LinkedList<Integer> list_1, LinkedList<Integer> list_2) {

        LinkedList<Integer> result = new LinkedList<>();

        int i = 0, j = 0;
        while (i < list_1.size() && j < list_2.size())
            if (list_1.get(i) < list_2.get(j))
                result.add(list_1.get(i++));
            else
                result.add(list_2.get(j++));
        while (i < list_1.size())
            result.add(list_1.get(i++));
        while (j < list_2.size())
            result.add(list_2.get(j++));

        return result;
    }

    public static LinkedList<Integer> mergeSort(LinkedList<Integer> list) {
        return mergeSort(list, 0, list.size());
    }

    public static void main(String[] args) {
        LinkedList<Integer> myList = new LinkedList<>(Arrays.asList(22, 45, 1234, 77, 4, 1111, 999, 12, 88, 44, 7777, 22, 33, 44, 666));
        LinkedList<Integer> sorted = mergeSort(myList);
        System.out.println(sorted);
    }
}
</code>```

Result:

```<code>[4, 12, 22, 22, 33, 44, 44, 45, 77, 88, 666, 999, 1111, 1234, 7777]
</code>```

UPDATE: As @rcgldr points out, the above solution doesn't meet the stated guidelines.  With this new version of the merge() method, the guidelines are met.  Note that this doesn't make the algorithm much more efficient (both versions create lots of lists and are quite INEFFICIENT), but it does save a bunch of walking to random positions in lists in favor of working from the front each list:

```<code>public static LinkedList<Integer> merge(LinkedList<Integer> list_1, LinkedList<Integer> list_2) {

    LinkedList<Integer> result = new LinkedList<>();

    while (list_1.size() > 0 && list_2.size() > 0)
        if (list_1.peek() < list_2.peek()) {
            result.add(list_1.getFirst());
            list_1.remove();
        }
        else {
            result.add(list_2.getFirst());
            list_2.remove();
        }
    result.addAll(list_1);
    result.addAll(list_2);

    return result;
}
</code>```

Also note that calling getFirst() and then remove() is redundant.  remmove() can be called by itself to both grab the next element and remove it from the list.  I went with calling both methods to meet the requirements.

Title: Java Program to sort

Body:
You were close in terms of getting your approach working.  Here's what I came up with.  I changed the logic to create new lists to contain the results at each level rather than creating new lists when you break up a list.  There's no reason to copy a list just to keep it in the same order.  It's the list in the new order that needs to be fresh storage.  This limits the number of copies and I think makes the logic easier, since you can then just append onto the end of each result list instead of having to have logic to set the right position in each list.

import java.util.Arrays;
import java.util.LinkedList;

class Test {

    public static LinkedList<Integer> mergeSort(LinkedList<Integer> list, int start, int count) {

        if (count < 2) {
            LinkedList<Integer> result = new LinkedList<>();
            result.add(list.get(start));
            return result;
        }

        int size1 = count / 2;
        int size2 = count - size1;

        LinkedList<Integer> list_1 = mergeSort(list, start, size1);
        LinkedList<Integer> list_2 = mergeSort(list, start + size1, size2);

        return merge(list_1, list_2);
    }

    public static LinkedList<Integer> merge(LinkedList<Integer> list_1, LinkedList<Integer> list_2) {

        LinkedList<Integer> result = new LinkedList<>();

        int i = 0, j = 0;
        while (i < list_1.size() && j < list_2.size())
            if (list_1.get(i) < list_2.get(j))
                result.add(list_1.get(i++));
            else
                result.add(list_2.get(j++));
        while (i < list_1.size())
            result.add(list_1.get(i++));
        while (j < list_2.size())
            result.add(list_2.get(j++));

        return result;
    }

    public static LinkedList<Integer> mergeSort(LinkedList<Integer> list) {
        return mergeSort(list, 0, list.size());
    }

    public static void main(String[] args) {
        LinkedList<Integer> myList = new LinkedList<>(Arrays.asList(22, 45, 1234, 77, 4, 1111, 999, 12, 88, 44, 7777, 22, 33, 44, 666));
        LinkedList<Integer> sorted = mergeSort(myList);
        System.out.println(sorted);
    }
}

Result:

[4, 12, 22, 22, 33, 44, 44, 45, 77, 88, 666, 999, 1111, 1234, 7777]

UPDATE: As @rcgldr points out, the above solution doesn't meet the stated guidelines.  With this new version of the merge() method, the guidelines are met.  Note that this doesn't make the algorithm much more efficient (both versions create lots of lists and are quite INEFFICIENT), but it does save a bunch of walking to random positions in lists in favor of working from the front each list:

public static LinkedList<Integer> merge(LinkedList<Integer> list_1, LinkedList<Integer> list_2) {

    LinkedList<Integer> result = new LinkedList<>();

    while (list_1.size() > 0 && list_2.size() > 0)
        if (list_1.peek() < list_2.peek()) {
            result.add(list_1.getFirst());
            list_1.remove();
        }
        else {
            result.add(list_2.getFirst());
            list_2.remove();
        }
    result.addAll(list_1);
    result.addAll(list_2);

    return result;
}

Also note that calling getFirst() and then remove() is redundant.  remmove() can be called by itself to both grab the next element and remove it from the list.  I went with calling both methods to meet the requirements.


问:
Spring Boot is not initializing data on startup with Spring JDBC getting errors on writing queries in a data.sql file
I am learning Spring Framework from online tutorials. In the tutorial, the instructor is using Spring JDBC and the H2 database and a data.sql file to populate tables. He also changed the dialect from "General SQL" to "MySQL" dialect as we are going to use MySQL in future videos, so I am just following the tutorial.

All just went well, but when I created data.sql and changed the dialect in my classpath, I was getting errors on a table name like this:

Unable to resolve
 and table names and columns are showing in red color as errors.

I don't know what's happening, and I have tried every solution on the Internet. I am attaching my source code and data.SQL screenshot.

data.sql file

Entity file

答:
You are not actually seeing errors, that is, IntelliJ doesn't know enough about your database to know whether you have any problem that should generate an error.

You need to have a database.

Your first screenshot has a link that says "Configure data source". Click that link, and go through the process to set up IntelliJ to work with your database.

Then you will be able to use IntelliJ's DB features, if you want to (or if your course requires you to use those features).

In this case, you will probably need to already have a table called category in that database with the right layout, or you will start seeing errors.


问:
java.util.Scanner does not return to Prompt
```<code>import java.util.Scanner;

class newClass {
    public static void main(String args[]) {
        Scanner s = new Scanner(System.in);
        while (s.hasNext()) {
            System.out.println(s.next());
        }
        s.close();
    }
}
</code>```

This program does not return to prompt (I have been running it through the Terminal). Why is that? How can I correct it?

答:
The Scanner will block waiting for input from System.in (standard input). You have to press Ctrl+C to exit the program, close the Input stream by pressing Ctrl+D or give the loop an exit condition (like typing "quit"), here is how you could do that:</p>

```<code>import java.util.Scanner;

class newClass {
    public static void main(String args[]) {
        Scanner s = new Scanner(System.in);
        while (s.hasNext()) {
            String nextVal = s.next();
            if (nextVal.equalsIgnoreCase("quit")) { break; }
            System.out.println(nextVal);
        }
        s.close();
    }
}
</code>```

Body:
import java.util.Scanner;

class newClass {
    public static void main(String args[]) {
        Scanner s = new Scanner(System.in);
        while (s.hasNext()) {
            System.out.println(s.next());
        }
        s.close();
    }
}

This program does not return to prompt (I have been running it through the Terminal). Why is that? How can I correct it?

Body:
The Scanner will block waiting for input from System.in (standard input). You have to press Ctrl+C to exit the program, close the Input stream by pressing Ctrl+D or give the loop an exit condition (like typing "quit"), here is how you could do that:

import java.util.Scanner;

class newClass {
    public static void main(String args[]) {
        Scanner s = new Scanner(System.in);
        while (s.hasNext()) {
            String nextVal = s.next();
            if (nextVal.equalsIgnoreCase("quit")) { break; }
            System.out.println(nextVal);
        }
        s.close();
    }
}


问:
How to dispatch post data object using async thunk redux axios middleware
I am trying to dispatch a post of an object data using async redux axios middleware.  I am getting 400 https response prob due to formatting.  Here is what I have for my code.  Any feedback is great!

```<code>import { createAsyncThunk } from '@reduxjs/toolkit';
import axios from 'axios';

export const postResults = createAsyncThunk(
  'results/postResults',
  async ({ data: TestData[] }) => {
        const response = await axios.post(`${url}/data/results`, { data });
        return response.data;
  }
);

const sendData = async (data) => {
  try {
    data = {
      result: 'passed',
      data_id: [0]
    };
    await dispatch(postResults(data));
  } catch (err) {
      console.log(err);
  }
};

</code>```

I am using sendData(data) in another function to trigger the event.

```<code>const processData = (e) => {
   //.....
   sendData(data);
}
</code>```

The output I am getting when I debug under xhr.js request.send(requestData):

```<code>requestData: "{\"data\":{\"result\":\"passed\",\"data_id\":[0]}}"
</code>```

I think the formatting is an issue which I have tried to remove data so I can be read and sent its request as

```<code>requestData: "{\"result\":\"passed\",\"data_id\":[0]}"
</code>```

Any thoughts or feedback!

答:
figured out, I removed the { } so its like this:

const response = await axios.post(${url}/data/results, data);

Body:
I am trying to dispatch a post of an object data using async redux axios middleware.  I am getting 400 https response prob due to formatting.  Here is what I have for my code.  Any feedback is great!

import { createAsyncThunk } from '@reduxjs/toolkit';
import axios from 'axios';

export const postResults = createAsyncThunk(
  'results/postResults',
  async ({ data: TestData[] }) => {
        const response = await axios.post(`${url}/data/results`, { data });
        return response.data;
  }
);

const sendData = async (data) => {
  try {
    data = {
      result: 'passed',
      data_id: [0]
    };
    await dispatch(postResults(data));
  } catch (err) {
      console.log(err);
  }
};

I am using sendData(data) in another function to trigger the event.

const processData = (e) => {
   //.....
   sendData(data);
}

The output I am getting when I debug under xhr.js request.send(requestData):

requestData: "{\"data\":{\"result\":\"passed\",\"data_id\":[0]}}"

I think the formatting is an issue which I have tried to remove data so I can be read and sent its request as

requestData: "{\"result\":\"passed\",\"data_id\":[0]}"

Any thoughts or feedback!