问:
Django socket connection timout
I am trying to check if a certain device (Lauterbach PowerDebug Pro) is connected to the network. I have the following code that I am using in Django view.

```<code>    def checkConnection(hostname, port, timeout=5):
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.settimeout(timeout)
        message = bytes.fromhex('{1024 bytes here}')
        s.sendto(message,(hostname,port))
        try:
            if s.recv(1024):
                return True
        except ConnectionResetError:
            return False
        except socket.timeout:
            return False
</code>```

If I run this function from the Django View (called through AJAX), it will return False.

If I run this code in a Python console, it will return True. If I run manage.py shell and manually write this code, it will return True.

However, if I run manage.py shell, import and call this function, it will return False, due to a timeout error.

How come? I can't figure out why it will not work. I have captured the messages using Wireshark and they are all the same. Below is the output.

Code written manually in Django shell (returned True):

No.     Time           Source                Destination

  Protocol Length Info
      233 17.202222      10.171.90.59          10.171.94.100         UDP      1066   59221 → 60010 Len=1024

Frame 233: 1066 bytes on wire (8528 bits), 1066 bytes captured (8528
  bits) on interface 0 Ethernet II, Src: IntelCor_c1:d7:3e
  (b4:6b:fc:c1:d7:3e), Dst: All-HSRP-routers_5a (00:00:0c:07:ac:5a)
  Internet Protocol Version 4, Src: 10.171.90.59, Dst: 10.171.94.100
  User Datagram Protocol, Src Port: 59221, Dst Port: 60010 Data (1024
  bytes)

0000  03 01 01 00 62 ea 46 fd 54 52 41 43 45 33 32 00

  ....b.F.TRACE32. 0010  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0020  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0030  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0040  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0050  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0060  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0070  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0080  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0090  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 00a0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 00b0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 00c0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 00d0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 00e0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 00f0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0100  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0110  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0120  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0130  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0140  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0150  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0160  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0170  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0180  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0190  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 01a0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 01b0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 01c0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 01d0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 01e0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 01f0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0200  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0210  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0220  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0230  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0240  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0250  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0260  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0270  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0280  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0290  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 02a0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 02b0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 02c0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 02d0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 02e0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 02f0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0300  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0310  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0320  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0330  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0340  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0350  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0360  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0370  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0380  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0390  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 03a0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 03b0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 03c0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 03d0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 03e0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 03f0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................
      Data: 0301010062ea46fd54524143453332000000000000000000…
      [Length: 1024]

No.     Time           Source                Destination

  Protocol Length Info
      234 17.220294      10.171.94.100         10.171.90.59          UDP      58     60002 → 59221 Len=16

Frame 234: 58 bytes on wire (464 bits), 58 bytes captured (464 bits)
  on interface 0 Ethernet II, Src: Cisco_74:52:0b (a4:6c:2a:74:52:0b),
  Dst: IntelCor_c1:d7:3e (b4:6b:fc:c1:d7:3e) Internet Protocol Version
  4, Src: 10.171.94.100, Dst: 10.171.90.59 User Datagram Protocol, Src
  Port: 60002, Dst Port: 59221 Data (16 bytes)

0000  23 00 00 00 0a ab 5a 3b 54 52 41 43 45 33 32 00

.....Z;TRACE32.

```<code>Data: 230000000aab5a3b5452414345333200
[Length: 16]
</code>```

checkConnection function imported and ran in Django shell (returned True):

No.     Time           Source                Destination

  Protocol Length Info
      437 53.946438      10.171.90.59          10.171.94.100         UDP      1066   59224 → 60010 Len=1024

Frame 437: 1066 bytes on wire (8528 bits), 1066 bytes captured (8528
  bits) on interface 0 Ethernet II, Src: IntelCor_c1:d7:3e
  (b4:6b:fc:c1:d7:3e), Dst: All-HSRP-routers_5a (00:00:0c:07:ac:5a)
  Internet Protocol Version 4, Src: 10.171.90.59, Dst: 10.171.94.100
  User Datagram Protocol, Src Port: 59224, Dst Port: 60010 Data (1024
  bytes)

0000  03 01 01 00 62 ea 46 fd 54 52 41 43 45 33 32 00

  ....b.F.TRACE32. 0010  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0020  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0030  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0040  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0050  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0060  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0070  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0080  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0090  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 00a0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 00b0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 00c0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 00d0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 00e0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 00f0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0100  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0110  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0120  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0130  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0140  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0150  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0160  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0170  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0180  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0190  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 01a0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 01b0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 01c0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 01d0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 01e0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 01f0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0200  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0210  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0220  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0230  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0240  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0250  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0260  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0270  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0280  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0290  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 02a0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 02b0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 02c0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 02d0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 02e0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 02f0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0300  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0310  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0320  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0330  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0340  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0350  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0360  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0370  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0380  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0390  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 03a0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 03b0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 03c0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 03d0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 03e0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 03f0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................
      Data: 0301010062ea46fd54524143453332000000000000000000…
      [Length: 1024]

No.     Time           Source                Destination

  Protocol Length Info
      438 53.948831      10.171.94.100         10.171.90.59          UDP      58     60002 → 59224 Len=16

Frame 438: 58 bytes on wire (464 bits), 58 bytes captured (464 bits)
  on interface 0 Ethernet II, Src: Cisco_74:52:0b (a4:6c:2a:74:52:0b),
  Dst: IntelCor_c1:d7:3e (b4:6b:fc:c1:d7:3e) Internet Protocol Version
  4, Src: 10.171.94.100, Dst: 10.171.90.59 User Datagram Protocol, Src
  Port: 60002, Dst Port: 59224 Data (16 bytes)

0000  23 00 00 00 0a ab 5a 3b 54 52 41 43 45 33 32 00

.....Z;TRACE32.

```<code>Data: 230000000aab5a3b5452414345333200
[Length: 16]
</code>```

So what gives?

Edit: It works for TCP connections (ex. checkConnection('10.11.12.13', 23) will return True). For some reason, only the UDP message will not be received.

In this case, checkConnection is:

```<code>    def checkConnection(hostname, port, timeout=5):
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.settimeout(timeout)
        try:
            s.connect((hostname, port))
            s.shutdown(socket.SHUT_WR)
            while True:
                try:
                    data = s.recv(1024)
                    if data:
                        s.close()
                        return True
        except socket.timeout:
            return False
        except TimeoutError:
            return False
        except ConnectionRefusedError:
            return False
        except ConnectionResetError:
            return False
</code>```

答:
It seems the trick is to use recvfrom() for UDP.

```<code>        try:
            data, address = s.recvfrom(1024)
            if data:
                return True
</code>```

recv()

  The recv() call is normally used only on a connected socket (see connect(2)).

  It is equivalent to the call:

recvfrom(fd, buf, len, flags, NULL, 0);

I still don't understand why recv() worked in all situations, except running from a Django view.

Title: Django socket connection timout

Body:
I am trying to check if a certain device (Lauterbach PowerDebug Pro) is connected to the network. I have the following code that I am using in Django view.

    def checkConnection(hostname, port, timeout=5):
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.settimeout(timeout)
        message = bytes.fromhex('{1024 bytes here}')
        s.sendto(message,(hostname,port))
        try:
            if s.recv(1024):
                return True
        except ConnectionResetError:
            return False
        except socket.timeout:
            return False

If I run this function from the Django View (called through AJAX), it will return False.

If I run this code in a Python console, it will return True. If I run manage.py shell and manually write this code, it will return True.

However, if I run manage.py shell, import and call this function, it will return False, due to a timeout error.

How come? I can't figure out why it will not work. I have captured the messages using Wireshark and they are all the same. Below is the output.

Code written manually in Django shell (returned True):

No.     Time           Source                Destination

  Protocol Length Info
      233 17.202222      10.171.90.59          10.171.94.100         UDP      1066   59221 → 60010 Len=1024

Frame 233: 1066 bytes on wire (8528 bits), 1066 bytes captured (8528
  bits) on interface 0 Ethernet II, Src: IntelCor_c1:d7:3e
  (b4:6b:fc:c1:d7:3e), Dst: All-HSRP-routers_5a (00:00:0c:07:ac:5a)
  Internet Protocol Version 4, Src: 10.171.90.59, Dst: 10.171.94.100
  User Datagram Protocol, Src Port: 59221, Dst Port: 60010 Data (1024
  bytes)

