问:
AssertJ assertThat Consumer
Im currently building a custom maven test report plugin that captures unit and integration tests results. While trying to capture as much test information as possible, I am able to capture AssertJ descriptions using something like this >

```<code>// initialize the description consumer
final StringBuilder descriptionReportBuilder = new
StringBuilder(String.format("Assertions:%n"));
Consumer<Description> descriptionConsumer = desc ->
descriptionReportBuilder.append(String.format("-- %s%n", desc));

// use the description consumer for any following assertions descriptions.
Assertions.setDescriptionConsumer(descriptionConsumer);

// execute some assertions
TolkienCharacter frodo = new TolkienCharacter("Frodo", 33, Race.HOBBIT);
assertThat(frodo.getName()).as("check name")
                      .isEqualTo("Frodo");
assertThat(frodo.getAge()).as("check age")
                      .isEqualTo(33);

// get the report
String descriptionReport = descriptionReportBuilder.toString();
</code>```

Is there anything similar in the framework for consuming or capturing the actual values from assetThats, that are exectued during a test. Iv navigated through the code but cannot find anything. I am able to extend the Assertion class but id opt for a better way

Any help appreciate.

Title: AssertJ assertThat Consumer

Body:
Im currently building a custom maven test report plugin that captures unit and integration tests results. While trying to capture as much test information as possible, I am able to capture AssertJ descriptions using something like this >

// initialize the description consumer
final StringBuilder descriptionReportBuilder = new
StringBuilder(String.format("Assertions:%n"));
Consumer<Description> descriptionConsumer = desc ->
descriptionReportBuilder.append(String.format("-- %s%n", desc));

// use the description consumer for any following assertions descriptions.
Assertions.setDescriptionConsumer(descriptionConsumer);

// execute some assertions
TolkienCharacter frodo = new TolkienCharacter("Frodo", 33, Race.HOBBIT);
assertThat(frodo.getName()).as("check name")
                      .isEqualTo("Frodo");
assertThat(frodo.getAge()).as("check age")
                      .isEqualTo(33);

// get the report
String descriptionReport = descriptionReportBuilder.toString();

Is there anything similar in the framework for consuming or capturing the actual values from assetThats, that are exectued during a test. Iv navigated through the code but cannot find anything. I am able to extend the Assertion class but id opt for a better way

Any help appreciate.


来源: stackexchange

问:
Can't write user_id from users table into posts table in database
I am trying to write post, and that post have content, adress and user_id in database. With content and adress I had no problem, but for user_id there is always 0 in database, no metter whitch user write post.
database pic

Here is my code:
Frontend- I get user data from context. And when I console.log(user.result[0].id) I get user_id (for example 155).

```<code>  const { user } = useContext(AuthContext);

    const addPost = async () => {
        console.log(user);
        await axios.post('http://localhost:3001/CreateAds', {
            user_id: user.result[0].id,
            content: formValues.content,
            adress: formValues.adress
</code>```

Backend:

```<code>app.post('/CreateAds', (req, res) => {
    const user_id=req.body.user_id;
    const content = req.body.content;
    const adress = req.body.adress;
    db.query("INSERT INTO posts(user_id,content,adress) VALUES (?,?,?)", [user_id, content, adress],
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to write post, and that post have content, adress and user_id in database. With content and adress I had no problem, but for user_id there is always 0 in database, no metter whitch user write post.
database pic

Here is my code:
Frontend- I get user data from context. And when I console.log(user.result[0].id) I get user_id (for example 155).

  const { user } = useContext(AuthContext);

    const addPost = async () => {
        console.log(user);
        await axios.post('http://localhost:3001/CreateAds', {
            user_id: user.result[0].id,
            content: formValues.content,
            adress: formValues.adress

Backend:

app.post('/CreateAds', (req, res) => {
    const user_id=req.body.user_id;
    const content = req.body.content;
    const adress = req.body.adress;
    db.query("INSERT INTO posts(user_id,content,adress) VALUES (?,?,?)", [user_id, content, adress],


问:
laravel Problem with html codes appearing in content
https://prnt.sc/mrPjcm6osjEq

hello everyone

I am facing the error you see in the picture, how can I solve it?

```<code><div class="card-body">
<p class="small">
{!! Str::limit($item->story, 120) !!}
</p>
</code>```

code generation laravel

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

i tried this function but the error is not resolved

Body:
https://prnt.sc/mrPjcm6osjEq

hello everyone

I am facing the error you see in the picture, how can I solve it?

{!! Str::limit($item->story, 120) !!}

code generation laravel

{!! !!}

i tried this function but the error is not resolved


问:
how I can clear of error Function has override specified but does not override anything
```<code>// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;

import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";

contract MinterYT is ERC721,ERC721Enumerable,ERC721URIStorage{
    using SafeMath for uint256;

    uint public constant mintPrice=0;
    function _beforeTokenTransfer(address from,address to,uint256 tokenId) internal override(ERC721,ERC721Enumerable)
    {
super._beforeTokenTransfer(from,to,tokenId);

    }
    function _burn(uint256 tokenId) public  view override(ERC721,ERC721URIStorage)
    returns(string memory)
    {
        return super.tokenURI(tokenId);

         }
  function supportsInterface(bytes4 interfaceId) public view  override(ERC721,ERC721Enumerable)
  returns(bool)
  {
      return super.supportsInterface(interfaceId);

  }
  constructor() ERC721("YTMinter","YTM"){}
function mint(string memory _uri) public payable
{
uint256 mintIndex=totalSupply();
_safeMint(msg.sender,mintIndex);
_setTokenURI(mintIndex, _uri);
}

}

