问:
Why does bitcore-lib not decode my bitcoin transaction hex correctly?
I am using bitcore-lib to decode transactions encoded in hexadecimal, but I'm getting a weird result. For comparison, I've used bitcoinjs-lib and it seems to be working just fine.

Example

Transaction

Network: bitcoin testnet

Hash: 1eadc4a09c6abc8f024f04031334941ee455cd4fb112850788214da5f631a3d5

Transaction hex:

```<code>01000000000101a0bc55f51d3da3c30b0e92cd37effff17264c3d89057e1e041644606d2a703b5010000001716001482681fa5f944a92d53deacb38850ebba2dd44d44ffffffff0240d2df03000000001976a9147ab6ee8c168f32077c1cc83facb49a91d7ee5dae88aca5a2ecae0800000017a914ca21182b9eca3c99175dd89ce548b72db3244db08702483045022100d4485d23e5d0d3d14a40f0fa9c404f24d55d3db77091bbfb96232610e6b3a5220220712e7736a4229ade64a69e712e842f0a3020cf8209b5f2641114c39a4e9a669201210236443d966162716f76a632e487db80511ce795b68e192e9890bc435ca3e50c1f00000000
</code>```

Try the hex code here: https://live.blockcypher.com/btc/decodetx/

Snippet:

```<code>const bitcore = require('bitcore-lib')
const bitcoinjs = require('bitcoinjs-lib')

const TX_HEX = '01000000000101a0bc55f51d3da3c30b0e92cd37effff17264c3d89057e1e041644606d2a703b5010000001716001482681fa5f944a92d53deacb38850ebba2dd44d44ffffffff0240d2df03000000001976a9147ab6ee8c168f32077c1cc83facb49a91d7ee5dae88aca5a2ecae0800000017a914ca21182b9eca3c99175dd89ce548b72db3244db08702483045022100d4485d23e5d0d3d14a40f0fa9c404f24d55d3db77091bbfb96232610e6b3a5220220712e7736a4229ade64a69e712e842f0a3020cf8209b5f2641114c39a4e9a669201210236443d966162716f76a632e487db80511ce795b68e192e9890bc435ca3e50c1f00000000'

const bitcoreTx = new bitcore.Transaction(Buffer.from(TX_HEX, 'hex'))
const bitcoinjsTx = bitcoinjs.Transaction.fromHex(Buffer.from(TX_HEX, 'hex'))

console.log(bitcoreTx.toJSON())
console.log(bitcoinjsTx)
</code>```

Results

bitcore (incorrect)

```<code>{ hash: '5f10810f9c514ab3f69b940c3dd7163af2f3a993a84e0e782fa5c39f5d0667a8',
  version: 1,
  inputs: [],
  outputs:
   [ { satoshis: 11762590741304222000,
       script: '0b0e92cd37effff17264c3d89057e1e041644606d2a703b5010000001716001482681fa5f944a92d53deacb38850ebba2dd44d44ffffffff0240d2df03000000001976a9147ab6ee8c168f32077c1cc83facb49a91d7ee5dae88aca5a2ecae0800000017a914ca21182b9eca3c99175dd89ce548b72db3244db08702483045022100d4485d23e5d0d3d14a40f0fa9c404f24d55d3db77091bbfb96232610e6b3a5220220712e7736a4229ade64a69e712e842f0a3020cf8209b5f2641114c39a4e9a66' } ],
  nLockTime: 35717522 }
</code>```

bitcoinjs (correct)

```<code>Transaction {
  version: 1,
  locktime: 0,
  ins:
   [ { hash: <Buffer a0 bc 55 f5 1d 3d a3 c3 0b 0e 92 cd 37 ef ff f1 72 64 c3 d8 90 57 e1 e0 41 64 46 06 d2 a7 03 b5>,
       index: 1,
       script: <Buffer 16 00 14 82 68 1f a5 f9 44 a9 2d 53 de ac b3 88 50 eb ba 2d d4 4d 44>,
       sequence: 4294967295,
       witness: [Array] } ],
  outs:
   [ { value: 65000000,
       script: <Buffer 76 a9 14 7a b6 ee 8c 16 8f 32 07 7c 1c c8 3f ac b4 9a 91 d7 ee 5d ae 88 ac> },
     { value: 37294482085,
       script: <Buffer a9 14 ca 21 18 2b 9e ca 3c 99 17 5d d8 9c e5 48 b7 2d b3 24 4d b0 87> } ] }
</code>```

答:
I'm posting this here because this is where I landed from my search for decoding a script and an address.

Decode a "normal" Script

A normal transaction output "script" looks like this:

```<code>76a9141a2e668007a28dbecb420a8e9ce8cdd1651f213d88ac
</code>```

When you break that down, you get this:

```<code>76 a9 14 1a2e668007a28dbecb420a8e9ce8cdd1651f213d 88 ac
</code>```
```<code>0x76 (118) OP_DUP
0x19  (25) OP_HASH160

0x14  (20) is the length of the pubKeyHash (20 bytes)
...        P2PKH (the pubKeyHash)

0x88 (136) OP_EQUALVERIFY
0xac (172) OP_CHECKSIG
</code>```

Bad Address?

The P2PKH address is only part of the address as you probably intend to use it.

You probably want a Base58Check address, which includes a version prefix byte as well as a 4 check hash bytes at the end.

For example:

```<code>4c 1a2e668007a28dbecb420a8e9ce8cdd1651f213d 6496ad2a
</code>```

If you then use the BaseX Base58 encoding you'll get back the friendly address you're familiar with:

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

Body:
I am using bitcore-lib to decode transactions encoded in hexadecimal, but I'm getting a weird result. For comparison, I've used bitcoinjs-lib and it seems to be working just fine.

Example

Transaction

Network: bitcoin testnet

Hash: 1eadc4a09c6abc8f024f04031334941ee455cd4fb112850788214da5f631a3d5

Transaction hex:

01000000000101a0bc55f51d3da3c30b0e92cd37effff17264c3d89057e1e041644606d2a703b5010000001716001482681fa5f944a92d53deacb38850ebba2dd44d44ffffffff0240d2df03000000001976a9147ab6ee8c168f32077c1cc83facb49a91d7ee5dae88aca5a2ecae0800000017a914ca21182b9eca3c99175dd89ce548b72db3244db08702483045022100d4485d23e5d0d3d14a40f0fa9c404f24d55d3db77091bbfb96232610e6b3a5220220712e7736a4229ade64a69e712e842f0a3020cf8209b5f2641114c39a4e9a669201210236443d966162716f76a632e487db80511ce795b68e192e9890bc435ca3e50c1f00000000

Try the hex code here: https://live.blockcypher.com/btc/decodetx/

Snippet:

const bitcore = require('bitcore-lib')
const bitcoinjs = require('bitcoinjs-lib')

const TX_HEX = '01000000000101a0bc55f51d3da3c30b0e92cd37effff17264c3d89057e1e041644606d2a703b5010000001716001482681fa5f944a92d53deacb38850ebba2dd44d44ffffffff0240d2df03000000001976a9147ab6ee8c168f32077c1cc83facb49a91d7ee5dae88aca5a2ecae0800000017a914ca21182b9eca3c99175dd89ce548b72db3244db08702483045022100d4485d23e5d0d3d14a40f0fa9c404f24d55d3db77091bbfb96232610e6b3a5220220712e7736a4229ade64a69e712e842f0a3020cf8209b5f2641114c39a4e9a669201210236443d966162716f76a632e487db80511ce795b68e192e9890bc435ca3e50c1f00000000'

const bitcoreTx = new bitcore.Transaction(Buffer.from(TX_HEX, 'hex'))
const bitcoinjsTx = bitcoinjs.Transaction.fromHex(Buffer.from(TX_HEX, 'hex'))

console.log(bitcoreTx.toJSON())
console.log(bitcoinjsTx)

Results

bitcore (incorrect)

{ hash: '5f10810f9c514ab3f69b940c3dd7163af2f3a993a84e0e782fa5c39f5d0667a8',
  version: 1,
  inputs: [],
  outputs:
   [ { satoshis: 11762590741304222000,
       script: '0b0e92cd37effff17264c3d89057e1e041644606d2a703b5010000001716001482681fa5f944a92d53deacb38850ebba2dd44d44ffffffff0240d2df03000000001976a9147ab6ee8c168f32077c1cc83facb49a91d7ee5dae88aca5a2ecae0800000017a914ca21182b9eca3c99175dd89ce548b72db3244db08702483045022100d4485d23e5d0d3d14a40f0fa9c404f24d55d3db77091bbfb96232610e6b3a5220220712e7736a4229ade64a69e712e842f0a3020cf8209b5f2641114c39a4e9a66' } ],
  nLockTime: 35717522 }

bitcoinjs (correct)

Transaction {
  version: 1,
  locktime: 0,
  ins:
   [ { hash: <Buffer a0 bc 55 f5 1d 3d a3 c3 0b 0e 92 cd 37 ef ff f1 72 64 c3 d8 90 57 e1 e0 41 64 46 06 d2 a7 03 b5>,
       index: 1,
       script: <Buffer 16 00 14 82 68 1f a5 f9 44 a9 2d 53 de ac b3 88 50 eb ba 2d d4 4d 44>,
       sequence: 4294967295,
       witness: [Array] } ],
  outs:
   [ { value: 65000000,
       script: <Buffer 76 a9 14 7a b6 ee 8c 16 8f 32 07 7c 1c c8 3f ac b4 9a 91 d7 ee 5d ae 88 ac> },
     { value: 37294482085,
       script: <Buffer a9 14 ca 21 18 2b 9e ca 3c 99 17 5d d8 9c e5 48 b7 2d b3 24 4d b0 87> } ] }

Body:
I'm posting this here because this is where I landed from my search for decoding a script and an address.

Decode a "normal" Script

A normal transaction output "script" looks like this:

76a9141a2e668007a28dbecb420a8e9ce8cdd1651f213d88ac

When you break that down, you get this:

76 a9 14 1a2e668007a28dbecb420a8e9ce8cdd1651f213d 88 ac

0x76 (118) OP_DUP
0x19  (25) OP_HASH160

0x14  (20) is the length of the pubKeyHash (20 bytes)
...        P2PKH (the pubKeyHash)

0x88 (136) OP_EQUALVERIFY
0xac (172) OP_CHECKSIG

Bad Address?

The P2PKH address is only part of the address as you probably intend to use it.

You probably want a Base58Check address, which includes a version prefix byte as well as a 4 check hash bytes at the end.

For example:

4c 1a2e668007a28dbecb420a8e9ce8cdd1651f213d 6496ad2a

If you then use the BaseX Base58 encoding you'll get back the friendly address you're familiar with:

Xd5GzCN6mp77BeVEe6FrgqQt8MA1ge4Fsw


来源: stackexchange

问:
Dataframe splitting in Python
i Have a dataframe DF ,  and column name DETAILS,  i want the value which are in double quotes (""), will make new column VALUE

DF=

```<code>      DETAILS
   Username as "JOHN"
   verifying the name
   click UserBox
   Password as "345678"
   Click login
   click checkbox
   Phonenumber as "34512345"
   Checking data
</code>```

I want my data frame look like this

DF=

```<code>     DETAILS                      VALUE
   Username as "JOHN"           "JOHN"
   verifying the name             NA
   click UserBox                  NA
   Password as "345678"          "3345678"
   Click login                    NA
   click checkbox                 NA
   Phonenumber as "34512345"     "34512345"
   Checking data                 NA

</code>```

答:
The str accessor has an extract method for that kind of use case:

```<code>DF['VALUE'] = DF['DETAILS'].str.extract('(".*?")')
</code>```

With your data, it gives as expected:

```<code>                     DETAILS       VALUE
0         Username as "JOHN"      "JOHN"
1         verifying the name         NaN
2              click UserBox         NaN
3       Password as "345678"    "345678"
4                Click login         NaN
5             click checkbox         NaN
6  Phonenumber as "34512345"  "34512345"
7              Checking data         NaN
</code>```

ContentLicense: CC BY-SA 4.0

Title: Dataframe splitting in Python

Body:
i Have a dataframe DF ,  and column name DETAILS,  i want the value which are in double quotes (""), will make new column VALUE

DF=

      DETAILS
   Username as "JOHN"
   verifying the name
   click UserBox
   Password as "345678"
   Click login
   click checkbox
   Phonenumber as "34512345"
   Checking data

I want my data frame look like this

DF=

     DETAILS                      VALUE
   Username as "JOHN"           "JOHN"
   verifying the name             NA
   click UserBox                  NA
   Password as "345678"          "3345678"
   Click login                    NA
   click checkbox                 NA
   Phonenumber as "34512345"     "34512345"
   Checking data                 NA

Body:
The str accessor has an extract method for that kind of use case:

DF['VALUE'] = DF['DETAILS'].str.extract('(".*?")')

With your data, it gives as expected:

                     DETAILS       VALUE
0         Username as "JOHN"      "JOHN"
1         verifying the name         NaN
2              click UserBox         NaN
3       Password as "345678"    "345678"
4                Click login         NaN
5             click checkbox         NaN
6  Phonenumber as "34512345"  "34512345"
7              Checking data         NaN


问:
Trying to display xml results in Html using js
im trying to display xml information which comes from this file

```<code><?xml version="1.0" encoding="UTF-8" ?>
<root>
    <key name="The Mintoons #690" type="int">1</key>
    <key name="The Mintoons #368" type="int">2</key>
    <key name="The Mintoons #979" type="int">3</key>
    <key name="The Mintoons #185" type="int">4</key>
    <key name="The Mintoons #499" type="int">5</key>
    <key name="The Mintoons #554" type="int">6</key>
</root>
</code>```

and my html is coded like this

```<code><!DOCTYPE html>
<html>
<style>
table,th,td {
  border : 1px solid black;
  border-collapse: collapse;
}
th,td {
  padding: 5px;
}
</style>
<body>

<button type="button" onclick="loadXMLDoc()">Reveal Results</button>
<br><br>
<table id="demo"></table>

<script>
function loadXMLDoc() {
  var xmlhttp = new XMLHttpRequest();
  xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      myFunction(this);
    }
  };
  xmlhttp.open("GET", "result.xml", true);
  xmlhttp.send();
}
function myFunction(xml) {
  var i;
  var xmlDoc = xml.responseXML;
  var table="<tr><th>Artist</th><th>Title</th></tr>";
  var x = xmlDoc.getElementsByTagName("key");
  for (i = 0; i <x.length; i++) {
    table += "<tr><td>" +
    x[i] +
    "</td><td>" +
    x[i].getAttribute("name")[0] +
    "</td></tr>";
  }
  document.getElementById("demo").innerHTML = table;
}
</script>

</body>
</html>

</code>```

i wanted to display in a table

NFT
Rarity

The Mintoons #690
1

The Mintoons #368
2

like this but rather than like this it displays

NFT
Rarity

[Object Element]
T

[Object Element]
T

i dunno what i did wrong here

答:
(Forming it as an answer after clarification in the comments)

Since x is a collection of DOM elements (in this case XML nodes but it could be HTML elements as well), x[i] is a single element object, so outputting it results in the string '[Object Element]'.

x[i].getAttribute("name") returns the content of the elements name attribute, which is the string "The Mintoons #690" for the first x[0]. So this could be used for the first column of the table.

x[i].getAttribute("name")[0] simply returns the first character of said string, which is "T" - probably not the desired result here. Retriving the inner content of the element (the content between the opening tag and closing tag - "1" for the first element) can be done with x[i].textContent.

So as a conclusion, function myFunction() can be:

```<code>function myFunction(xml) {
  var i;
  var xmlDoc = xml.responseXML;
  var table="<tr><th>Artist</th><th>Title</th></tr>";
  var x = xmlDoc.getElementsByTagName("key");
  for (i = 0; i <x.length; i++) {
    table += "<tr><td>" +
    x[i].getAttribute("name") +
    "</td><td>" +
    x[i].textContent +
    "</td></tr>";
  }
  document.getElementById("demo").innerHTML = table;
}
</code>```

As a side note, building an HTML sequence from an input or a fetched source can create a security weakness point. It may be fine if the source is absoultely trusted, but a more secure equivalent would be

```<code>function myFunction(xml) {
  var i;
  var xmlDoc = xml.responseXML;
  var x = xmlDoc.getElementsByTagName("key");

  var table = document.createElement("table");
  var tr, th, td;

  tr = document.createElement("tr");
  th = document.createElement("th");
  th.textContent = "Artist";
  tr.appendChild(th);
  th = document.createElement("th");
  th.textContent = "Title";
  tr.appendChild(th);
  table.appendChild(tr);

  for (i = 0; i < x.length; i++) {
    tr = document.createElement("tr");
    td = document.createElement("td");
    td.textContent = x[i].getAttribute("name");
    tr.appendChild(td);
    td = document.createElement("td");
    td.textContent = x[i].textContent;
    tr.appendChild(td);
    table.appendChild(tr);
  }
  document.getElementById("demo").appendChild(table);
}
</code>```

Body:
im trying to display xml information which comes from this file

<?xml version="1.0" encoding="UTF-8" ?>
<root>
    <key name="The Mintoons #690" type="int">1</key>
    <key name="The Mintoons #368" type="int">2</key>
    <key name="The Mintoons #979" type="int">3</key>
    <key name="The Mintoons #185" type="int">4</key>
    <key name="The Mintoons #499" type="int">5</key>
    <key name="The Mintoons #554" type="int">6</key>
</root>

and my html is coded like this

<!DOCTYPE html>

<button type="button" onclick="loadXMLDoc()">Reveal Results</button>

i wanted to display in a table

NFT
Rarity

The Mintoons #690
1

The Mintoons #368
2

like this but rather than like this it displays

NFT
Rarity

[Object Element]
T

[Object Element]
T

i dunno what i did wrong here

Body:
(Forming it as an answer after clarification in the comments)

Since x is a collection of DOM elements (in this case XML nodes but it could be HTML elements as well), x[i] is a single element object, so outputting it results in the string '[Object Element]'.

x[i].getAttribute("name") returns the content of the elements name attribute, which is the string "The Mintoons #690" for the first x[0]. So this could be used for the first column of the table.

x[i].getAttribute("name")[0] simply returns the first character of said string, which is "T" - probably not the desired result here. Retriving the inner content of the element (the content between the opening tag and closing tag - "1" for the first element) can be done with x[i].textContent.

So as a conclusion, function myFunction() can be:

function myFunction(xml) {
  var i;
  var xmlDoc = xml.responseXML;
  var table="<tr><th>Artist</th><th>Title</th></tr>";
  var x = xmlDoc.getElementsByTagName("key");
  for (i = 0; i <x.length; i++) {
    table += "<tr><td>" +
    x[i].getAttribute("name") +
    "</td><td>" +
    x[i].textContent +
    "</td></tr>";
  }
  document.getElementById("demo").innerHTML = table;
}

As a side note, building an HTML sequence from an input or a fetched source can create a security weakness point. It may be fine if the source is absoultely trusted, but a more secure equivalent would be

function myFunction(xml) {
  var i;
  var xmlDoc = xml.responseXML;
  var x = xmlDoc.getElementsByTagName("key");

  var table = document.createElement("table");
  var tr, th, td;

  tr = document.createElement("tr");
  th = document.createElement("th");
  th.textContent = "Artist";
  tr.appendChild(th);
  th = document.createElement("th");
  th.textContent = "Title";
  tr.appendChild(th);
  table.appendChild(tr);

  for (i = 0; i < x.length; i++) {
    tr = document.createElement("tr");
    td = document.createElement("td");
    td.textContent = x[i].getAttribute("name");
    tr.appendChild(td);
    td = document.createElement("td");
    td.textContent = x[i].textContent;
    tr.appendChild(td);
    table.appendChild(tr);
  }
  document.getElementById("demo").appendChild(table);
}


问:
React, MobX. The application state is not updated instantly
My store looks like this

```<code>count = 0
increment = () => {
this.count = this.count + 1;
}
</code>```

And my component, that wrapped in observer

```<code><button onClick = {()=>{
increment()
console.log(count, "after")
}}>{count}</button>
</code>```

I expect that the console.log line will already have the updated value. That is, count will be equal to one. The component itself is updated, that is, the count value is changed. But in the console.log line, the count value will first be 0, you press again, the count in the component is 2, but in console.log it is one

答:
That's just how closures works, it's not related to MobX. I expect that you have something like that in the code:

```<code>const {increment, count} = store

return <button onClick = {()=>{
  increment()
  console.log(count, "after")
  }}>{count}</button>
</code>```

So on the first render your onClick has count === 0 in the scope, when you press the button increment increments the count, but onClick still has the old value because that's what it had when it rendered first time. And so on.

You can read more in React docs about it.

With MobX you can overcome it by not destructuring the store, then you will always have latest values everywhere:

```<code>return <button onClick = {()=>{
  store.increment()
  console.log(store.count, "after")
  }}>{store.count}</button>
</code>```

Body:
My store looks like this

count = 0
increment = () => {
this.count = this.count + 1;
}

And my component, that wrapped in observer

<button onClick = {()=>{
increment()
console.log(count, "after")
}}>{count}</button>

I expect that the console.log line will already have the updated value. That is, count will be equal to one. The component itself is updated, that is, the count value is changed. But in the console.log line, the count value will first be 0, you press again, the count in the component is 2, but in console.log it is one

Body:
That's just how closures works, it's not related to MobX. I expect that you have something like that in the code:

const {increment, count} = store

return <button onClick = {()=>{
  increment()
  console.log(count, "after")
  }}>{count}</button>

So on the first render your onClick has count === 0 in the scope, when you press the button increment increments the count, but onClick still has the old value because that's what it had when it rendered first time. And so on.

You can read more in React docs about it.

With MobX you can overcome it by not destructuring the store, then you will always have latest values everywhere:

return <button onClick = {()=>{
  store.increment()
  console.log(store.count, "after")
  }}>{store.count}</button>


问:
Monitor buttons acting totally incorrectly - trying to switch input source instead of showing the OSD
I am a bit new here, English is not my native, so I am sorry for any possible misspelling.

I have a very odd problem - my Xiaomi Mi Surface Display 34" (XMMNTWQ34 model) monitor buttons act really strange - instead of calling the monitor OSD, pressing any of 4 present buttons tries to switch to another possible input source (this is even not their function!), but no luck: just 3 seconds of the black screen and it turns back to the initial image. Let me explain how I got into this.

I have a monitor named before, which has 4 input ports: 2 DP and 2 HDMI. There is a PC always connected to the monitor via the DP interface (DP1 to be exact). Today I tried to connect a second PC via HDMI to the HDMI1 port. It went totally good, I was able to switch between PCs using a monitor OSD. But I thought it was too long and complicated to press a dozen buttons on OSD just to change an input source, so started to google any other programmatical methods of doing such thing.

