问:
Does not recognize ROW_NUMBER() function OVER (PARTITION BY
Good afternoon

I am using the ROW_NUMBER() function
OVER (PARTITION BY, to bring only unique values of a concatenation of fields, however, when running the query, partition by works because it tells me the number of times the field that I indicate is repeated, but wanting to only bring a record from the list that appears it does not take it, so put only those with a value of 1 in my condition, it continues to bring me the entire data set.

```<code> SELECT DISTINCT
    C1_ID_ALERTA,
    C2_NOMBRE_USUARIO,
    C3_BP,
    C32_AREA_BANCARIA,
    C4_CONTRATO,
    C41_CENTRO_FINANCIERO,
    C5_CAMPO,
    C6_VALOR_ANTERIOR,
    C7_VALOR_ACTUAL,
    C8_FECHA_MODIFICACION,
    C9_HORA_MODIFICACION,
    C10_TIPO_LOG,
    enum
FROM (
    SELECT T1.*,ROW_NUMBER() OVER (PARTITION BY T1.C1_ID_ALERTA ORDER BY T1.C1_ID_ALERTA  DESC)as ENUM
        FROM (
            SELECT
            area_bancaria||contrato||valor_anterior||valor_actual C1_ID_ALERTA,
            nombre_usuario                         C2_NOMBRE_USUARIO,
            bp                                     C3_BP,
            area_bancaria                          C32_AREA_BANCARIA,
            contrato                               C4_CONTRATO,
            cenfinancierodes                       C41_CENTRO_FINANCIERO,
            campo                                  C5_CAMPO,
            valor_anterior                         C6_VALOR_ANTERIOR,
            valor_actual                           C7_VALOR_ACTUAL,
            fecha_modificacion                     C8_FECHA_MODIFICACION,
            hora_modificacion                      C9_HORA_MODIFICACION,
            tipo_log                               C10_TIPO_LOG
        FROM (SELECT  *
            FROM CAM_TBL_ALERTA_CONCENTRADO conc
               INNER JOIN  IBM_I2.I2_CONTRATOS cont
                 ON conc.contrato = LTRIM(cont.nocont,'0')
                 AND cont.institucion = conc.area_bancaria
                   WHERE
                        TIPO_LOG='LOG BP'
                        AND OPERACION='2'
                )
            )T1
        ) T2
                 WHERE  ENUM=1
                 AND C1_ID_ALERTA IS NOT NULL
                    AND C10_TIPO_LOG='LOG BP'
                    AND C5_CAMPO NOT IN ('GIRO_CNBV','BIRTHDT','D_F_ESCRITURA','CLAVE_COL',
                                        'CONSNUMBER','XSEXF','ADDRNUMBER','NAME_ORG1','NAME_ORG2','NAME_ORG3','TAXNUM',
                                        'RELTYP','ADDR_TYPE','NAME_LAST','NAME_LST2','NAMEMIDDLE','NAME_FIRST',
                                        'STREET','POST_CODE1','HOUSE_NUM1','LOCALIDAD','REGION','ROOMNUMBER',
                                        'TOWN','CLAVE_COL','ADDR_TYPE','RELTYP')
                    OR c5_campo='SMTP_ADDR'
                    OR c5_campo='TEL_NUMBER'
</code>```

It doesn't mark any error.

答:
Condition precedence rules say AND is evaluated before OR. So effectively you have:

```<code>WHERE
(
  ENUM=1
  AND C1_ID_ALERTA IS NOT NULL
  AND C10_TIPO_LOG='LOG BP'
  AND C5_CAMPO NOT IN (...)
)
OR c5_campo='SMTP_ADDR'
OR c5_campo='TEL_NUMBER'
</code>```

If either of those last two conditions is true, then that result will be included regardless of the ENUM value, because of the ORs.

You probably want some other order of evaluation, so you should add parentheses to get the order you need; possibly:

```<code>WHERE ENUM=1
AND C1_ID_ALERTA IS NOT NULL
AND
(
  (
    C10_TIPO_LOG='LOG BP'
    AND C5_CAMPO NOT IN (...)
  )
  OR c5_campo='SMTP_ADDR'
  OR c5_campo='TEL_NUMBER'
)
</code>```

but that's just a guess...

Body:
Good afternoon

I am using the ROW_NUMBER() function
OVER (PARTITION BY, to bring only unique values of a concatenation of fields, however, when running the query, partition by works because it tells me the number of times the field that I indicate is repeated, but wanting to only bring a record from the list that appears it does not take it, so put only those with a value of 1 in my condition, it continues to bring me the entire data set.

 SELECT DISTINCT
    C1_ID_ALERTA,
    C2_NOMBRE_USUARIO,
    C3_BP,
    C32_AREA_BANCARIA,
    C4_CONTRATO,
    C41_CENTRO_FINANCIERO,
    C5_CAMPO,
    C6_VALOR_ANTERIOR,
    C7_VALOR_ACTUAL,
    C8_FECHA_MODIFICACION,
    C9_HORA_MODIFICACION,
    C10_TIPO_LOG,
    enum
FROM (
    SELECT T1.*,ROW_NUMBER() OVER (PARTITION BY T1.C1_ID_ALERTA ORDER BY T1.C1_ID_ALERTA  DESC)as ENUM
        FROM (
            SELECT
            area_bancaria||contrato||valor_anterior||valor_actual C1_ID_ALERTA,
            nombre_usuario                         C2_NOMBRE_USUARIO,
            bp                                     C3_BP,
            area_bancaria                          C32_AREA_BANCARIA,
            contrato                               C4_CONTRATO,
            cenfinancierodes                       C41_CENTRO_FINANCIERO,
            campo                                  C5_CAMPO,
            valor_anterior                         C6_VALOR_ANTERIOR,
            valor_actual                           C7_VALOR_ACTUAL,
            fecha_modificacion                     C8_FECHA_MODIFICACION,
            hora_modificacion                      C9_HORA_MODIFICACION,
            tipo_log                               C10_TIPO_LOG
        FROM (SELECT  *
            FROM CAM_TBL_ALERTA_CONCENTRADO conc
               INNER JOIN  IBM_I2.I2_CONTRATOS cont
                 ON conc.contrato = LTRIM(cont.nocont,'0')
                 AND cont.institucion = conc.area_bancaria
                   WHERE
                        TIPO_LOG='LOG BP'
                        AND OPERACION='2'
                )
            )T1
        ) T2
                 WHERE  ENUM=1
                 AND C1_ID_ALERTA IS NOT NULL
                    AND C10_TIPO_LOG='LOG BP'
                    AND C5_CAMPO NOT IN ('GIRO_CNBV','BIRTHDT','D_F_ESCRITURA','CLAVE_COL',
                                        'CONSNUMBER','XSEXF','ADDRNUMBER','NAME_ORG1','NAME_ORG2','NAME_ORG3','TAXNUM',
                                        'RELTYP','ADDR_TYPE','NAME_LAST','NAME_LST2','NAMEMIDDLE','NAME_FIRST',
                                        'STREET','POST_CODE1','HOUSE_NUM1','LOCALIDAD','REGION','ROOMNUMBER',
                                        'TOWN','CLAVE_COL','ADDR_TYPE','RELTYP')
                    OR c5_campo='SMTP_ADDR'
                    OR c5_campo='TEL_NUMBER'

It doesn't mark any error.

Body:
Condition precedence rules say AND is evaluated before OR. So effectively you have:

WHERE
(
  ENUM=1
  AND C1_ID_ALERTA IS NOT NULL
  AND C10_TIPO_LOG='LOG BP'
  AND C5_CAMPO NOT IN (...)
)
OR c5_campo='SMTP_ADDR'
OR c5_campo='TEL_NUMBER'

If either of those last two conditions is true, then that result will be included regardless of the ENUM value, because of the ORs.

You probably want some other order of evaluation, so you should add parentheses to get the order you need; possibly:

WHERE ENUM=1
AND C1_ID_ALERTA IS NOT NULL
AND
(
  (
    C10_TIPO_LOG='LOG BP'
    AND C5_CAMPO NOT IN (...)
  )
  OR c5_campo='SMTP_ADDR'
  OR c5_campo='TEL_NUMBER'
)

but that's just a guess...


来源: stackexchange

问:
Values not split. "not enough values to unpack (expected 2, got 1)" when going through my text file line by line
```<code>def player_login():

    username = ""
    new = "0"

    while new not in ('1', '2'):
        print("Type 1 to Login")
        print("Type 2 to Register")
        new = input("")

    if new == '1':
        login_username = input('username: ')
        login_password = input('password: ')
        found_username = False

        with open('user_database.txt', 'r') as password_file:
            for line in password_file:
                username, password = line.strip().split(':')

                if login_username == username:
                    found_username = True
                    if login_password == password:
                        print('success!')
                    else:
                        print('login failure!')
                    break

        username = login_username
        if not found_username:
            print('username invalid')
    if new == '2':
        #code continues
player login()
</code>```

This is the error message I get:

line 18, in player_login

username, password = line.strip().split(':')

ValueError: not enough values to unpack (expected 2, got 1)

Its weird because this code used to work until I switched from PyCharm to VSC and I cannot figure out the problem. Any help is appreciated.

This is my text file if it helps:

```<code>asdaasda:asdaasda
asdfasdf:asdfasdf
hellohi:hellohi
</code>```

答:
user_database.txt has some line that is missing : (perhaps an empty line)

A simple fix is often to skip blank lines

    ...
    for line in fh:
        if not line:
            continue
        ...
```
<p>It's also often helpful to <code>enumerate()</code> to report bad lines</p>
<pre class="lang-py prettyprint-override"><code>for lineno, line in enumerate(fh, 1):
    ...
    if (<some validations fails>):
        print(f"bad line {lineno}: {line}")  # raise ValueError? to taste
</code>```

ContentLicense: CC BY-SA 4.0

Body:
def player_login():

    username = ""
    new = "0"

    while new not in ('1', '2'):
        print("Type 1 to Login")
        print("Type 2 to Register")
        new = input("")

    if new == '1':
        login_username = input('username: ')
        login_password = input('password: ')
        found_username = False

        with open('user_database.txt', 'r') as password_file:
            for line in password_file:
                username, password = line.strip().split(':')

                if login_username == username:
                    found_username = True
                    if login_password == password:
                        print('success!')
                    else:
                        print('login failure!')
                    break

        username = login_username
        if not found_username:
            print('username invalid')
    if new == '2':
        #code continues
player login()

This is the error message I get:

line 18, in player_login

username, password = line.strip().split(':')

ValueError: not enough values to unpack (expected 2, got 1)

Its weird because this code used to work until I switched from PyCharm to VSC and I cannot figure out the problem. Any help is appreciated.

This is my text file if it helps:

asdaasda:asdaasda
asdfasdf:asdfasdf
hellohi:hellohi

Body:
user_database.txt has some line that is missing : (perhaps an empty line)

A simple fix is often to skip blank lines

    ...
    for line in fh:
        if not line:
            continue
        ...

It's also often helpful to enumerate() to report bad lines

for lineno, line in enumerate(fh, 1):
    ...
    if (<some validations fails>):
        print(f"bad line {lineno}: {line}")  # raise ValueError? to taste


问:
Connections to Azure Redis Cache are high
I am using StackOverflow Redis on the Azure with the version 3.2.7 and I see the same issue of high counts of Clients Connections mentioned in below URLs. Is there any way to pass some params while connecting to Redis from client to ensure the connection should be closed automatically after certain idle time? OR Azure Redis itself should automatically close the same after seeing the idle property of the client?

I have already followed the best practices mentioned in the following blogs, but still, no luck in reducing the connections count.
Why are connections to Azure Redis Cache so high?
Azure Redis Cache max connections reached
https://gist.github.com/JonCole/925630df72be1351b21440625ff2671f

I came across this https://pranavprakash.net/2016/02/05/kill-idle-connections-to-redis/ article to kill them in bulk for idle one. Was looking for some properties or settings which will help us to do it automatically. Seems I am still missing something.

Thanks in advance
Gangadhar

答:
Implement IDisposable to dispose the object after its use</p>
```<code>        public void Dispose()
        {
            try {
                if (connection.IsValueCreated)
                {
                    connection.Value.Dispose();
                }
            } catch { }
        }
</code>```

Body:
Implement IDisposable to dispose the object after its use

        public void Dispose()
        {
            try {
                if (connection.IsValueCreated)
                {
                    connection.Value.Dispose();
                }
            } catch { }
        }


问:
Evenly push values from a flat array into same positioned rows of a 2d array
I need to evenly/synchronously push values from my second array into the rows of my first array.

The arrays which have the same size, but with different keys and depths.  The first is an array of rows and the second is a flat array.

```<code>$array1 = [
    12 => [130, 28, 1],
    19 => [52, 2, 3],
    34 => [85, 10, 5]
]

$array2 = [4, 38, 33]
</code>```

Preferred result:

```<code>[
    12 => [130, 28, 1, 4],
    19 => [52, 2, 3, 38],
    34 => [85, 10, 5, 33]
]
</code>```

(I would like to keep the same indices of array 1, however it is not mandatory.)

I have tried these methods, but none of them work because the first array keys are unpredictable.

```<code>$final = [];
foreach ($array1 as $idx => $val) {
    $final = [$val, $array2[$idx]];
}
</code>```

Another:

```<code>foreach ($array1 as $index => $subArray) {
    $array1 [$index][] = $array2[$index];
}
</code>```

答:
Here is one way to do this:

```<code>$merged = array_map('array_merge', $array1, array_chunk($array2, 1));
$result = array_combine(array_keys($array1), $merged);
</code>```

The second step with array_combine is necessary to reapply the non-sequential keys because array_map won't preserve them in the first step.

Body:
I need to evenly/synchronously push values from my second array into the rows of my first array.

The arrays which have the same size, but with different keys and depths.  The first is an array of rows and the second is a flat array.

$array1 = [
    12 => [130, 28, 1],
    19 => [52, 2, 3],
    34 => [85, 10, 5]
]

$array2 = [4, 38, 33]

Preferred result:

[
    12 => [130, 28, 1, 4],
    19 => [52, 2, 3, 38],
    34 => [85, 10, 5, 33]
]

(I would like to keep the same indices of array 1, however it is not mandatory.)

I have tried these methods, but none of them work because the first array keys are unpredictable.

$final = [];
foreach ($array1 as $idx => $val) {
    $final = [$val, $array2[$idx]];
}

Another:

foreach ($array1 as $index => $subArray) {
    $array1 [$index][] = $array2[$index];
}

Body:
Here is one way to do this:

$merged = array_map('array_merge', $array1, array_chunk($array2, 1));
$result = array_combine(array_keys($array1), $merged);

The second step with array_combine is necessary to reapply the non-sequential keys because array_map won't preserve them in the first step.


问:
How to fix / debug errors (invalid arrayify value) when deploying a solidity contract in Remix

Problem

I am trying to deploy a smart contract via Remix. Unfortunately, it fails with a very unhelpful error message.

Error Message

creation of MyContract errored: Error encoding arguments: Error: invalid arrayify value (argument="value", value="", code=INVALID_ARGUMENT, version=bytes/5.5.0)

Code

Here is the constructor the contract uses:

```<code>struct RRSet {
    uint32 inception;
    uint32 expiration;
    bytes20 hash;
}

constructor(bytes memory _anchors) {
    // Insert the 'trust anchors' - the key hashes that start the chain
    // of trust for all other records.
    anchors = _anchors;
    rrsets[keccak256(hex"00")][DNSTYPE_DS] = RRSet({
        inception: uint32(0),
        expiration: uint32(3767581600), // May 22 2089 - the latest date we can encode as of writing this
        hash: bytes20(keccak256(anchors))
    });
    emit RRSetUpdated(hex"00", anchors);
}
</code>```

Some thoughts

My contract uses is to inherit from an abstract contract as wells as from a regular contract. Is there a way to see where to error or originates from or is there a possiblity to debug it?

答:
The constructor takes a byte array as an argument.

When you pass an empty value, it results in the error message mentioned in your question. It's because you're effectively passing "no value" - not "empty byte array".

creation of MyContract errored: Error encoding arguments: Error: invalid arrayify value (argument="value", value="", code=INVALID_ARGUMENT, version=bytes/5.5.0)

If you want to pass an empty byte array, you need to use the [] or 0x expression (both options work):

Body:
Problem

I am trying to deploy a smart contract via Remix. Unfortunately, it fails with a very unhelpful error message.

Error Message

creation of MyContract errored: Error encoding arguments: Error: invalid arrayify value (argument="value", value="", code=INVALID_ARGUMENT, version=bytes/5.5.0)

Code

Here is the constructor the contract uses:

struct RRSet {
    uint32 inception;
    uint32 expiration;
    bytes20 hash;
}

constructor(bytes memory _anchors) {
    // Insert the 'trust anchors' - the key hashes that start the chain
    // of trust for all other records.
    anchors = _anchors;
    rrsets[keccak256(hex"00")][DNSTYPE_DS] = RRSet({
        inception: uint32(0),
        expiration: uint32(3767581600), // May 22 2089 - the latest date we can encode as of writing this
        hash: bytes20(keccak256(anchors))
    });
    emit RRSetUpdated(hex"00", anchors);
}

Some thoughts

My contract uses is to inherit from an abstract contract as wells as from a regular contract. Is there a way to see where to error or originates from or is there a possiblity to debug it?


问:
Smart Contract NFT how to add price by code to whole items in collection?
Greeting,

Could you tell me how to add price for every item in collection hosted by OpenSea ?

So, I have working code, It created:

1.Collection name (from construct before deploy)

2.NFT symbol  (from construct before deploy)

3.URI to ipfs (from construct before deploy ex: ipfs://QmQtP8RNjvcVtKqcPwukgckWF74ojBjzahVzE3qCCnqv4f/

My smart contract example:

```<code>// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.0 <0.9.0;

import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/access/Ownable.sol";

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

contract NFT is ERC721Enumerable, Ownable {
  using Strings for uint256;

  string public baseURI;
  string public baseExtension = ".json";
  uint256 public cost = 10000000000000000;
  uint256 public maxSupply = 10000;
  uint256 public maxMintAmount = 100;
  bool public paused = false;
  mapping(address => bool) public whitelisted;

  constructor(
    string memory _name,
    string memory _symbol,
    string memory _initBaseURI
  ) ERC721(_name, _symbol) {
    setBaseURI(_initBaseURI);
    mint(msg.sender, 5); // 5- for test
  }

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

  // public
  function mint(address _to, uint256 _mintAmount) public payable {
    uint256 supply = totalSupply();
    require(!paused);
    require(_mintAmount > 0);
    require(_mintAmount <= maxMintAmount);
    require(supply + _mintAmount <= maxSupply);

    if (msg.sender != owner()) {
        if(whitelisted[msg.sender] != true) {
          require(msg.value >= cost * _mintAmount);
        }
    }

    for (uint256 i = 1; i <= _mintAmount; i++) {
      _safeMint(_to, supply + i);
    }
  }

  function walletOfOwner(address _owner)
    public
    view
    returns (uint256[] memory)
  {
    uint256 ownerTokenCount = balanceOf(_owner);
    uint256[] memory tokenIds = new uint256[](ownerTokenCount);
    for (uint256 i; i < ownerTokenCount; i++) {
      tokenIds[i] = tokenOfOwnerByIndex(_owner, i);
    }
    return tokenIds;
  }

  function tokenURI(uint256 tokenId)
    public
    view
    virtual
    override
    returns (string memory)
  {
    require(
      _exists(tokenId),
      "ERC721Metadata: URI query for nonexistent token"
    );

    string memory currentBaseURI = _baseURI();
    return bytes(currentBaseURI).length > 0
        ? string(abi.encodePacked(currentBaseURI, tokenId.toString(), baseExtension))
        : "";
  }

  //only owner
  function setCost(uint256 _newCost) public onlyOwner {
    cost = _newCost;
  }

  function getCost() public view returns (uint256) {
    return cost;
  }

  function setmaxMintAmount(uint256 _newmaxMintAmount) public onlyOwner {
    maxMintAmount = _newmaxMintAmount;
  }

  function setBaseURI(string memory _newBaseURI) public onlyOwner {
    baseURI = _newBaseURI;
  }

  function setBaseExtension(string memory _newBaseExtension) public onlyOwner {
    baseExtension = _newBaseExtension;
  }

  function pause(bool _state) public onlyOwner {
    paused = _state;
  }

 function whitelistUser(address _user) public onlyOwner {
    whitelisted[_user] = true;
  }

  function removeWhitelistUser(address _user) public onlyOwner {
    whitelisted[_user] = false;
  }

  function withdraw() public onlyOwner {
      uint256 balance = address(this).balance;
      payable(msg.sender).transfer(balance);
  }
}
</code>```

and my item json file example:

```<code>{
  "description": "Test Description",
  "external_url": "http://testurl.com",
  "image": "ipfs://QmSrkLg3UR5AUthhCZfrK9nrX3fxJJ4aCJK7B99rUkCa72/4.png",
  "name": "Test Name #4",
  "symbol": "TNFT",
  "collection": {
    "name": "TestNFT123_321",
    "family": ""
  },
  "date": 1643919095,
  "attributes": {
    "Story": "In Caffe",
    "Company": "Test Company",
    "Some": "thing else"
  }
}
</code>```

On the OpenSea I have created collection name with items, but, with active price button.
What I made wrong?

Thanks for help.

答:
I investigated this issue, so:

Listing items on OpenSea could be with API endpoints (see OpenSea docs, and here).

OpenSea listing could be on mainnet or Rinkeby network only (as of today no Polygon, BSC ...)

There are a lot of clickers, which emulate add item, name, price on Polygon network.

Waiting for API V2 OpenSea =((

Body:
Greeting,

Could you tell me how to add price for every item in collection hosted by OpenSea ?

So, I have working code, It created:

1.Collection name (from construct before deploy)

2.NFT symbol  (from construct before deploy)

3.URI to ipfs (from construct before deploy ex: ipfs://QmQtP8RNjvcVtKqcPwukgckWF74ojBjzahVzE3qCCnqv4f/

My smart contract example:

// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.0 <0.9.0;

import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/access/Ownable.sol";

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

contract NFT is ERC721Enumerable, Ownable {
  using Strings for uint256;

  string public baseURI;
  string public baseExtension = ".json";
  uint256 public cost = 10000000000000000;
  uint256 public maxSupply = 10000;
  uint256 public maxMintAmount = 100;
  bool public paused = false;
  mapping(address => bool) public whitelisted;

  constructor(
    string memory _name,
    string memory _symbol,
    string memory _initBaseURI
  ) ERC721(_name, _symbol) {
    setBaseURI(_initBaseURI);
    mint(msg.sender, 5); // 5- for test
  }

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

  // public
  function mint(address _to, uint256 _mintAmount) public payable {
    uint256 supply = totalSupply();
    require(!paused);
    require(_mintAmount > 0);
    require(_mintAmount <= maxMintAmount);
    require(supply + _mintAmount <= maxSupply);

    if (msg.sender != owner()) {
        if(whitelisted[msg.sender] != true) {
          require(msg.value >= cost * _mintAmount);
        }
    }

    for (uint256 i = 1; i <= _mintAmount; i++) {
      _safeMint(_to, supply + i);
    }
  }

  function walletOfOwner(address _owner)
    public
    view
    returns (uint256[] memory)
  {
    uint256 ownerTokenCount = balanceOf(_owner);
    uint256[] memory tokenIds = new uint256[](ownerTokenCount);
    for (uint256 i; i < ownerTokenCount; i++) {
      tokenIds[i] = tokenOfOwnerByIndex(_owner, i);
    }
    return tokenIds;
  }

  function tokenURI(uint256 tokenId)
    public
    view
    virtual
    override
    returns (string memory)
  {
    require(
      _exists(tokenId),
      "ERC721Metadata: URI query for nonexistent token"
    );

    string memory currentBaseURI = _baseURI();
    return bytes(currentBaseURI).length > 0
        ? string(abi.encodePacked(currentBaseURI, tokenId.toString(), baseExtension))
        : "";
  }

  //only owner
  function setCost(uint256 _newCost) public onlyOwner {
    cost = _newCost;
  }

  function getCost() public view returns (uint256) {
    return cost;
  }

  function setmaxMintAmount(uint256 _newmaxMintAmount) public onlyOwner {
    maxMintAmount = _newmaxMintAmount;
  }

  function setBaseURI(string memory _newBaseURI) public onlyOwner {
    baseURI = _newBaseURI;
  }

  function setBaseExtension(string memory _newBaseExtension) public onlyOwner {
    baseExtension = _newBaseExtension;
  }

  function pause(bool _state) public onlyOwner {
    paused = _state;
  }

 function whitelistUser(address _user) public onlyOwner {
    whitelisted[_user] = true;
  }

  function removeWhitelistUser(address _user) public onlyOwner {
    whitelisted[_user] = false;
  }

  function withdraw() public onlyOwner {
      uint256 balance = address(this).balance;
      payable(msg.sender).transfer(balance);
  }
}

and my item json file example:

{
  "description": "Test Description",
  "external_url": "http://testurl.com",
  "image": "ipfs://QmSrkLg3UR5AUthhCZfrK9nrX3fxJJ4aCJK7B99rUkCa72/4.png",
  "name": "Test Name #4",
  "symbol": "TNFT",
  "collection": {
    "name": "TestNFT123_321",
    "family": ""
  },
  "date": 1643919095,
  "attributes": {
    "Story": "In Caffe",
    "Company": "Test Company",
    "Some": "thing else"
  }
}

On the OpenSea I have created collection name with items, but, with active price button.
What I made wrong?

Thanks for help.


问:
How can I test resource loader in spring boot using mockito
I am working on a spring boot 2.1.3 application which has a service which uses ResourceLoader class to read a text file from the resources directory:

```<code>import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class TestService {

  @Autowired
  ResourceLoader resourceLoader;

  public String testMethod(String test) {
    List<String> list = null;

    Resource resource = resourceLoader.getResource("classpath:test.txt");
    try (BufferedReader buffer = new BufferedReader(new InputStreamReader(resource.getInputStream()))) {
      list = buffer.lines().collect(Collectors.toList());
    } catch (Exception e) {
      System.out.println("error : " + e);
    }

    if (list.contains(test)) {
      return "in file";
    }

    return "not in file";
  }
}
</code>```

I am writing a unit test for this service using mockito:

```<code>@RunWith(MockitoJUnitRunner.class)
@ContextConfiguration()
public class AServiceTest {
  @InjectMocks
  private TestService cut;

  @Test
  public void testSuccessfulResponse() {
    String actualResponse = cut.method("teststring");
    String expectedResponse = getSuccessfulResponse();

    assertThat(actualResponse, is(expectedResponse));
  }
</code>```

But when I run the test resourceLoader is null?

How can I test the resourceLoader class in this example.

答:
For situation like these you can simply mock & inject the resourceLoader using the @Mock & @InjectMocks annoatations and return the expected resource which is also mocked.

The key parts are:

```<code>@Mock
ResourceLoader resourceLoader;

@InjectMocks
private TestService cut;

// ... inside the test class
when(resourceLoader.getResource(anyString())).thenReturn(mockResource);
</code>```

and the full code looks like this:

```<code>import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

@RunWith(MockitoJUnitRunner.class)
public class TestServiceTest {

  @Mock
  ResourceLoader resourceLoader;

  @InjectMocks
  private TestService cut;

  @Test
  public void testSuccessfulResponse() throws IOException {

    // Given
    String testString = "teststring";
    InputStream is = new ByteArrayInputStream(testString.getBytes());;
    Resource mockResource = mock(Resource.class);
    when(mockResource.getInputStream()).thenReturn(is);
    when(resourceLoader.getResource(anyString())).thenReturn(mockResource);

    // When
    String actualResponse = cut.testMethod(testString);

    // Then
    String expectedResponse = "in file";
    assertEquals(actualResponse, expectedResponse);
  }
}
</code>```

Body:
I am working on a spring boot 2.1.3 application which has a service which uses ResourceLoader class to read a text file from the resources directory:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class TestService {

  @Autowired
  ResourceLoader resourceLoader;

  public String testMethod(String test) {
    List<String> list = null;

    Resource resource = resourceLoader.getResource("classpath:test.txt");
    try (BufferedReader buffer = new BufferedReader(new InputStreamReader(resource.getInputStream()))) {
      list = buffer.lines().collect(Collectors.toList());
    } catch (Exception e) {
      System.out.println("error : " + e);
    }

    if (list.contains(test)) {
      return "in file";
    }

    return "not in file";
  }
}

I am writing a unit test for this service using mockito:

@RunWith(MockitoJUnitRunner.class)
@ContextConfiguration()
public class AServiceTest {
  @InjectMocks
  private TestService cut;

  @Test
  public void testSuccessfulResponse() {
    String actualResponse = cut.method("teststring");
    String expectedResponse = getSuccessfulResponse();

    assertThat(actualResponse, is(expectedResponse));
  }

But when I run the test resourceLoader is null?

How can I test the resourceLoader class in this example.

Body:
For situation like these you can simply mock & inject the resourceLoader using the @Mock & @InjectMocks annoatations and return the expected resource which is also mocked.

The key parts are:

@Mock
ResourceLoader resourceLoader;

@InjectMocks
private TestService cut;

// ... inside the test class
when(resourceLoader.getResource(anyString())).thenReturn(mockResource);

and the full code looks like this:

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

@RunWith(MockitoJUnitRunner.class)
public class TestServiceTest {

  @Mock
  ResourceLoader resourceLoader;

  @InjectMocks
  private TestService cut;

  @Test
  public void testSuccessfulResponse() throws IOException {

    // Given
    String testString = "teststring";
    InputStream is = new ByteArrayInputStream(testString.getBytes());;
    Resource mockResource = mock(Resource.class);
    when(mockResource.getInputStream()).thenReturn(is);
    when(resourceLoader.getResource(anyString())).thenReturn(mockResource);

    // When
    String actualResponse = cut.testMethod(testString);

    // Then
    String expectedResponse = "in file";
    assertEquals(actualResponse, expectedResponse);
  }
}


问:
Question on jsLint error: "Don't make functions within a loop"
I'm reading DOM Scripting by Jeremy Keith and testing the code in jsLint

In the code sample here it i'm getting an error that says ""Don't make functions within a loop".

When I try to fix it, I seem to be losing the scope of this

I need to see an example of how to fix this error.

Here is the jsfiddle: http://jsfiddle.net/pkdsleeper/ejvMj/

Thanks In Advance

sleeper

答:
Your code seems to work fine as is.  The this inside your event handler functions refers to the DOM object that fired the event, which is a
 element.  Thus you can change your styles by modifying the properties of this.  You can access the same object via a function parameter as well.

```<code>current_row.onmouseover = function (event) {
            console.log(this == event.currentTarget);
}
</code>```

That will log true to the console because this and event.currentTarget are the same DOM element object.

But yes, you are correct in that in the scope of your for loop, this (which you don't use in that exact scope) is the top level window object, but within the event handler functions, this is a different object.

ContentLicense: CC BY-SA 3.0

Body:
Your code seems to work fine as is.  The this inside your event handler functions refers to the DOM object that fired the event, which is a <tr> element.  Thus you can change your styles by modifying the properties of this.  You can access the same object via a function parameter as well.

current_row.onmouseover = function (event) {
            console.log(this == event.currentTarget);
}

That will log true to the console because this and event.currentTarget are the same DOM element object.

But yes, you are correct in that in the scope of your for loop, this (which you don't use in that exact scope) is the top level window object, but within the event handler functions, this is a different object.


问:
Get row only if specific condition is true but it overrides previous condition
I want to fetch all the rows whose status is not a or b.
But, if there are rows with two specific columns that are not null and status is c, then also fetch these rows.

This is how I tried to do it, but then it also fetches rows with status b where their column_a and column_b is not null

```<code>   select('*')
    ->whereNotIn('status',['a','b'])
    ->orWhere(function($query) {
          $query->where('column_a', "!=", null)
          ->where('column_b', "!=", null)
          ->where('status', "=", 'c');
    })
    ->get());
</code>```

答:
Try this</p>
```<code>whereNotIn('status', ['a', 'b'])->where([['column_a', '!=', null], ['column', '!=', null], ['status', 'c']])->get();
</code>```

Body:
I want to fetch all the rows whose status is not a or b.
But, if there are rows with two specific columns that are not null and status is c, then also fetch these rows.

This is how I tried to do it, but then it also fetches rows with status b where their column_a and column_b is not null

   select('*')
    ->whereNotIn('status',['a','b'])
    ->orWhere(function($query) {
          $query->where('column_a', "!=", null)
          ->where('column_b', "!=", null)
          ->where('status', "=", 'c');
    })
    ->get());

Body:
Try this

whereNotIn('status', ['a', 'b'])->where([['column_a', '!=', null], ['column', '!=', null], ['status', 'c']])->get();


问:
How can I validate entities with spring data r2dbc?
In Spring data JPA there are annotations that can be used to set up validations for entities in a declarative manner. They can be found in javax.validation.constraints.* or additionally in org.hibernate.validator.constraints.* (in the case when Hibernate is plugged in).

Example:

```<code>    @NotNull
    private String lastName;
</code>```

However, if the case of Spring data r2dbc they do not work out of the box.

Is there any simple and smooth way to set up validations for entities in Spring data r2dbc? That should not be too difficult in my opinion because probably it does not require full ORM support, just a matter of callbacks for checking object fields before persisting it.

答:
It works very fine with Bean Validation and Hibernate Validation.

You can use all the same annotations you did in JPA, since you do it in your DTOs.

See the example:

```<code>@Data
public class UserDto {

    private String name;

    @NotNull(message = "Last name can not be empty")
    private String lastName;

    @Min(value = 10, message = "Required min age is 10")
    @Max(value = 50, message = "Required max age is 50")
    private int age;
}
</code>```

Then your controller would be annotated:

```<code>@RestController
@RequestMapping("user")
public class RegistrationController {

    @Autowired
    private UserService userService;

    @PostMapping("register")
    public Mono<UserDto> register(@Valid @RequestBody Mono<UserDto> userDtoMono{
        return this.userService.registerUser(userDtoMono);
    }
}
</code>```

The only thing now is that you have to personalize your message, so that it returns the one you have set in your DTO. To override it you should create an ExceptionHandler.

```<code>@ControllerAdvice
public class ValidationHandler {

    @ExceptionHandler(WebExchangeBindException.class)
    public ResponseEntity<List<String>> handleException(WebExchangeBindException e) {
        var errors = e.getBindingResult()
                .getAllErrors()
                .stream()
                .map(DefaultMessageSourceResolvable::getDefaultMessage)
                .collect(Collectors.toList());
        return ResponseEntity.badRequest().body(errors);
    }

}
</code>```

I've been using it in my projects and got this example from: https://www.vinsguru.com/spring-webflux-validation/

Body:
In Spring data JPA there are annotations that can be used to set up validations for entities in a declarative manner. They can be found in javax.validation.constraints.* or additionally in org.hibernate.validator.constraints.* (in the case when Hibernate is plugged in).

Example:

    @NotNull
    private String lastName;

However, if the case of Spring data r2dbc they do not work out of the box.

Is there any simple and smooth way to set up validations for entities in Spring data r2dbc? That should not be too difficult in my opinion because probably it does not require full ORM support, just a matter of callbacks for checking object fields before persisting it.

Body:
It works very fine with Bean Validation and Hibernate Validation.

You can use all the same annotations you did in JPA, since you do it in your DTOs.

See the example:

@Data
public class UserDto {

    private String name;

    @NotNull(message = "Last name can not be empty")
    private String lastName;

    @Min(value = 10, message = "Required min age is 10")
    @Max(value = 50, message = "Required max age is 50")
    private int age;
}

Then your controller would be annotated:

@RestController
@RequestMapping("user")
public class RegistrationController {

    @Autowired
    private UserService userService;

    @PostMapping("register")
    public Mono<UserDto> register(@Valid @RequestBody Mono<UserDto> userDtoMono{
        return this.userService.registerUser(userDtoMono);
    }
}

The only thing now is that you have to personalize your message, so that it returns the one you have set in your DTO. To override it you should create an ExceptionHandler.

@ControllerAdvice
public class ValidationHandler {

    @ExceptionHandler(WebExchangeBindException.class)
    public ResponseEntity<List<String>> handleException(WebExchangeBindException e) {
        var errors = e.getBindingResult()
                .getAllErrors()
                .stream()
                .map(DefaultMessageSourceResolvable::getDefaultMessage)
                .collect(Collectors.toList());
        return ResponseEntity.badRequest().body(errors);
    }

}

I've been using it in my projects and got this example from: https://www.vinsguru.com/spring-webflux-validation/


问:
How to convert all Series values of a Dataframe from timedelta to minutes
I have this dataframe where every value's type is timedelta:

And I want to transform all values to minutes, but when coding:

```<code>df['time'] = df['time'].seconds/60
</code>```

I get the following error:

```<code>AttributeError: 'Series' object has no attribute 'seconds'
</code>```

How can I transform every value of the column in a simple way?

Thanks.

答:
When you have a DatetimeIndex series, you can access to a special accessor dt which give you some attributes and methods:

```<code>df['min'] = df['time'].dt.total_seconds().div(60)
print(df)

# Output
             time   min
0 0 days 00:53:00  53.0
1 0 days 00:45:00  45.0
</code>```

Setup:

```<code>df = pd.DataFrame({'time': [pd.Timedelta('0 days 00:53:00'),
                            pd.Timedelta('0 days 00:45:00')]})

</code>```

Body:
I have this dataframe where every value's type is timedelta:

And I want to transform all values to minutes, but when coding:

df['time'] = df['time'].seconds/60

I get the following error:

AttributeError: 'Series' object has no attribute 'seconds'

How can I transform every value of the column in a simple way?

Thanks.

Body:
When you have a DatetimeIndex series, you can access to a special accessor dt which give you some attributes and methods:

df['min'] = df['time'].dt.total_seconds().div(60)
print(df)

# Output
             time   min
0 0 days 00:53:00  53.0
1 0 days 00:45:00  45.0

Setup:

df = pd.DataFrame({'time': [pd.Timedelta('0 days 00:53:00'),
                            pd.Timedelta('0 days 00:45:00')]})


问:
How to set second yAxis scale according to data from first yAxis
I have an odd request. My boss wants me to improve an existing chart with a second axis.

The blue area must define the scale of the second axis, like a percentage of completion for the reading of the green area. The 100% value must be at the maximum of the blue area. I can collect the highest value of the blue area without any trouble, but I don't know how to set the properties of the second axis according to this value. The thing is that the second axis does not have any data associated, therefore, he isn't shown...

Any idea ?

PS : I tried to be as clear as possible, but maybe that was not the case. Don't hesitate to tell me if you need more explanations.

答:
You can use axis.linkedTo to get a second axis and data formatters to get the data formatted as percentages.

I'm not modifying the series data, only changing the text shown in the second yAxis scale, the tooltip and the data labels.

```<code>yAxis: [{
    // Default options
}, {
    linkedTo: 0,
    opposite: true,
    labels: {
        formatter: function () {
            return formatPercent(this.value);
        }
    }
}]
</code>```

Example on jsFiddle: http://jsfiddle.net/uPHZx/

Body:
You can use axis.linkedTo to get a second axis and data formatters to get the data formatted as percentages.

I'm not modifying the series data, only changing the text shown in the second yAxis scale, the tooltip and the data labels.

yAxis: [{
    // Default options
}, {
    linkedTo: 0,
    opposite: true,
    labels: {
        formatter: function () {
            return formatPercent(this.value);
        }
    }
}]

Example on jsFiddle: http://jsfiddle.net/uPHZx/


问:
Error when calling multiple deletes: "Default changeset implementation allows only one operation"
The server is returning an exception when trying to delete multiple items. I put the OData call inside a for loop, but it returns the error below:

{
  "code":"/IWBEP/CX_MGW_TECH_EXCEPTION",
  "message":"Default changeset implementation allows only one operation",
  "persistent":false,
  "targets":"..."
}
```
</blockquote>
<p>When I make the single line call, it is deleting correctly.</p>
<p>Here's the function I'm using to delete:</p>
<pre class="lang-js prettyprint-override"><code>onDelete(oEvent) {
  var that = this;
  var oModel = this.getView().getModel();
  oModel.setDeferredGroups(["group1"]);
  var oTable = this.getView().byId("LineItemsSmartTable").getTable();
  var oItems = oTable.getSelectedIndices();
  for (var i = 0; i < oItems.length; i++) {
    var j = oItems[i];
      var cpfKey = oTable.getContextByIndex(j).getProperty("Cpf");
      var sDelete = oModel.createKey("/CustomersSet", { Cpf: cpfKey });
      oModel.remove(sDelete, {
        success: function (oData, oResponse) {
          // ...
        },
        error: function (oError) {
          // ...
        },
      });
    }
  },
  // ...
}
</code>```

答:
I guess you have two possibilities. The first one is the optimal solution (but takes time to implement). The second one is hacky.

Implement changeset_process

With changeset_process all your requests will arrive in a single method. There are plenty of tutorials on how to implement it in the backend:

Disable useBatch

If you send your delete requests in individual requests (and not bundled in one big batch request) the error should go away. You can change this setting right before sending (remember to toggle it right after sending) or on a global level in the manifest.json (where you declare your model)

"dataSource": "mainService",
"settings": {
    "useBatch": false,
    ...
}
```
<hr />
<p>Maybe you also have this third option. I haven't tried it, just found it in the docs. If it works, it's also not optimal because requests will take much more time.</p>
<h2>Send your delete requests sequential (and not all at once).</h2>
<p>By setting the parameter <code>sequentializeRequests</code> of your OData model to true, all requests will be sequentialized.</p>
<pre class="lang-json prettyprint-override"><code>"dataSource": "mainService",
"settings": {
    "sequentializeRequests": true,
    ...
}
</code>```

Body:
The server is returning an exception when trying to delete multiple items. I put the OData call inside a for loop, but it returns the error below:

{
  "code":"/IWBEP/CX_MGW_TECH_EXCEPTION",
  "message":"Default changeset implementation allows only one operation",
  "persistent":false,
  "targets":"..."
}

When I make the single line call, it is deleting correctly.

Here's the function I'm using to delete:

onDelete(oEvent) {
  var that = this;
  var oModel = this.getView().getModel();
  oModel.setDeferredGroups(["group1"]);
  var oTable = this.getView().byId("LineItemsSmartTable").getTable();
  var oItems = oTable.getSelectedIndices();
  for (var i = 0; i < oItems.length; i++) {
    var j = oItems[i];
      var cpfKey = oTable.getContextByIndex(j).getProperty("Cpf");
      var sDelete = oModel.createKey("/CustomersSet", { Cpf: cpfKey });
      oModel.remove(sDelete, {
        success: function (oData, oResponse) {
          // ...
        },
        error: function (oError) {
          // ...
        },
      });
    }
  },
  // ...
}

Body:
I guess you have two possibilities. The first one is the optimal solution (but takes time to implement). The second one is hacky.

Implement changeset_process

With changeset_process all your requests will arrive in a single method. There are plenty of tutorials on how to implement it in the backend:

Disable useBatch

If you send your delete requests in individual requests (and not bundled in one big batch request) the error should go away. You can change this setting right before sending (remember to toggle it right after sending) or on a global level in the manifest.json (where you declare your model)

"dataSource": "mainService",
"settings": {
    "useBatch": false,
    ...
}

Maybe you also have this third option. I haven't tried it, just found it in the docs. If it works, it's also not optimal because requests will take much more time.

Send your delete requests sequential (and not all at once).

By setting the parameter sequentializeRequests of your OData model to true, all requests will be sequentialized.

"dataSource": "mainService",
"settings": {
    "sequentializeRequests": true,
    ...
}


问:
Close Electron app on click event
I have looked at the documentation for Electron regarding the 'frameless-window', but I just can't seem to make a button of my own work to close the application...

Any help would be appreciated! Thanks!

const electron = require('electron');
const url = require('url');
const path = require('path');

const {app, BrowserWindow} = electron;
let mainWindow;

// Listen for app to be ready
app.on('ready', function() {
  // create new window
  mainWindow = new BrowserWindow({width: 800, height: 600, frame: false});
  // Load html into window
  mainWindow.loadURL(url.format({
    pathname:path.join(__dirname,'main.html'),
    protocol: 'file:',
    slashes: true
  }));
  const closeApp = document.getElementById('closeApp');

  closeApp.addEventListener('click', () => {
    app.quit();
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Electron "Hello World"</title>
</head>
<body>
  <header>
    <p id="closeApp">close app</p>
  </header>
</body>
</html></code>```

答:
As of 2022, the confirmed solution will produce an error in console 'Uncaught ReferenceError: require is not defined'. We won't be utilizing the 'renderer.js' script in this example.

These are the steps to solve this:

In the Preload.js script

```<code>const { ipcRenderer } = require('electron');

document.getElementById('closeApp').addEventListener('click', () => {
  ipcRenderer.invoke('quit-app');
});
</code>```

In the Main.js script

```<code>ipcMain.handle('quit-app', () => {
  app.quit();
});
</code>```

Title: Close Electron app on click event

Body:
I have looked at the documentation for Electron regarding the 'frameless-window', but I just can't seem to make a button of my own work to close the application...

Any help would be appreciated! Thanks!

const electron = require('electron');
const url = require('url');
const path = require('path');

const {app, BrowserWindow} = electron;
let mainWindow;

// Listen for app to be ready
app.on('ready', function() {
  // create new window
  mainWindow = new BrowserWindow({width: 800, height: 600, frame: false});
  // Load html into window
  mainWindow.loadURL(url.format({
    pathname:path.join(__dirname,'main.html'),
    protocol: 'file:',
    slashes: true
  }));
  const closeApp = document.getElementById('closeApp');

  closeApp.addEventListener('click', () => {
    app.quit();
  });
});

<!DOCTYPE html>

  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Electron "Hello World"</title>

close app

Body:
As of 2022, the confirmed solution will produce an error in console 'Uncaught ReferenceError: require is not defined'. We won't be utilizing the 'renderer.js' script in this example.

These are the steps to solve this:

In the Preload.js script

const { ipcRenderer } = require('electron');

document.getElementById('closeApp').addEventListener('click', () => {
  ipcRenderer.invoke('quit-app');
});

In the Main.js script

ipcMain.handle('quit-app', () => {
  app.quit();
});


问:
Problems with double .get() in dictionary
I'm working with a nested dictionary were the entries looks like this:

```<code>net_info = {
            '17052242':{'lengthkm': 1.555787, 'uparea': 123.23709555834532, 'order': 2,
                        'strmDrop_t': 231.5, 'unitarea': 123.23709555834532},
            '21009006':{'lengthkm': 6.677901703662528,'uparea': 493.8188826654188,
                        'order': 2,'strmDrop_t': 5.3, 'unitarea': 36.89608111068623},
            .
            .
            .
             }

</code>```

Here is a line of code where I look for a key and a feature inside the dictionary using a double .get(). It works like a charm except when it can't find the key... I know it is because it is passing 0 as a key to the next .get(). My question is, is there a way to just return 0 if it can't find the key and not pass it to the next .get()?

```<code>unitarea_max = max(net_dictionary.get(in1,0).get('unitarea',0), \
net_dictionary.get(in2,0).get('unitarea',0))

</code>```

答:
You need to pass a dictionary to the next .get(). Since it's an empty dictionary you'll get the default from the second .get().

```<code>net_dictionary.get(in1,{}).get('unitarea',0)
</code>```

Body:
I'm working with a nested dictionary were the entries looks like this:

net_info = {
            '17052242':{'lengthkm': 1.555787, 'uparea': 123.23709555834532, 'order': 2,
                        'strmDrop_t': 231.5, 'unitarea': 123.23709555834532},
            '21009006':{'lengthkm': 6.677901703662528,'uparea': 493.8188826654188,
                        'order': 2,'strmDrop_t': 5.3, 'unitarea': 36.89608111068623},
            .
            .
            .
             }

Here is a line of code where I look for a key and a feature inside the dictionary using a double .get(). It works like a charm except when it can't find the key... I know it is because it is passing 0 as a key to the next .get(). My question is, is there a way to just return 0 if it can't find the key and not pass it to the next .get()?

unitarea_max = max(net_dictionary.get(in1,0).get('unitarea',0), \
net_dictionary.get(in2,0).get('unitarea',0))

Body:
You need to pass a dictionary to the next .get(). Since it's an empty dictionary you'll get the default from the second .get().

net_dictionary.get(in1,{}).get('unitarea',0)


问:
python skip importing a library
What I'd like to do is avoid an import that cause a problem. My code is like this:

main.py

```<code>import external_library
</code>```

external_library.py

```<code>import package_with_problem
</code>```

I know I could change external_library.py with something as

```<code>try:
    import package_with_problem
except:
    pass
</code>```

but I'm looking for a solution to implement in main.py. I would like a skip function that takes the package name as parameters and avoid the import.

答:
I found a workaround, I believe it exists a better way to do this but anyway, this is my possible solution for now.

Create a new empty file.

new_empty_file.py

```<code># nothing or print("Hello") to see something in output
</code>```

main.py

```<code>import new_empty_file
import sys
sys.modules['package_with_problem'] = new_empty_file
import external_library # this should use package_with_problem in cache that is new_empty_file
</code>```

If the import in external library has some subpackage, create a new function called as subpackage in new_empty_file as:

new_empty_file.py

```<code>def subpackage():
    return
</code>```

Unfortunately, it is necessary to have package_with_problem in sys and installed, so, not a good solution, it only avoid importing the real library.

Title: python skip importing a library

Body:
What I'd like to do is avoid an import that cause a problem. My code is like this:

main.py

import external_library

external_library.py

import package_with_problem

I know I could change external_library.py with something as

try:
    import package_with_problem
except:
    pass

but I'm looking for a solution to implement in main.py. I would like a skip function that takes the package name as parameters and avoid the import.

Body:
I found a workaround, I believe it exists a better way to do this but anyway, this is my possible solution for now.

Create a new empty file.

new_empty_file.py

# nothing or print("Hello") to see something in output

main.py

import new_empty_file
import sys
sys.modules['package_with_problem'] = new_empty_file
import external_library # this should use package_with_problem in cache that is new_empty_file

If the import in external library has some subpackage, create a new function called as subpackage in new_empty_file as:

new_empty_file.py

def subpackage():
    return

Unfortunately, it is necessary to have package_with_problem in sys and installed, so, not a good solution, it only avoid importing the real library.


问:
Autocomplete in Jupyter notebook not working
I have tried the following steps after the installation of Anaconda's latest version. I am not able to get the autocomplete feature working...

Any suggestions on what else I need to try...

Step 1
 1) pip install jupyter_contrib_nbextensions
 2) pip install jupyter_nbextensions_configurator
 3) jupyter contrib nbextension install --user
 4) jupyter nbextensions_configurator enable --user

Step 2: Open jupyter notebook
 - click on nbextensions tab
 - unckeck disable configuration for nbextensions without explicit compatibility
 - put a check on Hinterland

答:
Go to nbextensions and disable other autocomplete codes.
In my case TabNine was the issue.
enter image description here</p>


问:
brew installation for zsh?
Hi I just followed the thoughtbot laptop setup for my Mac Mini Server running OSX Lion
 Server. I'm not sure that everything is installed correctly. Please advise.

I don't have a ~/.bash_profile or ~/.bashrc but i do have a ~/.profile

But here are contents for .zshrc since I use .zsh.

```<code>   1 # load our own completion functions
   2 fpath=(~/.zsh/completion $fpath)
   3
   4 # completion
   5 autoload -U compinit
   6 compinit
   7
   8 # automatically enter directories without cd
   9 setopt auto_cd
  10
  11 # use vim as an editor
  12 export EDITOR=vim
  13
  14 # aliases
  15 if [ -e "$HOME/.aliases" ]; then
  16   source "$HOME/.aliases"
  17 fi
  18
  19 # vi mode
  20 bindkey -v
  21 bindkey "^F" vi-cmd-mode
  22 bindkey jj vi-cmd-mode
  23
  24 # use incremental search
  25 bindkey "^R" history-incremental-search-backward
  26
  27 # add some readline keys back
  28 bindkey "^A" beginning-of-line
  29 bindkey "^E" end-of-line
  30
  31 # handy keybindings
  32 bindkey "^P" history-search-backward
  33 bindkey "^Y" accept-and-hold
  34 bindkey "^N" insert-last-word
  35 bindkey -s "^T" "^[Isudo ^[A" # "t" for "toughguy"
  36
  37 # expand functions in the prompt
  38 setopt prompt_subst
  39
  40 # prompt
  41 export PS1='[${SSH_CONNECTION+"%n@%m:"}%~] '
  42
  43 # ignore duplicate history entries
  44 setopt histignoredups
  45
  46 # keep TONS of history
  47 export HISTSIZE=4096
  48
  49 # look for ey config in project dirs
  50 export EYRC=./.eyrc
  51
  52 # automatically pushd
  53 setopt auto_pushd
  54 export dirstacksize=5
  55
  56 # awesome cd movements from zshkit
  57 setopt AUTOCD
  58 setopt AUTOPUSHD PUSHDMINUS PUSHDSILENT PUSHDTOHOME
  59 setopt cdablevars
  60
  61 # Try to correct command line spelling
  62 setopt CORRECT CORRECT_ALL
  63
  64 # Enable extended globbing
  65 setopt EXTENDED_GLOB
  66
  67 # RVM
  68 [[ -s '/Users/pma/.rvm/scripts/rvm' ]] && source '/Users/pma/.rvm/scripts/rvm'
</code>```

Brew complains with brew doctor

```<code>[~] brew doctor
/usr/bin is in your PATH before Homebrew's bin. This means that system-
provided programs will be used before Homebrew-provided ones. This is an
issue if you install, for instance, Python.

Consider editing your .bashrc to put:
  /usr/local/bin
ahead of /usr/bin in your $PATH.
</code>```

zsh:

```<code>[~] zsh --version
zsh --version
zsh 4.3.11 (i386-apple-darwin11.0)
</code>```

So how can I ensure brew is installed correctly and remove the errors from brew doctor?

答:
Following @Sajjad's answer did help but I had to run that command every time I started a new terminal which was

```<code>export PATH="/opt/homebrew/bin:$PATH" >> ~/.zshrc
</code>```

I don't know much unix but what's going on here I believe is that we are appening
export PATH="/opt/homebrew/bin:$PATH" part to our .zshrc file which at the root of our file structure at the end of the file.

So, I ran

```<code>nano ~/.zshrc
</code>```

and added

```<code>export PATH="/opt/homebrew/bin:$PATH"
</code>```

at the end and it worked for all terminals from then on.

I am on the M1 if that is relevant

Title: brew installation for zsh?

Body:
Hi I just followed the thoughtbot laptop setup for my Mac Mini Server running OSX Lion
 Server. I'm not sure that everything is installed correctly. Please advise.

I don't have a ~/.bash_profile or ~/.bashrc but i do have a ~/.profile

But here are contents for .zshrc since I use .zsh.

   1 # load our own completion functions
   2 fpath=(~/.zsh/completion $fpath)
   3
   4 # completion
   5 autoload -U compinit
   6 compinit
   7
   8 # automatically enter directories without cd
   9 setopt auto_cd
  10
  11 # use vim as an editor
  12 export EDITOR=vim
  13
  14 # aliases
  15 if [ -e "$HOME/.aliases" ]; then
  16   source "$HOME/.aliases"
  17 fi
  18
  19 # vi mode
  20 bindkey -v
  21 bindkey "^F" vi-cmd-mode
  22 bindkey jj vi-cmd-mode
  23
  24 # use incremental search
  25 bindkey "^R" history-incremental-search-backward
  26
  27 # add some readline keys back
  28 bindkey "^A" beginning-of-line
  29 bindkey "^E" end-of-line
  30
  31 # handy keybindings
  32 bindkey "^P" history-search-backward
  33 bindkey "^Y" accept-and-hold
  34 bindkey "^N" insert-last-word
  35 bindkey -s "^T" "^[Isudo ^[A" # "t" for "toughguy"
  36
  37 # expand functions in the prompt
  38 setopt prompt_subst
  39
  40 # prompt
  41 export PS1='[${SSH_CONNECTION+"%n@%m:"}%~] '
  42
  43 # ignore duplicate history entries
  44 setopt histignoredups
  45
  46 # keep TONS of history
  47 export HISTSIZE=4096
  48
  49 # look for ey config in project dirs
  50 export EYRC=./.eyrc
  51
  52 # automatically pushd
  53 setopt auto_pushd
  54 export dirstacksize=5
  55
  56 # awesome cd movements from zshkit
  57 setopt AUTOCD
  58 setopt AUTOPUSHD PUSHDMINUS PUSHDSILENT PUSHDTOHOME
  59 setopt cdablevars
  60
  61 # Try to correct command line spelling
  62 setopt CORRECT CORRECT_ALL
  63
  64 # Enable extended globbing
  65 setopt EXTENDED_GLOB
  66
  67 # RVM
  68 [[ -s '/Users/pma/.rvm/scripts/rvm' ]] && source '/Users/pma/.rvm/scripts/rvm'

Brew complains with brew doctor

[~] brew doctor
/usr/bin is in your PATH before Homebrew's bin. This means that system-
provided programs will be used before Homebrew-provided ones. This is an
issue if you install, for instance, Python.

Consider editing your .bashrc to put:
  /usr/local/bin
ahead of /usr/bin in your $PATH.

zsh:

[~] zsh --version
zsh --version
zsh 4.3.11 (i386-apple-darwin11.0)

So how can I ensure brew is installed correctly and remove the errors from brew doctor?

Body:
Following @Sajjad's answer did help but I had to run that command every time I started a new terminal which was

export PATH="/opt/homebrew/bin:$PATH" >> ~/.zshrc

I don't know much unix but what's going on here I believe is that we are appening
export PATH="/opt/homebrew/bin:$PATH" part to our .zshrc file which at the root of our file structure at the end of the file.

So, I ran

nano ~/.zshrc

and added

export PATH="/opt/homebrew/bin:$PATH"

at the end and it worked for all terminals from then on.

I am on the M1 if that is relevant


问:
Reading from text file using StreamReader
I have a text file and I'm using a StreamReader for read the entire file to a String array (String[]). So I'm using the StreamReader.ReadToEnd().Split() method for this. But the text file can contain for example a full name (so words which I want to use as one String) so I wrote this file using '|' as separator but when I use StreamReader.ReadToEnd().Split('|') the String array contains elements like this "\r\nSomeString". I think it occurs when I'm using StreamWriter.WriteLine().

Is there a way I can handle this problem?

答:
Can you try System.IO.File

example:

```<code>string text = System.IO.File.ReadAllText(@"C:\Users\Public\TestFolder\WriteText.txt");

        // Display the file contents to the console. Variable text is a string.
        System.Console.WriteLine("Contents of WriteText.txt = {0}", text);

        // Example #2
        // Read each line of the file into a string array. Each element
        // of the array is one line of the file.
        string[] lines = System.IO.File.ReadAllLines(@"C:\Users\Public\TestFolder\WriteLines2.txt");

        // Display the file contents by using a foreach loop.
        System.Console.WriteLine("Contents of WriteLines2.txt = ");
        foreach (string line in lines)
        {
            // Use a tab to indent each line of the file.
            Console.WriteLine("\t" + line);
        }
        foreach (string line in System.IO.File.ReadAllLines(@"C:\Users\Public\TestFolder\WriteLines2.txt"))
        {
            var myArray = line.Split('\t');
        }

</code>```

Body:
Can you try System.IO.File

example:

string text = System.IO.File.ReadAllText(@"C:\Users\Public\TestFolder\WriteText.txt");

        // Display the file contents to the console. Variable text is a string.
        System.Console.WriteLine("Contents of WriteText.txt = {0}", text);

        // Example #2
        // Read each line of the file into a string array. Each element
        // of the array is one line of the file.
        string[] lines = System.IO.File.ReadAllLines(@"C:\Users\Public\TestFolder\WriteLines2.txt");

        // Display the file contents by using a foreach loop.
        System.Console.WriteLine("Contents of WriteLines2.txt = ");
        foreach (string line in lines)
        {
            // Use a tab to indent each line of the file.
            Console.WriteLine("\t" + line);
        }
        foreach (string line in System.IO.File.ReadAllLines(@"C:\Users\Public\TestFolder\WriteLines2.txt"))
        {
            var myArray = line.Split('\t');
        }


问:
Cookiecutter - choices with a custom entry
I am working with the cookicutter package and I would like to know if there is any way to have something like this:

```<code>#cookiecutter.json
{
"name": "default name",
"folder_name": ["foldername1", "foldername2", custom-created-folder-name]
}
</code>```

So, then when creating the repo, I would pick option 3 and be prompted to enter my own folder_name. I tried looking through the docs, but I could not find any reference to this.

答:
You don't have a really nice way to do this, as you always should show the prompt for a custom folder but you can do something like this:

```<code># cookiecutter.json
{
    "folder_name": ["foldername1", "foldername2", "other"],
    "custom_folder_name": ""
}

# your template folder
{% if not cookiecutter.folder_name == "other" %}{{cookiecutter.folder_name}}{% else %}{{cookiecutter.custom_folder_name}}{% endif %}
</code>```

Here is what happens:

```<code>$ cookiecutter template
Select folder_name:
1 - foldername1
2 - foldername2
3 - other
Choose from 1, 2, 3 (1, 2, 3) [1]: 1
custom_folder_name []:
$ ls
foldername1  template

$ cookiecutter template
Select folder_name:
1 - foldername1
2 - foldername2
3 - other
Choose from 1, 2, 3 (1, 2, 3) [1]: 3
custom_folder_name []:
Error: "." directory already exists

$ cookiecutter template
Select folder_name:
1 - foldername1
2 - foldername2
3 - other
Choose from 1, 2, 3 (1, 2, 3) [1]: 3
custom_folder_name []: custom_folder
$ ls
custom_folder  foldername1  template

$ cookiecutter template
Select folder_name:
1 - foldername1
2 - foldername2
3 - other
Choose from 1, 2, 3 (1, 2, 3) [1]: 2
custom_folder_name []: not_used
$ ls
custom_folder  foldername1  foldername2  template
</code>```

Body:
I am working with the cookicutter package and I would like to know if there is any way to have something like this:

#cookiecutter.json
{
"name": "default name",
"folder_name": ["foldername1", "foldername2", custom-created-folder-name]
}

So, then when creating the repo, I would pick option 3 and be prompted to enter my own folder_name. I tried looking through the docs, but I could not find any reference to this.

Body:
You don't have a really nice way to do this, as you always should show the prompt for a custom folder but you can do something like this:

# cookiecutter.json
{
    "folder_name": ["foldername1", "foldername2", "other"],
    "custom_folder_name": ""
}

# your template folder
{% if not cookiecutter.folder_name == "other" %}{{cookiecutter.folder_name}}{% else %}{{cookiecutter.custom_folder_name}}{% endif %}

Here is what happens:

$ cookiecutter template
Select folder_name:
1 - foldername1
2 - foldername2
3 - other
Choose from 1, 2, 3 (1, 2, 3) [1]: 1
custom_folder_name []:
$ ls
foldername1  template

$ cookiecutter template
Select folder_name:
1 - foldername1
2 - foldername2
3 - other
Choose from 1, 2, 3 (1, 2, 3) [1]: 3
custom_folder_name []:
Error: "." directory already exists

$ cookiecutter template
Select folder_name:
1 - foldername1
2 - foldername2
3 - other
Choose from 1, 2, 3 (1, 2, 3) [1]: 3
custom_folder_name []: custom_folder
$ ls
custom_folder  foldername1  template

$ cookiecutter template
Select folder_name:
1 - foldername1
2 - foldername2
3 - other
Choose from 1, 2, 3 (1, 2, 3) [1]: 2
custom_folder_name []: not_used
$ ls
custom_folder  foldername1  foldername2  template


问:
Mockito not working for a Boolean Function
I have a function which tells whether the office is open or closed. I have written a test case which is giving result as False but expecting True. I am not able to figure out reason.</p>
```<code>    public class Office {
        public LocalTime openTime;
        public LocalTime closeTime;
        public LocalTime currentTime;

            public boolean isOfficeOpen() {
            currentTime = getCurrentTime();

            if (currentTime.isAfter(openTime)&&currentTime.isBefore(closeTime)) {
                return true;
            } else {
                return false;
            }

        }
        public LocalTime getCurrentTime(){ return  LocalTime.now(); }
    }

:

@Test
public void is_office_open_pass_test(){
    Office offc = Mockito.mock(Office.class);
    LocalTime openingTime = LocalTime.parse("10:30:00");
    LocalTime closingTime = LocalTime.parse("23:00:00");
    LocalTime currentTime = openingTime.plusHours(1);
    Mockito.when(offc.getCurrentTime()).thenReturn(currentTime);
    boolean status = offc.isOfficeOpen();
    assertTrue(status);
}
</code>```

答:
Office.isOfficeOpen() is never called. Instead the mock is used. But because you didn't provide any behaviour with Mockito.when(offc.isOfficeOpen()).thenReturn(...); Mockito just returns null/false and your test fails.

But the big question is: why are you using Mockito here instead of testing the class directly?

Body:
I have a function which tells whether the office is open or closed. I have written a test case which is giving result as False but expecting True. I am not able to figure out reason.

    public class Office {
        public LocalTime openTime;
        public LocalTime closeTime;
        public LocalTime currentTime;

            public boolean isOfficeOpen() {
            currentTime = getCurrentTime();

            if (currentTime.isAfter(openTime)&&currentTime.isBefore(closeTime)) {
                return true;
            } else {
                return false;
            }

        }
        public LocalTime getCurrentTime(){ return  LocalTime.now(); }
    }

:

@Test
public void is_office_open_pass_test(){
    Office offc = Mockito.mock(Office.class);
    LocalTime openingTime = LocalTime.parse("10:30:00");
    LocalTime closingTime = LocalTime.parse("23:00:00");
    LocalTime currentTime = openingTime.plusHours(1);
    Mockito.when(offc.getCurrentTime()).thenReturn(currentTime);
    boolean status = offc.isOfficeOpen();
    assertTrue(status);
}


问:
Grouping nearby shapes
I have two shapes that are near each other, one of them is selected. I need to be able to group it together with the selected shape.

Thanks for your help!

Here's the code I came with but it doesn't seem to match the nearby shape.  In particular its not finding a 20ptx20pt rectangle offset about half its with to the left and half its height to the top:

```<code>Option Explicit
Sub Test()
Dim oSl As slide
Dim oSh As Shape
Dim oSh2 As Shape

Dim MainHeight As Long
Dim MainWidth As Long

MainHeight = 48.76
MainWidth = 88.45

Set oSl = Application.ActiveWindow.View.slide
Set oSh = ActiveWindow.Selection.ShapeRange(1)

        For Each oSh2 In oSl.Shapes
            If IsWithinRangey(oSh, oSh2, 0.4) Then
                oSh2.Select (False)
            End If
        Next
''        ActiveWindow.Selection.ShapeRange.Group

End Sub

Function IsWithinRangey(oSh As Shape, oSh2 As Shape, _
    AreaTolerance As Single) As Boolean
' Is the shape within the coordinates supplied?

    Dim WidthMin As Single
    Dim WidthMax As Single
    Dim HeightMin As Single
    Dim HeightMax As Single

    With oSh

        HeightMin = oSh.Height * (1 - AreaTolerance)
        HeightMax = oSh.Height * (1 + AreaTolerance)
        WidthMin = oSh.Width * (1 - AreaTolerance)
        WidthMax = oSh.Width * (1 + AreaTolerance)

        Debug.Print "==========================="
        Debug.Print "Shp: " & .Width & " x " & .Height
        Debug.Print "Min: " & WidthMin & " x " & HeightMin
        Debug.Print "Max: " & WidthMax & " x " & HeightMax
    End With

   With oSh2

        If oSh.Id <> oSh2.Id Then
            ShapeLeft = oSh.Left - (19.85) / 1
            ShapeTop = oSh.Top - (19.85) / 1

            Debug.Print ShapeLeft
            Debug.Print ShapeTop

            If .Left >= ShapeLeft And .Left < ShapeLeft + WidthMax Then
                If .Top >= ShapeTop And .Top < ShapeTop + HeightMax Then
                    If .Width >= WidthMin And .Width <= WidthMax Then
                        If .Height > HeightMin And .Height < HeightMax Then
                            IsWithinRangey = True
                    End If
                    End If
                End If
            End If
        End If
    End With

End Function
</code>```

答:
To make your code more efficient, I would restructure as follows:

```<code>Dim WidthMin As Single
Dim WidthMax As Single
Dim HeightMin As Single
Dim HeightMax As Single

Sub GroupCloseShapes()
    Dim oSl As Slide
    Dim oSh As Shape
    Dim oSh2 As Shape
    Dim MainHeight As Long
    Dim MainWidth As Long

    MainHeight = 48.76
    MainWidth = 88.45

    Set oSl = Application.ActiveWindow.View.Slide
    Set oSh = ActiveWindow.Selection.ShapeRange(1)

    With oSh
        HeightMin = oSh.Height * (1 - AreaTolerance)
        HeightMax = oSh.Height * (1 + AreaTolerance)
        WidthMin = oSh.Width * (1 - AreaTolerance)
        WidthMax = oSh.Width * (1 + AreaTolerance)
    End With

    For Each oSh2 In oSl.Shapes
        If oSh.ID <> oSh2.ID Then
            If IsWithinRangey(oSh, oSh2, 0.4) Then
                oSh2.Select (False)
            End If
        End If
    Next
'' ActiveWindow.Selection.ShapeRange.Group
End Sub

Function IsWithinRangey(oSh As Shape, oSh2 As Shape, AreaTolerance As Single) As Boolean ' Is the shape within the coordinates supplied?
    With oSh2
        .Select
        ShapeLeft = oSh.Left - (19.85) / 1
        ShapeTop = oSh.Top - (19.85) / 1
        Debug.Print ShapeLeft
        Debug.Print ShapeTop
        If .Left >= ShapeLeft And .Left < ShapeLeft + WidthMax Then
            If .Top >= ShapeTop And .Top < ShapeTop + HeightMax Then
                If .Width >= WidthMin And .Width <= WidthMax Then
                    If .Height > HeightMin And .Height < HeightMax Then
                        IsWithinRangey = True
                End If
                End If
            End If
        End If
    End With
End Function
</code>```

I've added a .Select method to make it clear which shape is currently being checked. Your problem is with the math calculations in the IsWithinRangey function. To debug them, click on the grey bar to the left of the code. This inserts a breakpoint:

Run the macro. It will stop at the breakpoint. Press F8 to step through each statement. Hover your mouse over the variable names to see their current values. Then adjust your calculations to find the shape you want and ignore the shape you don't want.

Title: Grouping nearby shapes

Body:
I have two shapes that are near each other, one of them is selected. I need to be able to group it together with the selected shape.

Thanks for your help!

Here's the code I came with but it doesn't seem to match the nearby shape.  In particular its not finding a 20ptx20pt rectangle offset about half its with to the left and half its height to the top:

Option Explicit
Sub Test()
Dim oSl As slide
Dim oSh As Shape
Dim oSh2 As Shape

Dim MainHeight As Long
Dim MainWidth As Long

MainHeight = 48.76
MainWidth = 88.45

Set oSl = Application.ActiveWindow.View.slide
Set oSh = ActiveWindow.Selection.ShapeRange(1)

        For Each oSh2 In oSl.Shapes
            If IsWithinRangey(oSh, oSh2, 0.4) Then
                oSh2.Select (False)
            End If
        Next
''        ActiveWindow.Selection.ShapeRange.Group

End Sub

Function IsWithinRangey(oSh As Shape, oSh2 As Shape, _
    AreaTolerance As Single) As Boolean
' Is the shape within the coordinates supplied?

    Dim WidthMin As Single
    Dim WidthMax As Single
    Dim HeightMin As Single
    Dim HeightMax As Single

    With oSh

        HeightMin = oSh.Height * (1 - AreaTolerance)
        HeightMax = oSh.Height * (1 + AreaTolerance)
        WidthMin = oSh.Width * (1 - AreaTolerance)
        WidthMax = oSh.Width * (1 + AreaTolerance)

        Debug.Print "==========================="
        Debug.Print "Shp: " & .Width & " x " & .Height
        Debug.Print "Min: " & WidthMin & " x " & HeightMin
        Debug.Print "Max: " & WidthMax & " x " & HeightMax
    End With

   With oSh2

        If oSh.Id <> oSh2.Id Then
            ShapeLeft = oSh.Left - (19.85) / 1
            ShapeTop = oSh.Top - (19.85) / 1

            Debug.Print ShapeLeft
            Debug.Print ShapeTop

            If .Left >= ShapeLeft And .Left < ShapeLeft + WidthMax Then
                If .Top >= ShapeTop And .Top < ShapeTop + HeightMax Then
                    If .Width >= WidthMin And .Width <= WidthMax Then
                        If .Height > HeightMin And .Height < HeightMax Then
                            IsWithinRangey = True
                    End If
                    End If
                End If
            End If
        End If
    End With

End Function

Body:
To make your code more efficient, I would restructure as follows:

Dim WidthMin As Single
Dim WidthMax As Single
Dim HeightMin As Single
Dim HeightMax As Single

Sub GroupCloseShapes()
    Dim oSl As Slide
    Dim oSh As Shape
    Dim oSh2 As Shape
    Dim MainHeight As Long
    Dim MainWidth As Long

    MainHeight = 48.76
    MainWidth = 88.45

    Set oSl = Application.ActiveWindow.View.Slide
    Set oSh = ActiveWindow.Selection.ShapeRange(1)

    With oSh
        HeightMin = oSh.Height * (1 - AreaTolerance)
        HeightMax = oSh.Height * (1 + AreaTolerance)
        WidthMin = oSh.Width * (1 - AreaTolerance)
        WidthMax = oSh.Width * (1 + AreaTolerance)
    End With

    For Each oSh2 In oSl.Shapes
        If oSh.ID <> oSh2.ID Then
            If IsWithinRangey(oSh, oSh2, 0.4) Then
                oSh2.Select (False)
            End If
        End If
    Next
'' ActiveWindow.Selection.ShapeRange.Group
End Sub

Function IsWithinRangey(oSh As Shape, oSh2 As Shape, AreaTolerance As Single) As Boolean ' Is the shape within the coordinates supplied?
    With oSh2
        .Select
        ShapeLeft = oSh.Left - (19.85) / 1
        ShapeTop = oSh.Top - (19.85) / 1
        Debug.Print ShapeLeft
        Debug.Print ShapeTop
        If .Left >= ShapeLeft And .Left < ShapeLeft + WidthMax Then
            If .Top >= ShapeTop And .Top < ShapeTop + HeightMax Then
                If .Width >= WidthMin And .Width <= WidthMax Then
                    If .Height > HeightMin And .Height < HeightMax Then
                        IsWithinRangey = True
                End If
                End If
            End If
        End If
    End With
End Function

I've added a .Select method to make it clear which shape is currently being checked. Your problem is with the math calculations in the IsWithinRangey function. To debug them, click on the grey bar to the left of the code. This inserts a breakpoint:

Run the macro. It will stop at the breakpoint. Press F8 to step through each statement. Hover your mouse over the variable names to see their current values. Then adjust your calculations to find the shape you want and ignore the shape you don't want.


问:
sorting std::vector<std::string> with numeric data
I have a vector<string> container but the strings are all numbers

EDIT: I tried this:

so now the logic seems to be borked

cleaned this up but experimenting with various attempts to cast std::string to an int is tough
lamba was useless and I have run out of ideas for casting std::string without some bug surfacing

```<code>template<typename Iterator>void bubbleSort(Iterator first, Iterator last){
    Iterator i, j;
    for (i = first; i != last; i++)
        for (j = first; j < i; j++)
            if (*i < *j)
                std::iter_swap(i, j); // or std::swap(*i, *j);
}
</code>```

My code to read the source data is

```<code>void loadgames(void) { // read the game app id's
ifstream inFile;
ofstream outFile;
string s;
inFile.open("game-list.txt");
if (inFile.is_open()) {
    while (std::getline(inFile, s)) {
        if(s.length() > 0)
            gamelist.push_back(s);
    };
    inFile.close();
}
//  bubbleSort(gamelist.begin(),gamelist.end());
outFile.open("game-list.txt");
if (outFile.is_open()) {
    for (i = gamelist.begin(); i != gamelist.end(); i++) {
        outFile << *i << endl;
    }
}
outFile.close();
</code>```

}

The call to is the problem of sorting my vector

```<code>bubbleSort(gamelist.begin(),gamelist.end());
</code>```

答:
As you already know, you can use std::sort() with a custom comparator.  The problem is your compare is setup wrong.  Its parameters need to be the container's value_type, not the container type.  And you have an erroneous . in it.

Try this instead:

```<code>std::vector<std::string> gamelist;
// fill gamelist as needed...

auto compare = [](const std::string &a, const std::string &b){
    return std::stoi(a) < std::stoi(b);
};

std::sort(gamelist.begin(), gamelist.end(), compare);
</code>```

Online Demo

However, I would suggest using std::vector<int> instead (or appropriate integer type, depending on your string contents), and simply parse the std::strings into integers with std::stoi() (or equivalent) before inserting them into the std::vector, eg:

```<code>std::vector<int> gamelist;
// fill gamelist as needed...
gamelist.push_back(std::stoi(someString));
...
std::sort(gamelist.begin(), gamelist.end());
</code>```

Online Demo

This will consume less memory and sort much faster, and it will reduce the complexity of the sort since you will be incurring the overhead of converting strings to integers only one time up front, not on every iteration of the sort algorithm (potentially parsing the same strings over and over).

Body:
I have a vector<string> container but the strings are all numbers

EDIT: I tried this:

so now the logic seems to be borked

cleaned this up but experimenting with various attempts to cast std::string to an int is tough
lamba was useless and I have run out of ideas for casting std::string without some bug surfacing

template<typename Iterator>void bubbleSort(Iterator first, Iterator last){
    Iterator i, j;
    for (i = first; i != last; i++)
        for (j = first; j < i; j++)
            if (*i < *j)
                std::iter_swap(i, j); // or std::swap(*i, *j);
}

My code to read the source data is

void loadgames(void) { // read the game app id's
ifstream inFile;
ofstream outFile;
string s;
inFile.open("game-list.txt");
if (inFile.is_open()) {
    while (std::getline(inFile, s)) {
        if(s.length() > 0)
            gamelist.push_back(s);
    };
    inFile.close();
}
//  bubbleSort(gamelist.begin(),gamelist.end());
outFile.open("game-list.txt");
if (outFile.is_open()) {
    for (i = gamelist.begin(); i != gamelist.end(); i++) {
        outFile << *i << endl;
    }
}
outFile.close();

}

The call to is the problem of sorting my vector

bubbleSort(gamelist.begin(),gamelist.end());

Body:
As you already know, you can use std::sort() with a custom comparator.  The problem is your compare is setup wrong.  Its parameters need to be the container's value_type, not the container type.  And you have an erroneous . in it.

Try this instead:

std::vector<std::string> gamelist;
// fill gamelist as needed...

auto compare = [](const std::string &a, const std::string &b){
    return std::stoi(a) < std::stoi(b);
};

std::sort(gamelist.begin(), gamelist.end(), compare);

Online Demo

However, I would suggest using std::vector<int> instead (or appropriate integer type, depending on your string contents), and simply parse the std::strings into integers with std::stoi() (or equivalent) before inserting them into the std::vector, eg:

std::vector<int> gamelist;
// fill gamelist as needed...
gamelist.push_back(std::stoi(someString));
...
std::sort(gamelist.begin(), gamelist.end());

Online Demo

This will consume less memory and sort much faster, and it will reduce the complexity of the sort since you will be incurring the overhead of converting strings to integers only one time up front, not on every iteration of the sort algorithm (potentially parsing the same strings over and over).


问:
Android DatePicker bug on maxDate
I have created a DatePickerDialog and I am trying to limit the picker to the max date of "today" (currently: 2020, 13 Jul), like this:

```<code>DatePickerDialog(
    activity,
    OnDateSetListener { _: DatePicker?, year: Int, monthOfYear: Int, dayOfMonth: Int ->
        selectedBirthday.set(year, monthOfYear, dayOfMonth)
    },
    1980, 7, 2
).apply {
    datePicker.maxDate = System.currentTimeMillis() // max date = today
}.show()
</code>```

The dialog opens correctly with default data ("1980, Aug 02").

However, I have found a bug when "1980, Aug 02" is selected and I change the year to 2020: The dialog then shows "2020, Aug 02" on top ignoring the maxDate limit setup on the datePicker, but the calendar below is correctly limited to July 13.

Screenshot:

If I click on "OK" button, the year, monthOfYear and dayOfMonth returned on my DateSetListener are 2020, Aug, 02, which is a future date from what I wanted. Is there any workaround to avoid this bug on the DatePickerDialog with the maxDate being ignored?

答:
It is a known bug. There is a ticket recorded 2020-09-29 and still open (in assigned state) as of 2022-02-08.

A similar bug tracker entry with the same issue created 2019-02-19 was closed on 2019-12-04 as "won't fix" due to it being low priority.

I am sorry to say this, but I believe this is not going to be fixed.

However, what you can do is extend the android.app.DatePickerDialog to introduce a fix yourself:

class MyDatePickerDialog(context: Context) : DatePickerDialog(context) {

    override fun onDateChanged(view: DatePicker, year: Int, month: Int, dayOfMonth: Int) {
        val newDate = Calendar.getInstance().apply { set(year, month, dayOfMonth) }
        val minDate = Date(datePicker.minDate)
        val maxDate = Date(datePicker.maxDate)
        newDate.time = minOf(maxDate, maxOf(minDate, newDate.time))
        super.onDateChanged(
            view,
            newDate.get(Calendar.YEAR),
            newDate.get(Calendar.MONTH),
            newDate.get(Calendar.DAY_OF_MONTH)
        )
    }
}
```

Title: Android DatePicker bug on maxDate

Body:
I have created a DatePickerDialog and I am trying to limit the picker to the max date of "today" (currently: 2020, 13 Jul), like this:

DatePickerDialog(
    activity,
    OnDateSetListener { _: DatePicker?, year: Int, monthOfYear: Int, dayOfMonth: Int ->
        selectedBirthday.set(year, monthOfYear, dayOfMonth)
    },
    1980, 7, 2
).apply {
    datePicker.maxDate = System.currentTimeMillis() // max date = today
}.show()

The dialog opens correctly with default data ("1980, Aug 02").

However, I have found a bug when "1980, Aug 02" is selected and I change the year to 2020: The dialog then shows "2020, Aug 02" on top ignoring the maxDate limit setup on the datePicker, but the calendar below is correctly limited to July 13.

Screenshot:

If I click on "OK" button, the year, monthOfYear and dayOfMonth returned on my DateSetListener are 2020, Aug, 02, which is a future date from what I wanted. Is there any workaround to avoid this bug on the DatePickerDialog with the maxDate being ignored?


问:
Is there an accepted "name" for an event that simply reports back a "message"
I have a "DataImporter" class [takes data from many sources and processes it] that I want to report back through an event when it "does something".
At the moment I have:
DataImporterStarted
DataImporterCompleted
DataImporterImportedData
DataImporterDeleted

But they all do the same thing...report back a simple string saying "Data Importer started at xx:xx" or "DataImporter Imported xxx Rows" etc.

Should I be keeping the events separate, or is there an accepted pattern/naming convention for this kind of "I'm doing something" event?
Thx

I was trying to avoid code like this:

```<code>var importer = new DataImporter();
importer.DataImporterStarted += new DataImporterStartedEventHandler(importer_DataImporterMessage);
importer.DataImported += new DataImportedEventHandler(importer_DataImporterMessage);
importer.DataImporterCompleted += new DataImporterCompletedEventHandler(importer_DataImporterMessage);
importer.RunDataImporter();
</code>```

答:
I would keep them separate as suggested in other answers, too.

To avoid duplication of the handling code, you could setup your events with compatible signatures. That would allow you to register the same event handler function to all events.

I don't know if this make sense in your case. It depends on the context.

Body:
I have a "DataImporter" class [takes data from many sources and processes it] that I want to report back through an event when it "does something".
At the moment I have:
DataImporterStarted
DataImporterCompleted
DataImporterImportedData
DataImporterDeleted

But they all do the same thing...report back a simple string saying "Data Importer started at xx:xx" or "DataImporter Imported xxx Rows" etc.

Should I be keeping the events separate, or is there an accepted pattern/naming convention for this kind of "I'm doing something" event?
Thx

I was trying to avoid code like this:

var importer = new DataImporter();
importer.DataImporterStarted += new DataImporterStartedEventHandler(importer_DataImporterMessage);
importer.DataImported += new DataImportedEventHandler(importer_DataImporterMessage);
importer.DataImporterCompleted += new DataImporterCompletedEventHandler(importer_DataImporterMessage);
importer.RunDataImporter();


问:
Values not split. "not enough values to unpack (expected 2, got 1)" when going through my text file line by line
```<code>def player_login():

    username = ""
    new = "0"

    while new not in ('1', '2'):
        print("Type 1 to Login")
        print("Type 2 to Register")
        new = input("")

    if new == '1':
        login_username = input('username: ')
        login_password = input('password: ')
        found_username = False

        with open('user_database.txt', 'r') as password_file:
            for line in password_file:
                username, password = line.strip().split(':')

                if login_username == username:
                    found_username = True
                    if login_password == password:
                        print('success!')
                    else:
                        print('login failure!')
                    break

        username = login_username
        if not found_username:
            print('username invalid')
    if new == '2':
        #code continues
player login()
</code>```

This is the error message I get:

line 18, in player_login

username, password = line.strip().split(':')

ValueError: not enough values to unpack (expected 2, got 1)

Its weird because this code used to work until I switched from PyCharm to VSC and I cannot figure out the problem. Any help is appreciated.

This is my text file if it helps:

```<code>asdaasda:asdaasda
asdfasdf:asdfasdf
hellohi:hellohi
</code>```

答:
One of the lines of the file does not have a : as @ti7 says. Some further debug steps.

```<code>
for i, line in enumerate(password_file):
    try:
        username, password = line.strip().split(':')
    except ValueError as e:
        print(i, line)
</code>```

The try except will now print out the line number and the text of any offending lines.

Body:
def player_login():

    username = ""
    new = "0"

    while new not in ('1', '2'):
        print("Type 1 to Login")
        print("Type 2 to Register")
        new = input("")

    if new == '1':
        login_username = input('username: ')
        login_password = input('password: ')
        found_username = False

        with open('user_database.txt', 'r') as password_file:
            for line in password_file:
                username, password = line.strip().split(':')

                if login_username == username:
                    found_username = True
                    if login_password == password:
                        print('success!')
                    else:
                        print('login failure!')
                    break

        username = login_username
        if not found_username:
            print('username invalid')
    if new == '2':
        #code continues
player login()

This is the error message I get:

line 18, in player_login

username, password = line.strip().split(':')

ValueError: not enough values to unpack (expected 2, got 1)

Its weird because this code used to work until I switched from PyCharm to VSC and I cannot figure out the problem. Any help is appreciated.

This is my text file if it helps:

asdaasda:asdaasda
asdfasdf:asdfasdf
hellohi:hellohi

Body:
One of the lines of the file does not have a : as @ti7 says. Some further debug steps.

for i, line in enumerate(password_file):
    try:
        username, password = line.strip().split(':')
    except ValueError as e:
        print(i, line)

The try except will now print out the line number and the text of any offending lines.


问:
Selecting first non null value in a model
Let's say I have a model class that looks like this:

```<code>   public class ModelTest {
        public string val1 {get;set;}
        public string val2 {get;set;}
        public string val3 {get;set;}
   }
</code>```

Somewhere in my code this ModelTest gets its data. The caveat is that, only 1 of them will hold a value

```<code>   var model = new ModelTest() {val1=null, val2="value", val3=null} //Sudo code
</code>```

What I am trying to do somehow, is compare a value to whichever 1 of the 3 items can potentially have a values, so something like:

```<code>     var testCompare = "someValue"

     if (testCompare == model. ....//how can I get the NOT NULL value from ModelTest here for comparison
</code>```

答:
While your data model isn't ideal, it is possible to check each of the properties by utilizing the || operator to compare each value. As long as your testCompare variable does not contain null, you can also omit a null check.

```<code>if (model.val1 == testCompare ||
    model.val2 == testCompare ||
    model.val3 == testCompare)
{ }
</code>```

As mentioned in the comments, if you want a more succinct version, you can use the null coalescing operator, ??, to check subsequent properties if your prior property returns null. At the end of the null coalescing chain, the first non-null property will be compared to your testCompare string. Note that you must wrap all three properties in parentheses and that this has different behavior; it only tests the first non-null property whereas the previous version tests ALL properties for a match.

```<code>if (testCompare == (model.val1 ?? model.val2 ?? model.val3))
{
}
</code>```

Body:
Let's say I have a model class that looks like this:

   public class ModelTest {
        public string val1 {get;set;}
        public string val2 {get;set;}
        public string val3 {get;set;}
   }

Somewhere in my code this ModelTest gets its data. The caveat is that, only 1 of them will hold a value

   var model = new ModelTest() {val1=null, val2="value", val3=null} //Sudo code

What I am trying to do somehow, is compare a value to whichever 1 of the 3 items can potentially have a values, so something like:

     var testCompare = "someValue"

     if (testCompare == model. ....//how can I get the NOT NULL value from ModelTest here for comparison

Body:
While your data model isn't ideal, it is possible to check each of the properties by utilizing the || operator to compare each value. As long as your testCompare variable does not contain null, you can also omit a null check.

if (model.val1 == testCompare ||
    model.val2 == testCompare ||
    model.val3 == testCompare)
{ }

As mentioned in the comments, if you want a more succinct version, you can use the null coalescing operator, ??, to check subsequent properties if your prior property returns null. At the end of the null coalescing chain, the first non-null property will be compared to your testCompare string. Note that you must wrap all three properties in parentheses and that this has different behavior; it only tests the first non-null property whereas the previous version tests ALL properties for a match.

if (testCompare == (model.val1 ?? model.val2 ?? model.val3))
{
}