</code>```

the error was

TypeError: Function has override specified but does not override anything.
--> contracts/Mint.sol:13:85:
|
13 | function _beforeTokenTransfer(address from,address to,uint256 tokenId) internal override(ERC721,ERC721Enumerable)
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

TypeError: Invalid contracts specified in override list: "ERC721" and "ERC721Enumerable".
--> contracts/Mint.sol:13:85:
|
13 | function _beforeTokenTransfer(address from,address to,uint256 tokenId) internal override(ERC721,ERC721Enumerable)
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Note: This contract:
--> @openzeppelin/contracts/token/ERC721/ERC721.sol:19:1:
|
19 | contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
| ^ (Relevant source part starts here and spans across multiple lines).
Note: This contract:
--> @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol:14:1:
|
14 | abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
| ^ (Relevant source part starts here and spans across multiple lines).

TypeError: Overriding function visibility differs.
--> contracts/Mint.sol:18:5:
|
18 | function _burn(uint256 tokenId) public view override(ERC721,ERC721URIStorage)
| ^ (Relevant source part starts here and spans across multiple lines).
Note: Overridden function is here:
--> @openzeppelin/contracts/token/ERC721/ERC721.sol:321:5:
|
321 | function _burn(uint256 tokenId) internal virtual {
| ^ (Relevant source part starts here and spans across multiple lines).

TypeError: Overriding function return types differ.
--> contracts/Mint.sol:18:5:
|
18 | function _burn(uint256 tokenId) public view override(ERC721,ERC721URIStorage)
| ^ (Relevant source part starts here and spans across multiple lines).
Note: Overridden function is here:
--> @openzeppelin/contracts/token/ERC721/ERC721.sol:321:5:
|
321 | function _burn(uint256 tokenId) internal virtual {
| ^ (Relevant source part starts here and spans across multiple lines).

TypeError: Overriding function visibility differs.
--> contracts/Mint.sol:18:5:
|
18 | function _burn(uint256 tokenId) public view override(ERC721,ERC721URIStorage)
| ^ (Relevant source part starts here and spans across multiple lines).
Note: Overridden function is here:
--> @openzeppelin/contracts/token/ERC721/ERC721.sol:321:5:
|
321 | function _burn(uint256 tokenId) internal virtual {
| ^ (Relevant source part starts here and spans across multiple lines).

TypeError: Overriding function return types differ.
--> contracts/Mint.sol:18:5:
|
18 | function _burn(uint256 tokenId) public view override(ERC721,ERC721URIStorage)
| ^ (Relevant source part starts here and spans across multiple lines).
Note: Overridden function is here:
--> @openzeppelin/contracts/token/ERC721/ERC721.sol:321:5:
|
321 | function _burn(uint256 tokenId) internal virtual {
| ^ (Relevant source part starts here and spans across multiple lines).

TypeError: Overriding function visibility differs.
--> contracts/Mint.sol:18:5:
|
18 | function _burn(uint256 tokenId) public view override(ERC721,ERC721URIStorage)
| ^ (Relevant source part starts here and spans across multiple lines).
Note: Overridden function is here:
--> @openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol:55:5:
|
55 | function _burn(uint256 tokenId) internal virtual override {
| ^ (Relevant source part starts here and spans across multiple lines).

TypeError: Overriding function return types differ.
--> contracts/Mint.sol:18:5:
|
18 | function _burn(uint256 tokenId) public view override(ERC721,ERC721URIStorage)
| ^ (Relevant source part starts here and spans across multiple lines).
Note: Overridden function is here:
--> @openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol:55:5:
|
55 | function _burn(uint256 tokenId) internal virtual override {
| ^ (Relevant source part starts here and spans across multiple lines).

TypeError: Derived contract must override function "_beforeTokenTransfer". Two or more base classes define function with same name and parameter types.
--> contracts/Mint.sol:9:1:
|
9 | contract MinterYT is ERC721,ERC721Enumerable,ERC721URIStorage{
| ^ (Relevant source part starts here and spans across multiple lines).
Note: Definition in "ERC721":
--> @openzeppelin/contracts/token/ERC721/ERC721.sol:467:5:
|
467 | function _beforeTokenTransfer(
| ^ (Relevant source part starts here and spans across multiple lines).
Note: Definition in "ERC721Enumerable":
--> @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol:60:5:
|
60 | function _beforeTokenTransfer(
| ^ (Relevant source part starts here and spans across multiple lines).

TypeError: Derived contract must override function "tokenURI". Two or more base classes define function with same name and parameter types.
--> contracts/Mint.sol:9:1:
|
9 | contract MinterYT is ERC721,ERC721Enumerable,ERC721URIStorage{
| ^ (Relevant source part starts here and spans across multiple lines).
Note: Definition in "ERC721":
--> @openzeppelin/contracts/token/ERC721/ERC721.sol:93:5:
|
93 | function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
| ^ (Relevant source part starts here and spans across multiple lines).
Note: Definition in "ERC721URIStorage":
--> @openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol:20:5:
|
20 | function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
| ^ (Relevant source part starts here and spans across multiple lines).

TypeError: Wrong argument count for function call: 3 arguments given but expected 4.
--> contracts/Mint.sol:15:1:
|
15 | super._beforeTokenTransfer(from,to,tokenId);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

the result is image link was send metamask wallet in 0 eth

Body:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;

import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";

contract MinterYT is ERC721,ERC721Enumerable,ERC721URIStorage{
    using SafeMath for uint256;

    uint public constant mintPrice=0;
    function _beforeTokenTransfer(address from,address to,uint256 tokenId) internal override(ERC721,ERC721Enumerable)
    {
super._beforeTokenTransfer(from,to,tokenId);

    }
    function _burn(uint256 tokenId) public  view override(ERC721,ERC721URIStorage)
    returns(string memory)
    {
        return super.tokenURI(tokenId);

         }
  function supportsInterface(bytes4 interfaceId) public view  override(ERC721,ERC721Enumerable)
  returns(bool)
  {
      return super.supportsInterface(interfaceId);

  }
  constructor() ERC721("YTMinter","YTM"){}
function mint(string memory _uri) public payable
{
uint256 mintIndex=totalSupply();
_safeMint(msg.sender,mintIndex);
_setTokenURI(mintIndex, _uri);
}

}

the error was

TypeError: Function has override specified but does not override anything.
--> contracts/Mint.sol:13:85:
|
13 | function _beforeTokenTransfer(address from,address to,uint256 tokenId) internal override(ERC721,ERC721Enumerable)
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

TypeError: Invalid contracts specified in override list: "ERC721" and "ERC721Enumerable".
--> contracts/Mint.sol:13:85:
|
13 | function _beforeTokenTransfer(address from,address to,uint256 tokenId) internal override(ERC721,ERC721Enumerable)
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Note: This contract:
--> @openzeppelin/contracts/token/ERC721/ERC721.sol:19:1:
|
19 | contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
| ^ (Relevant source part starts here and spans across multiple lines).
Note: This contract:
--> @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol:14:1:
|
14 | abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
| ^ (Relevant source part starts here and spans across multiple lines).

TypeError: Overriding function visibility differs.
--> contracts/Mint.sol:18:5:
|
18 | function _burn(uint256 tokenId) public view override(ERC721,ERC721URIStorage)
| ^ (Relevant source part starts here and spans across multiple lines).
Note: Overridden function is here:
--> @openzeppelin/contracts/token/ERC721/ERC721.sol:321:5:
|
321 | function _burn(uint256 tokenId) internal virtual {
| ^ (Relevant source part starts here and spans across multiple lines).

TypeError: Overriding function return types differ.
--> contracts/Mint.sol:18:5:
|
18 | function _burn(uint256 tokenId) public view override(ERC721,ERC721URIStorage)
| ^ (Relevant source part starts here and spans across multiple lines).
Note: Overridden function is here:
--> @openzeppelin/contracts/token/ERC721/ERC721.sol:321:5:
|
321 | function _burn(uint256 tokenId) internal virtual {
| ^ (Relevant source part starts here and spans across multiple lines).

TypeError: Overriding function visibility differs.
--> contracts/Mint.sol:18:5:
|
18 | function _burn(uint256 tokenId) public view override(ERC721,ERC721URIStorage)
| ^ (Relevant source part starts here and spans across multiple lines).
Note: Overridden function is here:
--> @openzeppelin/contracts/token/ERC721/ERC721.sol:321:5:
|
321 | function _burn(uint256 tokenId) internal virtual {
| ^ (Relevant source part starts here and spans across multiple lines).

TypeError: Overriding function return types differ.
--> contracts/Mint.sol:18:5:
|
18 | function _burn(uint256 tokenId) public view override(ERC721,ERC721URIStorage)
| ^ (Relevant source part starts here and spans across multiple lines).
Note: Overridden function is here:
--> @openzeppelin/contracts/token/ERC721/ERC721.sol:321:5:
|
321 | function _burn(uint256 tokenId) internal virtual {
| ^ (Relevant source part starts here and spans across multiple lines).

TypeError: Overriding function visibility differs.
--> contracts/Mint.sol:18:5:
|
18 | function _burn(uint256 tokenId) public view override(ERC721,ERC721URIStorage)
| ^ (Relevant source part starts here and spans across multiple lines).
Note: Overridden function is here:
--> @openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol:55:5:
|
55 | function _burn(uint256 tokenId) internal virtual override {
| ^ (Relevant source part starts here and spans across multiple lines).

TypeError: Overriding function return types differ.
--> contracts/Mint.sol:18:5:
|
18 | function _burn(uint256 tokenId) public view override(ERC721,ERC721URIStorage)
| ^ (Relevant source part starts here and spans across multiple lines).
Note: Overridden function is here:
--> @openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol:55:5:
|
55 | function _burn(uint256 tokenId) internal virtual override {
| ^ (Relevant source part starts here and spans across multiple lines).

TypeError: Derived contract must override function "_beforeTokenTransfer". Two or more base classes define function with same name and parameter types.
--> contracts/Mint.sol:9:1:
|
9 | contract MinterYT is ERC721,ERC721Enumerable,ERC721URIStorage{
| ^ (Relevant source part starts here and spans across multiple lines).
Note: Definition in "ERC721":
--> @openzeppelin/contracts/token/ERC721/ERC721.sol:467:5:
|
467 | function _beforeTokenTransfer(
| ^ (Relevant source part starts here and spans across multiple lines).
Note: Definition in "ERC721Enumerable":
--> @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol:60:5:
|
60 | function _beforeTokenTransfer(
| ^ (Relevant source part starts here and spans across multiple lines).

TypeError: Derived contract must override function "tokenURI". Two or more base classes define function with same name and parameter types.
--> contracts/Mint.sol:9:1:
|
9 | contract MinterYT is ERC721,ERC721Enumerable,ERC721URIStorage{
| ^ (Relevant source part starts here and spans across multiple lines).
Note: Definition in "ERC721":
--> @openzeppelin/contracts/token/ERC721/ERC721.sol:93:5:
|
93 | function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
| ^ (Relevant source part starts here and spans across multiple lines).
Note: Definition in "ERC721URIStorage":
--> @openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol:20:5:
|
20 | function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
| ^ (Relevant source part starts here and spans across multiple lines).

TypeError: Wrong argument count for function call: 3 arguments given but expected 4.
--> contracts/Mint.sol:15:1:
|
15 | super._beforeTokenTransfer(from,to,tokenId);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

the result is image link was send metamask wallet in 0 eth


问:
Updating a PM2 script file to use maximum cores
I have been using PM2 for years now and i've only just noticed that it is using a single core of my Raspberry Pi 3. I now want it to use all 4 cores in cluster mode, so when heavy processing is happening in one of the cores, my application doesn't hang up and softlock for a few seconds.

I have found the file that is responsible for handling the PM2 process of my application at

```<code>/etc/systemd/system/pm2-userNameGoesHere.process
</code>```

Opening this file gives me what I assume to be the config files for PM2. I don't know what I need to add to this file in order to set the number of cores to 'max'.

Body:
I have been using PM2 for years now and i've only just noticed that it is using a single core of my Raspberry Pi 3. I now want it to use all 4 cores in cluster mode, so when heavy processing is happening in one of the cores, my application doesn't hang up and softlock for a few seconds.

I have found the file that is responsible for handling the PM2 process of my application at

/etc/systemd/system/pm2-userNameGoesHere.process

Opening this file gives me what I assume to be the config files for PM2. I don't know what I need to add to this file in order to set the number of cores to 'max'.


问:
Is there a way to get handle of already opened ChromeDriver window in another process using Selenium?
So let's imagine that I have 2 running processes.
In the 1st process I create an instance of selemium ChromeDriver, which has it's service on http://localhost:49402.

What I want to do: to use this opened window from another process, or at least to open new window / tab with environment of 1st window (cookies, session etc.).
I tried to use selemium.webdriver.Remote, and it launches a new window, but it seems to be independent from the 1st one.

Is there a way to do what I want?


问:
Error While Updating Jenkins to the latest version
I used this link to update my jenkins:
https://gist.github.com/ricardo-dlc/1a6cbd9d48e4fa791b022b1eebc15de5

but it is not working and ends with some errors.
Is there any other way to update jenkins to the latest version?
Note that I am running my jenkins on a docker container.


问:
Is there have an alternative OneSignal mobile push notification platform
My problem is I can't use OneSignal with FCM (Firebase Cloud Message (Legacy)) with contains a "Server Key" because I don't have a permission to enable FCM (Legacy). So I wanna to using mobile push notification which is omni and can using with multiplatform like Android and IOS

I want the platform that have a FREE option and most likely OneSignal because I building a small app which not have a budget right now.

Is Anyone have some platform recommend to me, Or you have other way you can also recommend for me.

Thank a lot for your kindness!

Ps. I already open FCM (V1) but I don't know where is any platform are using it.

I try many platform but I not suit to our app because it still using FCM (Legacy)

OneSignal

PubNub


问:
kex_exchange_identification: banner line contains invalid characters
When I try to init the AOSP repo, the foloowing mistakes occurred

```<code>Get ssh:xxxxxxxxxxxxxxxxxxxx/repo
kex_exchange_identification: banner line contains invalid characters
fatal: Could not read from remote repository.
</code>```

How to fix this error and init the repo?
Thanks.

Body:
When I try to init the AOSP repo, the foloowing mistakes occurred

Get ssh:xxxxxxxxxxxxxxxxxxxx/repo
kex_exchange_identification: banner line contains invalid characters
fatal: Could not read from remote repository.

How to fix this error and init the repo?
Thanks.


问:
detect deadlock and resume query in stored procedure
I am trying to run a query in a loop on 4 mil records (100000 records per batch). I don't want to lock the table, but still, I am receiving a deadlock situation. Here is my proc:

```<code>BEGIN

SET autocommit = 0;