0000  03 01 01 00 62 ea 46 fd 54 52 41 43 45 33 32 00

  ....b.F.TRACE32. 0010  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0020  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0030  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0040  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0050  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0060  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0070  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0080  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0090  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 00a0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 00b0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 00c0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 00d0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 00e0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 00f0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0100  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0110  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0120  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0130  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0140  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0150  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0160  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0170  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0180  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0190  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 01a0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 01b0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 01c0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 01d0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 01e0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 01f0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0200  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0210  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0220  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0230  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0240  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0250  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0260  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0270  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0280  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0290  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 02a0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 02b0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 02c0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 02d0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 02e0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 02f0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0300  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0310  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0320  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0330  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0340  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0350  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0360  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0370  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0380  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0390  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 03a0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 03b0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 03c0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 03d0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 03e0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 03f0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................
      Data: 0301010062ea46fd54524143453332000000000000000000…
      [Length: 1024]

No.     Time           Source                Destination

  Protocol Length Info
      234 17.220294      10.171.94.100         10.171.90.59          UDP      58     60002 → 59221 Len=16

Frame 234: 58 bytes on wire (464 bits), 58 bytes captured (464 bits)
  on interface 0 Ethernet II, Src: Cisco_74:52:0b (a4:6c:2a:74:52:0b),
  Dst: IntelCor_c1:d7:3e (b4:6b:fc:c1:d7:3e) Internet Protocol Version
  4, Src: 10.171.94.100, Dst: 10.171.90.59 User Datagram Protocol, Src
  Port: 60002, Dst Port: 59221 Data (16 bytes)

0000  23 00 00 00 0a ab 5a 3b 54 52 41 43 45 33 32 00

.....Z;TRACE32.

Data: 230000000aab5a3b5452414345333200
[Length: 16]

checkConnection function imported and ran in Django shell (returned True):

No.     Time           Source                Destination

  Protocol Length Info
      437 53.946438      10.171.90.59          10.171.94.100         UDP      1066   59224 → 60010 Len=1024

Frame 437: 1066 bytes on wire (8528 bits), 1066 bytes captured (8528
  bits) on interface 0 Ethernet II, Src: IntelCor_c1:d7:3e
  (b4:6b:fc:c1:d7:3e), Dst: All-HSRP-routers_5a (00:00:0c:07:ac:5a)
  Internet Protocol Version 4, Src: 10.171.90.59, Dst: 10.171.94.100
  User Datagram Protocol, Src Port: 59224, Dst Port: 60010 Data (1024
  bytes)

0000  03 01 01 00 62 ea 46 fd 54 52 41 43 45 33 32 00

  ....b.F.TRACE32. 0010  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0020  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0030  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0040  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0050  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0060  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0070  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0080  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0090  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 00a0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 00b0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 00c0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 00d0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 00e0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 00f0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0100  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0110  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0120  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0130  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0140  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0150  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0160  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0170  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0180  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0190  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 01a0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 01b0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 01c0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 01d0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 01e0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 01f0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0200  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0210  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0220  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0230  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0240  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0250  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0260  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0270  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0280  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0290  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 02a0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 02b0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 02c0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 02d0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 02e0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 02f0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0300  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0310  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0320  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0330  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0340  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0350  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0360  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0370  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0380  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 0390  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 03a0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 03b0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 03c0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 03d0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 03e0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................ 03f0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  ................
      Data: 0301010062ea46fd54524143453332000000000000000000…
      [Length: 1024]

No.     Time           Source                Destination

  Protocol Length Info
      438 53.948831      10.171.94.100         10.171.90.59          UDP      58     60002 → 59224 Len=16

Frame 438: 58 bytes on wire (464 bits), 58 bytes captured (464 bits)
  on interface 0 Ethernet II, Src: Cisco_74:52:0b (a4:6c:2a:74:52:0b),
  Dst: IntelCor_c1:d7:3e (b4:6b:fc:c1:d7:3e) Internet Protocol Version
  4, Src: 10.171.94.100, Dst: 10.171.90.59 User Datagram Protocol, Src
  Port: 60002, Dst Port: 59224 Data (16 bytes)

0000  23 00 00 00 0a ab 5a 3b 54 52 41 43 45 33 32 00

.....Z;TRACE32.

Data: 230000000aab5a3b5452414345333200
[Length: 16]

So what gives?

Edit: It works for TCP connections (ex. checkConnection('10.11.12.13', 23) will return True). For some reason, only the UDP message will not be received.

In this case, checkConnection is:

    def checkConnection(hostname, port, timeout=5):
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.settimeout(timeout)
        try:
            s.connect((hostname, port))
            s.shutdown(socket.SHUT_WR)
            while True:
                try:
                    data = s.recv(1024)
                    if data:
                        s.close()
                        return True
        except socket.timeout:
            return False
        except TimeoutError:
            return False
        except ConnectionRefusedError:
            return False
        except ConnectionResetError:
            return False

Body:
It seems the trick is to use recvfrom() for UDP.

        try:
            data, address = s.recvfrom(1024)
            if data:
                return True

recv()

  The recv() call is normally used only on a connected socket (see connect(2)).

  It is equivalent to the call:

recvfrom(fd, buf, len, flags, NULL, 0);

I still don't understand why recv() worked in all situations, except running from a Django view.


来源: stackexchange

问:
JavaScript Set value in object
I'm pretty new in JS  and something weird happen to me.
I try to set different value in an object and all the value of the table are changed
It appears the problems come from the creation of the object via a the object call "materialStd"

Value obj.line[0].material.flow of should stay at 123 instead of 3

Is someone able to explain what is happening there Thanks

https://jsfiddle.net/vx6fno9p/5/

var materialStd = {
  flow: 123,
  name: 'Raoul'
};
var obj = {
  id: 0,
  line: [{
      id: 1,
      material: materialStd
    },
    {
      id: 2,
      material: materialStd
    },
    {
      id: 3,
      material: materialStd
    }
  ]
}

testerror();

function testerror() {
  console.info(obj);
  //On appel une fct test

  console.log('' + obj.line[0].material.flow);
  console.log('' + obj.line[1].material.flow);
  console.log('' + obj.line[2].material.flow);

  test(obj);

  console.log('' + obj.line[0].material.flow);
  console.log('' + obj.line[1].material.flow);
  console.log('' + obj.line[2].material.flow);

}

function test(objetTraiter) {
  //  objetTraiter.line[0].material.flow=1;
  // objetTraiter.line[1].material.flow=2;
  objetTraiter.line[2].material.flow = 3;
  console.log('' + objetTraiter.line[0].material.flow);
  console.log('' + objetTraiter.line[1].material.flow);
  console.log('' + objetTraiter.line[2].material.flow);

}```

答:
When you use material: materialStd, you are not getting a copy of the object materialStd, just a reference.

so when you update here objetTraiter.line[2].material.flow=3;

this actually changes the materialStd object, because objetTraiter.line[2].material has the reference to materialStd and not an independent object.

You must clone the object for you requirement.
There are multiple ways to clone the object, JSON.parse(JSON.stringify(obj)) is one of it.

see How do I correctly clone a JavaScript object? for more info on object cloning.

You may find your desired results in below example

var materialStd = {
  flow: 123,
  name: 'Raoul'
};

function cloneObject(obj) {
  return JSON.parse(JSON.stringify(obj))
}

var obj = {
  id: 0,
  line: [{
      id: 1,
      material: cloneObject(materialStd)  // clones
    },
    {
      id: 2,
      material: cloneObject(materialStd)
    },
    {
      id: 3,
      material: cloneObject(materialStd)
    }
  ]
}

testerror();

function testerror() {
  console.info(obj);
  //On appel une fct test

  console.log('' + obj.line[0].material.flow);
  console.log('' + obj.line[1].material.flow);
  console.log('' + obj.line[2].material.flow);

  test(obj);

  console.log('' + obj.line[0].material.flow);
  console.log('' + obj.line[1].material.flow);
  console.log('' + obj.line[2].material.flow);

}

function test(objetTraiter) {
  //  objetTraiter.line[0].material.flow=1;
  // objetTraiter.line[1].material.flow=2;
  objetTraiter.line[2].material.flow = 3;
  console.log('' + objetTraiter.line[0].material.flow);
  console.log('' + objetTraiter.line[1].material.flow);
  console.log('' + objetTraiter.line[2].material.flow);

}```

ContentLicense: CC BY-SA 4.0

Title: JavaScript Set value in object


答:
You problem is about reference, when you write :

```<code>line: [
    {id:1, material:materialStd},
    {id:2, material:materialStd},
    {id:3, material:materialStd}
]
</code>```