Some fact: there are no drivers for this monitor on the Internet (it actually works at full 3440x1440@144 Hz resolution/refresh rate via DP interface without any trouble, but Windows sees it as "Generic PnP Monitor", so I see no way to fix it without a relevant driver).

I have found that any VESA-compatible monitor has the 0x60 parameter, which means exactly "input source", so altering the value of this parameter switches the input source without the need to call an OSD. I have found that the possible values of this 0x60 parameter for my monitor provided by several utilities are: 0x0F, 0x10, 0x11, and 0x12. But setting any of these values got me no luck - the screen just flashed black and nothing more. Moreover, those utilities showed that the current value of the 0x60 parameter was 0x07 - described as "S-Video 1" input source, and it did not change at any made tries. But my monitor does not even have such input ports!

But I discovered a total disaster a bit later - when I tried to switch the input source via OSD, I was not able to call it - any of the 4 buttons on the monitor was causing a black flash and nothing more! So OSD is now totally unavailable! This is madness. I can't enter the OSD, I can't change the input source without turning off any one of 2 connected PCs, I can't do anything which is supposed to be made via OSD. Rebooting and reattaching of every possible thing has no effect - even with 2 PCs being connected to monitor and waiting to enter a BIOS password (no OS loaded whatsoever): pressing any button on the monitor causes only black flash and nothing more, no OSD called. I guess this is a strictly monitor firmware issue because the OSD worked well until yesterday.

I have absolutely no idea how to solve this, I googled this all day long, but no luck. System restore did not change anything. Please help. Thank you all very much.

答:
Same issue after using ControlMyMonitor App. At the time being, i didn't found any solution to get the OSD back. And I didn't found any solution to factory reset the monitor, I don't know if it's possible.

I strongly discourage users to use any kind of VESA com application on this Xiaomi 34 monitor !

Now, the best solution in order to switch inputs, is to disconnect or shutdown one of the computer connected, ans it will switch automaticaly to the only one remaining. (Or use a VESA script...)


问:
How to log notifications laravel 8 after fired
guys, I create a panel with laravel 8 and create some emails jobs that must send emails to specific users on specific dates it works fine. I created the database with 2 columns user_id (id of the user that email sent to him/er) and type (type of emails such as Weekly, monthly, reset password, etc...) named Emails also.
I added these lines to my EventserviceProvider that mentioned on the documents

'Illuminate\Mail\Events\MessageSent' => ['App\Listeners\LogSentMessage',],

then I defined these two on my email files (app/mail) these two data will pass to mailjob also then i can catch them on my handle function to use like this:

Mail::to($user->email)->send(new Firstweek($firstname,$user->id,'week1'));

to log these emails have been sent or not then if the email is sent this listener will run and save data to the database. till here all works fine.

I use the default reset password system of laravel that used notifications. my problem is when I request the reset password after sending the reset password email I face an error related to these requested logs that want to get user_id and type that needed for Email but I really do not have any idea how I can pass these data to notifications.

I really need your helps tank you so much.

答: You can pass extra arguments to the Password reset event e.g new \Illuminate\Auth\Events\PasswordReset($user, $type_id) and attach a listener in your EventServiceProvider


问:
How can I write a where clause in SQL to filter a DATETIME column by the time of day?
I have data that is timestamped with a DATETIME column and I want to filter it down to the set of records where the DATETIME is between 9:30am and 5:30pm for any day.  What's the best way to do this?

UPDATE: Changed because I need precision to the minute, not just hour.  Sorry about that.

答:
Similar to above code, just add the DATEPART(mi, column) for your MINUTE requirement

However, note this will suffer in performance as functions on the columns will avoid using index (non-sargeable)

If you are using SQL 2008, they have DATE and TIME new data types that you can use to compare. If not, in SQL 2005, perhaps you can create computed columns for TIME portion and utilize it

OwnerDisplayName: Bialecki

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Milen A. Radev

OwnerDisplayName: jerryhung


问:
Adding query parameters to URL on HTTP request
I was looking at a few post regrading query parameters in my URL and I couldn't quite find what I was looking for.

So far the external API I am fetching data from requires a specific I will call in this case "tag" parameter when making HTTP request in the browser.

Here is my Post model with a tag defined as a field

```<code>package com.example.blog.post;

import javax.persistence.*;

@Entity
@Table(name = "post")
public class Post{

    @Id
    @GeneratedValue
    private Long id;

    private String tag;

    public Post() {

    }

    public void setId(Long id) {
        this.id = id;
    }

    public Long getId() {

        return id;
    }

    public String getTag() {
        return tag;
    }
}
</code>```

And here is my controller class and the "getPosts()" method is where I am fetching the external data but it requires a tag parameter (query parameter) in order to complete the response. How do I incorporate the "tag" query parameter in this case?

```<code>package com.example.blog.post;

import org.springframework.web.bind.annotation.*;
import java.util.*;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;
import com.example.blog.HttpRequest;

@RestController
@RequestMapping
public class PostController {

    private PostRepository postRepository;

    private RestTemplate restTemplate;

//    @GetMapping("/api/ping")
//    public ResponseEntity<?> ping(){
//        String res = request.body();
//        return new ResponseEntity<>(res,HttpStatus.OK);
//    }

    @GetMapping("/api/posts")
    public ResponseEntity<?> getPosts(@RequestParam(value="tag") String tag){
        try{
            HttpRequest request = HttpRequest.get("https://api.blogs.io/blog/posts").connectTimeout(12000);
            String res = request.body();
            return new ResponseEntity<>(res,HttpStatus.OK);
        }catch (Exception e){
            e.printStackTrace();
            return new ResponseEntity<>("Error!,please try again",HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}
</code>```

答:
Simply change your method to

```<code>@GetMapping("/api/posts")
public ResponseEntity<?> getPosts(@RequestParam("tag") String tag){...}
</code>```

Then you also need to send that query param in url like

```<code>http://localhost:8080/api/posts?tag=java
</code>```

Body:
I was looking at a few post regrading query parameters in my URL and I couldn't quite find what I was looking for.

So far the external API I am fetching data from requires a specific I will call in this case "tag" parameter when making HTTP request in the browser.

Here is my Post model with a tag defined as a field

package com.example.blog.post;

import javax.persistence.*;

@Entity
@Table(name = "post")
public class Post{

    @Id
    @GeneratedValue
    private Long id;

    private String tag;

    public Post() {

    }

    public void setId(Long id) {
        this.id = id;
    }

    public Long getId() {

        return id;
    }

    public String getTag() {
        return tag;
    }
}

And here is my controller class and the "getPosts()" method is where I am fetching the external data but it requires a tag parameter (query parameter) in order to complete the response. How do I incorporate the "tag" query parameter in this case?

package com.example.blog.post;

import org.springframework.web.bind.annotation.*;
import java.util.*;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;
import com.example.blog.HttpRequest;

@RestController
@RequestMapping
public class PostController {

    private PostRepository postRepository;

    private RestTemplate restTemplate;

//    @GetMapping("/api/ping")
//    public ResponseEntity<?> ping(){
//        String res = request.body();
//        return new ResponseEntity<>(res,HttpStatus.OK);
//    }