WHILE (SELECT COUNT(*) FROM AirDNAAnnualPropertyPerformance_Quartiles WHERE Processed= 0 ) > 0  DO

    START TRANSACTION;

    UPDATE AirDNAAnnualPropertyPerformance A JOIN
        AirDNAAnnualPropertyPerformance_Quartiles B ON A.PropertyID = B.PropertyID JOIN
         (
        SELECT PropertyID
        FROM AirDNAAnnualPropertyPerformance_Quartiles
        WHERE Processed = 0
            LIMIT 100000
    ) C ON A.PropertyID = C.PropertyID
    SET A.Quartile = B.tile, B.Processed = 1;

    COMMIT;

    DO SLEEP(2);

END WHILE;

END
</code>```

What is the best way to run this query, even if there is a deadlock? I want to catch it and continue without breaking out of the loop.

Body:
I am trying to run a query in a loop on 4 mil records (100000 records per batch). I don't want to lock the table, but still, I am receiving a deadlock situation. Here is my proc:

BEGIN

SET autocommit = 0;

WHILE (SELECT COUNT(*) FROM AirDNAAnnualPropertyPerformance_Quartiles WHERE Processed= 0 ) > 0  DO

    START TRANSACTION;

    UPDATE AirDNAAnnualPropertyPerformance A JOIN
        AirDNAAnnualPropertyPerformance_Quartiles B ON A.PropertyID = B.PropertyID JOIN
         (
        SELECT PropertyID
        FROM AirDNAAnnualPropertyPerformance_Quartiles
        WHERE Processed = 0
            LIMIT 100000
    ) C ON A.PropertyID = C.PropertyID
    SET A.Quartile = B.tile, B.Processed = 1;

    COMMIT;

    DO SLEEP(2);

END WHILE;

END

What is the best way to run this query, even if there is a deadlock? I want to catch it and continue without breaking out of the loop.


问:
homoscedasticity, residual vs fitted plot with negative pattern issue
I ran a Pooled-OLS, including several dummy variables and interaction variables.

Dependent variable is

log(price/size+1)

and independent variables are year_dummy(21 years) + region dummy(70 regions) + distance to A + height + heightyear_dummy + heightdistance + distance*year_dummy other characteristics

I wanted to see

how height's effect on price varies according to year
how height's effect on price varies according to distance
how distance's effect on price varies according to year
I found this model did not meet homoscedasticity assumption. and residual vs fitted plot looks like thisenter image description here

I know there are several ways to solve heteroscedasticity issue such as WLS, taking log to independent variable,

but my case they did not work, as you can see, the plot has a negative trend.

Any idea and comments are welcomed.enter image description here

any idea and solution for the issue I have


问:
Ora can run on worker thread in nodejs?
Is it possible to run ora in nodejs worker?

I have a simple example I use to run ora in another worker. but the problem is freezes after the first output.

app.ts:

```<code>import { Worker, isMainThread, parentPort } from 'worker_threads';
import path from 'path';

const worker = new Worker(path.resolve(__dirname, './worker'));
</code>```

worker.ts:

```<code>import ora from 'ora';

console.log('in worker!!!');
ora('starting...').start();
</code>```

Do I miss something here? or ora can't run on Worker?

Title: Ora can run on worker thread in nodejs?

Body:
Is it possible to run ora in nodejs worker?

I have a simple example I use to run ora in another worker. but the problem is freezes after the first output.

app.ts:

import { Worker, isMainThread, parentPort } from 'worker_threads';
import path from 'path';

const worker = new Worker(path.resolve(__dirname, './worker'));

worker.ts:

import ora from 'ora';

console.log('in worker!!!');
ora('starting...').start();

Do I miss something here? or ora can't run on Worker?


问:
Configuration of STM32 pins for 2 microphones acquisition
Please help me. I am trying to configure pins for reading the data coming from 2 microphones mount in a X-NUCLEO-CCA02M2. To read the data I am using a NUCLEO-F401RE.

I read all the documentation for tthe expansion but nothing is working. In this moment watching the figure below I set using I2S2 the pin PB15 (I2S2_SD) and the pin PB13 (I2S2_CK). I add DMA in circular mode and set the frequency to 96kHz. The communication was set in half duplex in master reception mode. This pins were choose after watching the schematic of CCA02M2.

Here the schematics of NUCLEO and expansion.

[Schematic of NUCLEO-F401RE]

[Schematic of CCA02M2]

All the information used were taken from a STM pdf here is a screenshot.

[How to set a 2 microphones configuration]

After all the configuration I used this function the start the reception mode:

HAL_I2S_RECEIVE_DMA()

And the relative callback to check which data were read by the microphone. The problem is that the data read are always 0. Another problem is that I don't understand why the MOSI pin is used to read the data in the STM pdf.

Please can some help me?


问:
How to move specific messages from one topic to another on demand in Pulsar (using pulsar-admin)?
I have a requirement of moving specific messages from DLQ to RETRY queue. I want to use pulsar-admin for this task.
I have message-id for all the messages.

~note: don't want to copy and produce manually, it is error prone

Any other approach is acceptable.


问:
Facebook clone: graphql query returns null for mongodb user Object ID
I am trying to create a facebook clone using the MERNG stack.

Currently I'm creating the mutations and queries for the application. Most of the time they are working fine, except for whenever I'm trying to return the userID that is associated with the comments. The value returned is always null.

Here is an example when I'm using my getPostById query:

getPostById query as shown on apollographql sandbox

Here's the typedefs:

const typeDefs = gql`
    type User {
        _id: ID!
        createdAt: String!
        firstName: String!
        lastName: String!
        email: String!
        password: String!
        gender: String!
        phoneNumber: String!
        birthYear: Int!
        birthMonth: Int!
        birthDay: Int!
        profilePicture: String
        cover: String
        friends: [User]
        following: [User]
        followers: [User]
        requests: [User]
        search: [User]
        userDetails: UserDetails
        savedPosts: [Post]
    }

    type Auth {
        token: ID!
        user: User!
    }

    type UserDetails {
        _id: ID!
        createdAt: String!
        userId: String!
        bio: String
        otherName: String
        job: String
        workplace: String
        highschool: String
        college: String
        currentCity: String
        hometown: String
        relationship: String
        instagram: String
    }

    type Post {
        _id: ID!
        createdAt: String!
        userId: String!
        firstName: String!
        lastName: String!
        profilePic: String!
        type: String
        text: String!
        images: [String]!
        background: String
        reacts: [React]!
        reactCount: Int
        comments: [Comment]!
        commentCount: Int
    }

    type Comment {
        _id: ID!
        createdAt: String!
        userID: String
        firstName: String
        lastName: String
        profilePicture: String
        text: String
        image: String
        reacts: [React]!
        reactCount: Int
    }

    type React {
        _id: ID!
        createdAt: String!
        userId: String!
        firstName: String!
        lastName: String!
        profilePic: String!
        postId: String!
        react: String!
    }

    input RegisterInput {
        firstName: String!
        lastName: String!
        email: String!
        password: String!
        confirmPassword: String!
        gender: String!
        phoneNumber: String!
        birthYear: Int!
        birthMonth: Int!
        birthDay: Int!
    }

    type Query {
        getPosts: [Post]
        getPostById(postId: ID!): Post
    }

    type Mutation {
        register(registerInput: RegisterInput): Auth!
        login(email: String!, password: String!): Auth!

        createPost(text: String!, type: String, images: [String], background: String): Post!
        deletePost(postId: ID!): String!
        reactToPost(postId: ID!, reactionType: String!): Post!

        createComment(postId: ID!, text: String!, images: [String]): Post!
        deleteComment(postId: ID!, commentId: ID!): Post!
        reactToComment(postId: ID!, commentId: ID!, reactionType: String!): Comment!
    }
`;
```
<p>Here is the specific resolver for the example query:</p>
<pre class="lang-js prettyprint-override"><code>Query: {
        // Get all user posts
        async getPosts() {
            try {
                const posts = await Post.find().sort({ createdAt: -1 });
                return posts;
            } catch (err) {
                throw new Error(err);
            }
        },
        // Get a post by it's ID
        async getPostById(_, { postId }) {
            try {
                // Await the post
                const post = await Post.findById(postId);
                console.log(post.userId);
                // If the post exists return it
                if (post) {
                    return post;
                }
                // If the post doesn't exist show that it's not been found
                throw new Error('Post not found');
            } catch (err) {
                // Throw a new error otherwise
                throw new Error(err);
            }
        },
    },
</code>```

Here's my mongoose model:

const { Schema, model } = require('mongoose');

const { ObjectId } = Schema;

const postSchema = new Schema({
    createdAt: {
        type: String,
    },
    userId: {
        type: ObjectId,
        ref: 'User',
        required: true,
    },
    firstName: {
        type: String,
        required: true,
        trim: true,
        text: true,
    },
    lastName: {
        type: String,
        required: true,
        trim: true,
        text: true,
    },
    profilePicture: {
        type: String,
        trim: true,
        default: 'https://res.cloudinary.com/dmhcnhtng/image/upload/v1643044376/avatars/default_pic_jeaybr.png',
    },
    type: {
        type: String,
        enum: ['profilePicture', 'coverPicture', null],
        default: null,
    },
    text: {
        type: String,
    },
    images: {
        type: Array,
    },
    background: {
        type: String,
    },
    comments: [
        {
            createdAt: {
                type: Date,
                required: true,
            },
            userId: {
                type: ObjectId,
                ref: 'User',
                required: true,
            },
            firstName: {
                type: String,
                required: true,
                trim: true,
                text: true,
            },
            lastName: {
                type: String,
                required: true,
                trim: true,
                text: true,
            },
            profilePicture: {
                type: String,
                trim: true,
                default: 'https://res.cloudinary.com/dmhcnhtng/image/upload/v1643044376/avatars/default_pic_jeaybr.png',
            },
            text: {
                type: String,
            },
            image: {
                type: String,
            },
            reacts: [
                {
                    createdAt: {
                        type: String,
                        require: true,
                    },
                    userId: {
                        type: ObjectId,
                        ref: 'User',
                        required: true,
                    },
                    firstName: {
                        type: String,
                        required: true,
                        trim: true,
                        text: true,
                    },
                    lastName: {
                        type: String,
                        required: true,
                        trim: true,
                        text: true,
                    },
                    profilePicture: {
                        type: String,
                        trim: true,
                        default:
                            'https://res.cloudinary.com/dmhcnhtng/image/upload/v1643044376/avatars/default_pic_jeaybr.png',
                    },
                    reactionType: {
                        type: String,
                        enum: ['like', 'love', 'haha', 'sad', 'angry', 'wow'],
                        required: true,
                    },
                },
            ],
        },
    ],
    reacts: [
        {
            createdAt: {
                type: String,
                required: true,
            },
            userId: {
                type: ObjectId,
                ref: 'User',
            },
            firstName: {
                type: String,
                required: true,
                trim: true,
                text: true,
            },
            lastName: {
                type: String,
                required: true,
                trim: true,
                text: true,
            },
            profilePicture: {
                type: String,
                trim: true,
                default: 'https://res.cloudinary.com/dmhcnhtng/image/upload/v1643044376/avatars/default_pic_jeaybr.png',
            },
            reactionType: {
                type: String,
                enum: ['like', 'love', 'haha', 'sad', 'angry', 'wow'],
                required: true,
            },
        },
    ],
});
```