The same object is put at the 3 places. So when you do objetTraiter.line[2].material.flow=3, it changes the object which is present in the 3 line objects.

In Javascript, to clone data object without keeping the same reference, we can use
JSON.parse(JSON.stringify(obj)). (reference)

So you could use :

```<code>line: [
    {id:1, material: JSON.parse(JSON.stringify(materialStd))},
    {id:2, material: JSON.parse(JSON.stringify(materialStd))},
    {id:3, material: JSON.parse(JSON.stringify(materialStd))}
]
</code>```

Title: JavaScript Set value in object

Body:
I'm pretty new in JS  and something weird happen to me.
I try to set different value in an object and all the value of the table are changed
It appears the problems come from the creation of the object via a the object call "materialStd"

Value obj.line[0].material.flow of should stay at 123 instead of 3

Is someone able to explain what is happening there Thanks

https://jsfiddle.net/vx6fno9p/5/

var materialStd = {
  flow: 123,
  name: 'Raoul'
};
var obj = {
  id: 0,
  line: [{
      id: 1,
      material: materialStd
    },
    {
      id: 2,
      material: materialStd
    },
    {
      id: 3,
      material: materialStd
    }
  ]
}

testerror();

function testerror() {
  console.info(obj);
  //On appel une fct test

  console.log('' + obj.line[0].material.flow);
  console.log('' + obj.line[1].material.flow);
  console.log('' + obj.line[2].material.flow);

  test(obj);

  console.log('' + obj.line[0].material.flow);
  console.log('' + obj.line[1].material.flow);
  console.log('' + obj.line[2].material.flow);

}

function test(objetTraiter) {
  //  objetTraiter.line[0].material.flow=1;
  // objetTraiter.line[1].material.flow=2;
  objetTraiter.line[2].material.flow = 3;
  console.log('' + objetTraiter.line[0].material.flow);
  console.log('' + objetTraiter.line[1].material.flow);
  console.log('' + objetTraiter.line[2].material.flow);

}

Body:
You problem is about reference, when you write :

line: [
    {id:1, material:materialStd},
    {id:2, material:materialStd},
    {id:3, material:materialStd}
]

The same object is put at the 3 places. So when you do objetTraiter.line[2].material.flow=3, it changes the object which is present in the 3 line objects.

In Javascript, to clone data object without keeping the same reference, we can use
JSON.parse(JSON.stringify(obj)). (reference)

So you could use :

line: [
    {id:1, material: JSON.parse(JSON.stringify(materialStd))},
    {id:2, material: JSON.parse(JSON.stringify(materialStd))},
    {id:3, material: JSON.parse(JSON.stringify(materialStd))}
]


问:
Turn `ReloadOnChange` off in config source for WebApplicationFactory
This is both a question and an answer. I've fixed my problem, but it seems a bit wrong.

My original problem is running my asp.net core integration tests in a bitbucket pipeline causes  System.IO.IOException: The configured user limit (128) on the number of inotify instances has been reached. Some solutions call for changing some setting through sysctl, but that is restricted by bitbucket, so that isn't an option for me.

The second way of fixing this, as noted in these stackoverflow answers, is to turn reloadOnChange off.

My new problem is now, how do we best do this for the test WebApplicationFactory?

One solution that has worked for me, which is the least amount of code, seems like a total hack. I iterate through all the JsonConfigurationSource and set ReloadOnChange to false.

Full solution:

```<code>public class TestApplicationFactory : WebApplicationFactory<Startup>
{
    protected override void ConfigureWebHost(IWebHostBuilder builder)
    {
        builder.ConfigureAppConfiguration(config =>
        {
            foreach (var source in config.Sources)
            {
                if (source is JsonConfigurationSource)
                {
                    var jsonConfigSource = (JsonConfigurationSource) source;
                    jsonConfigSource.ReloadOnChange = false;
                }
            }
        });
    }
}
</code>```

Another solution, that I haven't tried, may be to override CreateWebHostBuilder(). However, it seems like more code and a lot of copy and paste from the default one.

Am I missing something? Is there a better way to do this?

答:
builder.ConfigureAppConfiguration is there to configure your (main) application.

You can use builder.ConfigureHostConfiguration (see docs) to explicitly configure files to be read for the host.

```<code>builder.ConfigureHostConfiguration((hostingContext, config) =>
{
    config.AddJsonFile("appsettings.json", optional: false, reloadOnChange: false);
});
</code>```

The host configuration is loaded. ASP.NET Core from 3.0 is built based on Generic host (rather than the Web Host of the former versions).

Body:
This is both a question and an answer. I've fixed my problem, but it seems a bit wrong.

My original problem is running my asp.net core integration tests in a bitbucket pipeline causes  System.IO.IOException: The configured user limit (128) on the number of inotify instances has been reached. Some solutions call for changing some setting through sysctl, but that is restricted by bitbucket, so that isn't an option for me.

The second way of fixing this, as noted in these stackoverflow answers, is to turn reloadOnChange off.

My new problem is now, how do we best do this for the test WebApplicationFactory?

One solution that has worked for me, which is the least amount of code, seems like a total hack. I iterate through all the JsonConfigurationSource and set ReloadOnChange to false.

Full solution:

public class TestApplicationFactory : WebApplicationFactory<Startup>
{
    protected override void ConfigureWebHost(IWebHostBuilder builder)
    {
        builder.ConfigureAppConfiguration(config =>
        {
            foreach (var source in config.Sources)
            {
                if (source is JsonConfigurationSource)
                {
                    var jsonConfigSource = (JsonConfigurationSource) source;
                    jsonConfigSource.ReloadOnChange = false;
                }
            }
        });
    }
}

Another solution, that I haven't tried, may be to override CreateWebHostBuilder(). However, it seems like more code and a lot of copy and paste from the default one.

Am I missing something? Is there a better way to do this?

Body:
builder.ConfigureAppConfiguration is there to configure your (main) application.

You can use builder.ConfigureHostConfiguration (see docs) to explicitly configure files to be read for the host.

builder.ConfigureHostConfiguration((hostingContext, config) =>
{
    config.AddJsonFile("appsettings.json", optional: false, reloadOnChange: false);
});

The host configuration is loaded. ASP.NET Core from 3.0 is built based on Generic host (rather than the Web Host of the former versions).


问:
JsonDeserialize set inherited properties also when objectmapper readvalue
JsonDeserialize not working when objectmapper readvalue for inherited properties.

Vehicle Class

```<code>@Getter
@Setter
@JsonDeserialize(builder = Vehicle.VehicleBuilder.class)
@Builder(builderClassName = "VehicleBuilder", toBuilder = true)
public class Vehicle{
    private String name;
    private String noOfTyres;
    @JsonPOJOBuilder(withPrefix = "")
    public static class VehicleBuilder{
    }
}
</code>```

Car class

```<code>@Getter
@Setter
@JsonDeserialize(builder = Car.CarBuilder.class)
@Builder(builderClassName = "CarBuilder", toBuilder = true)
public class Car extends Vehicle {
    private String carType;

    @JsonPOJOBuilder(withPrefix = "")
    public static class CarBuilder extends VehicleBuilder {
    }
}
</code>```

I don't want to create @NoArgsConstructor ,@AllArgsConstructor in both classes.
My issue when Car car = om.readValue(jsonValue,Car.class);
When I parse Json to java object the parent class properties are not setting properly.

As of now I'm using @NoArgsConstructor ,@AllArgsConstructor for work around for the use case.

Is there any way to use it along with @JsonDeserialize and @JsonPOJOBuilder?

答:
The problem with the code is that it assumes that builders in inherited classes will set the parent properties as well. Unfortunately, they don't do that out of the box. However, this is something that can be achieved with Lombok but requires some additional code, as described in this post.

A complete solution could look as follows.

Parent Class

```<code>@Getter
@Setter
@JsonDeserialize
@Builder(builderClassName = "VehicleBuilder", builderMethodName = "vehicleBuilder")
public class Vehicle {
    private String name;
    private String noOfTyres;

}
</code>```

Child Class

```<code>@Getter
@Setter
@JsonDeserialize(builder = Car.CarBuilder.class)
public class Car extends Vehicle {

    private String carType;

    @Builder
    public Car(String name, String noOfTyres, String carType) {
        super(name, noOfTyres);
        this.carType = carType;
    }

    @JsonPOJOBuilder(withPrefix = "")
    public static class CarBuilder extends VehicleBuilder {
    }

}
</code>```

Notice that the builder on the extending class is achieved by supplying a constructor with the @Builder annotation. Also take notice that the extending class does not set annotation parameter toBuilder=true as that will require access to parent properties which are private. This can be achieved by setting parent class properties to protected.