    @GetMapping("/api/posts")
    public ResponseEntity<?> getPosts(@RequestParam(value="tag") String tag){
        try{
            HttpRequest request = HttpRequest.get("https://api.blogs.io/blog/posts").connectTimeout(12000);
            String res = request.body();
            return new ResponseEntity<>(res,HttpStatus.OK);
        }catch (Exception e){
            e.printStackTrace();
            return new ResponseEntity<>("Error!,please try again",HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}

Body:
Simply change your method to

@GetMapping("/api/posts")
public ResponseEntity<?> getPosts(@RequestParam("tag") String tag){...}

Then you also need to send that query param in url like

http://localhost:8080/api/posts?tag=java


问:
SMTPAuthenticationError in Weblate (which uses Django)
I checked quite a few stackoverflow questions about this and none doesn't seem to be the exact case as me and didn't really work for me so posting this question. So I'm trying to setup weblate using docker which wants me to set weblate email host user, password etc. to send mails to users when using the site, my current docker-compose.override.yml looks like this:

```<code>version: '3'
services:
  weblate:
    ports:
      - 1111:8080
    environment:
      WEBLATE_EMAIL_HOST: smtp.mymailserver.com
      WEBLATE_EMAIL_PORT: 465
      WEBLATE_EMAIL_HOST_USER: translate@domain.com
      WEBLATE_EMAIL_HOST_PASSWORD: password
      WEBLATE_SERVER_EMAIL: translate@domain.com
      WEBLATE_DEFAULT_FROM_EMAIL: translate@domain.com
      WEBLATE_SITE_DOMAIN: translate.mydomain.com
      WEBLATE_ADMIN_PASSWORD: mypass
      WEBLATE_ADMIN_EMAIL: myemail@domain.com
</code>```

I checked this with gmail app in mobile with the same outgoing server configuration and it worked perfectly fine there (I was able to send mails from it) but whenever I try it with weblate, I'm seeing this error:

```<code>SMTPAuthenticationError: (535, b'Authentication credentials invalid')
</code>```

This is the whole error I get in the logs

答:
You don't have SSL enabled, that might be reason for server rejecting the crendentials. Try enabling WEBLATE_EMAIL_USE_SSL.

PS: In the upcoming release, this will be turned on automatically for port 465, see https://github.com/WeblateOrg/weblate/commit/efacbf5d7e36c7207e985744639564e7edfc2fbb

Body:
I checked quite a few stackoverflow questions about this and none doesn't seem to be the exact case as me and didn't really work for me so posting this question. So I'm trying to setup weblate using docker which wants me to set weblate email host user, password etc. to send mails to users when using the site, my current docker-compose.override.yml looks like this:

version: '3'
services:
  weblate:
    ports:
      - 1111:8080
    environment:
      WEBLATE_EMAIL_HOST: smtp.mymailserver.com
      WEBLATE_EMAIL_PORT: 465
      WEBLATE_EMAIL_HOST_USER: translate@domain.com
      WEBLATE_EMAIL_HOST_PASSWORD: password
      WEBLATE_SERVER_EMAIL: translate@domain.com
      WEBLATE_DEFAULT_FROM_EMAIL: translate@domain.com
      WEBLATE_SITE_DOMAIN: translate.mydomain.com
      WEBLATE_ADMIN_PASSWORD: mypass
      WEBLATE_ADMIN_EMAIL: myemail@domain.com

I checked this with gmail app in mobile with the same outgoing server configuration and it worked perfectly fine there (I was able to send mails from it) but whenever I try it with weblate, I'm seeing this error:

SMTPAuthenticationError: (535, b'Authentication credentials invalid')

This is the whole error I get in the logs


问:
NOT EXISTS is not working for multiple records which has same value
I am try to create a SQL query for the user should have revoke entry in Database for the respective grant access for that study.
For ex, if the user is having total count of 20 GRANT records then the user should have total count of REVOKE records. If not we need to enter the missing records.

I have created the following query. The query is working fine for the user who is having single Grant record for study but if the user is having Multiple grant record for particular study its not working.

For ex. User A is having two GRANT records and 1 REVOKE records for study ABC. the below query is not showing any output since the REVOKE record is already listed for that study.

But we have only one REVOKE records for that study. So I want to display that MISSING  GRANT record

```<code>SELECT Getdate() [RequestedDate],
   Getdate() [ApprovedDate],
   A.requestedfor,
   'XXX'    [ApprovedBy],
   A.projectnumber,
   'Revoke'  [AccessRequestType]

FROM   [dbo].[Table1] A
WHERE  A.requestedfor  = 1234
   AND A.accessrequesttype = 'Grant'
   AND NOT EXISTS (SELECT *
                   FROM   [dbo].[Table1] B
                   WHERE  B.requestedfor =1234
                          AND B.accessrequesttype = 'Revoke'
                          AND A.projectnumber =  B.projectnumber
                          AND A.accessgroup = B. accessgroup
                          AND A.RequestedFor = B. RequestedFor
                          )
</code>```

答:
By numbering the rows we can pair up GRANTs with REVOKEs, and return unmatched/excess GRANTs as new Revoke entries:</p>
```<code> select
   Getdate() [RequestedDate],
   Getdate() [ApprovedDate],
   A.requestedfor,
   'XXX'    [ApprovedBy],
   A.projectnumber,
   'Revoke'  [AccessRequestType]
from (
    SELECT requestedfor, projectnumber, seq=row_number() over (order by RequestedFor)
    FROM Table1
    where RequestedFor=1234
    and AccessRequestType='Grant'
    except
    SELECT requestedfor, projectnumber, seq=row_number() over (order by RequestedFor)
    FROM Table1
    where RequestedFor=1234
    and AccessRequestType='Revoke'
    ) a
     ```
@maxim's proposal should also work.
</code>```

Body:
I am try to create a SQL query for the user should have revoke entry in Database for the respective grant access for that study.
For ex, if the user is having total count of 20 GRANT records then the user should have total count of REVOKE records. If not we need to enter the missing records.

I have created the following query. The query is working fine for the user who is having single Grant record for study but if the user is having Multiple grant record for particular study its not working.

For ex. User A is having two GRANT records and 1 REVOKE records for study ABC. the below query is not showing any output since the REVOKE record is already listed for that study.

But we have only one REVOKE records for that study. So I want to display that MISSING  GRANT record

SELECT Getdate() [RequestedDate],
   Getdate() [ApprovedDate],
   A.requestedfor,
   'XXX'    [ApprovedBy],
   A.projectnumber,
   'Revoke'  [AccessRequestType]

FROM   [dbo].[Table1] A
WHERE  A.requestedfor  = 1234
   AND A.accessrequesttype = 'Grant'
   AND NOT EXISTS (SELECT *
                   FROM   [dbo].[Table1] B
                   WHERE  B.requestedfor =1234
                          AND B.accessrequesttype = 'Revoke'
                          AND A.projectnumber =  B.projectnumber
                          AND A.accessgroup = B. accessgroup
                          AND A.RequestedFor = B. RequestedFor
                          )

Body:
By numbering the rows we can pair up GRANTs with REVOKEs, and return unmatched/excess GRANTs as new Revoke entries:

 select
   Getdate() [RequestedDate],
   Getdate() [ApprovedDate],
   A.requestedfor,
   'XXX'    [ApprovedBy],
   A.projectnumber,
   'Revoke'  [AccessRequestType]
from (
    SELECT requestedfor, projectnumber, seq=row_number() over (order by RequestedFor)
    FROM Table1
    where RequestedFor=1234
    and AccessRequestType='Grant'
    except
    SELECT requestedfor, projectnumber, seq=row_number() over (order by RequestedFor)
    FROM Table1
    where RequestedFor=1234
    and AccessRequestType='Revoke'
    ) a
     ```
@maxim's proposal should also work.


问:
Running grafana behind apache2 reverse proxy
I need to run grafana and kibana on a same server while running behind Apache2 reverse proxy

I manage to succeed with kibana, but grafana cause me some problems; in fact I don't how how to run the sub path.

I want these two services to run like this : X.X.X.X/kibana and X.X.X.X/grafana.

Here is my apache2 config and my grafana settings:

```<code><VirtualHost *:80>
ServerName http://myipadress/kibana
ProxyRequests Off
ProxyPreserveHost On
ProxyPass / http://myipadress:5601/
ProxyPassReverse / http://myipadress:5601/
</VirtualHost>

#--------------GRAFANA----------------------------
<VirtualHost *:80>
ServerName http://myipadress/grafana
ProxyRequests On
ProxyPreserveHost On
ProxyPass / http://myipadress:3000/
ProxyPassReverse / http://myipadress:3000/
</VirtualHost>
</code>```

For grafana :

```<code>protocol = http
http_port = 3000
domain = myipadress
root_url = %(protocol)s://%(domain)s:%(http_port)s/grafana
serve_from_sub_path = true
</code>```

Does anyone know what I did wrong

Cheers

答:
Hello after loosing too much time on it, I decided to change my reverse proxy and use NGINX.
I fact, there is a example of configuration in grafana's documentation, and I just added these lines

```<code>  location /kibana {
    proxy_pass http://localhost:5601/kibana;
  }
</code>```

And it just work for me

Body:
I need to run grafana and kibana on a same server while running behind Apache2 reverse proxy

I manage to succeed with kibana, but grafana cause me some problems; in fact I don't how how to run the sub path.

I want these two services to run like this : X.X.X.X/kibana and X.X.X.X/grafana.

Here is my apache2 config and my grafana settings:

<VirtualHost *:80>
ServerName http://myipadress/kibana
ProxyRequests Off
ProxyPreserveHost On
ProxyPass / http://myipadress:5601/
ProxyPassReverse / http://myipadress:5601/
</VirtualHost>

#--------------GRAFANA----------------------------
<VirtualHost *:80>
ServerName http://myipadress/grafana
ProxyRequests On
ProxyPreserveHost On
ProxyPass / http://myipadress:3000/
ProxyPassReverse / http://myipadress:3000/
</VirtualHost>

For grafana :

protocol = http
http_port = 3000
domain = myipadress
root_url = %(protocol)s://%(domain)s:%(http_port)s/grafana
serve_from_sub_path = true

Does anyone know what I did wrong

Cheers

Body:
Hello after loosing too much time on it, I decided to change my reverse proxy and use NGINX.
I fact, there is a example of configuration in grafana's documentation, and I just added these lines

  location /kibana {
    proxy_pass http://localhost:5601/kibana;
  }

And it just work for me


问:
/bin/bash: invalid optionash: -
I'm new with Docker, so sorry if this is a noob question :(

A friend shared with me his project and I'm trying to create the container but I have an error.

Here is my input:

```<code>docker build -t project-py -f project-py/prod/Dockerfile .
</code>```

And here is the error:

```<code> => ERROR [19/27] RUN build.sh                                                                                0.2s
------
 > [19/27] RUN build.sh:
: invalid optionash: -
------
failed to solve with frontend dockerfile.v0: failed to build LLB: executor failed running [/bin/sh -c build.sh]: runc did not terminate sucessfully
</code>```

What I understand so far is he doesn't understand this line in my build.sh : #!/bin/bash -e

I have done some test:

leave the build.sh file blank = works

remove the "-e" = give the error bad interpreter

My friend doesn't have the error...

Here is my Dockerfile:

```<code># based on https://github.com/dockerfiles/django-uwsgi-nginx
FROM amazonlinux

ENV HOME /home/appuser
ENV AWS_DEFAULT_REGION us-east-1

# Install required packages and remove the cache when done
RUN yum update -y && yum install -y \
    amazon-linux-extras awscli git \
    make glibc-devel gcc patch mysql-devel \
    enchant pyOpenSSL python3 python3-devel python3-pip python3-setuptools python-imaging \
    which vim git \
    && yum clean all

RUN cd /tmp && \
    curl -O https://s3.amazonaws.com/amazoncloudwatch-agent/amazon_linux/amd64/latest/amazon-cloudwatch-agent.rpm && \
    rpm -U ./amazon-cloudwatch-agent.rpm && \
    rm amazon-cloudwatch-agent.rpm

RUN amazon-linux-extras enable nginx1 && yum install -y nginx && yum clean all

#breaking this up to benefit from docker caching...
RUN pip3 install --upgrade pip supervisor uwsgitop \
  && useradd -m appuser \
    && chown -R appuser:appuser /home/appuser \
    && mkdir /var/log/project

# this is our log config
COPY project-py/prod/amazon-cloudwatch-agent/amazon-cloudwatch-agent.json /opt/aws/amazon-cloudwatch-agent/etc/config.json
# this is a hacked version of the ctl script that doesn't use systemd/initd to start it
COPY project-py/prod/amazon-cloudwatch-agent/amazon-cloudwatch-agent-ctl /opt/aws/amazon-cloudwatch-agent/bin/

USER appuser

# COPY requirements.txt and RUN pip install BEFORE adding the rest of your code, this will cause Docker's caching mechanism
# to prevent re-installing all your dependencies when you made a change a line or two in your app.
COPY --chown=appuser:appuser project-py/requirements/production.txt $HOME/project-py/requirements.txt

RUN python3 -m venv $HOME/venv && /bin/bash -c "source $HOME/venv/bin/activate; pip3 install -r $HOME/project-py/requirements.txt"

# add our stuff. break it up so that we can benefit from docker caching
COPY --chown=appuser:appuser project-docs $HOME/project-docs
COPY --chown=appuser:appuser project-static $HOME/project-static
COPY --chown=appuser:appuser project-www $HOME/project-www
COPY --chown=appuser:appuser project-py/assets/fonts $HOME/project-py/assets/fonts
COPY --chown=appuser:appuser project-py/*.py $HOME/project-py/
COPY --chown=appuser:appuser project-py/project $HOME/project-py/project
COPY --chown=appuser:appuser project-py/templates $HOME/project-py/templates
COPY --chown=appuser:appuser project-py/tools $HOME/project-py/tools
COPY project-py/prod/build.sh /usr/local/bin/
RUN build.sh
</code>```

Here is the build.sh :

```<code>#!/bin/bash -e

source $HOME/venv/bin/activate
echo "compiling translations..."
pybabel compile --use-fuzzy -d $HOME/project-py/hourglass/translations
</code>```

I'm working on W10 build 2004 on a surface Pro 7, with this version of docker :

```<code>Client: Docker Engine - Community
 Cloud integration: 1.0.2
 Version:           19.03.13
 API version:       1.40
 Go version:        go1.13.15
 Git commit:        4484c46d9d
 Built:             Wed Sep 16 17:00:27 2020
 OS/Arch:           windows/amd64
 Experimental:      false

Server: Docker Engine - Community
 Engine:
  Version:          19.03.13
  API version:      1.40 (minimum version 1.12)
  Go version:       go1.13.15
  Git commit:       4484c46d9d
  Built:            Wed Sep 16 17:07:04 2020
  OS/Arch:          linux/amd64
  Experimental:     false
 containerd:
  Version:          v1.3.7
  GitCommit:        8fba4e9a7d01810a393d5d25a3621dc101981175
 runc:
  Version:          1.0.0-rc10
  GitCommit:        dc9208a3303feef5b3839f4323d9beb36df0a9dd
 docker-init:
  Version:          0.18.0
  GitCommit:        fec3683
</code>```

Thanks a lot for your help

答:
In Dockfile add this line before RUN ./setup.sh

```<code>RUN cat setup.sh | sed '1 s/\r$//' > setup.sh

</code>```

basically, it will remove \r from the first line.

Title: /bin/bash: invalid optionash: -

Body:
I'm new with Docker, so sorry if this is a noob question :(

A friend shared with me his project and I'm trying to create the container but I have an error.

Here is my input:

docker build -t project-py -f project-py/prod/Dockerfile .

And here is the error:

 => ERROR [19/27] RUN build.sh                                                                                0.2s
------
 > [19/27] RUN build.sh:
: invalid optionash: -
------
failed to solve with frontend dockerfile.v0: failed to build LLB: executor failed running [/bin/sh -c build.sh]: runc did not terminate sucessfully

What I understand so far is he doesn't understand this line in my build.sh : #!/bin/bash -e

I have done some test:

leave the build.sh file blank = works

remove the "-e" = give the error bad interpreter

My friend doesn't have the error...

Here is my Dockerfile:

# based on https://github.com/dockerfiles/django-uwsgi-nginx
FROM amazonlinux

ENV HOME /home/appuser
ENV AWS_DEFAULT_REGION us-east-1

# Install required packages and remove the cache when done
RUN yum update -y && yum install -y \
    amazon-linux-extras awscli git \
    make glibc-devel gcc patch mysql-devel \
    enchant pyOpenSSL python3 python3-devel python3-pip python3-setuptools python-imaging \
    which vim git \
    && yum clean all

RUN cd /tmp && \
    curl -O https://s3.amazonaws.com/amazoncloudwatch-agent/amazon_linux/amd64/latest/amazon-cloudwatch-agent.rpm && \
    rpm -U ./amazon-cloudwatch-agent.rpm && \
    rm amazon-cloudwatch-agent.rpm

RUN amazon-linux-extras enable nginx1 && yum install -y nginx && yum clean all

#breaking this up to benefit from docker caching...
RUN pip3 install --upgrade pip supervisor uwsgitop \
  && useradd -m appuser \
    && chown -R appuser:appuser /home/appuser \
    && mkdir /var/log/project

# this is our log config
COPY project-py/prod/amazon-cloudwatch-agent/amazon-cloudwatch-agent.json /opt/aws/amazon-cloudwatch-agent/etc/config.json
# this is a hacked version of the ctl script that doesn't use systemd/initd to start it
COPY project-py/prod/amazon-cloudwatch-agent/amazon-cloudwatch-agent-ctl /opt/aws/amazon-cloudwatch-agent/bin/

USER appuser

# COPY requirements.txt and RUN pip install BEFORE adding the rest of your code, this will cause Docker's caching mechanism
# to prevent re-installing all your dependencies when you made a change a line or two in your app.
COPY --chown=appuser:appuser project-py/requirements/production.txt $HOME/project-py/requirements.txt

RUN python3 -m venv $HOME/venv && /bin/bash -c "source $HOME/venv/bin/activate; pip3 install -r $HOME/project-py/requirements.txt"

# add our stuff. break it up so that we can benefit from docker caching
COPY --chown=appuser:appuser project-docs $HOME/project-docs
COPY --chown=appuser:appuser project-static $HOME/project-static
COPY --chown=appuser:appuser project-www $HOME/project-www
COPY --chown=appuser:appuser project-py/assets/fonts $HOME/project-py/assets/fonts
COPY --chown=appuser:appuser project-py/*.py $HOME/project-py/
COPY --chown=appuser:appuser project-py/project $HOME/project-py/project
COPY --chown=appuser:appuser project-py/templates $HOME/project-py/templates
COPY --chown=appuser:appuser project-py/tools $HOME/project-py/tools
COPY project-py/prod/build.sh /usr/local/bin/
RUN build.sh

Here is the build.sh :

#!/bin/bash -e

source $HOME/venv/bin/activate
echo "compiling translations..."
pybabel compile --use-fuzzy -d $HOME/project-py/hourglass/translations

I'm working on W10 build 2004 on a surface Pro 7, with this version of docker :

Client: Docker Engine - Community
 Cloud integration: 1.0.2
 Version:           19.03.13
 API version:       1.40
 Go version:        go1.13.15
 Git commit:        4484c46d9d
 Built:             Wed Sep 16 17:00:27 2020
 OS/Arch:           windows/amd64
 Experimental:      false

Server: Docker Engine - Community
 Engine:
  Version:          19.03.13
  API version:      1.40 (minimum version 1.12)
  Go version:       go1.13.15
  Git commit:       4484c46d9d
  Built:            Wed Sep 16 17:07:04 2020
  OS/Arch:          linux/amd64
  Experimental:     false
 containerd:
  Version:          v1.3.7
  GitCommit:        8fba4e9a7d01810a393d5d25a3621dc101981175
 runc:
  Version:          1.0.0-rc10
  GitCommit:        dc9208a3303feef5b3839f4323d9beb36df0a9dd
 docker-init:
  Version:          0.18.0
  GitCommit:        fec3683

Thanks a lot for your help

Body:
In Dockfile add this line before RUN ./setup.sh

RUN cat setup.sh | sed '1 s/\r$//' > setup.sh

basically, it will remove \r from the first line.


问:
How to print specific data based on its rank in data frame
I have data of cooking oil and its boiling temp and ranked it by highest boiling temp

```<code>print(df_ranked)

    ranking               oil  boil_temp
0         1           avocado        270
1         2         sunflower        252
2         3       beef_tallow        250
3         3  butter_clarified        250
4         3           mustard        250
5         4              palm        235
6         5              corn        230
7         6         grapeseed        216
8         7            canola        204
9         8           coconut        200
10        9          olive_ev        160
11       10            butter        150
</code>```

I used print function to print data with certain rank and this is the result

```<code>print(df_ranked.loc[df_ranked['ranking'].isin([3])])

 ranking               oil  boil_temp
2        3       beef_tallow        250
3        3  butter_clarified        250
4        3           mustard        250
</code>```

I want the result to be more simple like this

```<code>beef_tallow, 250
butter_clarified, 250
mustard, 250
</code>```

or this

```<code>Oil with third highest boiling temperature: beef_tallow, butter_clarified, mustard
</code>```

I tried using loop to get result like that, but the code I used seems to be wrong because it didn't print anything

```<code>for i in df_ranked['ranking'].items():
  for x in df_ranked['oil'].items():
    if (i==3):
       print(f'Oil with third highest boiling temperature:{x}')
</code>```

答:
If need all joined values first aggregate join and then loop in Series:

```<code>s = df.groupby('ranking')['oil'].agg(', '.join)
print (s)
1                                    avocado
2                                  sunflower
3     beef_tallow, butter_clarified, mustard
4                                       palm
5                                       corn
6                                  grapeseed
7                                     canola
8                                    coconut
9                                   olive_ev
10                                    butter
Name: oil, dtype: object
Oil with 1 highest boiling tem

for i, v in s.items():
    print(f'Oil with {i} highest boiling temperature:{v}')
</code>```

If need both columns join them and loop in groupby object:

```<code>g = df[['oil','boil_temp']].astype(str).agg(', '.join, axis=1).groupby(df['ranking'])

for i, v in g:
    print(f"Oil with {i} highest boiling temperature:")
    print('\n'.join(v))
Oil with 1 highest boiling temperature:
avocado, 270
Oil with 2 highest boiling temperature:
sunflower, 252
Oil with 3 highest boiling temperature:
beef_tallow, 250
butter_clarified, 250
mustard, 250
Oil with 4 highest boiling temperature:
palm, 235
Oil with 5 highest boiling temperature:
corn, 230
Oil with 6 highest boiling temperature:
grapeseed, 216
Oil with 7 highest boiling temperature:
canola, 204
Oil with 8 highest boiling temperature:
coconut, 200
Oil with 9 highest boiling temperature:
olive_ev, 160
Oil with 10 highest boiling temperature:
butter, 150
</code>```

Body:
I have data of cooking oil and its boiling temp and ranked it by highest boiling temp

print(df_ranked)

    ranking               oil  boil_temp
0         1           avocado        270
1         2         sunflower        252
2         3       beef_tallow        250
3         3  butter_clarified        250
4         3           mustard        250
5         4              palm        235
6         5              corn        230
7         6         grapeseed        216
8         7            canola        204
9         8           coconut        200
10        9          olive_ev        160
11       10            butter        150

I used print function to print data with certain rank and this is the result

print(df_ranked.loc[df_ranked['ranking'].isin([3])])

 ranking               oil  boil_temp
2        3       beef_tallow        250
3        3  butter_clarified        250
4        3           mustard        250

I want the result to be more simple like this

beef_tallow, 250
butter_clarified, 250
mustard, 250

or this

Oil with third highest boiling temperature: beef_tallow, butter_clarified, mustard

I tried using loop to get result like that, but the code I used seems to be wrong because it didn't print anything

for i in df_ranked['ranking'].items():
  for x in df_ranked['oil'].items():
    if (i==3):
       print(f'Oil with third highest boiling temperature:{x}')

Body:
If need all joined values first aggregate join and then loop in Series:

s = df.groupby('ranking')['oil'].agg(', '.join)
print (s)
1                                    avocado
2                                  sunflower
3     beef_tallow, butter_clarified, mustard
4                                       palm
5                                       corn
6                                  grapeseed
7                                     canola
8                                    coconut
9                                   olive_ev
10                                    butter
Name: oil, dtype: object
Oil with 1 highest boiling tem

for i, v in s.items():
    print(f'Oil with {i} highest boiling temperature:{v}')

If need both columns join them and loop in groupby object:

g = df[['oil','boil_temp']].astype(str).agg(', '.join, axis=1).groupby(df['ranking'])

for i, v in g:
    print(f"Oil with {i} highest boiling temperature:")
    print('\n'.join(v))
Oil with 1 highest boiling temperature:
avocado, 270
Oil with 2 highest boiling temperature:
sunflower, 252
Oil with 3 highest boiling temperature:
beef_tallow, 250
butter_clarified, 250
mustard, 250
Oil with 4 highest boiling temperature:
palm, 235
Oil with 5 highest boiling temperature:
corn, 230
Oil with 6 highest boiling temperature:
grapeseed, 216
Oil with 7 highest boiling temperature:
canola, 204
Oil with 8 highest boiling temperature:
coconut, 200
Oil with 9 highest boiling temperature:
olive_ev, 160
Oil with 10 highest boiling temperature:
butter, 150


问:
Java, Calculate the number of days between two dates

Possible Duplicate:

  Calculating the Difference Between Two Java Date Instances

In Java, I want to calculate the number of days between two dates.

In my database they are stored as a DATE datatype, but in my code they are strings.

I want to calculate the no of days between those two strings.

答:
try this code

```<code>     Calendar cal1 = new GregorianCalendar();
     Calendar cal2 = new GregorianCalendar();

     SimpleDateFormat sdf = new SimpleDateFormat("ddMMyyyy");

     Date date = sdf.parse("your first date");
     cal1.setTime(date)
     date = sdf.parse("your second date");
     cal2.setTime(date);

    //cal1.set(2008, 8, 1);
     //cal2.set(2008, 9, 31);
     System.out.println("Days= "+daysBetween(cal1.getTime(),cal2.getTime()));
</code>```

this function

```<code>     public int daysBetween(Date d1, Date d2){
             return (int)( (d2.getTime() - d1.getTime()) / (1000 * 60 * 60 * 24));
     }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
try this code

     Calendar cal1 = new GregorianCalendar();
     Calendar cal2 = new GregorianCalendar();

     SimpleDateFormat sdf = new SimpleDateFormat("ddMMyyyy");

     Date date = sdf.parse("your first date");
     cal1.setTime(date)
     date = sdf.parse("your second date");
     cal2.setTime(date);

    //cal1.set(2008, 8, 1);
     //cal2.set(2008, 9, 31);
     System.out.println("Days= "+daysBetween(cal1.getTime(),cal2.getTime()));

this function

     public int daysBetween(Date d1, Date d2){
             return (int)( (d2.getTime() - d1.getTime()) / (1000 * 60 * 60 * 24));
     }


问:
Mixed Integer Programming with Large number of constraints
I have a lot of constraints(in millions) and want to solve a mixed integer problem. Tried using PuLP and OR-Tools(with SCIP solver), but they failed to solve the problem. I tried using DuaLip for parallel/distributed computing using spark, but it doesn't seem to have good documentation for usage. How should I proceed further?</p>

答:
AFAIK there do not exist continuous LP solvers that do distributed computing. That would require some decomposition scheme. As LPs solve very fast we don't use those techniques anymore. An LP with a few million constraints is not very large these days. Quite often interior-point algorithms do quite well on these large problems (relative to Simplex algorithms). We solve LPs of this size on a completely routine basis on fairly standard hardware.

Your PuLP problem is likely more related to PuLP having problems generating the problem than the solver solving it. (Note that PuLP is not a solver). Python based modeling tools may be slower in generating easy LPs than the solver needs to solve it.

Note: the situation for MIP solvers is very different.


问:
Variables get corrupted
I’m developing an iPhone App using Objective-C, based on Apple’s UIKit.

I’ve created some class instance in UIViewController and found my class instance pointer get corrupted randomly. Due to class instance pointer corrupted, I always get an EXC_BAD_ACCESS crash like this:
    Exception Type:  EXC_BAD_ACCESS (SIGSEGV)
    Exception Codes: KERN_INVALID_ADDRESS at 0xa095633c
    Crashed Thread:  0

It shows that when my code is trying to access the class instance, it’s already turned into a ridiculous address:0xa095633c, which is beyond memory space and even binary image space.

Does any have any suggestion what kind of incorrect coding could possibly lead to class instance get corrupted?

答:
There are a lot of things that can cause that. Just to name a few:

Accessing an already deleted object

Improper multithreading

Bugs in pointer arithmetic

Stack corruption

Going out of array's bounds

Learn to use debugger and debug logging to track down where and when the invalid pointer has appeared.

Try to create a small test program which reproduces the problem so you can post code example.

Title: Variables get corrupted


答:
You could use:

```<code>s = (df_ranked.loc[df_ranked['ranking'].isin([3]), ['oil', 'boil_temp']]
              .astype(str).agg(', '.join, axis=1)
     )
# 2         beef_tallow, 250
# 3    butter_clarified, 250
# 4             mustard, 250
# dtype: object

print('\n'.join(s))
</code>```

output:

```<code>beef_tallow, 250
butter_clarified, 250
mustard, 250
</code>```

Title: How to print specific data based on its rank in data frame

Body:
You could use:

s = (df_ranked.loc[df_ranked['ranking'].isin([3]), ['oil', 'boil_temp']]
              .astype(str).agg(', '.join, axis=1)
     )
# 2         beef_tallow, 250
# 3    butter_clarified, 250
# 4             mustard, 250
# dtype: object

print('\n'.join(s))

output:

beef_tallow, 250
butter_clarified, 250
mustard, 250


问:
Testing Redis functionalities with Jest
I have the following file that connect to a redis database: index.js

```<code>const redis = require('redis');
const logger = require('../logger');
const config = require('../env');

const client = redis.createClient({
    host: config.redis.host,
    port: config.redis.port
});

const connect = () => {
    client.on('connect', () => {
        logger.info(`Redis connected on port: ${client?.options?.port}`);
    });
    client.on('error', err => {
        logger.error(`500 - Could not connect to Redis: ${err}`);
    });
};

const close = () => {
    client.quit();
};

module.exports = { connect, close, client };
</code>```

And a helper file containing some Redis functionalities:

```<code>const util = require('util');
const { client } = require('./index.js');

const set = ({ key, data, mode, expiresIn }) => {
    client.set(key, data, mode, expiresIn);
};

const get = key => {
    client.get = util.promisify(client.get);
    return client.get(key);
};

const remove = key => {
    client.del(key);
};

const getKeys = keyPattern => {
    client.keys = util.promisify(client.keys);
    return client.keys(keyPattern);
};

module.exports = { set, get, remove, getKeys };
</code>```

Now I want to test these functionalities with Jest, should I mock the Redis in mocks folder ? or just create a separate database for the test environment to test the functionalities?

答:
As jeeves said, i'd agree its subjective. I am in the process of writing Jest tests for my redis service, but from the action - so i am checking that my action gets and sets from a mock redis.

Explicitly on your code above there is very little logic taking place, so i would suggest that tests were not needed - else you would be pretty close to testing that promisify / redis itself is working, and we need to assume that their code is ok.

Title: Testing Redis functionalities with Jest

Body:
I have the following file that connect to a redis database: index.js

const redis = require('redis');
const logger = require('../logger');
const config = require('../env');

const client = redis.createClient({
    host: config.redis.host,
    port: config.redis.port
});

const connect = () => {
    client.on('connect', () => {
        logger.info(`Redis connected on port: ${client?.options?.port}`);
    });
    client.on('error', err => {
        logger.error(`500 - Could not connect to Redis: ${err}`);
    });
};

const close = () => {
    client.quit();
};

module.exports = { connect, close, client };

And a helper file containing some Redis functionalities:

const util = require('util');
const { client } = require('./index.js');

const set = ({ key, data, mode, expiresIn }) => {
    client.set(key, data, mode, expiresIn);
};

const get = key => {
    client.get = util.promisify(client.get);
    return client.get(key);
};

const remove = key => {
    client.del(key);
};

const getKeys = keyPattern => {
    client.keys = util.promisify(client.keys);
    return client.keys(keyPattern);
};

module.exports = { set, get, remove, getKeys };

Now I want to test these functionalities with Jest, should I mock the Redis in mocks folder ? or just create a separate database for the test environment to test the functionalities?


问:
R combine month names with strings
I would like to combine each month name with three strings: 'min', 'max', 'mean'

I tried this:

paste(month.name,rep(c('min','max','mean'),12))
```

but, instead of "January min", "January max", "January mean",... I get a wrong sequence "January min"    "February max"   "March mean" ...

Do you have any suggestions? Thank you

bioglp

答:
put the rep around the months, and specify you want the months repeated 3 times with each = 3

paste(rep(month.name, each = 3), c("min","max","mean"))

# [1] "January min"    "January max"    "January mean"   "February min"
# [5] "February max"   "February mean"  "March min"      "March max"
# etc
```

Title: R combine month names with strings

Body:
I would like to combine each month name with three strings: 'min', 'max', 'mean'

I tried this:

paste(month.name,rep(c('min','max','mean'),12))

but, instead of "January min", "January max", "January mean",... I get a wrong sequence "January min"    "February max"   "March mean" ...

Do you have any suggestions? Thank you

bioglp


问:
How to detect device in smarty in prestashop 1.7 in a TPL file?
I want the following:

& I understand I have to take the codes from context.php of PrestaShop but I seem to be making an error. A link to getcontext is as follows: (The code to detect mobile device is here)
https://github.com/PrestaShop/PrestaShop/blob/develop/classes/Context.php

```<code>{if isset($products) AND $products}
             {$tabname=rand()+count($products)}
            {if isset($display_mode) && $display_mode == 'carousel'}
                {include file="{$items_owl_carousel_tpl}" items=$products image_size=$image_size}
            {else}
                {if device is MOBILE} /* Correct Code Needed */
                    {include file="{$items_normal_tpl}" items=$products image_size="homepage_default"}
                {else device is NOT MOBILE} /* Correct Code Needed */
                    {include file="{$items_normal_tpl}" items=$products image_size="home_default"}
                {/if}
            {/if}
        {/if}
</code>```

What codes should I enter in the IF condition to make sure it detects mobile and not mobile.

Also is the IF condition written properly, what should I change in this code?

This is .TPL File.

答:
In Prestashop 1.7.8.2 it works this --></p>
```<code>{assign var="dispositivo" value="desktop"}

{if Context::getContext()->isMobile()}

    {assign var="dispositivo" value="mobile"}

{else if  Context::getContext()->isTablet()}

    {assign var="dispositivo" value="tablet"}

{else}

    {assign var="dispositivo" value="desktop"}

{/if}
</code>```

Body:
I want the following:

& I understand I have to take the codes from context.php of PrestaShop but I seem to be making an error. A link to getcontext is as follows: (The code to detect mobile device is here)
https://github.com/PrestaShop/PrestaShop/blob/develop/classes/Context.php

{if isset($products) AND $products}
             {$tabname=rand()+count($products)}
            {if isset($display_mode) && $display_mode == 'carousel'}
                {include file="{$items_owl_carousel_tpl}" items=$products image_size=$image_size}
            {else}
                {if device is MOBILE} /* Correct Code Needed */
                    {include file="{$items_normal_tpl}" items=$products image_size="homepage_default"}
                {else device is NOT MOBILE} /* Correct Code Needed */
                    {include file="{$items_normal_tpl}" items=$products image_size="home_default"}
                {/if}
            {/if}
        {/if}

What codes should I enter in the IF condition to make sure it detects mobile and not mobile.

Also is the IF condition written properly, what should I change in this code?

This is .TPL File.

Body:
In Prestashop 1.7.8.2 it works this -->

{assign var="dispositivo" value="desktop"}

{if Context::getContext()->isMobile()}

    {assign var="dispositivo" value="mobile"}

{else if  Context::getContext()->isTablet()}

    {assign var="dispositivo" value="tablet"}

{else}

    {assign var="dispositivo" value="desktop"}

{/if}


问:
VSCode deal the command parameter as literal
I want to build a Rasterizer project with opencv.The below command work well in shell(some parameter is omitted, such as -static-libgcc):

g++ *.cpp -g -o Rasterizer `pkg-config --libs opencv`
```
<p>However, when I want to do the same thing with VSCode, it fails and throw an error:</p>
<pre class="lang-cpp prettyprint-override"><code>g++: error: `pkg-config --libs opencv`: No such file or directory
</code>```

The log tells me that the executed task in VSCode is(also omit some parameters)

g++ *.cpp -g -o Rasterizer '`pkg-config --libs opencv`'
```
<p>I think the reason is the parameter</p>
````pkg-config --libs opencv`
```
<p>is surrounded by a pair of quotes <code>'</code> and saw as literal. How can I solve this problem?</p>
<p><strong>The whole error message can be seen here:</strong></p>
```> Executing task: g++ /home/cs18/GAMES101/pa1/*.cpp -fdiagnostics-color=always -g -o /home/cs18/GAMES101/pa1/build/main -static-libgcc -fexec-charset=GBK '`pkg-config --libs opencv`' <

g++: error: `pkg-config --libs opencv`: No such file or directory
The terminal process "/bin/bash '-c', 'g++ /home/cs18/GAMES101/pa1/*.cpp -fdiagnostics-color=always -g -o /home/cs18/GAMES101/pa1/build/main -static-libgcc -fexec-charset=GBK '`pkg-config --libs opencv`''" failed to launch (exit code: 1).
```
<p>My VSCode configuration file <code>task.json</code>:</p>
<pre class="lang-json prettyprint-override"><code>{
    "tasks": [
        {
            "type": "shell",
            "label": "C/C++: g++ build active file",
            "command": "g++",
            "args": [
                "${fileDirname}/*.cpp",
                "-fdiagnostics-color=always",
                "-g",
                "-o",
                "${fileDirname}/build/${fileBasenameNoExtension}",
                "-static-libgcc",
                "-fexec-charset=GBK",
                "`pkg-config --libs opencv`"
            ],
            "presentation": {
                "echo": true,
                "reveal": "always",
                "focus": false,
                "panel": "new"
            },
            "options": {
                "cwd": "${fileDirname}"
            },
            "problemMatcher": [
                "$gcc"
            ],
            "group": {
                "kind": "build",
                "isDefault": true
            },
            "detail": "Task generated by Debugger."
        }
    ],
    "version": "2.0.0"
}
</code>```

答:
let's try this .

```<code>   {
        "tasks": [
            {
                "type": "shell",
                "label": "C/C++: g++ build active file",
                "command": "g++",
                "args": [
                    "${fileDirname}/*.cpp",
                    "-fdiagnostics-color=always",
                    "-g",
                    "-o",
                    "${fileDirname}/build/${fileBasenameNoExtension}",
                    "-static-libgcc",
                    "-fexec-charset=GBK",
                    "${PKG_RET}"
                ],
       "options": {
            "env": {
                "PKG_RET": "${input:pkg_ret}"
            }
        },
                "presentation": {
                    "echo": true,
                    "reveal": "always",
                    "focus": false,
                    "panel": "new"
                },
                "options": {
                    "cwd": "${fileDirname}"
                },
                "problemMatcher": [
                    "$gcc"
                ],
                "group": {
                    "kind": "build",
                    "isDefault": true
                },
                "detail": "Task generated by Debugger."
            }
        ],
        "version": "2.0.0"
    },
"inputs": [
    {
        "id": "pkg_ret",
        "type": "command",
        "command": "shellCommand.execute",
        "args": {
            "command": "pkg-config --libs opencv"
        }
    }
]
</code>```

refer : Using a shell command as VSCode task variable value

Body:
I want to build a Rasterizer project with opencv.The below command work well in shell(some parameter is omitted, such as -static-libgcc):

g++ *.cpp -g -o Rasterizer `pkg-config --libs opencv`

However, when I want to do the same thing with VSCode, it fails and throw an error:

g++: error: `pkg-config --libs opencv`: No such file or directory

The log tells me that the executed task in VSCode is(also omit some parameters)

g++ *.cpp -g -o Rasterizer '`pkg-config --libs opencv`'

I think the reason is the parameter

`pkg-config --libs opencv`

is surrounded by a pair of quotes ' and saw as literal. How can I solve this problem?

The whole error message can be seen here:

> Executing task: g++ /home/cs18/GAMES101/pa1/*.cpp -fdiagnostics-color=always -g -o /home/cs18/GAMES101/pa1/build/main -static-libgcc -fexec-charset=GBK '`pkg-config --libs opencv`' <

g++: error: `pkg-config --libs opencv`: No such file or directory
The terminal process "/bin/bash '-c', 'g++ /home/cs18/GAMES101/pa1/*.cpp -fdiagnostics-color=always -g -o /home/cs18/GAMES101/pa1/build/main -static-libgcc -fexec-charset=GBK '`pkg-config --libs opencv`''" failed to launch (exit code: 1).

My VSCode configuration file task.json:

{
    "tasks": [
        {
            "type": "shell",
            "label": "C/C++: g++ build active file",
            "command": "g++",
            "args": [
                "${fileDirname}/*.cpp",
                "-fdiagnostics-color=always",
                "-g",
                "-o",
                "${fileDirname}/build/${fileBasenameNoExtension}",
                "-static-libgcc",
                "-fexec-charset=GBK",
                "`pkg-config --libs opencv`"
            ],
            "presentation": {
                "echo": true,
                "reveal": "always",
                "focus": false,
                "panel": "new"
            },
            "options": {
                "cwd": "${fileDirname}"
            },
            "problemMatcher": [
                "$gcc"
            ],
            "group": {
                "kind": "build",
                "isDefault": true
            },
            "detail": "Task generated by Debugger."
        }
    ],
    "version": "2.0.0"
}

Body:
let's try this .

   {
        "tasks": [
            {
                "type": "shell",
                "label": "C/C++: g++ build active file",
                "command": "g++",
                "args": [
                    "${fileDirname}/*.cpp",
                    "-fdiagnostics-color=always",
                    "-g",
                    "-o",
                    "${fileDirname}/build/${fileBasenameNoExtension}",
                    "-static-libgcc",
                    "-fexec-charset=GBK",
                    "${PKG_RET}"
                ],
       "options": {
            "env": {
                "PKG_RET": "${input:pkg_ret}"
            }
        },
                "presentation": {
                    "echo": true,
                    "reveal": "always",
                    "focus": false,
                    "panel": "new"
                },
                "options": {
                    "cwd": "${fileDirname}"
                },
                "problemMatcher": [
                    "$gcc"
                ],
                "group": {
                    "kind": "build",
                    "isDefault": true
                },
                "detail": "Task generated by Debugger."
            }
        ],
        "version": "2.0.0"
    },
"inputs": [
    {
        "id": "pkg_ret",
        "type": "command",
        "command": "shellCommand.execute",
        "args": {
            "command": "pkg-config --libs opencv"
        }
    }
]

refer : Using a shell command as VSCode task variable value


问:
NestJs/Swagger(OpenAPI) defining nested objects in query parameters
I'm trying to correctly define OpenAPI spec for the purposes of generating api client from that spec. I've encoutered a problem where we have a complex query object with nested objects and arrays of objects for get a GET route.

Lets take these classes as an example.

```<code>class Person {
  @ApiProperty()
  name!: string
  @ApiProperty()
  location!: string
}

class CompanyDto {
  @ApiProperty()
  name!: string

  @ApiProperty({
    type: [Person],
  })
  employees!: Person[]
}
</code>```

And a get request with @Query decorator.

```<code>  @Get('test')
  async testing(@Query() dto: CompanyDto): Promise<void> {
    // ...
  }
</code>```

What I'm getting is.

```<code>    {
      get: {
        operationId: 'testing',
        parameters: [
          {
            name: 'name',
            required: true,
            in: 'query',
            schema: {
              type: 'string',
            },
          },
          {
            name: 'name',
            in: 'query',
            required: true,
            schema: {
              type: 'string',
            },
          },
          {
            name: 'location',
            in: 'query',
            required: true,
            schema: {
              type: 'string',
            },
          },
        ],
        responses: {
          '200': {
            description: '',
          },
        },
        tags: ['booking'],
      },
    }
</code>```

I've also tries to define Query params by adding @ApiQuery decorator and it almost works.

```<code>  @ApiQuery({
    style: 'deepObject',
    type: CompanyDto,
  })
</code>```

--

```<code>{
  get: {
    operationId: 'testing',
    parameters: [
      {
        name: 'name',
        required: true,
        in: 'query',
        schema: {
          type: 'string',
        },
      },
      {
        name: 'name',
        in: 'query',
        required: true,
        schema: {
          type: 'string',
        },
      },
      {
        name: 'location',
        in: 'query',
        required: true,
        schema: {
          type: 'string',
        },
      },
      {
        name: 'name',
        in: 'query',
        required: true,
        schema: {
          type: 'string',
        },
      },
      {
        name: 'employees',
        in: 'query',
        required: true,
        schema: {
          type: 'array',
          items: {
            $ref: '#/components/schemas/Person',
          },
        },
      },
    ],
    responses: {
      '200': {
        description: '',
      },
    },
    tags: ['booking'],
  },
}
</code>```

However now I'm getting duplicate query definitions mashed in to one. Is there a way to prevent or overwrite @Query definition? Or just a better way to define complex @Query in general?

答:
Ended up creating a custom decorator to extract query without generating OpenAPI Spec.

```<code>export const SilentQuery = createParamDecorator(
  (data: string | undefined, ctx: ExecutionContext) => {
    const request = ctx.switchToHttp().getRequest()
    if (data) {
      return request.query[data]
    } else {
      return request.query
    }
  },
)
</code>```

So now you can use @ApiQuery with deepObject style.

Also if your're using ValidationPipes with class-validator for example. Make sure to set validateCustomDecorators to true

```<code>@SilentQuery(new ValidationPipe({ validateCustomDecorators: true }))
</code>```

Body:
I'm trying to correctly define OpenAPI spec for the purposes of generating api client from that spec. I've encoutered a problem where we have a complex query object with nested objects and arrays of objects for get a GET route.

Lets take these classes as an example.

class Person {
  @ApiProperty()
  name!: string
  @ApiProperty()
  location!: string
}

class CompanyDto {
  @ApiProperty()
  name!: string

  @ApiProperty({
    type: [Person],
  })
  employees!: Person[]
}

And a get request with @Query decorator.

  @Get('test')
  async testing(@Query() dto: CompanyDto): Promise<void> {
    // ...
  }

What I'm getting is.

    {
      get: {
        operationId: 'testing',
        parameters: [
          {
            name: 'name',
            required: true,
            in: 'query',
            schema: {
              type: 'string',
            },
          },
          {
            name: 'name',
            in: 'query',
            required: true,
            schema: {
              type: 'string',
            },
          },
          {
            name: 'location',
            in: 'query',
            required: true,
            schema: {
              type: 'string',
            },
          },
        ],
        responses: {
          '200': {
            description: '',
          },
        },
        tags: ['booking'],
      },
    }

I've also tries to define Query params by adding @ApiQuery decorator and it almost works.

  @ApiQuery({
    style: 'deepObject',
    type: CompanyDto,
  })

--

{
  get: {
    operationId: 'testing',
    parameters: [
      {
        name: 'name',
        required: true,
        in: 'query',
        schema: {
          type: 'string',
        },
      },
      {
        name: 'name',
        in: 'query',
        required: true,
        schema: {
          type: 'string',
        },
      },
      {
        name: 'location',
        in: 'query',
        required: true,
        schema: {
          type: 'string',
        },
      },
      {
        name: 'name',
        in: 'query',
        required: true,
        schema: {
          type: 'string',
        },
      },
      {
        name: 'employees',
        in: 'query',
        required: true,
        schema: {
          type: 'array',
          items: {
            $ref: '#/components/schemas/Person',
          },
        },
      },
    ],
    responses: {
      '200': {
        description: '',
      },
    },
    tags: ['booking'],
  },
}

However now I'm getting duplicate query definitions mashed in to one. Is there a way to prevent or overwrite @Query definition? Or just a better way to define complex @Query in general?

Body:
Ended up creating a custom decorator to extract query without generating OpenAPI Spec.

export const SilentQuery = createParamDecorator(
  (data: string | undefined, ctx: ExecutionContext) => {
    const request = ctx.switchToHttp().getRequest()
    if (data) {
      return request.query[data]
    } else {
      return request.query
    }
  },
)

So now you can use @ApiQuery with deepObject style.

Also if your're using ValidationPipes with class-validator for example. Make sure to set validateCustomDecorators to true

@SilentQuery(new ValidationPipe({ validateCustomDecorators: true }))


问:
TypeError: create_int(): incompatible function arguments
I've Been Recently Learning Computer Vision using python, and when making a hand detector project, I encountered this error :-

```<code>Traceback (most recent call last):
File "c:\Users\idhant\OneDrive - 007lakshya\Idhant\Programming\Projects\MY MACHINE
LEARNING PROJECTS\Hand Tracking Module.py", line 64, in <module>
main()
File "c:\Users\idhant\OneDrive - 007lakshya\Idhant\Programming\Projects\MY MACHINE
LEARNING PROJECTS\Hand Tracking Module.py", line 41, in main
detector = handDetector()
File "c:\Users\idhant\OneDrive - 007lakshya\Idhant\Programming\Projects\MY MACHINE
LEARNING PROJECTS\Hand Tracking Module.py", line 13, in __init__
self.hands = self.mpHands.Hands(self.mode, self.maxHands, self.detectionCon,
self.trackCon)
File "C:\Users\idhant\AppData\Roaming\Python\Python39\site-
packages\mediapipe\python\solutions\hands.py", line 114, in __init__
super().__init__(
File "C:\Users\idhant\AppData\Roaming\Python\Python39\site-
packages\mediapipe\python\solution_base.py", line 258, in __init__
self._input_side_packets = {
File "C:\Users\idhant\AppData\Roaming\Python\Python39\site-
packages\mediapipe\python\solution_base.py", line 259, in <dictcomp>
name: self._make_packet(self._side_input_type_info[name], data)
File "C:\Users\idhant\AppData\Roaming\Python\Python39\site-
packages\mediapipe\python\solution_base.py", line 513, in _make_packet
return getattr(packet_creator, 'create_' + packet_data_type.value)(data)
TypeError: create_int(): incompatible function arguments. The following argument types
are supported:
1. (arg0: int) -> mediapipe.python._framework_bindings.packet.Packet

Invoked with: 0.5
[ WARN:0] global D:\a\opencv-python\opencv-
python\opencv\modules\videoio\src\cap_msmf.cpp (438) `anonymous-
 namespace'::SourceReaderCB::~SourceReaderCB terminating async callback
</code>```

And I tried Very Much Debugging it, But Not Successfull :(, So Please Help me, Here's The Code That I've Written:-

```<code>import cv2
import mediapipe as mp
import time

class handDetector():
    def __init__(self, mode=False, maxHands = 2, detectionCon=0.5, trackCon = 0.5):
        self.mode = mode
        self.maxHands = maxHands
        self.detectionCon = detectionCon
        self.trackCon = trackCon

        self.mpHands = mp.solutions.hands
        self.hands = self.mpHands.Hands(self.mode, self.maxHands, self.detectionCon,
                                        self.trackCon)
        self.mpDraw = mp.solutions.drawing_utils

def findHands(self, img, draw=True):
    imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    results = self.hands.process(imgRGB)
    # print(results.multi_hand_landmarks)

    if results.multi_hand_landmarks:
        for handLms in results.multi_hand_landmarks:
            if draw:
                self.mpDraw.draw_landmarks(img, handLms, self.mpHands.HAND_CONNECTIONS)
    return img

            # for id, lm in enumerate(handLms.landmark):
            #     # print(id, lm)
            #     h, w, c = img.shape
            #     cx, cy = int(lm.x*w), int(lm.y*h)
            #     print(id, cx, cy)
            #     # if id == 4:
            #     cv2.circle(img, (cx, cy), 15, (255,0,255), cv2.FILLED)

def main():
    pTime = 0
    cTime = 0
    cap = cv2.VideoCapture(0)
    detector = handDetector()

while True:
    success, img = cap.read()
    img = detector.findHands(img)

    cTime = time.time()
    fps = 1/(cTime-pTime)
    pTime = cTime

    cv2.putText(img, str(int(fps)),(10, 70), cv2.FONT_HERSHEY_COMPLEX, 3, (255,0,255),3)

    cv2.imshow("Image", img)
    cv2.waitKey(1)

if __name__ == "__main__":
    main()
</code>```

I've Tried Making A Class of Hand Detector, Which Does the same thing to detect hand but we can also use it in our other files, That's why I've written this code, and encountered this issue!

答:
I was facing the same issue, just add model_complexity to your init function and you are good to go:

def __init__(self, mode=False, model_complexity=1, upBody=False, smooth=True, detectionCon=0.5, trackCon=0.5):
```

Body:
I've Been Recently Learning Computer Vision using python, and when making a hand detector project, I encountered this error :-

Traceback (most recent call last):
File "c:\Users\idhant\OneDrive - 007lakshya\Idhant\Programming\Projects\MY MACHINE
LEARNING PROJECTS\Hand Tracking Module.py", line 64, in <module>
main()
File "c:\Users\idhant\OneDrive - 007lakshya\Idhant\Programming\Projects\MY MACHINE
LEARNING PROJECTS\Hand Tracking Module.py", line 41, in main
detector = handDetector()
File "c:\Users\idhant\OneDrive - 007lakshya\Idhant\Programming\Projects\MY MACHINE
LEARNING PROJECTS\Hand Tracking Module.py", line 13, in __init__
self.hands = self.mpHands.Hands(self.mode, self.maxHands, self.detectionCon,
self.trackCon)
File "C:\Users\idhant\AppData\Roaming\Python\Python39\site-
packages\mediapipe\python\solutions\hands.py", line 114, in __init__
super().__init__(
File "C:\Users\idhant\AppData\Roaming\Python\Python39\site-
packages\mediapipe\python\solution_base.py", line 258, in __init__
self._input_side_packets = {
File "C:\Users\idhant\AppData\Roaming\Python\Python39\site-
packages\mediapipe\python\solution_base.py", line 259, in <dictcomp>
name: self._make_packet(self._side_input_type_info[name], data)
File "C:\Users\idhant\AppData\Roaming\Python\Python39\site-
packages\mediapipe\python\solution_base.py", line 513, in _make_packet
return getattr(packet_creator, 'create_' + packet_data_type.value)(data)
TypeError: create_int(): incompatible function arguments. The following argument types
are supported:
1. (arg0: int) -> mediapipe.python._framework_bindings.packet.Packet

Invoked with: 0.5
[ WARN:0] global D:\a\opencv-python\opencv-
python\opencv\modules\videoio\src\cap_msmf.cpp (438) `anonymous-
 namespace'::SourceReaderCB::~SourceReaderCB terminating async callback

And I tried Very Much Debugging it, But Not Successfull :(, So Please Help me, Here's The Code That I've Written:-

import cv2
import mediapipe as mp
import time

class handDetector():
    def __init__(self, mode=False, maxHands = 2, detectionCon=0.5, trackCon = 0.5):
        self.mode = mode
        self.maxHands = maxHands
        self.detectionCon = detectionCon
        self.trackCon = trackCon

        self.mpHands = mp.solutions.hands
        self.hands = self.mpHands.Hands(self.mode, self.maxHands, self.detectionCon,
                                        self.trackCon)
        self.mpDraw = mp.solutions.drawing_utils

def findHands(self, img, draw=True):
    imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    results = self.hands.process(imgRGB)
    # print(results.multi_hand_landmarks)

    if results.multi_hand_landmarks:
        for handLms in results.multi_hand_landmarks:
            if draw:
                self.mpDraw.draw_landmarks(img, handLms, self.mpHands.HAND_CONNECTIONS)
    return img

            # for id, lm in enumerate(handLms.landmark):
            #     # print(id, lm)
            #     h, w, c = img.shape
            #     cx, cy = int(lm.x*w), int(lm.y*h)
            #     print(id, cx, cy)
            #     # if id == 4:
            #     cv2.circle(img, (cx, cy), 15, (255,0,255), cv2.FILLED)

def main():
    pTime = 0
    cTime = 0
    cap = cv2.VideoCapture(0)
    detector = handDetector()

while True:
    success, img = cap.read()
    img = detector.findHands(img)

    cTime = time.time()
    fps = 1/(cTime-pTime)
    pTime = cTime

    cv2.putText(img, str(int(fps)),(10, 70), cv2.FONT_HERSHEY_COMPLEX, 3, (255,0,255),3)

    cv2.imshow("Image", img)
    cv2.waitKey(1)

if __name__ == "__main__":
    main()

I've Tried Making A Class of Hand Detector, Which Does the same thing to detect hand but we can also use it in our other files, That's why I've written this code, and encountered this issue!


问:
How can I patch sqlite3 cursor.execute in my unit test?
I want to assert that sqlite3's execute method was called in a subclass.

Here's my module.py:

```<code>import sqlite3

class foo(object):
    def __init__(self):
        self.conn = sqlite3.connect("bla.db")
        self.cursor = self.conn.cursor()

    def table(self):
        self.cursor.execute("create table")

class foobar(foo):
    def __init__(self):
        super().__init__()

    def load(self):
        return self.table()
</code>```

Here's my test file:

```<code>from module import foobar

@patch("module.sqlite3")
def test_foobar(mock_sqllite3):
    foobar().load()
    mock_sqllite3.connect().conn().cursor().execute().assert_called_once()
</code>```

I'm getting an assertion error, but more to the point, I think i am way off in patching this properly

Is it possible to just mock the foo class attribute self.cursor?

答:
Instead of using callable brackets () you should be using .return_value on each object that was called.

I have created two test functions; one simply mocks execute to facilitate a return value, and the other replaces the function altogether to achieve custom logic on the arguments.

```<code>import sqlite3
from unittest.mock import patch

class foo(object):
    def __init__(self):
        self.conn = sqlite3.connect("bla.db")
        self.cursor = self.conn.cursor()

    def table(self, p: str = None):
        return self.cursor.execute("create table")

class foobar(foo):
    def __init__(self):
        super().__init__()

    def load(self, p: str = None):
        return self.table(p)

@patch("__main__.sqlite3", spec=sqlite3)
def test_foobar(mock_sqllite3):
    mock_execute = (
        mock_sqllite3
            .connect
            .return_value
            .cursor
            .return_value
            .execute
    )

    mock_execute.return_value = "test"

    res = foobar().load()

    assert res == "test"
    mock_execute.assert_called_once()
    mock_execute.assert_called_with("create table")

@patch("__main__.sqlite3", spec=sqlite3)
def test_foobar_with_func_override(mock_sqllite3):
    mock_cursor = (
        mock_sqllite3
            .connect
            .return_value
            .cursor
    )

    mock_cursor.return_value.execute = lambda a: a.upper()

    res = foobar().load("test")

    assert res == "CREATE TABLE"
</code>```

Let me know if any of this was not clear :)

Body:
I want to assert that sqlite3's execute method was called in a subclass.

Here's my module.py:

import sqlite3

class foo(object):
    def __init__(self):
        self.conn = sqlite3.connect("bla.db")
        self.cursor = self.conn.cursor()

    def table(self):
        self.cursor.execute("create table")

class foobar(foo):
    def __init__(self):
        super().__init__()

    def load(self):
        return self.table()

Here's my test file:

from module import foobar

@patch("module.sqlite3")
def test_foobar(mock_sqllite3):
    foobar().load()
    mock_sqllite3.connect().conn().cursor().execute().assert_called_once()

I'm getting an assertion error, but more to the point, I think i am way off in patching this properly

Is it possible to just mock the foo class attribute self.cursor?

Body:
Instead of using callable brackets () you should be using .return_value on each object that was called.

I have created two test functions; one simply mocks execute to facilitate a return value, and the other replaces the function altogether to achieve custom logic on the arguments.

import sqlite3
from unittest.mock import patch

class foo(object):
    def __init__(self):
        self.conn = sqlite3.connect("bla.db")
        self.cursor = self.conn.cursor()

    def table(self, p: str = None):
        return self.cursor.execute("create table")

class foobar(foo):
    def __init__(self):
        super().__init__()

    def load(self, p: str = None):
        return self.table(p)

@patch("__main__.sqlite3", spec=sqlite3)
def test_foobar(mock_sqllite3):
    mock_execute = (
        mock_sqllite3
            .connect
            .return_value
            .cursor
            .return_value
            .execute
    )

    mock_execute.return_value = "test"

    res = foobar().load()

    assert res == "test"
    mock_execute.assert_called_once()
    mock_execute.assert_called_with("create table")

@patch("__main__.sqlite3", spec=sqlite3)
def test_foobar_with_func_override(mock_sqllite3):
    mock_cursor = (
        mock_sqllite3
            .connect
            .return_value
            .cursor
    )

    mock_cursor.return_value.execute = lambda a: a.upper()

    res = foobar().load("test")

    assert res == "CREATE TABLE"

Let me know if any of this was not clear :)