I've tried changing the type in the typedefs, but I don't want to return a user object, I just want the userID to show up in the comments array.

I find it weird that the userID shows up for the post but not for the comments. When I check my database on MongoDB atlas the userID is there, but I can't fetch it with graphQl.

Any help is much appreciated as I've been stuck on this conundrum for a number of hours.

Body:
I am trying to create a facebook clone using the MERNG stack.

Currently I'm creating the mutations and queries for the application. Most of the time they are working fine, except for whenever I'm trying to return the userID that is associated with the comments. The value returned is always null.

Here is an example when I'm using my getPostById query:

getPostById query as shown on apollographql sandbox

Here's the typedefs:

const typeDefs = gql`
    type User {
        _id: ID!
        createdAt: String!
        firstName: String!
        lastName: String!
        email: String!
        password: String!
        gender: String!
        phoneNumber: String!
        birthYear: Int!
        birthMonth: Int!
        birthDay: Int!
        profilePicture: String
        cover: String
        friends: [User]
        following: [User]
        followers: [User]
        requests: [User]
        search: [User]
        userDetails: UserDetails
        savedPosts: [Post]
    }

    type Auth {
        token: ID!
        user: User!
    }

    type UserDetails {
        _id: ID!
        createdAt: String!
        userId: String!
        bio: String
        otherName: String
        job: String
        workplace: String
        highschool: String
        college: String
        currentCity: String
        hometown: String
        relationship: String
        instagram: String
    }

    type Post {
        _id: ID!
        createdAt: String!
        userId: String!
        firstName: String!
        lastName: String!
        profilePic: String!
        type: String
        text: String!
        images: [String]!
        background: String
        reacts: [React]!
        reactCount: Int
        comments: [Comment]!
        commentCount: Int
    }

    type Comment {
        _id: ID!
        createdAt: String!
        userID: String
        firstName: String
        lastName: String
        profilePicture: String
        text: String
        image: String
        reacts: [React]!
        reactCount: Int
    }

    type React {
        _id: ID!
        createdAt: String!
        userId: String!
        firstName: String!
        lastName: String!
        profilePic: String!
        postId: String!
        react: String!
    }

    input RegisterInput {
        firstName: String!
        lastName: String!
        email: String!
        password: String!
        confirmPassword: String!
        gender: String!
        phoneNumber: String!
        birthYear: Int!
        birthMonth: Int!
        birthDay: Int!
    }

    type Query {
        getPosts: [Post]
        getPostById(postId: ID!): Post
    }

    type Mutation {
        register(registerInput: RegisterInput): Auth!
        login(email: String!, password: String!): Auth!

        createPost(text: String!, type: String, images: [String], background: String): Post!
        deletePost(postId: ID!): String!
        reactToPost(postId: ID!, reactionType: String!): Post!

        createComment(postId: ID!, text: String!, images: [String]): Post!
        deleteComment(postId: ID!, commentId: ID!): Post!
        reactToComment(postId: ID!, commentId: ID!, reactionType: String!): Comment!
    }
`;

Here is the specific resolver for the example query:

Query: {
        // Get all user posts
        async getPosts() {
            try {
                const posts = await Post.find().sort({ createdAt: -1 });
                return posts;
            } catch (err) {
                throw new Error(err);
            }
        },
        // Get a post by it's ID
        async getPostById(_, { postId }) {
            try {
                // Await the post
                const post = await Post.findById(postId);
                console.log(post.userId);
                // If the post exists return it
                if (post) {
                    return post;
                }
                // If the post doesn't exist show that it's not been found
                throw new Error('Post not found');
            } catch (err) {
                // Throw a new error otherwise
                throw new Error(err);
            }
        },
    },

Here's my mongoose model:

const { Schema, model } = require('mongoose');

const { ObjectId } = Schema;

const postSchema = new Schema({
    createdAt: {
        type: String,
    },
    userId: {
        type: ObjectId,
        ref: 'User',
        required: true,
    },
    firstName: {
        type: String,
        required: true,
        trim: true,
        text: true,
    },
    lastName: {
        type: String,
        required: true,
        trim: true,
        text: true,
    },
    profilePicture: {
        type: String,
        trim: true,
        default: 'https://res.cloudinary.com/dmhcnhtng/image/upload/v1643044376/avatars/default_pic_jeaybr.png',
    },
    type: {
        type: String,
        enum: ['profilePicture', 'coverPicture', null],
        default: null,
    },
    text: {
        type: String,
    },
    images: {
        type: Array,
    },
    background: {
        type: String,
    },
    comments: [
        {
            createdAt: {
                type: Date,
                required: true,
            },
            userId: {
                type: ObjectId,
                ref: 'User',
                required: true,
            },
            firstName: {
                type: String,
                required: true,
                trim: true,
                text: true,
            },
            lastName: {
                type: String,
                required: true,
                trim: true,
                text: true,
            },
            profilePicture: {
                type: String,
                trim: true,
                default: 'https://res.cloudinary.com/dmhcnhtng/image/upload/v1643044376/avatars/default_pic_jeaybr.png',
            },
            text: {
                type: String,
            },
            image: {
                type: String,
            },
            reacts: [
                {
                    createdAt: {
                        type: String,
                        require: true,
                    },
                    userId: {
                        type: ObjectId,
                        ref: 'User',
                        required: true,
                    },
                    firstName: {
                        type: String,
                        required: true,
                        trim: true,
                        text: true,
                    },
                    lastName: {
                        type: String,
                        required: true,
                        trim: true,
                        text: true,
                    },
                    profilePicture: {
                        type: String,
                        trim: true,
                        default:
                            'https://res.cloudinary.com/dmhcnhtng/image/upload/v1643044376/avatars/default_pic_jeaybr.png',
                    },
                    reactionType: {
                        type: String,
                        enum: ['like', 'love', 'haha', 'sad', 'angry', 'wow'],
                        required: true,
                    },
                },
            ],
        },
    ],
    reacts: [
        {
            createdAt: {
                type: String,
                required: true,
            },
            userId: {
                type: ObjectId,
                ref: 'User',
            },
            firstName: {
                type: String,
                required: true,
                trim: true,
                text: true,
            },
            lastName: {
                type: String,
                required: true,
                trim: true,
                text: true,
            },
            profilePicture: {
                type: String,
                trim: true,
                default: 'https://res.cloudinary.com/dmhcnhtng/image/upload/v1643044376/avatars/default_pic_jeaybr.png',
            },
            reactionType: {
                type: String,
                enum: ['like', 'love', 'haha', 'sad', 'angry', 'wow'],
                required: true,
            },
        },
    ],
});

I've tried changing the type in the typedefs, but I don't want to return a user object, I just want the userID to show up in the comments array.

I find it weird that the userID shows up for the post but not for the comments. When I check my database on MongoDB atlas the userID is there, but I can't fetch it with graphQl.

Any help is much appreciated as I've been stuck on this conundrum for a number of hours.


问:
Cannot find module when import class in typescript
I import the class "User" in the index.ts and want to output a user. When compiling, I get the error message "Cannot find module". However, as soon as I consider the extension .js when importing, it works.

In all the tutorials I've watched now, I don't see anywhere that the extension is taken into consider when importing.

User.ts

```<code>export class User {
    static getUser() {
        return {
            "email": "john.doe@example.com",
            "password": "123456"
        }
    }
}
</code>```

index.ts

```<code>import {User} from "./User";

const user = User.getUser()
console.log(user)
</code>```

package.json

```<code>...
"type": "module",
  "scripts": {
    "compile": "tsc",
    "start": "npm run compile && node ./dist/index.js"
  },
...
</code>```

tsconfig.json

```<code>{
  "compilerOptions": {
    "rootDirs": ["src"],
    "outDir": "dist",
    "lib": ["es2020"],
    "target": "esnext",
    "module": "esnext",
    "moduleResolution": "node",
    "esModuleInterop": true,
    "types": ["node"]
  }
}
</code>```

Body:
I import the class "User" in the index.ts and want to output a user. When compiling, I get the error message "Cannot find module". However, as soon as I consider the extension .js when importing, it works.

In all the tutorials I've watched now, I don't see anywhere that the extension is taken into consider when importing.

User.ts

export class User {
    static getUser() {
        return {
            "email": "john.doe@example.com",
            "password": "123456"
        }
    }
}

index.ts

import {User} from "./User";

const user = User.getUser()
console.log(user)

package.json

...
"type": "module",
  "scripts": {
    "compile": "tsc",
    "start": "npm run compile && node ./dist/index.js"
  },
...

tsconfig.json

{
  "compilerOptions": {
    "rootDirs": ["src"],
    "outDir": "dist",
    "lib": ["es2020"],
    "target": "esnext",
    "module": "esnext",
    "moduleResolution": "node",
    "esModuleInterop": true,
    "types": ["node"]
  }
}


问:
Three js selective glow with different strength for different object
I have several objects in my scene that should have different strength of neon/glowing effect. Besides glowing objects there are also non glowing, so I am wondering how it is possible to achieve selective glowing effects for different object with different strength?
To make selective glow I can make non glowing objects black and first render glowing objects, then render non-glowing with restored colors and combine glowing + non-glowing renders. But I am not sure how I can control glowing strength for each glowing object with this approach</p>


问:
How to handle mobile hardware back button in react js
Product Search Page Screeshot

User lands on to Home page.

Then home to Search page.

Then go to Filter page when tap on filter button on search page.

Then select Filter like category, color which updates the browser URL.

When new query and user press apply button.

Then we that query string we come back on search page and product loads again.