Body:
JsonDeserialize not working when objectmapper readvalue for inherited properties.

Vehicle Class

@Getter
@Setter
@JsonDeserialize(builder = Vehicle.VehicleBuilder.class)
@Builder(builderClassName = "VehicleBuilder", toBuilder = true)
public class Vehicle{
    private String name;
    private String noOfTyres;
    @JsonPOJOBuilder(withPrefix = "")
    public static class VehicleBuilder{
    }
}

Car class

@Getter
@Setter
@JsonDeserialize(builder = Car.CarBuilder.class)
@Builder(builderClassName = "CarBuilder", toBuilder = true)
public class Car extends Vehicle {
    private String carType;

    @JsonPOJOBuilder(withPrefix = "")
    public static class CarBuilder extends VehicleBuilder {
    }
}

I don't want to create @NoArgsConstructor ,@AllArgsConstructor in both classes.
My issue when Car car = om.readValue(jsonValue,Car.class);
When I parse Json to java object the parent class properties are not setting properly.

As of now I'm using @NoArgsConstructor ,@AllArgsConstructor for work around for the use case.

Is there any way to use it along with @JsonDeserialize and @JsonPOJOBuilder?

Body:
The problem with the code is that it assumes that builders in inherited classes will set the parent properties as well. Unfortunately, they don't do that out of the box. However, this is something that can be achieved with Lombok but requires some additional code, as described in this post.

A complete solution could look as follows.

Parent Class

@Getter
@Setter
@JsonDeserialize
@Builder(builderClassName = "VehicleBuilder", builderMethodName = "vehicleBuilder")
public class Vehicle {
    private String name;
    private String noOfTyres;

}

Child Class

@Getter
@Setter
@JsonDeserialize(builder = Car.CarBuilder.class)
public class Car extends Vehicle {

    private String carType;

    @Builder
    public Car(String name, String noOfTyres, String carType) {
        super(name, noOfTyres);
        this.carType = carType;
    }

    @JsonPOJOBuilder(withPrefix = "")
    public static class CarBuilder extends VehicleBuilder {
    }

}

Notice that the builder on the extending class is achieved by supplying a constructor with the @Builder annotation. Also take notice that the extending class does not set annotation parameter toBuilder=true as that will require access to parent properties which are private. This can be achieved by setting parent class properties to protected.


问:
How to extract information from pandas dataframe column
I have the dataframe below and I want to extract some information from column A and then create other columns to add them based on their types.
Below is an example to illustrate this.

```<code>In [0]: df
Out[0]:
          A
0 1258GA 25/01/20 TABLE 090626  038272
1 GOODIES 762088 A714816
2 TABLE AA88547 734963 GOODIES
3 WATER 02/450 FROM TOMORROW 48246
4 02H12 ALSCA 00548246B GOODIES
</code>```

And I want to have the result below.

```<code>In [1]: df
Out[1]:
          A                               Category             Date      Hour
0 1258GA 25/01/20 TABLE 090626  038272    TABLE           25/01/20
1 GOODIES 762088 A714816                  GOODIES
2 TABLE AA88547 734963 GOODIES            TABLE GOODIES
3 WATER 02/450 FROM TOMORROW 48246        WATER
4 02H12 ALSCA 00548246B GOODIES           GOODIES                        02H12
</code>```

I've tried many things but haven't got that result

答:
Maybe this helps:</p>

```<code>df['A'].str.findall(r'\b[A-Z]+\b').str.join(' ')

0                  TABLE
1                GOODIES
2          TABLE GOODIES
3    WATER FROM TOMORROW
4          ALSCA GOODIES
</code>```

Body:
I have the dataframe below and I want to extract some information from column A and then create other columns to add them based on their types.
Below is an example to illustrate this.

In [0]: df
Out[0]:
          A
0 1258GA 25/01/20 TABLE 090626  038272
1 GOODIES 762088 A714816
2 TABLE AA88547 734963 GOODIES
3 WATER 02/450 FROM TOMORROW 48246
4 02H12 ALSCA 00548246B GOODIES

And I want to have the result below.

In [1]: df
Out[1]:
          A                               Category             Date      Hour
0 1258GA 25/01/20 TABLE 090626  038272    TABLE           25/01/20
1 GOODIES 762088 A714816                  GOODIES
2 TABLE AA88547 734963 GOODIES            TABLE GOODIES
3 WATER 02/450 FROM TOMORROW 48246        WATER
4 02H12 ALSCA 00548246B GOODIES           GOODIES                        02H12

I've tried many things but haven't got that result

Body:
Maybe this helps:

df['A'].str.findall(r'\b[A-Z]+\b').str.join(' ')

0                  TABLE
1                GOODIES
2          TABLE GOODIES
3    WATER FROM TOMORROW
4          ALSCA GOODIES


问:
How to find the Z score of just one value?
I know the syntax of finding the z-score:

```<code>from scipy import stats
z = stats.zscore(a,axis = 0)
</code>```

However, the value of that is accepted is in the form of an array. I just want the Z-score calculation of one value

My current code is:

```<code>import numpy as np

mean=100
sd=10
a = [(50-100)/10]
from scipy import stats
z = stats.zscore(a)
print(z)
</code>```

I want the z-score of just a in the above code

答:
Using cumulative distribution function (cdf).

```<code>scipy.stats.norm.cdf(1.64)
</code>```

Returned value is 0.94949741652589625.

Meaning the Z-score value of 1.64 is 0.9495.

This will work.

Body:
I know the syntax of finding the z-score:

from scipy import stats
z = stats.zscore(a,axis = 0)

However, the value of that is accepted is in the form of an array. I just want the Z-score calculation of one value

My current code is:

import numpy as np

mean=100
sd=10
a = [(50-100)/10]
from scipy import stats
z = stats.zscore(a)
print(z)

I want the z-score of just a in the above code

Body:
Using cumulative distribution function (cdf).

scipy.stats.norm.cdf(1.64)

Returned value is 0.94949741652589625.

Meaning the Z-score value of 1.64 is 0.9495.

This will work.


问:
The remote end hung up unexpectedly while git cloning
My git client repeatedly fails with the following error after trying to clone the repository for some time.

What could be the issue here?

Note: I have registered my SSH key with the GIT hosting provider

```<code>Receiving objects:  13% (1309/10065), 796.00 KiB | 6 KiB/s
fatal: The remote end hung up unexpectedly
</code>```

答: I had to remove the branch flag for the git clone command.

ContentLicense: CC BY-SA 3.0

Body:
My git client repeatedly fails with the following error after trying to clone the repository for some time.

What could be the issue here?

Note: I have registered my SSH key with the GIT hosting provider

Receiving objects:  13% (1309/10065), 796.00 KiB | 6 KiB/s
fatal: The remote end hung up unexpectedly


问:
Extract only numbers and only string from pandas dataframe
I am trying to extract only numbers and only strings in two different dataframes. I am using regular expression to extract numbers and string.

```<code>import pandas as pd

df_num = pd.DataFrame({
        'Colors': ['lila1.5', 'rosa2.5', 'gelb3.5', 'grün4', 'rot5', 'schwarz6', 'grau7', 'weiß8', 'braun9', 'hellblau10'],
        'Animals': ['hu11nd', '12welpe', '13katze', 's14chlange', 'vo15gel', '16papagei', 'ku17h', '18ziege', '19pferd',
                    'esel20']
    })

for column in df_num.columns:
    df_num[column] = df_num[column].str.extract('(\d+)').astype(float)

print(df_num)
</code>```

I have also tried using '([\d+][\d+\.\d+])' and '([\d+\.\d+])'

Here I am getting output but not what I am expecting. Though I am expecting float numbers I am not getting 1.5 or 2.5.

I am getting something like below image:

```<code>df_str = pd.DataFrame({
        'Colors': ['lila1.5', 'rosa2.5', 'gelb3', 'grün4', 'rot5', 'schwarz6', 'grau7', 'weiß8', 'braun9', 'hellblau10'],
        'Animals': ['hu11nd', '12welpe', '13katze', 's14chlange', 'vo15gel', '16papagei', 'ku17h', '18ziege', '19pferd',
                    'esel20']
    })

for column in df_str.columns:
    df_str[column] = df_str[column].str.extract('([a-zA-Z]+)')

print(df_str)
</code>```

In this case when the number is at the end or in the beginning then I am getting the string but if the number placed in the middle or any other place then the result which I expect I am not getting.
Current output is like below image:

I think my regular expression is not correct. Which will be the right regular expression to solve these problems? Or is there any other way to extract only numbers and only strings in pandas dataframe?

答:
The easiest way to go about this is to define some functions:</p>

```<code>def text(x):
    return x.str.replace(r'[0-9.]+','')
def values(x):
    return x.str.extract(r'([0-9.]+)', expand = False)

df_str.transform([text,values])

          Colors          Animals
       text values      text values
0      lila    1.5      hund     11
1      rosa    2.5     welpe     12
2      gelb      3     katze     13
3      grün      4  schlange     14
4       rot      5     vogel     15
5   schwarz      6   papagei     16
6      grau      7       kuh     17
7      weiß      8     ziege     18
8     braun      9     pferd     19
9  hellblau     10      esel     20
</code>```

Body:
I am trying to extract only numbers and only strings in two different dataframes. I am using regular expression to extract numbers and string.

import pandas as pd

df_num = pd.DataFrame({
        'Colors': ['lila1.5', 'rosa2.5', 'gelb3.5', 'grün4', 'rot5', 'schwarz6', 'grau7', 'weiß8', 'braun9', 'hellblau10'],
        'Animals': ['hu11nd', '12welpe', '13katze', 's14chlange', 'vo15gel', '16papagei', 'ku17h', '18ziege', '19pferd',
                    'esel20']
    })

for column in df_num.columns:
    df_num[column] = df_num[column].str.extract('(\d+)').astype(float)

print(df_num)

I have also tried using '([\d+][\d+\.\d+])' and '([\d+\.\d+])'

Here I am getting output but not what I am expecting. Though I am expecting float numbers I am not getting 1.5 or 2.5.

I am getting something like below image:

df_str = pd.DataFrame({
        'Colors': ['lila1.5', 'rosa2.5', 'gelb3', 'grün4', 'rot5', 'schwarz6', 'grau7', 'weiß8', 'braun9', 'hellblau10'],
        'Animals': ['hu11nd', '12welpe', '13katze', 's14chlange', 'vo15gel', '16papagei', 'ku17h', '18ziege', '19pferd',
                    'esel20']
    })

for column in df_str.columns:
    df_str[column] = df_str[column].str.extract('([a-zA-Z]+)')

print(df_str)

In this case when the number is at the end or in the beginning then I am getting the string but if the number placed in the middle or any other place then the result which I expect I am not getting.
Current output is like below image:

I think my regular expression is not correct. Which will be the right regular expression to solve these problems? Or is there any other way to extract only numbers and only strings in pandas dataframe?

Body:
The easiest way to go about this is to define some functions:

def text(x):
    return x.str.replace(r'[0-9.]+','')
def values(x):
    return x.str.extract(r'([0-9.]+)', expand = False)

df_str.transform([text,values])

          Colors          Animals
       text values      text values
0      lila    1.5      hund     11
1      rosa    2.5     welpe     12
2      gelb      3     katze     13
3      grün      4  schlange     14
4       rot      5     vogel     15
5   schwarz      6   papagei     16
6      grau      7       kuh     17
7      weiß      8     ziege     18
8     braun      9     pferd     19
9  hellblau     10      esel     20


问:
Define PK_name via JPA annotation
I am using spring boot with SQL server and I want to define the PK_name from spring rather than let it generated automatically.

Hibernate is adding a suffix number to the primary key.

So instead of PK__Team__3214EC07FA39AD63  I would like to give this name PK_Team

```<code> @Entity
public class Team {
  @Id
@Column(name = "Id" )
private Integer id;
@Column(name = "FirstName")
private String firstName;
@Column(name = "FamilyName")
private String familyName;
@Column(name = "Email")
private String email;

public Integer getId() {
    return id;
}

public void setId(Integer id) {
    this.id = id;
}
</code>```

答:
It is not possible to specify the name however I think it is probably possible to prevent the suffix universally via a custom dialect which overrides the

org.hibernate.dialect.Dialect#getAddPrimaryKeyConstraintString(String constraintName)

method.

You cannot do anything about the name passed in however you can substring it to remove the suffix.

```<code>public class MyCustomSqlServerDialect extend SqlServer2012Dialect{

    @Override
    public String getAddPrimaryKeyConstraintString(String constraintName) {
        // default implementation
        // return " add constraint " + constraintName + " primary key ";

        return " add constraint " +
                    constraintName.subString(0, constraintName.lastIndexOf("__")) +
                        " primary key "
    }
}
</code>```

Then obviously just set this dialect in the relevant Spring/Hibernate property.

Title: Define PK_name via JPA annotation

Body:
I am using spring boot with SQL server and I want to define the PK_name from spring rather than let it generated automatically.

Hibernate is adding a suffix number to the primary key.

So instead of PK__Team__3214EC07FA39AD63  I would like to give this name PK_Team

 @Entity
public class Team {
  @Id
@Column(name = "Id" )
private Integer id;
@Column(name = "FirstName")
private String firstName;
@Column(name = "FamilyName")
private String familyName;
@Column(name = "Email")
private String email;

public Integer getId() {
    return id;
}

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

Body:
It is not possible to specify the name however I think it is probably possible to prevent the suffix universally via a custom dialect which overrides the

org.hibernate.dialect.Dialect#getAddPrimaryKeyConstraintString(String constraintName)

method.

You cannot do anything about the name passed in however you can substring it to remove the suffix.

public class MyCustomSqlServerDialect extend SqlServer2012Dialect{