Now problem is

When we press back button we again go to filter

When we to got home page when we are on search.

When we select filter on filter page like category, colors and press back button
filters get unselected as URL again update, so how to tackle that or disable hardware back button of mobile phone.
Filter Page Screenshot


问:
Pytorch: Quantize weights to unisgned 8 bit
I am trying to quantize the weights of the BERT model to unsigned 8 bits, and working with PyTorch. It works well with int8 datatype, but throws an error for unsigned int8 bits.

Am using the 'dynamic_quantize' function for the same.

```<code>quantized_model = torch.quantization.quantize_dynamic( model, {torch.nn.Linear}, dtype=torch.quint8 )
</code>```

But it throws the error 'AssertionError: The only supported dtypes for dynamic quantized linear are qint8 and float16 got: torch.quint8'.

Is there any specific reason for this not to be supported? Could I use any other method to quantize the weights to unsigned int8 bits?

Here is a link to the colab sheet:
https://colab.research.google.com/drive/14G_jdLuZD5846jUDZUdGNf1x0DMz8GKK?usp=sharing

Thanks!

Body:
I am trying to quantize the weights of the BERT model to unsigned 8 bits, and working with PyTorch. It works well with int8 datatype, but throws an error for unsigned int8 bits.

Am using the 'dynamic_quantize' function for the same.

quantized_model = torch.quantization.quantize_dynamic( model, {torch.nn.Linear}, dtype=torch.quint8 )

But it throws the error 'AssertionError: The only supported dtypes for dynamic quantized linear are qint8 and float16 got: torch.quint8'.

Is there any specific reason for this not to be supported? Could I use any other method to quantize the weights to unsigned int8 bits?

Here is a link to the colab sheet:
https://colab.research.google.com/drive/14G_jdLuZD5846jUDZUdGNf1x0DMz8GKK?usp=sharing

Thanks!


问:
replacing certain values in a column based upon matched criteria between datasets with python
I have a large dataset of books that have ISBN, prices, suggested retail, and the discount given by the publisher. The pricing and discount will change, by the publisher, and I have to go in and update it. I have tried to do so by matching the ISBN with the first or original dataset with the second dataset (the second dataset has the updated prices and discounts). Then once the ISBN is matched, I try to substitute the retail price from the second or new dataset into the first or original dataset. I have tried the following lines of code using python and pandas dataFrame:

```<code>    if firstone['ISBN'].equals(secondone['ISBN]):
         firstone['retail'].replace(secondone['retail'])
</code>```

I have also tried to put it into a function where:

```<code>    firstone = inventory
    secondone = inventory2

    def updatedretail():
         if firstone['ISBN'].equals(secondone['ISBN]):
              firstone['retail'].replace(secondone['retail'])
         return firstone

     inventory.apply(updatedretail)
</code>```

This is in a pandas dataframe. the variable inventory is the original dataset and the varibale inventory2 is the second dataset with the updated retail prices and discount. So, the variable firstone and secondone applies to the dataset inventory and inventory2. It has not changed the retail prices on the first dataset to reflect the newly given retail prices in the second dataset. So, for example when I try to locate ISBN:

```<code>               inventory[inventory['ISBN'] == 9780061121364]
</code>```

it still shows the old retail/discount and not the new one from the second dataset. I need to substitute the new prices from the second dataset into the first dataset once it matches based on ISBN. When I tried to run the function, I received the following error message:

```<code>             TypeError: updatedretail() takes 0 positional arguments but 1 was given
</code>```

So, please help. How could I substitute the values from the second dataset into the original dataset (while keeping all of the other data intact) after matching it based upon shared identifiable characteristics (which is the ISBN).