    @Override
    public String getAddPrimaryKeyConstraintString(String constraintName) {
        // default implementation
        // return " add constraint " + constraintName + " primary key ";

        return " add constraint " +
                    constraintName.subString(0, constraintName.lastIndexOf("__")) +
                        " primary key "
    }
}

Then obviously just set this dialect in the relevant Spring/Hibernate property.


问:
How to update a file in server using SFTP in Paramiko
I want to go to a path on a remote SFTP server and verify if the file is present. If the file is present, then I want to open the file and update its contents.

Is it possible with SFTP in Paramiko?

答:
Paramiko SFTP client has SFTPClient.open method that is an equivalent of regular Python open function. It returns a file-like object, which you can then use as if you were editing a local file:

```<code>ssh = paramiko.SSHClient()
# ...
ssh.connect(...)

sftp = ssh.open_sftp()

with sftp.open("/remote/path/file.txt", "r+") as f:
    f.seek(10)
    f.write(b'foo')
</code>```

Body:
Paramiko SFTP client has SFTPClient.open method that is an equivalent of regular Python open function. It returns a file-like object, which you can then use as if you were editing a local file:

ssh = paramiko.SSHClient()
# ...
ssh.connect(...)

sftp = ssh.open_sftp()

with sftp.open("/remote/path/file.txt", "r+") as f:
    f.seek(10)
    f.write(b'foo')


问:
Azure created DefaultResourceGroup-EAU resource group
Today I am noticing that the Azure Group, I dont know when Azure created the

"DefaultResourceGroup-EAU" resource group, and in this group two item is placed

I am not using any Azure Container Registry service and AKS, should I remove this group because it paying in my invoice, I just only have Azure Web Apps and Azure SQL databases and one VM only, should its impact on my above mentioned services after deletion?

答:
certainly not in terms of how those services function, but monitoring might be impaired if you delete those.
Those resources look like they were created alongside AKS cluster. Doesn't mean that they were only being used for that, but highly likely.</p>


问:
Can I use one mysql database for two projects?
I want to make an android app that have two sites, one is for customer and the other one is for driver and operator. I'm a little confused how to do this. I thought I would make two projects but have one database.
How do I do this? Or is there a better way? Please forgive this stupid question. I'm still learning btw.</p>

答:
There is NO hard rule.

Largely depends on why or why not?

Architectural Patterns and Design Patterns are not meant for avoiding duplication or tight-coupling. They are not rules. These are very matured well tried and well tested convenience patterns.

Many times there will be redundancy or tight-coupling by policy or by business rule or legislation or efficiencies or to avoid maintenance complexity.

To answer your question…

E.g. You require an application which has large data input say to 10–50 Lakh records per 24 hours. These records need to be processed and reports updated ASAP before the end of Calendar day which is 12 midnight.

It makes sense to have the two different projects with a common database:

Which processes the data and generates reports in the background even possibly based on a scheduler
A UI based application which allows users to input data and view reports.
Something like an email or sms campaign.

In this case both projects will be accessing the same database or databases. You may have master data on an RDBMS server and trasactional data on NoSQL database for analytics and reports etc.

In QA or at the end of delivery you will anyways know what went right or wrong with your architecture and design.

You may want to discuss these things with your applications architect. Have a good academic relation with your applications and solutions architect. It will give you great insights.


问:
How can I check the 21 characters starting from 1de2458 in windbg?
After reading the docs,I'm doing it this way:

```<code>ds /c 21 1de2458
</code>```

But only get a screen of ??,how to do it the right way?

答:
Most likely the address doesn't point to a STRING, ANSI_STRING or UNICODE_STRING structure (these are C style structs for representing strings and they hold more that just the characters).

If you want to dump memory as characters use the da command for Ascii or du for Unicode characters. This works for e.g. strings in .NET.

Body:
After reading the docs,I'm doing it this way:

ds /c 21 1de2458

But only get a screen of ??,how to do it the right way?


问:
from django.utils import importlib, six ImportError: cannot import name 'importlib' from 'django.utils'
I am using below version

python 3.7.4
Django 2.0.5
MySQL 5.5
restframework 3.0

while running getting error as below, please help me

File "C:\Users\Imbesat Anwar\AppData\Local\Programs\Python\Python37\lib\site-packages\rest_framework\settings.py", line 22, in
    from django.utils import importlib, six
ImportError: cannot import name 'importlib' from 'django.utils' (C:\Users\Imbesat Anwar\AppData\Local\Programs\Python\Python37\lib\site-packages\django\utils__init__.py)

答: You need to upgrade your djangorestframework to 3.1 or higher.


问:
Edabit task doesn't show correct result
I'm doing a simple task which requires to sort a list by expression result and running this code:

```<code>   def sort_by_answer(lst):
        ans = []
        dict = {}
        for i in lst:
            if 'x' in i:
                i = i.replace('x', '*')
            dict.update({i: eval(i)})
        dict = {k: v for k, v in sorted(dict.items(), key=lambda item: item[1])}
        res = list(dict.keys())
        for i in res:
            if '*' in i:
                i = i.replace('*', 'x')
                ans.append(i)
            else:
                ans.append(i)
        return ans
</code>```

It checks out but the site for which i'm doing this test(here's a link to the task(https://edabit.com/challenge/9zf6scCreprSaQAPq) tells my that my list is not correctly sorted, which it is, can someone help me improve this code or smth so it works in every case-scenario?

P.S.

```<code>if 'x' in i:
      i = i.replace('x', '*')
</code>```

This is made so i can use the eval function but the site input has 'x' instead of '*' in their lists..

答:
I don't think it is an issue with your code, probably they are using something older that 3.6 and it is messing up the order of the dict. A tuple would be safer.

```<code>def sort_by_answer(lst):
    string = ','.join(lst).replace('x','*')
    l = string.split(',')
    d = [(k.replace('*','x'), eval(k)) for k in l]
    ans = [expr for expr, value in sorted(d, key = lambda x: x[1])]
    return ans
</code>```

EDIT:
@Ch3steR's answer is more pythonic:

```<code>def sort_by_answer(lst):
    return sorted(lst, key= lambda x: eval(x.replace('x','*')))
</code>```

Title: Edabit task doesn't show correct result

Body:
I'm doing a simple task which requires to sort a list by expression result and running this code:

   def sort_by_answer(lst):
        ans = []
        dict = {}
        for i in lst:
            if 'x' in i:
                i = i.replace('x', '*')
            dict.update({i: eval(i)})
        dict = {k: v for k, v in sorted(dict.items(), key=lambda item: item[1])}
        res = list(dict.keys())
        for i in res:
            if '*' in i:
                i = i.replace('*', 'x')
                ans.append(i)
            else:
                ans.append(i)
        return ans

It checks out but the site for which i'm doing this test(here's a link to the task(https://edabit.com/challenge/9zf6scCreprSaQAPq) tells my that my list is not correctly sorted, which it is, can someone help me improve this code or smth so it works in every case-scenario?

P.S.

if 'x' in i:
      i = i.replace('x', '*')

This is made so i can use the eval function but the site input has 'x' instead of '*' in their lists..

Body:
I don't think it is an issue with your code, probably they are using something older that 3.6 and it is messing up the order of the dict. A tuple would be safer.

def sort_by_answer(lst):
    string = ','.join(lst).replace('x','*')
    l = string.split(',')
    d = [(k.replace('*','x'), eval(k)) for k in l]
    ans = [expr for expr, value in sorted(d, key = lambda x: x[1])]
    return ans

EDIT:
@Ch3steR's answer is more pythonic:

def sort_by_answer(lst):
    return sorted(lst, key= lambda x: eval(x.replace('x','*')))


问:
How to use plotly in R shiny
I am trying to add graph for the output which i have generated using shiny. I am getting error for graph generation. Can someone please have a look and assist. The bar graph parameters are calculation based outputs generated from calculations.</p>

```<code>server
output$graph<- renderPlotly({

  plotly( x= c(as.numeric(input$contract), round(frateperton()), differencerate()),

         y= c('Contract Rate', 'ZBC Rate', 'Difference'),

         name = "Zero Based Rate Chart",

         type = "bar")

})

UI
plotlyOutput("graph"),

</code>```

答:
First of all, two remarks on your post :

it is not reproducible, see here to learn what a reproducible example is and how to make one

clearly you haven't searched enough. Typing "r shiny plotly output" in any search engine gives several potential solutions (here for example).

To avoid duplicated posts, please consider these two points next time.

Now, here's the answer (using iris data since your example is not reproducible):

```<code>library(shiny)
library(plotly)

ui <- fluidPage(
  selectInput("choice", "Choose", choices = names(iris), selected = NULL),
  plotlyOutput("graph")
  )

server <- function(input, output, session){

  output$graph <- renderPlotly({
    plot_ly(iris, x = ~get(input$choice), y = ~Sepal.Length, type = 'scatter', mode = 'markers')
  })
}

shinyApp(ui, server)
</code>```

Title: How to use plotly in R shiny

Body:
I am trying to add graph for the output which i have generated using shiny. I am getting error for graph generation. Can someone please have a look and assist. The bar graph parameters are calculation based outputs generated from calculations.

server
output$graph<- renderPlotly({

  plotly( x= c(as.numeric(input$contract), round(frateperton()), differencerate()),

         y= c('Contract Rate', 'ZBC Rate', 'Difference'),

         name = "Zero Based Rate Chart",

         type = "bar")

})

UI
plotlyOutput("graph"),

Body:
First of all, two remarks on your post :

it is not reproducible, see here to learn what a reproducible example is and how to make one

clearly you haven't searched enough. Typing "r shiny plotly output" in any search engine gives several potential solutions (here for example).

To avoid duplicated posts, please consider these two points next time.

Now, here's the answer (using iris data since your example is not reproducible):

library(shiny)
library(plotly)

ui <- fluidPage(
  selectInput("choice", "Choose", choices = names(iris), selected = NULL),
  plotlyOutput("graph")
  )

server <- function(input, output, session){

  output$graph <- renderPlotly({
    plot_ly(iris, x = ~get(input$choice), y = ~Sepal.Length, type = 'scatter', mode = 'markers')
  })
}

shinyApp(ui, server)


问:
Read console output of a shell script in Perl
Let's say I've got a shell script called print_error.sh looking like this:

```<code>#!/usr/bin/bash

echo "ERROR: Bla bla, yada yada."
exit 1
</code>```

Now I'm in a Perl script, calling this shell script with

```<code>system("print_error.sh")
</code>```

I now want to read the console output of print_error.sh and write it to a Log4perl logger.

How can I achieve this?

答:
Either use backticks:

```<code>my $results = `print_error.sh`;
</code>```

or see open:

http://perldoc.perl.org/functions/open.html

Body:
Let's say I've got a shell script called print_error.sh looking like this:

#!/usr/bin/bash

echo "ERROR: Bla bla, yada yada."
exit 1

Now I'm in a Perl script, calling this shell script with

system("print_error.sh")

I now want to read the console output of print_error.sh and write it to a Log4perl logger.

How can I achieve this?

Body:
Either use backticks:

my $results = `print_error.sh`;

or see open:

http://perldoc.perl.org/functions/open.html


问:
using variable from .js file to .cs file
Im programming in Visual Code C#, i'm making a chat application in SignalR, i want to store messages in a database in MongoDB. I need a help, that how can I use the 'message' and the 'user' variable from chat.js file in the Pogram.cs?

chat.js

"use strict";

var connection = new signalR.HubConnectionBuilder().withUrl("/chatHub").build();

//Disable send button until connection is established
document.getElementById("sendButton").disabled = true;

connection.on("ReceiveMessage", function (user, message) {
    var msg = message.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
    var encodedMsg = user + ": " + msg;
    var li = document.createElement("li");
    li.textContent = encodedMsg;
    document.getElementById("messagesList").appendChild(li);
});

connection.start().then(function () {
    document.getElementById("sendButton").disabled = false;
}).catch(function (err) {
    return console.error(err.toString());
});

document.getElementById("sendButton").addEventListener("click", function (event) {
    var user = document.getElementById("userInput").value;
    var message = document.getElementById("messageInput").value;
    connection.invoke("SendMessage", user, message).catch(function (err) {
        return console.error(err.toString());
    });
    event.preventDefault();
});```
</div>
</div>
</p>

<p><strong>Program.cs</strong></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>namespace bcwebchat
{

    public class Message{
    public DateTime Sent;
    public string Msg;
}

public class Program
    {
        public static void Main(string[] args)
        {

            var client = new MongoClient("mongodb://localhost:27017");

            var db = client.GetDatabase("DemoInsert");

            var collec = db.GetCollection<Message>("DemoInsert");

            collec.InsertOne(new Message
            {
                Sent = DateTime.Now,
                Msg = "blaaahahaah"
            });</code>```

I want to use the user and the message in here:

collec.InsertOne(new Message
{
    Sent = DateTime.Now,
    Msg = "blaaahahaah"
});```

答:
Just following this section Microsoft SignalR

First, you should create a ASP.NET Web Application

Then, create a ChatHub and insert message, it should work

```<code>public class ChatHub : Hub
{
    public async Task SendMessage(string user, string message)
    {
            // insert your message to database
            collec.InsertOne(new Message
            {
                Sent = DateTime.Now,
                Msg = message
            });
            await Clients.All.SendAsync("ReceiveMessage", user, message);
    }
}
</code>```

```<code>public void ConfigureServices(IServiceCollection services)
{
     services.AddRazorPages();
     services.AddSignalR();
}
</code>```

```<code> public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
 {
      //some code here

      app.UseEndpoints(endpoints =>
      {
          endpoints.MapRazorPages();
         endpoints.MapHub<ChatHub>("/chatHub");
      });
}
</code>```

Body:
Im programming in Visual Code C#, i'm making a chat application in SignalR, i want to store messages in a database in MongoDB. I need a help, that how can I use the 'message' and the 'user' variable from chat.js file in the Pogram.cs?

chat.js

"use strict";

var connection = new signalR.HubConnectionBuilder().withUrl("/chatHub").build();

//Disable send button until connection is established
document.getElementById("sendButton").disabled = true;

connection.on("ReceiveMessage", function (user, message) {
    var msg = message.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
    var encodedMsg = user + ": " + msg;
    var li = document.createElement("li");
    li.textContent = encodedMsg;
    document.getElementById("messagesList").appendChild(li);
});

connection.start().then(function () {
    document.getElementById("sendButton").disabled = false;
}).catch(function (err) {
    return console.error(err.toString());
});

document.getElementById("sendButton").addEventListener("click", function (event) {
    var user = document.getElementById("userInput").value;
    var message = document.getElementById("messageInput").value;
    connection.invoke("SendMessage", user, message).catch(function (err) {
        return console.error(err.toString());
    });
    event.preventDefault();
});

Program.cs

namespace bcwebchat
{

    public class Message{
    public DateTime Sent;
    public string Msg;
}

public class Program
    {
        public static void Main(string[] args)
        {

            var client = new MongoClient("mongodb://localhost:27017");

            var db = client.GetDatabase("DemoInsert");

            var collec = db.GetCollection<Message>("DemoInsert");

            collec.InsertOne(new Message
            {
                Sent = DateTime.Now,
                Msg = "blaaahahaah"
            });

I want to use the user and the message in here:

collec.InsertOne(new Message
{
    Sent = DateTime.Now,
    Msg = "blaaahahaah"
});

Body:
Just following this section Microsoft SignalR

First, you should create a ASP.NET Web Application

Then, create a ChatHub and insert message, it should work

public class ChatHub : Hub
{
    public async Task SendMessage(string user, string message)
    {
            // insert your message to database
            collec.InsertOne(new Message
            {
                Sent = DateTime.Now,
                Msg = message
            });
            await Clients.All.SendAsync("ReceiveMessage", user, message);
    }
}

public void ConfigureServices(IServiceCollection services)
{
     services.AddRazorPages();
     services.AddSignalR();
}

 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
 {
      //some code here

      app.UseEndpoints(endpoints =>
      {
          endpoints.MapRazorPages();
         endpoints.MapHub<ChatHub>("/chatHub");
      });
}


问:
Google Pagespeed giving error "cloned graph missing node" in eliminate render blocking resource
Google pagespeed is giving error "cloned graph missing node". I have used styled components to eliminate render blocking resource . What does this error mean?</p>

答:
I had the same error. In my case there where faulty script and link Tags - for some reason the src and href attributes where empty. By removing those Tags I fixed the issue.

To look deeper into the reason behind this error you can find the code where the error is thrown here
https://github.com/GoogleChrome/lighthouse/blob/fa70748c46fc1fb4236417ecb8848f965cd1613f/lighthouse-core/lib/dependency-graph/base-node.js

```<code>const clonedThisNode = idsToIncludedClones.get(this.id);
if (!clonedThisNode) throw new Error('Cloned graph missing node');
return clonedThisNode;
</code>```

Body:
I had the same error. In my case there where faulty script and link Tags - for some reason the src and href attributes where empty. By removing those Tags I fixed the issue.

To look deeper into the reason behind this error you can find the code where the error is thrown here
https://github.com/GoogleChrome/lighthouse/blob/fa70748c46fc1fb4236417ecb8848f965cd1613f/lighthouse-core/lib/dependency-graph/base-node.js

const clonedThisNode = idsToIncludedClones.get(this.id);
if (!clonedThisNode) throw new Error('Cloned graph missing node');
return clonedThisNode;


问:
How do I reuse Angular form on server side for validation?
I want to reuse same set of validators on client and server side with Angular 4.4.5 and NodeJS 7.10.1 (latest in Ubuntu repos). I believe it's possible.

My basic idea is to have HTTP endpoint working on NodeJS and Express which accepts POST request with JSON data from Angular form, creates same form with received data and checks it.

My attempts were unsuccessful, I don't know how to use same version of Typescript as Angular uses and how to import component with form. It would be ideal to see some simple example that work. I'll share my attempts soon.

答:
After a long search I found a solution. Angular now supports workspaces with libraries and server side rendering of forms (ssr) using Node and Express.js. So Angular 8+ basically already has everything needed.

What I do is I put all my shared code in a library so I can use it in the frontend and also reuse it on a SSR app (validation). I don't think that this is necessary, but a clean structure is helpful.

To create the structure I just used the cli:

Create new workspace.

Generate library for shared code.

Generate application for the frontend (normal ng app).

Generate application for the validation server and run ng add @nguniversal/express-engine on it.

You can find all relevant information on how to do this in the tutorials:

SSR/Universal: https://angular.io/guide/universal

CLI: https://angular.io/cli

Reactive Forms: https://angular.io/guide/reactive-forms

Now I used the generated server.ts and deleted most of it (example handlers).
At fist, I had some problem with JSON parsing. But the body-parser can do it.

```<code>// ...
import * as bodyParser from "body-parser";
// ...
export function app() {
  const server = express();
  server.use(bodyParser.json());
  // ...
</code>```

Then I added this handler:

```<code>  server.post('/api/validate', (req, res) => {
    // createFormGroup is from my code,
    // because I generate the form from TypeScript classes.
    // You can just use a FormBuilder in your component
    // and export the function so you can use it here.
    const fg = createFormGroup();
    fg.patchValue(req.body);
    res.status(200).send({
        "accepted" : "VALID" === fg.status
        // You can send additional information, like errors
      });
  });
</code>```

Calling fg.updateValueAndValidity() does not seem to be necessary as patchValue already does all that.

Time to build and start the server.

Somehow I now have a problem where the build script doesn't work with --prod.
But this does:

ng build; ng run validation:server:production; npm  run serve:ssr

You should get:

Node Express server listening on http://localhost:4000

And that's it. Really easy.

I use curl for testing:

```<code>curl.exe --data "@data.json" -H "Content-Type: application/json" -X POST http://localhost:4000/api/validate
</code>```

I don't know how to debug this, but console.log works just fine. And to test the code that you use on this server you should just use unit tests (jasmine) anyway. So even though this is slow to start I'm just glad I can now validate code on the server.

It might make sense to compare req.body and fg.value recursively for equality, to make sure it's still the same data after validation.

Body:
After a long search I found a solution. Angular now supports workspaces with libraries and server side rendering of forms (ssr) using Node and Express.js. So Angular 8+ basically already has everything needed.

What I do is I put all my shared code in a library so I can use it in the frontend and also reuse it on a SSR app (validation). I don't think that this is necessary, but a clean structure is helpful.

To create the structure I just used the cli:

Create new workspace.

Generate library for shared code.

Generate application for the frontend (normal ng app).

Generate application for the validation server and run ng add @nguniversal/express-engine on it.

You can find all relevant information on how to do this in the tutorials:

SSR/Universal: https://angular.io/guide/universal

CLI: https://angular.io/cli

Reactive Forms: https://angular.io/guide/reactive-forms

Now I used the generated server.ts and deleted most of it (example handlers).
At fist, I had some problem with JSON parsing. But the body-parser can do it.

// ...
import * as bodyParser from "body-parser";
// ...
export function app() {
  const server = express();
  server.use(bodyParser.json());
  // ...

Then I added this handler:

  server.post('/api/validate', (req, res) => {
    // createFormGroup is from my code,
    // because I generate the form from TypeScript classes.
    // You can just use a FormBuilder in your component
    // and export the function so you can use it here.
    const fg = createFormGroup();
    fg.patchValue(req.body);
    res.status(200).send({
        "accepted" : "VALID" === fg.status
        // You can send additional information, like errors
      });
  });

Calling fg.updateValueAndValidity() does not seem to be necessary as patchValue already does all that.

Time to build and start the server.

Somehow I now have a problem where the build script doesn't work with --prod.
But this does:

ng build; ng run validation:server:production; npm  run serve:ssr

You should get:

Node Express server listening on http://localhost:4000

And that's it. Really easy.

I use curl for testing:

curl.exe --data "@data.json" -H "Content-Type: application/json" -X POST http://localhost:4000/api/validate

I don't know how to debug this, but console.log works just fine. And to test the code that you use on this server you should just use unit tests (jasmine) anyway. So even though this is slow to start I'm just glad I can now validate code on the server.

It might make sense to compare req.body and fg.value recursively for equality, to make sure it's still the same data after validation.


问:
What is the basic setup for securing PowerBI reports?
We are looking at the possible migration of reports from our reporting platform to PowerBI and have got PowerBI Desktop installed for a few quick tests; made a database connection, written a simple report and published it successfully. In this process, it has raised the question of what we would need to do, to restrict access to the reports we create for users outside of our organisation?

Someone mentioned that we need a PowerBI server, but cannot find a straight forward answer to confirm that and to identify what needs to be installed, etc.,

If we can get a bit of a "dummies guide to setting up" or reference to an article that explains in fairly simple terms that would be great.

答:
You can do three things for users outside your organisation:

1) You can use Azure Active Directory B2B, to add in external users and allocated the a Power BI Pro Licences and the secure the reports the normal way on a workspace or app

2) You can use Power BI Embedded A SKU's. Using this service you can create a web portal that uses this to display your own reports. You have to build you own front end, user login etc, it will just show the reports

3) You can use Power BI Report Server (PBRS) as an external website, you'll still need to add users to AD, but they don't have to be pro users. The link is for SSRS 2008, but most of it should apply as PBRS is a superset of SSRS


问:
How to ask the user if they wish to input another value in c
This is how i attempted it, how ever when i enter q it just skips a line in command and continues the program.   </p>

```<code>int main()
{
int a;
char c;
cont(&a);
while(a != 'q' && a != 'Q')
{
while ( ( c = getchar() ) != EOF)
{
    putchar( r13( c ) );
 }
}

return 0;
 }
</code>```

答:
You need to pass the reference of a to cont() -

```<code>void cont(int* a)
{
    printf("If you do not want to enter a value press q");
    scanf("%c", a);
}
</code>```

and call it like that:

```<code>cont(&a);
</code>```

otherwise, only the the copy of a (that is passed to the function) is changed, not a itself.

If you want to change the value of a in the function, then you need to store the return value somewhere, but you ignored it (e.g. a = cont(a);).

Or, give a reference (e.g. address of) a to the function, so it will be able to change the value of a.

Body:
This is how i attempted it, how ever when i enter q it just skips a line in command and continues the program.

int main()
{
int a;
char c;
cont(&a);
while(a != 'q' && a != 'Q')
{
while ( ( c = getchar() ) != EOF)
{
    putchar( r13( c ) );
 }
}

return 0;
 }

Body:
You need to pass the reference of a to cont() -

void cont(int* a)
{
    printf("If you do not want to enter a value press q");
    scanf("%c", a);
}

and call it like that:

cont(&a);

otherwise, only the the copy of a (that is passed to the function) is changed, not a itself.

If you want to change the value of a in the function, then you need to store the return value somewhere, but you ignored it (e.g. a = cont(a);).

Or, give a reference (e.g. address of) a to the function, so it will be able to change the value of a.


问:
How can I make setInterval also work when a tab is inactive in Chrome?
I have a setInterval running a piece of code 30 times a second. This works great, however when I select another tab (so that the tab with my code becomes inactive), the setInterval is set to an idle state for some reason.

I made this simplified test case (http://jsfiddle.net/7f6DX/3/):

```<code>var $div = $('div');
var a = 0;

setInterval(function() {
    a++;
    $div.css("left", a)
}, 1000 / 30);
</code>```

If you run this code and then switch to another tab, wait a few seconds and go back, the animation continues at the point it was when you switched to the other tab.

So the animation isn't running 30 times a second in case the tab is inactive. This can be confirmed by counting the amount of times the setInterval function is called each second - this will not be 30 but just 1 or 2 if the tab is inactive.

I guess that this is done by design so as to improve system performance, but is there any way to disable this behavior?

It’s actually a disadvantage in my scenario.

答:
It is quite old question but I encountered the same issue.

If you run your web on chrome, you could read through this post Background Tabs in Chrome 57.

Basically the interval timer could run if it haven't run out of the timer budget.

The consumption of budget is based on CPU time usage of the task inside timer.

Based on my scenario, I draw video to canvas and transport to WebRTC.

The webrtc video connection would keep updating even the tab is inactive.

However you have to use setInterval instead of requestAnimationFrame but itt is not recommended for UI rendering though.

It would be better to listen visibilityChange event and change render mechenism accordingly.

Besides, you could try what Kaan Soral suggests and it should works based on the documentation.

Body:
I have a setInterval running a piece of code 30 times a second. This works great, however when I select another tab (so that the tab with my code becomes inactive), the setInterval is set to an idle state for some reason.

I made this simplified test case (http://jsfiddle.net/7f6DX/3/):

var $div = $('div');
var a = 0;

setInterval(function() {
    a++;
    $div.css("left", a)
}, 1000 / 30);

If you run this code and then switch to another tab, wait a few seconds and go back, the animation continues at the point it was when you switched to the other tab.

So the animation isn't running 30 times a second in case the tab is inactive. This can be confirmed by counting the amount of times the setInterval function is called each second - this will not be 30 but just 1 or 2 if the tab is inactive.

I guess that this is done by design so as to improve system performance, but is there any way to disable this behavior?

It’s actually a disadvantage in my scenario.


问:
Update title dynamically on Apexcharts
I am using Updateseries to update x and y axis. How can i update title?</p>

```<code>$.getJSON('chartData.php', {
    devicename: feature.get('id')
}, (response) => {
    chart.updateSeries([{
        data: response
    }])

    let chart = new ApexCharts(document.getElementById("chart"), options)
    chart.updateOptions({
    title: 'Water Consumption per day on December 2019 for '
  })

 });
</code>```

答:
this code can update the title in the chart.</p>

```<code>*ApexCharts.exec('id', "updateOptions", {*
        title:{
            text:title1
        }
    });
</code>```

Title: Update title dynamically on Apexcharts

Body:
I am using Updateseries to update x and y axis. How can i update title?

$.getJSON('chartData.php', {
    devicename: feature.get('id')
}, (response) => {
    chart.updateSeries([{
        data: response
    }])

    let chart = new ApexCharts(document.getElementById("chart"), options)
    chart.updateOptions({
    title: 'Water Consumption per day on December 2019 for '
  })

 });

Body:
this code can update the title in the chart.

*ApexCharts.exec('id', "updateOptions", {*
        title:{
            text:title1
        }
    });