Body:
I have a large dataset of books that have ISBN, prices, suggested retail, and the discount given by the publisher. The pricing and discount will change, by the publisher, and I have to go in and update it. I have tried to do so by matching the ISBN with the first or original dataset with the second dataset (the second dataset has the updated prices and discounts). Then once the ISBN is matched, I try to substitute the retail price from the second or new dataset into the first or original dataset. I have tried the following lines of code using python and pandas dataFrame:

    if firstone['ISBN'].equals(secondone['ISBN]):
         firstone['retail'].replace(secondone['retail'])

I have also tried to put it into a function where:

    firstone = inventory
    secondone = inventory2

    def updatedretail():
         if firstone['ISBN'].equals(secondone['ISBN]):
              firstone['retail'].replace(secondone['retail'])
         return firstone

     inventory.apply(updatedretail)

This is in a pandas dataframe. the variable inventory is the original dataset and the varibale inventory2 is the second dataset with the updated retail prices and discount. So, the variable firstone and secondone applies to the dataset inventory and inventory2. It has not changed the retail prices on the first dataset to reflect the newly given retail prices in the second dataset. So, for example when I try to locate ISBN:

               inventory[inventory['ISBN'] == 9780061121364]

it still shows the old retail/discount and not the new one from the second dataset. I need to substitute the new prices from the second dataset into the first dataset once it matches based on ISBN. When I tried to run the function, I received the following error message:

             TypeError: updatedretail() takes 0 positional arguments but 1 was given

So, please help. How could I substitute the values from the second dataset into the original dataset (while keeping all of the other data intact) after matching it based upon shared identifiable characteristics (which is the ISBN).


问:
How to force lower version Zxing QRcode
I'm trying to make QRcode with version 6 41x41 modules, there is requirement for old system.
Here my String data:

```<code>"H 4A91K       BB7998  M11AU10406   CBU 4A91471     H 000160        69H 69578 00009Y000                            @N                                      "
</code>```

I try to generated using Zxing library, the lower possibility I can get only version 7 using below parameter:

```<code>Map<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
hints.put(EncodeHintType.QR_VERSION, 7);
</code>```

I try to compare some web API can generate QRcode as version 6

https://goqr.me/api/

https://www.barcode-generator.org/

How I can force zxing to version 6 based on my String data requirement? is that possible?

Thank you for your support.

Title: How to force lower version Zxing QRcode

Body:
I'm trying to make QRcode with version 6 41x41 modules, there is requirement for old system.
Here my String data:

"H 4A91K       BB7998  M11AU10406   CBU 4A91471     H 000160        69H 69578 00009Y000                            @N                                      "

I try to generated using Zxing library, the lower possibility I can get only version 7 using below parameter:

Map<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
hints.put(EncodeHintType.QR_VERSION, 7);

I try to compare some web API can generate QRcode as version 6

https://goqr.me/api/

https://www.barcode-generator.org/

How I can force zxing to version 6 based on my String data requirement? is that possible?

Thank you for your support.


问:
eigen custom type expression template type issue
I want to use Eigen with a custom type, which happens to be implementing the expression template pradigm itself:

Basically, I got my base class:

```<code>namespace NS
{

template<class Expr>
class MyTypeExpression
{
public:
    double eval() const { return static_cast<Expr const&>(*this).eval(); }
};

}
</code>```

My custom type:

```<code>namespace NS
{

class MyType : public MyTypeExpression<MyType>
{
public:
    MyType(double value = 0) : m_value(value) {}

    template<typename Expr> MyType(const MyTypeExpression<Expr>& expr) : m_value(expr.eval()) {}

    ~MyType() {}

    double eval() const { return m_value; }

    template<typename Expr> MyType& operator= (const MyTypeExpression<Expr>& expr) { m_value  = expr.eval(); return *this; }
    template<typename Expr> MyType& operator+=(const MyTypeExpression<Expr>& expr) { m_value += expr.eval(); return *this; }
    template<typename Expr> MyType& operator-=(const MyTypeExpression<Expr>& expr) { m_value -= expr.eval(); return *this; }
    template<typename Expr> MyType& operator*=(const MyTypeExpression<Expr>& expr) { m_value *= expr.eval(); return *this; }
    template<typename Expr> MyType& operator/=(const MyTypeExpression<Expr>& expr) { m_value /= expr.eval(); return *this; }
private:
    double m_value;
};

}
</code>```

an my operators:

```<code>namespace NS
{
    template<class Expr> inline const Expr& conj(const NS::MyTypeExpression<Expr>& x)  { return *static_cast<const Expr*>(&x); }
    template<class Expr> inline const Expr& real(const NS::MyTypeExpression<Expr>& x)  { return *static_cast<const Expr*>(&x); }
    template<class Expr> inline MyType      imag(const NS::MyTypeExpression<Expr>&)    { return NS::MyType(); }
    template<class Expr> inline MyType      abs (const NS::MyTypeExpression<Expr>& x)  { return NS::MyType(std::fabs(x.eval())); }
    template<class Expr> inline MyType      abs2(const NS::MyTypeExpression<Expr>& x)  { const double y = x.eval(); return NS::MyType(y*y); }
}

template<class Lhs, class Rhs>
NS::MyTypeBinaryExpression<Lhs,Rhs,NS::OpSum> operator+(const NS::MyTypeExpression<Lhs>& lhs, const NS::MyTypeExpression<Rhs>& rhs)
    { return NS::MyTypeBinaryExpression<Lhs,Rhs,NS::OpSum>(*static_cast<const Lhs*>(&lhs), *static_cast<const Rhs*>(&rhs)); }

template<class Lhs, class Rhs>
NS::MyTypeBinaryExpression<Lhs,Rhs,NS::OpSub> operator-(const NS::MyTypeExpression<Lhs>& lhs, const NS::MyTypeExpression<Rhs>& rhs)
    { return NS::MyTypeBinaryExpression<Lhs,Rhs,NS::OpSub>(*static_cast<const Lhs*>(&lhs), *static_cast<const Rhs*>(&rhs)); }

template<class Lhs, class Rhs>
NS::MyTypeBinaryExpression<Lhs,Rhs,NS::OpProd> operator*(const NS::MyTypeExpression<Lhs>& lhs, const NS::MyTypeExpression<Rhs>& rhs)
    { return NS::MyTypeBinaryExpression<Lhs,Rhs,NS::OpProd>(*static_cast<const Lhs*>(&lhs), *static_cast<const Rhs*>(&rhs)); }

template<class Lhs, class Rhs>
NS::MyTypeBinaryExpression<Lhs,Rhs,NS::OpDiv> operator/(const NS::MyTypeExpression<Lhs>& lhs, const NS::MyTypeExpression<Rhs>& rhs)
    { return NS::MyTypeBinaryExpression<Lhs,Rhs,NS::OpDiv>(*static_cast<const Lhs*>(&lhs), *static_cast<const Rhs*>(&rhs)); }

template<class Expr>
std::ostream& operator<<(std::ostream& out, const NS::MyTypeExpression<Expr>& x) { out << x.eval(); return out; }
</code>```

A simple test works fine:

```<code>NS::MyType a(1);
NS::MyType b(2);

std::cout << a + b << std::endl;
</code>```

But using my type with eigen yeilds a tone of errors:

```<code>typedef Eigen::Matrix< NS::MyType, Eigen::Dynamic, 1 > Vector;
Vector a(10);
std::cout << a << std::endl;

/usr/include/eigen3/Eigen/src/Core/IO.h:175:14: error: no match for ‘operator<<’ (operand types are ‘std::stringstream’ {aka ‘std::__cxx11::basic_stringstream<char>’} and ‘const Scalar’ {aka ‘const NS::MyType’})
  175 |         sstr << m.coeff(i,j);
</code>```

I did implemented a Eigen::NumTraits for my type but maybe I did it wrong...

```<code>namespace Eigen
{

template<> struct NumTraits<NS::MyType> : NumTraits<double> // permits to get the epsilon, dummy_precision, lowest, highest functions
{
  typedef NS::MyType Real;
  typedef NS::MyType NonInteger;
  typedef NS::MyType Nested;

  enum {
    IsComplex = 0,
    IsInteger = 0,
    IsSigned = 1,
    RequireInitialization = 1,
    ReadCost = 1,
    AddCost = 3,
    MulCost = 3
  };
};

}
</code>```

I will attach a full minimal working example.

Has anyone ever experienced such an issue with eigen ?

Edit: I copy-pasted the wrong base class, it is now corrected

Body:
I want to use Eigen with a custom type, which happens to be implementing the expression template pradigm itself:

Basically, I got my base class:

namespace NS
{

template<class Expr>
class MyTypeExpression
{
public:
    double eval() const { return static_cast<Expr const&>(*this).eval(); }
};

}

My custom type:

namespace NS
{

class MyType : public MyTypeExpression<MyType>
{
public:
    MyType(double value = 0) : m_value(value) {}

    template<typename Expr> MyType(const MyTypeExpression<Expr>& expr) : m_value(expr.eval()) {}

    ~MyType() {}

    double eval() const { return m_value; }

    template<typename Expr> MyType& operator= (const MyTypeExpression<Expr>& expr) { m_value  = expr.eval(); return *this; }
    template<typename Expr> MyType& operator+=(const MyTypeExpression<Expr>& expr) { m_value += expr.eval(); return *this; }
    template<typename Expr> MyType& operator-=(const MyTypeExpression<Expr>& expr) { m_value -= expr.eval(); return *this; }
    template<typename Expr> MyType& operator*=(const MyTypeExpression<Expr>& expr) { m_value *= expr.eval(); return *this; }
    template<typename Expr> MyType& operator/=(const MyTypeExpression<Expr>& expr) { m_value /= expr.eval(); return *this; }
private:
    double m_value;
};

}

an my operators:

namespace NS
{
    template<class Expr> inline const Expr& conj(const NS::MyTypeExpression<Expr>& x)  { return *static_cast<const Expr*>(&x); }
    template<class Expr> inline const Expr& real(const NS::MyTypeExpression<Expr>& x)  { return *static_cast<const Expr*>(&x); }
    template<class Expr> inline MyType      imag(const NS::MyTypeExpression<Expr>&)    { return NS::MyType(); }
    template<class Expr> inline MyType      abs (const NS::MyTypeExpression<Expr>& x)  { return NS::MyType(std::fabs(x.eval())); }
    template<class Expr> inline MyType      abs2(const NS::MyTypeExpression<Expr>& x)  { const double y = x.eval(); return NS::MyType(y*y); }
}

template<class Lhs, class Rhs>
NS::MyTypeBinaryExpression<Lhs,Rhs,NS::OpSum> operator+(const NS::MyTypeExpression<Lhs>& lhs, const NS::MyTypeExpression<Rhs>& rhs)
    { return NS::MyTypeBinaryExpression<Lhs,Rhs,NS::OpSum>(*static_cast<const Lhs*>(&lhs), *static_cast<const Rhs*>(&rhs)); }

template<class Lhs, class Rhs>
NS::MyTypeBinaryExpression<Lhs,Rhs,NS::OpSub> operator-(const NS::MyTypeExpression<Lhs>& lhs, const NS::MyTypeExpression<Rhs>& rhs)
    { return NS::MyTypeBinaryExpression<Lhs,Rhs,NS::OpSub>(*static_cast<const Lhs*>(&lhs), *static_cast<const Rhs*>(&rhs)); }

template<class Lhs, class Rhs>
NS::MyTypeBinaryExpression<Lhs,Rhs,NS::OpProd> operator*(const NS::MyTypeExpression<Lhs>& lhs, const NS::MyTypeExpression<Rhs>& rhs)
    { return NS::MyTypeBinaryExpression<Lhs,Rhs,NS::OpProd>(*static_cast<const Lhs*>(&lhs), *static_cast<const Rhs*>(&rhs)); }

template<class Lhs, class Rhs>
NS::MyTypeBinaryExpression<Lhs,Rhs,NS::OpDiv> operator/(const NS::MyTypeExpression<Lhs>& lhs, const NS::MyTypeExpression<Rhs>& rhs)
    { return NS::MyTypeBinaryExpression<Lhs,Rhs,NS::OpDiv>(*static_cast<const Lhs*>(&lhs), *static_cast<const Rhs*>(&rhs)); }

template<class Expr>
std::ostream& operator<<(std::ostream& out, const NS::MyTypeExpression<Expr>& x) { out << x.eval(); return out; }

A simple test works fine:

NS::MyType a(1);
NS::MyType b(2);

std::cout << a + b << std::endl;

But using my type with eigen yeilds a tone of errors:

typedef Eigen::Matrix< NS::MyType, Eigen::Dynamic, 1 > Vector;
Vector a(10);
std::cout << a << std::endl;

/usr/include/eigen3/Eigen/src/Core/IO.h:175:14: error: no match for ‘operator<<’ (operand types are ‘std::stringstream’ {aka ‘std::__cxx11::basic_stringstream<char>’} and ‘const Scalar’ {aka ‘const NS::MyType’})
  175 |         sstr << m.coeff(i,j);

I did implemented a Eigen::NumTraits for my type but maybe I did it wrong...

namespace Eigen
{

template<> struct NumTraits<NS::MyType> : NumTraits<double> // permits to get the epsilon, dummy_precision, lowest, highest functions
{
  typedef NS::MyType Real;
  typedef NS::MyType NonInteger;
  typedef NS::MyType Nested;

  enum {
    IsComplex = 0,
    IsInteger = 0,
    IsSigned = 1,
    RequireInitialization = 1,
    ReadCost = 1,
    AddCost = 3,
    MulCost = 3
  };
};

}

I will attach a full minimal working example.

Has anyone ever experienced such an issue with eigen ?

Edit: I copy-pasted the wrong base class, it is now corrected


问:
Implementing in APP Update not working for andoird studio
The in app update is not working no errors just not implementing
I have created the code in oncreate function

```<code>
</code>```

```<code>public static int UPDATE_CODE = 22;    //for adding inapp update
AppUpdateManager appUpdateManager;     //for adding inapp update

</code>```

private void inAppUp()   //for in APP update
{
appUpdateManager = AppUpdateManagerFactory.create(this);
Task task = appUpdateManager.getAppUpdateInfo();
task.addOnSuccessListener(appUpdateInfo -> {
if (appUpdateInfo.updateAvailability() == UpdateAvailability.UPDATE_AVAILABLE
appUpdateInfo.isUpdateTypeAllowed(AppUpdateType.FLEXIBLE))
{
try {
appUpdateManager.startUpdateFlowForResult(appUpdateInfo,AppUpdateType.FLEXIBLE,MainActivity.this,UPDATE_CODE);
catch (IntentSender.SendIntentException e) {
e.printStackTrace();
}
}
});

calling listerner
appUpdateManager.registerListener(listener);
}
//inAPPup ends here

```<code>//in app update installing a listerner
</code>```

InstallStateUpdatedListener listener = installState ->
{
if (installState.installStatus() == InstallStatus.DOWNLOADED){

popUp();  // calling popUp method to show snackbor to user
}
};

popUP shows Snackbar when app in updated
private void popUp() {
Snackbar snackbar = Snackbar.make(findViewById(android.R.id.content),
"Your APP is almost Updated",
Snackbar.LENGTH_INDEFINITE
);

snackbar.setAction("Reload", new View.OnClickListener() {
@Override
public void onClick(View view) {
appUpdateManager.completeUpdate();
}
});
snackbar.setTextColor(Color.parseColor("#FF0000"));
snackbar.show();
}

```<code>@Override
</code>```

protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode==UPDATE_CODE)
{
if (resultCode != RESULT_OK){}
}
}

```<code>
</code>```

The app update is not working

Body:
The in app update is not working no errors just not implementing
I have created the code in oncreate function

public static int UPDATE_CODE = 22;    //for adding inapp update
AppUpdateManager appUpdateManager;     //for adding inapp update

private void inAppUp()   //for in APP update
{
appUpdateManager = AppUpdateManagerFactory.create(this);
Task task = appUpdateManager.getAppUpdateInfo();
task.addOnSuccessListener(appUpdateInfo -> {
if (appUpdateInfo.updateAvailability() == UpdateAvailability.UPDATE_AVAILABLE
appUpdateInfo.isUpdateTypeAllowed(AppUpdateType.FLEXIBLE))
{
try {
appUpdateManager.startUpdateFlowForResult(appUpdateInfo,AppUpdateType.FLEXIBLE,MainActivity.this,UPDATE_CODE);
catch (IntentSender.SendIntentException e) {
e.printStackTrace();
}
}
});

calling listerner
appUpdateManager.registerListener(listener);
}
//inAPPup ends here

//in app update installing a listerner

InstallStateUpdatedListener listener = installState ->
{
if (installState.installStatus() == InstallStatus.DOWNLOADED){

popUp();  // calling popUp method to show snackbor to user
}
};

popUP shows Snackbar when app in updated
private void popUp() {
Snackbar snackbar = Snackbar.make(findViewById(android.R.id.content),
"Your APP is almost Updated",
Snackbar.LENGTH_INDEFINITE
);

snackbar.setAction("Reload", new View.OnClickListener() {
@Override
public void onClick(View view) {
appUpdateManager.completeUpdate();
}
});
snackbar.setTextColor(Color.parseColor("#FF0000"));
snackbar.show();
}

@Override

protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode==UPDATE_CODE)
{
if (resultCode != RESULT_OK){}
}
}

The app update is not working


问:
open multiple tabs/windows programatically on mobile browser
I have an array of links I want to open on a button click.

While it works as expected on Firefox Desktop it doesn't work on Firefox Mobile

Firefox Desktop blocks the opening (as expected) and asks if I want to give permission to open popups.  If I allow it all links are opened as expected.

The problem with Firefox Mobile is that only the first link in the array is opened consistently, after that sometimes a second link (not necessarily the second link in the array) is opened after Firefox Mobile asking if I want to allow it.

I had a look a multiple questions here, none worked so far, so my question targets mobile specifically (since it works on desktop as expected)

Is there a possibility to open multiple links an a mobile browser (even with manually allowing popups)?

What I tried so far

```<code>// I loop through a list of links which are present in the document
 document.querySelectorAll('a.shop-link').forEach((link) => {
   //none works
   window.open(link.href, '_blank')
   //also tried it with higher delay
   setTimeout(() => window.open(link.href, '_blank'), 100)
   link.click()
})
</code>```

Body:
I have an array of links I want to open on a button click.

While it works as expected on Firefox Desktop it doesn't work on Firefox Mobile

Firefox Desktop blocks the opening (as expected) and asks if I want to give permission to open popups.  If I allow it all links are opened as expected.

The problem with Firefox Mobile is that only the first link in the array is opened consistently, after that sometimes a second link (not necessarily the second link in the array) is opened after Firefox Mobile asking if I want to allow it.

I had a look a multiple questions here, none worked so far, so my question targets mobile specifically (since it works on desktop as expected)

Is there a possibility to open multiple links an a mobile browser (even with manually allowing popups)?

What I tried so far

// I loop through a list of links which are present in the document
 document.querySelectorAll('a.shop-link').forEach((link) => {
   //none works
   window.open(link.href, '_blank')
   //also tried it with higher delay
   setTimeout(() => window.open(link.href, '_blank'), 100)
   link.click()
})


问:
In git is there a way to link external files?
I often have external documentation in the form of PDF files. It would be great to put them into a project's git repo - but to store only a link to the file's source in the repo proper and have the actual file only locally.

When the repo gets distributed, only the link and probably a hash would be transferred. The actual file would downloaded from the external link on checkout.

For example manual.pdf as a link to https://example.com/manual.pdf.

Is there a way to do this, maybe with an extension?

Pros

avoids blobs in the repo

I might not have redistribution rights on a file. While it's normal not to care about this, this problem would be avoided entirely by linking to the file instead of redistributing it.

Cons

the upstream file might disappear.


问:
RuntimeError: “max_cpu” not implemented for ‘ComplexFloat’ in Pytorch
I have a tensor of shape torch.Size([128, 1, 480]) and I want to get the maximum value of the tensor. The tensor has float complex numbers and I am running my code on CPU, but the code results in the following error:

RuntimeError: “max_cpu” not implemented for ‘ComplexFloat’

It seems that the max function is not implemented for running on CPU yet. Is there any alternatives to use instead?


问:
check to see if it is a featured image or a post image in wordpress
I am making WordPress images responsive, I have considered 3 sizes for the featured image and 2 sizes for the post image, and now I want to add sizes alt to the featured image and post image :

sizes featured image : sizes="(min-width: 1200px) 1118px, 95.45vw"

sizes post image : sizes="(min-width: 1200px) 1094px, calc(95.45vw - 32px)"

how can I condition that if the image is featured it will add the following: sizes="(min-width: 1200px) 1118px, 95.45vw"

and if the image was posted, put the following: sizes="(min-width: 1200px) 1094px, calc(95.45vw - 32px)"

these are the 2 codes I use :

```<code>function blog_1( $sizes, $size ) {
  return '(min-width: 1200px) 1118px, 95.45vw';
} add_filter( 'wp_calculate_image_sizes', 'blog_1', 10 , 2 );

function blog_2( $sizes, $size ) {
  return '(min-width: 1200px) 1094px, calc(95.45vw - 32px)';
} add_filter( 'wp_calculate_image_sizes', 'blog_2', 10 , 2 );
</code>```

Body:
I am making WordPress images responsive, I have considered 3 sizes for the featured image and 2 sizes for the post image, and now I want to add sizes alt to the featured image and post image :

sizes featured image : sizes="(min-width: 1200px) 1118px, 95.45vw"

sizes post image : sizes="(min-width: 1200px) 1094px, calc(95.45vw - 32px)"

how can I condition that if the image is featured it will add the following: sizes="(min-width: 1200px) 1118px, 95.45vw"

and if the image was posted, put the following: sizes="(min-width: 1200px) 1094px, calc(95.45vw - 32px)"

these are the 2 codes I use :

function blog_1( $sizes, $size ) {
  return '(min-width: 1200px) 1118px, 95.45vw';
} add_filter( 'wp_calculate_image_sizes', 'blog_1', 10 , 2 );

function blog_2( $sizes, $size ) {
  return '(min-width: 1200px) 1094px, calc(95.45vw - 32px)';
} add_filter( 'wp_calculate_image_sizes', 'blog_2', 10 , 2 );


问:
AWS Kinesis Minimum Buffer Limit for Dynamic Partitioning
I'm changing a Kinesis delivery stream (to S3) to use dynamic partitioning.

I'm choosing to use inline parsing on one record attribute as the data it receives is in JSON format.

This will then create objects in the S3 bucket with prefixes with the extracted attribute value.

This is all easy to configure. The big gotcha I have found is that when dynamic partitioning is enabled the minimum buffer limit (before Kinesis sends data to S3) is increased from 1MB to 64MB, this is going to hit my pipeline throughput as I currently have it set at 1MB.

Does anyone know why the minimum limit is increased so significantly when dynamic partitioning is enabled ?


问:
Illuminate Database Query Exception Error
I can't solve Illuminate\Database\QueryException error when I run php artisan migrate for laravel project although I find many source on internet. I can't solve any answers with following Illuminate\Database\QueryException SQLSTATE[42000] and Artisan migrate error: Illuminate\Database\QueryException. Please answer me.

```<code>PHP Warning:  Module "pdo_mysql" is already loaded in Unknown on line 0

Warning: Module "pdo_mysql" is already loaded in Unknown on line 0

   Illuminate\Database\QueryException

  SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: NO) (SQL: select * from information_schema.tables where table_schema = laravelbackend and table_name = migrations
and table_type = 'BASE TABLE')

  at C:\connectflutterlaravel\laravelbackend\vendor\laravel\framework\src\Illuminate\Database\Connection.php:760
    756▕         // If an exception occurs when attempting to run a query, we'll format the error
    757▕         // message to include the bindings with SQL, which will make this exception a
    758▕         // lot more helpful to the developer instead of just the database's errors.
    759▕         catch (Exception $e) {
  ➜ 760▕             throw new QueryException(
    761▕                 $query, $this->prepareBindings($bindings), $e
    762▕             );
    763▕         }
    764▕     }

  1   C:\connectflutterlaravel\laravelbackend\vendor\laravel\framework\src\Illuminate\Database\Connectors\Connector.php:70
      PDOException::("SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: NO)")

  2   C:\connectflutterlaravel\laravelbackend\vendor\laravel\framework\src\Illuminate\Database\Connectors\Connector.php:70
      PDO::__construct("mysql:host=127.0.0.1;port=3306;dbname=laravelbackend", "root", "", [])
</code>```

I found those 4 errors in C:\connectflutterlaravel\laravelbackend\vendor\laravel\framework\src\Illuminate\Database\Connectors\Connector.php enter image description here

Body:
I can't solve Illuminate\Database\QueryException error when I run php artisan migrate for laravel project although I find many source on internet. I can't solve any answers with following Illuminate\Database\QueryException SQLSTATE[42000] and Artisan migrate error: Illuminate\Database\QueryException. Please answer me.

PHP Warning:  Module "pdo_mysql" is already loaded in Unknown on line 0

Warning: Module "pdo_mysql" is already loaded in Unknown on line 0

   Illuminate\Database\QueryException

  SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: NO) (SQL: select * from information_schema.tables where table_schema = laravelbackend and table_name = migrations
and table_type = 'BASE TABLE')

  at C:\connectflutterlaravel\laravelbackend\vendor\laravel\framework\src\Illuminate\Database\Connection.php:760
    756▕         // If an exception occurs when attempting to run a query, we'll format the error
    757▕         // message to include the bindings with SQL, which will make this exception a
    758▕         // lot more helpful to the developer instead of just the database's errors.
    759▕         catch (Exception $e) {
  ➜ 760▕             throw new QueryException(
    761▕                 $query, $this->prepareBindings($bindings), $e
    762▕             );
    763▕         }
    764▕     }

  1   C:\connectflutterlaravel\laravelbackend\vendor\laravel\framework\src\Illuminate\Database\Connectors\Connector.php:70
      PDOException::("SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: NO)")

  2   C:\connectflutterlaravel\laravelbackend\vendor\laravel\framework\src\Illuminate\Database\Connectors\Connector.php:70
      PDO::__construct("mysql:host=127.0.0.1;port=3306;dbname=laravelbackend", "root", "", [])

I found those 4 errors in C:\connectflutterlaravel\laravelbackend\vendor\laravel\framework\src\Illuminate\Database\Connectors\Connector.php enter image description here


问:
Advent of Code Day 2 - Javascript Array Processing Issue
I am currently completing the Day 2 challenge of Advent of Code and noticed that when I convert the given challenge text into a string in the format of

```<code>const rounds = 'B Y\n'+
'A X\n'+
'B Y\n'+
'A Y\n'+
'A Z\n'+
'B Y\n'+
'B Z\n'+
'C Y\n'+
'A X;

</code>```

Here is the link to the full input

It creates issues when running a forEach and for loop with the whole dataset after splitting the string using Array.prototype.split(\n). The issue it is causing is the first index starts at around 1500 and ends 2500 for a dataset of about 5000 values. This is my solution to the challenge

```<code>import rounds from "./rounds.js";

const choiceMap = {
  A: {
    type: "Rock",
    points: 1,
  },
  B: {
    type: "Paper",
    points: 2,
  },
  C: {
    type: "Scissors",
    points: 3,
  },
  Y: {
    type: "Rock",
    points: 1,
  },
  X: {
    type: "Paper",
    points: 2,
  },
  Z: {
    type: "Scissors",
    points: 3,
  },
};

const pointMap = {
  Rock: {
    win: "Scissors",
    loss: "Paper",
  },
  Scissors: {
    win: "Paper",
    loss: "Rock",
  },
  Paper: {
    win: "Rock",
    loss: "Scissors",
  },
};

class RockPaperScissors {
  constructor(rounds) {
    this.rounds = rounds.trim().split("\n");
  }
  determinePoints = (choice, opponentChoice) => {
    let points = 0;
    choice = choiceMap[choice];
    opponentChoice = choiceMap[opponentChoice];
    points += choice.points;

    if (pointMap[choice.type].win === opponentChoice.type) points += 6;
    else if (choice.type === opponentChoice.type) points += 3;

    return points;
  };
  getPoints() {
    let points = 0;

    this.rounds.forEach((round, index) => {
      if (index === 0) console.log("first round");
      console.log(round, index);
      const [opponentChoice, choice] = round.split(" ");
      points += this.determinePoints(choice, opponentChoice);
    });
    return points;
  }
}

const elfGames = new RockPaperScissors(rounds);
elfGames.getPoints();
</code>```

This is the start of my console output showing that loop did not start and end in the right positions

```<code>B X 1499
B Z 1500
B Z 1501
B Y 1502
C Y 1503
B Y 1504
C Y 1505
B Y 1506
B Z 1507
...
B Z 2493
B Y 2494
C X 2495
B X 2496
C X 2497
A X 2498
B ZB Y 2499
</code>```

As you've probably noticed theres an issue with the last line which cause my code to fail.

Could I get suggestions on how to deal with this large dataset?

Body:
I am currently completing the Day 2 challenge of Advent of Code and noticed that when I convert the given challenge text into a string in the format of

const rounds = 'B Y\n'+
'A X\n'+
'B Y\n'+
'A Y\n'+
'A Z\n'+
'B Y\n'+
'B Z\n'+
'C Y\n'+
'A X;

Here is the link to the full input

It creates issues when running a forEach and for loop with the whole dataset after splitting the string using Array.prototype.split(\n). The issue it is causing is the first index starts at around 1500 and ends 2500 for a dataset of about 5000 values. This is my solution to the challenge

import rounds from "./rounds.js";

const choiceMap = {
  A: {
    type: "Rock",
    points: 1,
  },
  B: {
    type: "Paper",
    points: 2,
  },
  C: {
    type: "Scissors",
    points: 3,
  },
  Y: {
    type: "Rock",
    points: 1,
  },
  X: {
    type: "Paper",
    points: 2,
  },
  Z: {
    type: "Scissors",
    points: 3,
  },
};

const pointMap = {
  Rock: {
    win: "Scissors",
    loss: "Paper",
  },
  Scissors: {
    win: "Paper",
    loss: "Rock",
  },
  Paper: {
    win: "Rock",
    loss: "Scissors",
  },
};

class RockPaperScissors {
  constructor(rounds) {
    this.rounds = rounds.trim().split("\n");
  }
  determinePoints = (choice, opponentChoice) => {
    let points = 0;
    choice = choiceMap[choice];
    opponentChoice = choiceMap[opponentChoice];
    points += choice.points;

    if (pointMap[choice.type].win === opponentChoice.type) points += 6;
    else if (choice.type === opponentChoice.type) points += 3;

    return points;
  };
  getPoints() {
    let points = 0;

    this.rounds.forEach((round, index) => {
      if (index === 0) console.log("first round");
      console.log(round, index);
      const [opponentChoice, choice] = round.split(" ");
      points += this.determinePoints(choice, opponentChoice);
    });
    return points;
  }
}

const elfGames = new RockPaperScissors(rounds);
elfGames.getPoints();

This is the start of my console output showing that loop did not start and end in the right positions

B X 1499
B Z 1500
B Z 1501
B Y 1502
C Y 1503
B Y 1504
C Y 1505
B Y 1506
B Z 1507
...
B Z 2493
B Y 2494
C X 2495
B X 2496
C X 2497
A X 2498
B ZB Y 2499

As you've probably noticed theres an issue with the last line which cause my code to fail.

Could I get suggestions on how to deal with this large dataset?


问:
how to mitigate possible failures of js string-similarity
i am trying to get the manufacturer of a product based on their name and for that i am using string-similarity package for nodeJs by comparing the name to an existing list of manufactureres that i have. the problem i got is that sometimes it deviates completely from an obvious best match.

i am running this on runkit :

```<code>var stringSimilarity = require("string-similarity")

var matches = stringSimilarity.findBestMatch("BLENDER MOULINETTE MOULINEX AR6801EG - 200G - 800W AVEC - BOL 1.5L -  BLANC - GARANTIE 1 AN"
.toLowerCase()
.replace(/\-/g, '')
.replace(/[0-9]./g,'')
.replace(/\s/g,''), [
  "intel",
  "moulinex",
  "cuiseurs",
  "under armour"
]);
</code>```

and these are the results

0: {target: "intel", rating: 0.1111111111111111}

1: {target: "moulinex", rating: 0.24561403508771928}

2: {target: "cuiseurs", rating: 0}

3: {target: "under armour", rating: 0.26666666666666666}

the issue here is that "under armour" is the most rated match while "moulinex" which is literally in the name is less favorable. I tried to clean up the input string by removing numbers and spaces but it didn't change the outcome, just better ratings.

Body:
i am trying to get the manufacturer of a product based on their name and for that i am using string-similarity package for nodeJs by comparing the name to an existing list of manufactureres that i have. the problem i got is that sometimes it deviates completely from an obvious best match.

i am running this on runkit :

var stringSimilarity = require("string-similarity")

var matches = stringSimilarity.findBestMatch("BLENDER MOULINETTE MOULINEX AR6801EG - 200G - 800W AVEC - BOL 1.5L -  BLANC - GARANTIE 1 AN"
.toLowerCase()
.replace(/\-/g, '')
.replace(/[0-9]./g,'')
.replace(/\s/g,''), [
  "intel",
  "moulinex",
  "cuiseurs",
  "under armour"
]);

and these are the results

0: {target: "intel", rating: 0.1111111111111111}

1: {target: "moulinex", rating: 0.24561403508771928}

2: {target: "cuiseurs", rating: 0}

3: {target: "under armour", rating: 0.26666666666666666}

the issue here is that "under armour" is the most rated match while "moulinex" which is literally in the name is less favorable. I tried to clean up the input string by removing numbers and spaces but it didn't change the outcome, just better ratings.


问:
Convert byte[] to string with before inserting in TableView
I got a class "Transaction" with Attributes in it like the id(byte[]), sender(byte[]), receiver(byte[]) and amount (double).

```<code>public class Transaction implements Serializable
{
    private transient byte[] txId;

    private byte[] sender;

    private byte[] receiver;

    private double amount;
</code>```

Now I want to display these attributes in a TableView and this is the Method I´m using for:

```<code>    @FXML
    void refreshButtonPressed(ActionEvent event) {
        List<Transaction> incomingList =
        DependencyManager.getAccountStorage().getAccount(publicKey).getIncomingTransactions();
        incomingTransactions = FXCollections.observableList(incomingList);
        idCol.setCellValueFactory(new PropertyValueFactory<Transaction, String>("txId"));
        senderCol.setCellValueFactory(new PropertyValueFactory<Transaction, String>("sender"));
        receiverCol.setCellValueFactory(new PropertyValueFactory<Transaction, String>("receiver"));
        amountCol.setCellValueFactory(new PropertyValueFactory<Transaction, String>("amount"));
        incomingView.setItems(incomingTransactions);
}
</code>```

Well the good thing is - it works, basically. But i want to convert to byte[] to a String with my own converter i wrote because this standard byte to String conversion is not really readable by the User.

Thats the method im using for the conversion: (Its from bouncycastle).

```<code>public static String digestToHex( byte[] digest )
    {
        return Hex.toHexString( digest );
    }
</code>```

So is there any way to convert the data before it is displayed?

Body:
I got a class "Transaction" with Attributes in it like the id(byte[]), sender(byte[]), receiver(byte[]) and amount (double).

public class Transaction implements Serializable
{
    private transient byte[] txId;

    private byte[] sender;

    private byte[] receiver;

    private double amount;

Now I want to display these attributes in a TableView and this is the Method I´m using for:

    @FXML
    void refreshButtonPressed(ActionEvent event) {
        List<Transaction> incomingList =
        DependencyManager.getAccountStorage().getAccount(publicKey).getIncomingTransactions();
        incomingTransactions = FXCollections.observableList(incomingList);
        idCol.setCellValueFactory(new PropertyValueFactory<Transaction, String>("txId"));
        senderCol.setCellValueFactory(new PropertyValueFactory<Transaction, String>("sender"));
        receiverCol.setCellValueFactory(new PropertyValueFactory<Transaction, String>("receiver"));
        amountCol.setCellValueFactory(new PropertyValueFactory<Transaction, String>("amount"));
        incomingView.setItems(incomingTransactions);
}

Well the good thing is - it works, basically. But i want to convert to byte[] to a String with my own converter i wrote because this standard byte to String conversion is not really readable by the User.

Thats the method im using for the conversion: (Its from bouncycastle).

public static String digestToHex( byte[] digest )
    {
        return Hex.toHexString( digest );
    }

So is there any way to convert the data before it is displayed?


问:
Using functions in view/user interface, but created in controller
How can be verified the type of input with the help of Exceptions? In case if the given input is incorrect, the user must be warned. The Exception should not be in the user interface, but in the function which executes the desired operations with the correct input.

I tried to put the function in UI, but IntelliJ warns me to put there try catch clause..., but we should do it without that.


问:
Chainlink link oracle cannot fulfill request?
when I call chain link oracle to request data, I just can't get the response fulfilled with
correct response on the chainlink operator

but can't get fulfilled response, I checked the transaction on goerli

the eth on admin is

How can I get the fulfilled response correctly?