text:
Q: What could turn on the TCP Keep-Alive flag? Is my traffic being corrupted? Background
I'm stress testing my client-server application. Both ends are C++ programs with event detection via epoll.
In this test they are each running on CentOS 7 in an Oracle VirtualBox 5.0.22 instance, communicating over VirtualBox's Host-Only Ethernet Adaptor (type: Intel PRO/1000 MT Desktop (82504EM)).
The client opens a TCP/IP connection to the server, exchanges some application-level handshake messages, and maintains it by pumping through a single ASCII 20 (whitespace) every ten seconds. Call this a "ping". After a certain number of expected "pings" have been missed by either side, the connection is closed.
Under some circumstances, the server can also open a connection to the client to re-establish communication faster (e.g. after the server has restarted). In most configurations, the client will actually end up re-opening its own outgoing connection too and the server's connection will be closed as "redundant".
This is working okay at small scales, but when I try to simulate there being many clients on a network, things fall apart. Since the server needs each client to be on a distinct IP, for the simulation I create some "virtual interfaces" in 192.168.21.0/24, and play with routing.
Say I'm simulating 20 clients. To set up the 12th, I'll execute this on my client VM:
ip link add link enp0s8 sbsim12 type macvlan
ip link set up dev sbsim12
ip addr add 192.168.21.12/24 broadcast 192.168.21.255 dev sbsim12

(enp0s8 is the VirtualBox Host-Only Adaptor)
Then, on the server VM:
ip route add 192.168.21.0/24 dev enp0s8

An instance of my client can then bind to 192.168.21.12 and, henceforth, in my system, that appears to be its IP.
Problem
This mechanism worked rather well for us when our application used UDP comms. It also works fine at small scales. However, when I start up more and more clients at a time, I start to see strange behaviour. Symptoms vary, but the general pattern appears to be the TCP/IP connection stalling. With masses of debug output in my application, I can see that the sending side is correctly detecting EPOLLOUT on the socket and sending to it, but the receiving side occasionally never detects EPOLLIN so data effectively goes missing. This occurs every few runs, with increasing probability as the number of clients grows.
Having spent what feels like a decade forensically analysing the correctness of my application's logic, I'm starting to wonder whether I'm hitting some kind of networking bug at a lower layer, either within the MAC VLAN realm or the VirtualBox driver realm.
In order to rule that out, I need somebody with a much better understanding of TCP than I have, to confirm or deny that the following is really weird.
What on earth is going on in this packet stream?

No.     Time           Source                Destination           Protocol Info
  26496 581.345275     192.168.21.51         192.168.99.100        TCP      42551→cisco-sccp(2000) [SYN] Seq=0 Win=29200 Len=0 MSS=1460 SACK_PERM=1 TSval=377482702 TSecr=0 WS=128
  26499 581.345711     192.168.99.100        192.168.21.51         TCP      cisco-sccp(2000)→42551 [SYN, ACK] Seq=0 Ack=1 Win=28960 Len=0 MSS=1460 SACK_PERM=1 TSval=381905815 TSecr=377482702 WS=128
  26500 581.345936     192.168.21.51         192.168.99.100        TCP      42551→cisco-sccp(2000) [ACK] Seq=1 Ack=1 Win=29312 Len=0 TSval=377482703 TSecr=381905815
  26516 581.349421     192.168.99.100        192.168.21.51         TCP      cisco-sccp(2000)→42551 [PSH, ACK] Seq=1 Ack=1 Win=29312 Len=131 TSval=381905865 TSecr=377482703
  26519 581.349661     192.168.21.51         192.168.99.100        TCP      42551→cisco-sccp(2000) [ACK] Seq=1 Ack=132 Win=30336 Len=0 TSval=377482706 TSecr=381905865
  26647 581.394528     192.168.21.51         192.168.99.100        TCP      42551→cisco-sccp(2000) [PSH, ACK] Seq=1 Ack=132 Win=30336 Len=131 TSval=377482751 TSecr=381905865
  26648 581.394574     192.168.99.100        192.168.21.51         TCP      cisco-sccp(2000)→42551 [ACK] Seq=132 Ack=132 Win=30336 Len=0 TSval=381905911 TSecr=377482751
  26690 581.401738     192.168.21.51         192.168.99.100        TCP      42551→cisco-sccp(2000) [PSH, ACK] Seq=132 Ack=132 Win=30336 Len=289 TSval=377482758 TSecr=381905911
  26691 581.401756     192.168.99.100        192.168.21.51         TCP      cisco-sccp(2000)→42551 [ACK] Seq=132 Ack=421 Win=31360 Len=0 TSval=381905918 TSecr=377482758
  26735 581.418696     192.168.99.100        192.168.21.51         TCP      cisco-sccp(2000)→42551 [PSH, ACK] Seq=132 Ack=421 Win=31360 Len=48 TSval=381905935 TSecr=377482758
  26737 581.418927     192.168.21.51         192.168.99.100        TCP      42551→cisco-sccp(2000) [ACK] Seq=421 Ack=180 Win=30336 Len=0 TSval=377482776 TSecr=381905935
  26749 581.432843     192.168.99.100        192.168.21.51         TCP      cisco-sccp(2000)→42551 [PSH, ACK] Seq=180 Ack=421 Win=31360 Len=45 TSval=381905949 TSecr=377482776
  26751 581.433022     192.168.21.51         192.168.99.100        TCP      42551→cisco-sccp(2000) [ACK] Seq=421 Ack=225 Win=30336 Len=0 TSval=377482790 TSecr=381905949
  26758 581.436982     192.168.21.51         192.168.99.100        TCP      42551→cisco-sccp(2000) [PSH, ACK] Seq=421 Ack=225 Win=30336 Len=819 TSval=377482793 TSecr=381905949
  26793 581.476317     192.168.99.100        192.168.21.51         TCP      cisco-sccp(2000)→42551 [ACK] Seq=225 Ack=1240 Win=33024 Len=0 TSval=381905993 TSecr=377482793
  26892 581.579434     192.168.99.100        192.168.21.51         TCP      cisco-sccp(2000)→42551 [PSH, ACK] Seq=225 Ack=1240 Win=33024 Len=64 TSval=381906096 TSecr=377482793
  26950 581.619040     192.168.21.51         192.168.99.100        TCP      42551→cisco-sccp(2000) [ACK] Seq=1240 Ack=289 Win=30336 Len=0 TSval=377482976 TSecr=381906096
  27012 581.652478     192.168.21.51         192.168.99.100        TCP      42551→cisco-sccp(2000) [PSH, ACK] Seq=1240 Ack=289 Win=30336 Len=1230 TSval=377483007 TSecr=381906096
  27013 581.652520     192.168.99.100        192.168.21.51         TCP      cisco-sccp(2000)→42551 [ACK] Seq=289 Ack=2470 Win=35968 Len=0 TSval=381906168 TSecr=377483007
  28392 590.844958     192.168.99.100        192.168.21.51         TCP      cisco-sccp(2000)→42551 [PSH, ACK] Seq=289 Ack=2470 Win=35968 Len=1 TSval=381915361 TSecr=377483007
  28427 590.955619     192.168.21.51         192.168.99.100        TCP      42551→cisco-sccp(2000) [PSH, ACK] Seq=2470 Ack=289 Win=30336 Len=1 TSval=377492312 TSecr=381906168
  28428 590.955628     192.168.99.100        192.168.21.51         TCP      cisco-sccp(2000)→42551 [ACK] Seq=290 Ack=2471 Win=35968 Len=0 TSval=381915472 TSecr=377492312
  28457 591.077735     192.168.99.100        192.168.21.51         TCP      [TCP Keep-Alive] cisco-sccp(2000)→42551 [PSH, ACK] Seq=289 Ack=2471 Win=35968 Len=1 TSval=381915594 TSecr=377492312
  28494 591.161676     192.168.21.51         192.168.99.100        TCP      [TCP Keep-Alive] 42551→cisco-sccp(2000) [PSH, ACK] Seq=2470 Ack=289 Win=30336 Len=1 TSval=377492518 TSecr=381906168
  28495 591.161733     192.168.99.100        192.168.21.51         TCP      [TCP Keep-Alive ACK] cisco-sccp(2000)→42551 [ACK] Seq=290 Ack=2471 Win=35968 Len=0 TSval=381915678 TSecr=377492518 SLE=2470 SRE=2471
  28526 591.367239     192.168.21.51         192.168.99.100        TCP      [TCP Keep-Alive] 42551→cisco-sccp(2000) [PSH, ACK] Seq=2470 Ack=289 Win=30336 Len=1 TSval=377492724 TSecr=381906168
  28527 591.367344     192.168.99.100        192.168.21.51         TCP      [TCP Keep-Alive ACK] cisco-sccp(2000)→42551 [ACK] Seq=290 Ack=2471 Win=35968 Len=0 TSval=381915883 TSecr=377492724 SLE=2470 SRE=2471
  28566 591.776390     192.168.99.100        192.168.21.51         TCP      [TCP Keep-Alive] cisco-sccp(2000)→42551 [PSH, ACK] Seq=289 Ack=2471 Win=35968 Len=1 TSval=381916293 TSecr=377492724
  28567 591.780375     192.168.21.51         192.168.99.100        TCP      [TCP Keep-Alive] 42551→cisco-sccp(2000) [PSH, ACK] Seq=2470 Ack=289 Win=30336 Len=1 TSval=377493137 TSecr=381906168
  28568 591.780472     192.168.99.100        192.168.21.51         TCP      [TCP Keep-Alive ACK] cisco-sccp(2000)→42551 [ACK] Seq=290 Ack=2471 Win=35968 Len=0 TSval=381916297 TSecr=377493137 SLE=2470 SRE=2471
  28601 592.243918     192.168.99.100        192.168.21.51         TCP      [TCP Keep-Alive] cisco-sccp(2000)→42551 [PSH, ACK] Seq=289 Ack=2471 Win=35968 Len=1 TSval=381916760 TSecr=377493137
  28639 592.607472     192.168.21.51         192.168.99.100        TCP      [TCP Keep-Alive] 42551→cisco-sccp(2000) [PSH, ACK] Seq=2470 Ack=289 Win=30336 Len=1 TSval=377493964 TSecr=381906168
  28640 592.607575     192.168.99.100        192.168.21.51         TCP      [TCP Keep-Alive ACK] cisco-sccp(2000)→42551 [ACK] Seq=290 Ack=2471 Win=35968 Len=0 TSval=381917124 TSecr=377493964 SLE=2470 SRE=2471
  28729 593.177610     192.168.99.100        192.168.21.51         TCP      [TCP Keep-Alive] cisco-sccp(2000)→42551 [PSH, ACK] Seq=289 Ack=2471 Win=35968 Len=1 TSval=381917694 TSecr=377493964
  28826 594.259300     192.168.21.51         192.168.99.100        TCP      [TCP Keep-Alive] 42551→cisco-sccp(2000) [PSH, ACK] Seq=2470 Ack=289 Win=30336 Len=1 TSval=377495616 TSecr=381906168
  28827 594.259358     192.168.99.100        192.168.21.51         TCP      [TCP Keep-Alive ACK] cisco-sccp(2000)→42551 [ACK] Seq=290 Ack=2471 Win=35968 Len=0 TSval=381918776 TSecr=377495616 SLE=2470 SRE=2471
  28863 595.043696     192.168.99.100        192.168.21.51         TCP      [TCP Keep-Alive] cisco-sccp(2000)→42551 [PSH, ACK] Seq=289 Ack=2471 Win=35968 Len=1 TSval=381919560 TSecr=377495616
  29669 597.563164     192.168.21.51         192.168.99.100        TCP      [TCP Keep-Alive] 42551→cisco-sccp(2000) [PSH, ACK] Seq=2470 Ack=289 Win=30336 Len=1 TSval=377498920 TSecr=381906168
  29670 597.563296     192.168.99.100        192.168.21.51         TCP      [TCP Keep-Alive ACK] cisco-sccp(2000)→42551 [ACK] Seq=290 Ack=2471 Win=35968 Len=0 TSval=381922079 TSecr=377498920 SLE=2470 SRE=2471
  30012 598.779594     192.168.99.100        192.168.21.51         TCP      [TCP Keep-Alive] cisco-sccp(2000)→42551 [PSH, ACK] Seq=289 Ack=2471 Win=35968 Len=1 TSval=381923296 TSecr=377498920
  30485 604.179630     192.168.21.51         192.168.99.100        TCP      [TCP Keep-Alive] 42551→cisco-sccp(2000) [PSH, ACK] Seq=2470 Ack=289 Win=30336 Len=1 TSval=377505536 TSecr=381906168
  30486 604.179745     192.168.99.100        192.168.21.51         TCP      [TCP Keep-Alive ACK] cisco-sccp(2000)→42551 [ACK] Seq=290 Ack=2471 Win=35968 Len=0 TSval=381928696 TSecr=377505536 SLE=2470 SRE=2471
  30679 606.251285     192.168.99.100        192.168.21.51         TCP      [TCP Keep-Alive] cisco-sccp(2000)→42551 [PSH, ACK] Seq=289 Ack=2471 Win=35968 Len=1 TSval=381930768 TSecr=377505536
  30824 610.881089     192.168.21.51         192.168.99.100        TCP      42551→cisco-sccp(2000) [FIN, PSH, ACK] Seq=2471 Ack=289 Win=30336 Len=1 TSval=377512238 TSecr=381906168
  30825 610.881786     192.168.21.51         192.168.99.100        TCP      45431→cisco-sccp(2000) [SYN] Seq=0 Win=29200 Len=0 MSS=1460 SACK_PERM=1 TSval=377512238 TSecr=0 WS=128
  30826 610.881829     192.168.99.100        192.168.21.51         TCP      cisco-sccp(2000)→45431 [SYN, ACK] Seq=0 Ack=1 Win=28960 Len=0 MSS=1460 SACK_PERM=1 TSval=381935398 TSecr=377512238 WS=128
  30858 610.885132     192.168.99.100        192.168.21.51         TCP      cisco-sccp(2000)→42551 [FIN, PSH, ACK] Seq=290 Ack=2473 Win=35968 Len=1 TSval=381935401 TSecr=377512238
  30937 611.883833     192.168.21.51         192.168.99.100        TCP      [TCP Spurious Retransmission] 45431→cisco-sccp(2000) [SYN] Seq=0 Win=29200 Len=0 MSS=1460 SACK_PERM=1 TSval=377513240 TSecr=0 WS=128
  30938 611.884005     192.168.99.100        192.168.21.51         TCP      [TCP Retransmission] cisco-sccp(2000)→45431 [SYN, ACK] Seq=0 Ack=1 Win=28960 Len=0 MSS=1460 SACK_PERM=1 TSval=381936400 TSecr=377512238 WS=128
  30973 612.884024     192.168.99.100        192.168.21.51         TCP      [TCP Retransmission] cisco-sccp(2000)→45431 [SYN, ACK] Seq=0 Ack=1 Win=28960 Len=0 MSS=1460 SACK_PERM=1 TSval=381937400 TSecr=377512238 WS=128
  30996 613.887453     192.168.21.51         192.168.99.100        TCP      [TCP Spurious Retransmission] 45431→cisco-sccp(2000) [SYN] Seq=0 Win=29200 Len=0 MSS=1460 SACK_PERM=1 TSval=377515244 TSecr=0 WS=128
  30997 613.887564     192.168.99.100        192.168.21.51         TCP      [TCP Retransmission] cisco-sccp(2000)→45431 [SYN, ACK] Seq=0 Ack=1 Win=28960 Len=0 MSS=1460 SACK_PERM=1 TSval=381938404 TSecr=377512238 WS=128
  31123 616.083906     192.168.99.100        192.168.21.51         TCP      [TCP Retransmission] cisco-sccp(2000)→45431 [SYN, ACK] Seq=0 Ack=1 Win=28960 Len=0 MSS=1460 SACK_PERM=1 TSval=381940600 TSecr=377512238 WS=128
  31195 617.395119     192.168.21.51         192.168.99.100        TCP      [TCP Spurious Retransmission] 42551→cisco-sccp(2000) [FIN, PSH, ACK] Seq=2470 Ack=289 Win=30336 Len=2 TSval=377518752 TSecr=381906168
  31196 617.395213     192.168.99.100        192.168.21.51         TCP      [TCP Dup ACK 30858#1] cisco-sccp(2000)→42551 [ACK] Seq=292 Ack=2473 Win=35968 Len=0 TSval=381941911 TSecr=377518752 SLE=2470 SRE=2473
  31197 617.891274     192.168.21.51         192.168.99.100        TCP      [TCP Spurious Retransmission] 45431→cisco-sccp(2000) [SYN] Seq=0 Win=29200 Len=0 MSS=1460 SACK_PERM=1 TSval=377519248 TSecr=0 WS=128
  31198 617.891377     192.168.99.100        192.168.21.51         TCP      [TCP Retransmission] cisco-sccp(2000)→45431 [SYN, ACK] Seq=0 Ack=1 Win=28960 Len=0 MSS=1460 SACK_PERM=1 TSval=381942407 TSecr=377512238 WS=128
  31358 621.211512     192.168.99.100        192.168.21.51         TCP      [TCP Retransmission] cisco-sccp(2000)→42551 [FIN, PSH, ACK] Seq=289 Ack=2473 Win=35968 Len=2 TSval=381945728 TSecr=377518752
  31392 622.484650     192.168.99.100        192.168.21.51         TCP      [TCP Retransmission] cisco-sccp(2000)→45431 [SYN, ACK] Seq=0 Ack=1 Win=28960 Len=0 MSS=1460 SACK_PERM=1 TSval=381947001 TSecr=377512238 WS=128
  31465 625.907246     192.168.21.51         192.168.99.100        TCP      [TCP Spurious Retransmission] 45431→cisco-sccp(2000) [SYN] Seq=0 Win=29200 Len=0 MSS=1460 SACK_PERM=1 TSval=377527264 TSecr=0 WS=128
  31466 625.907346     192.168.99.100        192.168.21.51         TCP      [TCP Retransmission] cisco-sccp(2000)→45431 [SYN, ACK] Seq=0 Ack=1 Win=28960 Len=0 MSS=1460 SACK_PERM=1 TSval=381950423 TSecr=377512238 WS=128
  31847 634.085643     192.168.99.100        192.168.21.51         TCP      [TCP Retransmission] cisco-sccp(2000)→45431 [SYN, ACK] Seq=0 Ack=1 Win=28960 Len=0 MSS=1460 SACK_PERM=1 TSval=381958602 TSecr=377512238 WS=128
  32326 641.938500     192.168.21.51         192.168.99.100        TCP      [TCP Spurious Retransmission] 45431→cisco-sccp(2000) [SYN] Seq=0 Win=29200 Len=0 MSS=1460 SACK_PERM=1 TSval=377543296 TSecr=0 WS=128
  32327 641.938568     192.168.99.100        192.168.21.51         TCP      [TCP Retransmission] cisco-sccp(2000)→45431 [SYN, ACK] Seq=0 Ack=1 Win=28960 Len=0 MSS=1460 SACK_PERM=1 TSval=381966455 TSecr=377512238 WS=128
  32458 643.859279     192.168.21.51         192.168.99.100        TCP      [TCP Spurious Retransmission] 42551→cisco-sccp(2000) [FIN, PSH, ACK] Seq=2470 Ack=289 Win=30336 Len=2 TSval=377545216 TSecr=381906168
  32459 643.859394     192.168.99.100        192.168.21.51         TCP      [TCP Dup ACK 30858#2] cisco-sccp(2000)→42551 [ACK] Seq=292 Ack=2473 Win=35968 Len=0 TSval=381968375 TSecr=377545216 SLE=2470 SRE=2473
  32861 651.099614     192.168.99.100        192.168.21.51         TCP      [TCP Retransmission] cisco-sccp(2000)→42551 [FIN, PSH, ACK] Seq=289 Ack=2473 Win=35968 Len=2 TSval=381975616 TSecr=377545216
  33374 658.088603     192.168.99.100        192.168.21.51         TCP      [TCP Retransmission] cisco-sccp(2000)→45431 [SYN, ACK] Seq=0 Ack=1 Win=28960 Len=0 MSS=1460 SACK_PERM=1 TSval=381982605 TSecr=377512238 WS=128
  34426 674.002725     192.168.21.51         192.168.99.100        TCP      [TCP Spurious Retransmission] 45431→cisco-sccp(2000) [SYN] Seq=0 Win=29200 Len=0 MSS=1460 SACK_PERM=1 TSval=377575360 TSecr=0 WS=128
  34433 674.004602     192.168.99.100        192.168.21.51         TCP      cisco-sccp(2000)→45431 [RST, ACK] Seq=668009898 Ack=1 Win=0 Len=0

A: Everyone I've spoken to agrees that there is "weirdness" in the TCP interactions.
I rewrote my application so that it could talk to multiple simulated clients at the same IP but different ports, and the problem entirely vanished.
So, either macvlan in kernel 3.10.0 is not fit for use in this manner, or I set it up incorrectly. Or both.


text:
Q: Plotting with different color for a single curve How to plot a function $f(x)=\frac{3(4+x)}{3(2-x)-16}$ (say $x \in [-15,15]$ ) with the condition that i want to give different color for each of the following cases
(i) when $\frac{x+4}{3x+10}>0$ and $\frac{x^2+8x+12}{3x+10}>0$
(ii) when $\frac{x+4}{3x+10}>0$ and $\frac{x^2+8x+12}{3x+10}<0$
(iii) when  $\frac{x+4}{3x+10}<0$ and $\frac{x^2+8x+12}{3x+10}>0$

A: Admittedly, not very different from the naïve answer already posted, just avoided repeating the function definitions.
f[x_] := (3 (x + 4))/(3 (2 - x) - 16);

g[x_] := (x + 4)/(3 x + 10);

h[x_] := (x^2 + 8 x + 12)/(3 x + 10);

a[x_] := (g[x] > 0 && h[x] > 0);
b[x_] := (g[x] > 0 && h[x] < 0);
c[x_] := (g[x] < 0 && h[x] > 0);

Plot[{f[x] && a[x], f[x] && b[x], f[x] && c[x]}, {x, -15, 15},
  PlotRange -> {-3, 3}, PlotStyle -> Thickness[.01], Frame -> True,
  Axes -> False]

A: You could use the option ColorFunction with ColorFunctionScaling->False. First your conditions:
cond1[x_] := (x+4)/(3x+10)>0 && (x^2+8x+12)/(3x+10)>0
cond2[x_] := (x+4)/(3x+10)>0 && (x^2+8x+12)/(3x+10)<0
cond3[x_] := (x+4)/(3x+10)<0 && (x^2+8x+12)/(3x+10)>0

And your function:
f[x_] := (3(4+x))/(3(2-x)-16)

Then:
Plot[f[x], {x, -15, 15},
    PlotRange -> {All, {-3, 3}},
    ColorFunctionScaling -> False,
    ColorFunction -> Function @ Piecewise[
        {
        {ColorData[97][1], cond1[#]},
        {ColorData[97][2], cond2[#]},
        {ColorData[97][3], cond3[#]}
        },
        ColorData[97][4]
    ]
]

A: An alternative way to specify a color function:
cf = ColorData[97] @
     (1 + {1, 2}.UnitStep[{(# + 4)/(3 # + 10), (#^2 + 8 # + 12)/(3 # + 10)}]) &;

f[x_] := (3 (4 + x))/(3 (2 - x) - 16)
Plot[f[x], {x, -15, 15},
  PlotRange -> {All, {-3, 3}},
  BaseStyle -> AbsoluteThickness[5],
  ColorFunction -> cf,
  ColorFunctionScaling -> False]

A: Naïve solution:
f1[x_] /; And[(x + 4)/(3 x + 10) > 0, (x^2 + 8 x + 12)/(3 x + 10) > 0] := (3 (4 + x))/(3 (2 - x) - 16)
f2[x_] /; And[(x + 4)/(3 x + 10) > 0, (x^2 + 8 x + 12)/(3 x + 10) < 0] := (3 (4 + x))/(3 (2 - x) - 16)
f3[x_] /; And[(x + 4)/(3 x + 10) < 0, (x^2 + 8 x + 12)/(3 x + 10) > 0] := (3 (4 + x))/(3 (2 - x) - 16)

Plot[{f1[x], f2[x], f3[x]}, {x, -15, 15}, PlotRange -> {All, {-10, 10}}]

redpajama_set_name: RedPajamaStackExchange


text:
Q: Backbone Views and webshims for form values What is the best way to make use of webshims in a backbone project?  Is there  a way to avoid using it globally and only loading it for a specific view?

A: Yes this is possible. But I would always include the modernizr and polyfiller.js in the base setup.
In case you are doing this you should configure at least waitReady and basePath:
webshims.setOptions({ waitReady: false, basePath: "/js/libs/shims/" });

Your code for your view could look like this:
Backbone.View.extend({

  initialize: function(){
    //Load webshims
    webshims.polyfill('forms forms-ext mediaelement');
  },

  render: function() {
    this.$el.html( this.template(this.model.attributes) );
    //update new created elements
    this.$el.updatePolyfill();
    return this;
  }

});

Normally webshims delays jQuery's 'ready' event until all features are implented. In case you want to use webshims only in a specific view you can't delay it. In case you want to use the polyfilled JS/DOM API. You should wrap your JS code, which uses those APIs in a webshims.ready callback:
render: function() {
    var thisObject = this;
    this.$el.html( this.template(this.model.attributes) );
    //update new created elements
    this.$el.updatePolyfill();

    //wait until video API is implemented and then use it
    webshims.ready('mediaelement', function(){
        $('video', thisObject.$el).play();
    });
    return this;
}

In case you want to speed up things, you can load it inside your view and after window.load:
   $(window).on('load', function(){
      //preload after onload
      webshims.polyfill('forms forms-ext mediaelement');
   });

This way webshims is loaded either as soon as the view starts to initialize or after onload. webshims might give you a warning in this case, that you have called it twice, but this won't hurt.


text:
Q: Connect and pass Auth token to a SignalR hub with CORS enabled I have three ASP.NET WebAPI endpoints:

*

*Identity server, which generates bearer tokens (serverA.com);

*SignalR server with hub (serverB.com);

*Some endpoint with a simple ASP.NET MVC view and SignalR JS client script (serverC.com).

All three servers use OAuth2 middleware as Auth mechanism. Microsoft.Owin.Cors is configured as well.
Servers use only HTTPS requests.
SignalR v2.2.0 is installed on serverB.com.
I can successfully make a cross-domain request from serverC.com to serverA.com to get bearer token, but, actually, I don't know how to pass auth token while connecting to serverB.com
There are two ways I found so far:

*

*Pass auth token as a query string (not secure);

*Apply this setting to the jQuery.ajax
$.ajaxSetup({
beforeSend: function (xhr) {
    xhr.setRequestHeader('tokenKey', 'tokenValue');
}});
but it forces SignalR to use long polling only.
Is there any other way to send auth token (not in query string) so it can be consumed and validated by OAauth BearerAuthorizationProvider? Maybe, cookies, headers or any other way?
Update
CORS middleware set up for both environments to allow all data and accept credentials.
Here is my OWIN middleware:
var requestUri = context.Request.Uri.AbsolutePath;
if (string.Equals(requestUri, authRoute, StringComparison.OrdinalIgnoreCase))
{
     if (!context.Request.Headers.ContainsKey("Authorization") || string.IsNullOrEmpty(context.Request.Headers["Authorization"]))
     {
           context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
     }
     else
     {
           context.Response.Cookies.Append("BearerToken", context.Request.Headers["Authorization"]);
     }
  }
  else
  {
      await Next.Invoke(context);
  }

Then I do first Ajax request:
$.ajax({
        url: self.communicationHubUrl + '/authenticate',
        type: 'post',
        cache: false,
        crossDomain: true,
        beforeSend: function(xhr) {
             xhr.setRequestHeader('Authorization', self.accessToken);
       });

middleware sets auth token from header to the response cookies.
Then I call hub.Start so SignalR begins to send ajax requests.
But for some reasons I don't quite understand, cookies are present in request only if I enable xhr.withCredentials = true for ALL ajax requests via $.ajaxSetup
        $.ajaxSetup({
            xhrFields: {
                withCredentials: true
            }
        });

Without this setting request doesn't include cookies. On the other hand, I guess it's not a good decision to force all ajax requests to enable such settings.
Furthermore, I've faced strange behavior in Oauth middleware: ValidateIdentity method is not invoked when request from signalR comes so instead of 401 Unauthorized, I'm getting deafult principal.

A: I think that putting the auth token insied a cookie will be your best bet. Unlike the ajaxSetup option, cookies are sent with EventSource and WebSocket requests.
You might need to add some middleware to the SignalR server (serverB.com) that sets the appropriate cookie when you POST the auth token before starting the SignalR connection.


text:
Q: Singletons in Unity I want to keep my player when switching scenes but without getting lots of copies of it , so I found out about singletons.You do something like this:
public class Player : Monobehaviour
{
   private static Player instance = null;
   void Start()
       {
        if (instance == null)
          {
            instance = this;
            DontDestroyOnLoad(gameobject);
          }
        else
         Destroy(gameobject);

       }
}

And it's pretty hard for me to understand.I get how static variables work , they belong to the class not to the instance.So , first my objects is in scene A.I switch to scene B,a new gameobject will be created with the script Player on it.Now , since instance holds the reference to the gameobject in scene A , why won't the else statement get called and a new gameobject will actually be created?Also , if you could explain a little bit more detailed than unitydoc how DontDestroyOnLoad() works , I'd be thankful.

A: This code runs after the object is created. In fact it runs on a script on the GameObject.  The else statement will run, and it will destroy the GameObject this script is attached to, which is what you want because you already had another copy in the world from previously (the one that is referenced by the "instance" variable).

A: JSchiff is correct that this code will run after an instance of this object is created, storing the current instance in your static variable for unconditional access to "the current instance" or destroying new instances if there is one already. The else branch in your code will run.
To answer your extended question about DontDestroyOnLoad and it's interaction with this static variable: all the objects in the Engine are held in memory by the Engine. A Scene can be thought of as a "collection of objects in memory" by the engine. When a scene is unloaded, all objects in that collection are destroyed, unless the engine has been told DontDestroyOnLoad (as in un-load, although documentation refers to it as a "swap". You can load scenes without unloading scenes, this might have been terminology which just grew outdated but that's conjecture on my part).
These ideas are combined to make your Singleton, a highly accessible (in this case static instance variable), persistent (through DontDestroyOnLoad), one of a kind (through destroying any instance after the first) object. This isn't the only way to apply the Singleton pattern, but it is a common one in Unity.


text:
Q: Hyperref bug with a \def The following very MWE shows the issue, which disappears when the call to hyperref is commented:
\documentclass{article}

\def\n{\textup{\tiny N}}
\def\t{\textup{\tiny T}}

\usepackage{hyperref}

\begin{document}

${}_{\t}$
$_{\t}$
${}_{\t}$
$_\t$

\end{document}

However, it compiles fine when hyperref is called before the two \def.

A: If you use \newcommand instead of \def, you'll clearly see the source of the problem:
! LaTeX Error: Command \t already defined.
               Or name \end... illegal, see p.192 of the manual.

The \t command is defined in the LaTeX Internal Character Representation for the "tie accent" and hyperref assumes this is the meaning of \t. Since it has to do several patches for its working, you end up with \t being essentially redefined to its original meaning, which can be seen if you add \show\t after \begin{document}
> \t=macro:
->\PD1-cmd \t \PD1\t .

Without your redefinition and without hyperref, you'd get
> \t=macro:
->\OML-cmd \t \OML\t .

which is essentially the same (the encoding name may change when \show is used for technical reasons which are beyond the scope of this answer).
Moral: don't use \def if you don't know precisely what you're doing. And never redefine a command with \renewcommand if you don't know precisely about it.


text:
Q: In C#, Is Expression API better than Reflection Nowadays, I'm exploring C# Expression APIs. So I could use some help understanding how it works, including the difference between Expression and Reflection. I also want to understand if Expressions are merely syntactic sugar, or are they indeed better than Reflection performance-wise?
Good examples as well as links to good articles would be appreciated. :-)

A: Regarding calling one method :

*

*Direct call can't be beaten speed-wise.

*Using Expression API is globally similar to using Reflection.Emit or Delegate.CreateDelegate speed-wise (Small differences could be measured; as always optimizing for speed without measurements and goals is useless).
They all generate IL and the framework will compile it to native code at some point. But you still pay the cost of one indirection level for calling the delegate and one method call inside your delegate.
The expression API is more limited, but an order of magnitude simpler to use, as it doesn't require you to learn IL.

*The Dynamic Language Runtime either used directly or via the dynamic keyword of C# 4 add a little overhead but stay near emitting code as it cache most checks related to parameter types, access and the rest.
When used via the dynamic keyword it's also get the neatest syntax as it looks like a normal method call. But if you use dynamic you are limited to method calls while the library is able to do a lot more (See IronPython)

*System.Reflection.MethodInfo.Invoke is slow : in addition to what other methods do it need to check access rights, check arguments count, type, ... against the MethodInfo each time you call the method.

Jon Skeet also get some good points in this answer : Delegate.CreateDelegate vs DynamicMethod vs Expression

Some samples, the same thing done different ways.
You could already see from the line count and complexity which solutions are easy to maintain and which should be avoided from a long term maintenance standpoint.
Most of the samples are pointless but they demonstrate the basic code generation classes / syntaxes of C#, for more info there is always the MSDN
PS: Dump is a LINQPad method.
public class Foo
{
    public string Bar(int value) { return value.ToString(); }
}

void Main()
{
    object foo = new Foo();

    // We have an instance of something and want to call a method with this signature on it :
    // public string Bar(int value);

    Console.WriteLine("Cast and Direct method call");
    {
        var result = ((Foo)foo).Bar(42);
        result.Dump();
    }
    Console.WriteLine("Create a lambda closing on the local scope.");
    {
        // Useless but i'll do it at the end by manual il generation

        Func<int, string> func = i => ((Foo)foo).Bar(i);
        var result = func(42);
        result.Dump();
    }
    Console.WriteLine("Using MethodInfo.Invoke");
    {
        var method = foo.GetType().GetMethod("Bar");
        var result = (string)method.Invoke(foo, new object[] { 42 });
        result.Dump();
    }
    Console.WriteLine("Using the dynamic keyword");
    {
        var dynamicFoo = (dynamic)foo;
        var result = (string)dynamicFoo.Bar(42);
        result.Dump();
    }
    Console.WriteLine("Using CreateDelegate");
    {
        var method = foo.GetType().GetMethod("Bar");
        var func = (Func<int, string>)Delegate.CreateDelegate(typeof(Func<int, string>), foo, method);
        var result = func(42);
        result.Dump();
    }
    Console.WriteLine("Create an expression and compile it to call the delegate on one instance.");
    {
        var method = foo.GetType().GetMethod("Bar");
        var thisParam = Expression.Constant(foo);
        var valueParam = Expression.Parameter(typeof(int), "value");
        var call = Expression.Call(thisParam, method, valueParam);
        var lambda = Expression.Lambda<Func<int, string>>(call, valueParam);
        var func = lambda.Compile();
        var result = func(42);
        result.Dump();
    }
    Console.WriteLine("Create an expression and compile it to a delegate that could be called on any instance.");
    {
        // Note that in this case "Foo" must be known at compile time, obviously in this case you want
        // to do more than call a method, otherwise just call it !
        var type = foo.GetType();
        var method = type.GetMethod("Bar");
        var thisParam = Expression.Parameter(type, "this");
        var valueParam = Expression.Parameter(typeof(int), "value");
        var call = Expression.Call(thisParam, method, valueParam);
        var lambda = Expression.Lambda<Func<Foo, int, string>>(call, thisParam, valueParam);
        var func = lambda.Compile();
        var result = func((Foo)foo, 42);
        result.Dump();
    }
    Console.WriteLine("Create a DynamicMethod and compile it to a delegate that could be called on any instance.");
    {
        // Same thing as the previous expression sample. Foo need to be known at compile time and need
        // to be provided to the delegate.

        var type = foo.GetType();
        var method = type.GetMethod("Bar");

        var dynamicMethod = new DynamicMethod("Bar_", typeof(string), new [] { typeof(Foo), typeof(int) }, true);
        var il = dynamicMethod.GetILGenerator();
        il.DeclareLocal(typeof(string));
        il.Emit(OpCodes.Ldarg_0);
        il.Emit(OpCodes.Ldarg_1);
        il.Emit(OpCodes.Call, method);
        il.Emit(OpCodes.Ret);
        var func = (Func<Foo, int, string>)dynamicMethod.CreateDelegate(typeof(Func<Foo, int, string>));
        var result = func((Foo)foo, 42);
        result.Dump();
    }
    Console.WriteLine("Simulate closure without closures and in a lot more lines...");
    {
        var type = foo.GetType();
        var method = type.GetMethod("Bar");

        // The Foo class must be public for this to work, the "skipVisibility" argument of
        // DynamicMethod.CreateDelegate can't be emulated without breaking the .Net security model.

        var assembly = AppDomain.CurrentDomain.DefineDynamicAssembly(
            new AssemblyName("MyAssembly"), AssemblyBuilderAccess.Run);
        var module = assembly.DefineDynamicModule("MyModule");
        var tb = module.DefineType("MyType", TypeAttributes.Class | TypeAttributes.Public);

        var fooField = tb.DefineField("FooInstance", type, FieldAttributes.Public);
        var barMethod = tb.DefineMethod("Bar_", MethodAttributes.Public, typeof(string), new [] { typeof(int) });
        var il = barMethod.GetILGenerator();
        il.DeclareLocal(typeof(string));
        il.Emit(OpCodes.Ldarg_0); // this
        il.Emit(OpCodes.Ldfld, fooField);
        il.Emit(OpCodes.Ldarg_1); // arg
        il.Emit(OpCodes.Call, method);
        il.Emit(OpCodes.Ret);

        var closureType = tb.CreateType();

        var instance = closureType.GetConstructors().Single().Invoke(new object[0]);

        closureType.GetField(fooField.Name).SetValue(instance, foo);

        var methodOnClosureType = closureType.GetMethod("Bar_");

        var func = (Func<int, string>)Delegate.CreateDelegate(typeof(Func<int, string>), instance,
            closureType.GetMethod("Bar_"));
        var result = func(42);
        result.Dump();
    }
}

A: Reflection does perform slower. For a good article on it see this article.

A: This guy actually measured it.
http://www.palmmedia.de/Blog/2012/2/4/reflection-vs-compiled-expressions-vs-delegates-performance-comparison
In short: compiled expression that is cached to a static var and reused - performs much faster than reflection.


text:
Q: How do you emit generic events in Angular 2+? I'm building a component library in Angular(9). I want to build a button component that takes an event type as a property and then emits that type when the button is clicked.
My understanding of how custom events in Angular work is:
Child declares an EventEmitter
  @Output() buttonClicked = new EventEmitter<Event>();

Parent binds to that event (which you can then respond to)
<my-component (buttonClicked)="buttonClicked($event)"></my-component>

What I'd like to do is something like this. Of course the syntax is wrong, but to give you an idea:
  // custom button class
  @Input() eventType: string;
  @Output() [eventType] = new EventEmitter<Event>();

Any help appreciated.

A: Unfortunately Angular doesn't allow us to use generic types for our @Input or @Output. You of course can write something like @Output() eventType = new EventEmitter<T>();, but there's will not be a chance to pass the <T> to the component's class.
Angular uses AOT (Ahead Of Time) compilation under that hood, so it cannot know what kind of dynamic data you would like to pass inside of the component in the future.
The only thing you can do here it's to use any type:
@Output() eventType = new EventEmitter<any>();


text:
Q: How to execute python script file (filename.py) using sikuli I have a python code (name.py) written in separate file and now I want to execute that code using sikuli.
I have tried
        openApp but its not working
could be possible I did some mistake but still looking for working logic.

A: openApp is for running an application for example: openApp("calc.exe"). Please read about importing python modules. Technically this has nothing to do with Sikuli.

A: Try this:
run(python name.py)

I use similar approach to run my ruby scripts. My problem with it is that it waits for your script to finish, but it shouldn't realy be a problem in 90% of the cases.

A: Do you want to run the file as an executable script or use its contents?
As an executable script make sure that the file is a valid script and will execute something when called and then use suprocess.Popen() from another .py file to execute that file.
To use the module's contents make sure the file is on the PYTHONPATH and use import name and everything within name will now be available for use.


text:
Q: Isekai manga where the protagonist is born the son of a noble or as a prince who wants to become an adventurer The MC is reborn as an aristocrat child or a prince, and when he is five and a half years old, he disguises himself so can go to a guild in to be on an adventure. When he becomes an adventurer, he goes to a forest to search for some medicine plant but meets with an orphan boy, who is attacked by a wolf. He saves him and becomes friends with him, later coming to his home and healing his sister.

A: This is The Child Loved By God, aka Kami ni Aisareta Ko

An old person who had piled up good deeds in Japan reaches the end of his life, and is reincarnated into another world as Lean Olgott, the grandson of a certain king. One day, the boy, who was raised showered with love by his family, noticed that he had been bestowed the title "The Child Loved by God." ...

He reincarnates as a prince at birth. At the age of 6 he goes out and registers as an adventurer - just to gather herbs, but ends up encountering a wolf attacking another child adventurer. He saves him, and ends up going to meet his sister, healing her immediately with a prayer.

Found by searching mangaupdates.com for the tags Adventurer/s and Child protagonist.


text:
Q: Active Directory SSL certificate I already setup wifi AD authorization. When users connect, they see an error that the certificate is self-signed and not trusted. I bought a signed SSL, but I don't know how to feed it to AD.
thanks in advance
i tried replacing the certificate but they are not the same at all


text:
Q: LDAP query that retrieves all the groups to which the user has access I need a LDAP query that retrieves all the groups to which the user has access.
I´m using Java and must properly configure attributes (searchbase, searchFilter and searchCtls) as follows
String searchBase = "OU=Groups,DC=domain,DC=net";
String searchFilter = "(objectClass=*)";
String returnedAtts[] = { "tokenGroups" };
SearchControls searchCtls = new SearchControls();
searchCtls.setSearchScope(SearchControls.OBJECT_SCOPE);
searchCtls.setReturningAttributes(returnedAtts);

NamingEnumeration answer = ctx.search(searchBase, searchFilter, searchCtls);

A: We have defined many LDAP queries for Microsoft Active Directory (Assuming AD by OU=Groups,DC=domain,DC=net).
-jim


text:
Q: How can I design a relational database with words that are all related to each other I'm developing a simple language game about antonyms, synonyms and 'similar speaking' words.
If you play in the 'Synonyms screen', the game will show you two synonyms and two unrelated words and you have to guess wich are the synonyms.
If you play in the 'Antonyms screen', the game will show you two antonyms and two unrelated words and you have to guess wich are the antonyms.
If you play in the 'Speaking screen', the game will show you two 'similar speaking' words, will speak one of each and you have to guess wich is.
My problem is that you can have more than one synonyms, like:
angry: enraged, furious, irated, offended, etc..
love: affection, passion, devotion, etc..
My first idea is something like this one:
Table Synonyms:
+-----------+-------------------+
|   word    |     related       |
+-----------+-------------------+
| angry     |   enraged         |
| angry     |   furious         |
| angry     |   irated          |
| angry     |   offended        |
| enraged   |   furious         |
| enraged   |   irated          |
| enraged   |   offended        |
| furious   |   irated          |
| furious   |   offended        |
| irated    |   offended        |
| love      |   affection       |
| love      |   passion         |
| love      |   devotion        |
| affection |   pasion          |
| ....      |   ....            |
+-----------+-------------------+

And build the antonyms and speaking tables in the same way.
But it seems like a lot of work and it's difficult to add/remove one synonym.
Also, I don't know where I can put the information about how to speak every word. Maybe another table like:
+-----------+-------------------+
|   word    |  pronuciation     |
+-----------+-------------------+
| angry     |   ˈaNGgrē         |
| enraged   |   enˈrājd         |
| ....      |   ....            |
+-----------+-------------------+

A: The associative entity idea is a good way to handle this, but it has a drawback that you might want to consider.
Something that hasn't been addressed in some other answers is how you're going to maintain all of this data. It's going to be a lot of work, particularly if you want to be able to get from one word to any of its synonyms (or antonyms) without knowing which of your words you're starting from.  Consider your example of {angry, enraged, furious, irritated, offended}.  That's a set of five synonyms.  If you used associative entities you'd have these pairs: angry=enraged, angry=furious,... etc. You'd also have to do them the other way around: enraged=angry, furious=angry, and so forth.
Five synonyms isn't a lot.  However, if you make an associative table for 5 synonyms you're going to have 10 entries. For 6 synonyms you'll have 15 and for 7 synonyms you'll have 21. You can see how this might get out of hand.
Alternative: Association via a root
The good news is that there's another way to do this.  If you pick one of your synonyms and make it the base or root word (say in your case "angry") then you can have one record for each of these words in one table (five synonyms = five records, include "angry" in your list of words) and then a second table containing just the roots (for example "angry")
The key (pun intended) is to have the list of words point at their base or root word.  This would be via a foreign key.
So in your word table, you might have something like this:

*

*angry = angry

*enraged = angry

*furious = angry

*irritated = angry

*offended = angry
Now, you might want to use a meaningless numerical key instead of "angry" in the second column in each of the above.  That might make things easier for a variety of practical reasons.  In that case you'd have a second table with just the base words with their meaningless numerical keys, for example:

*

*123, angry

So your word table looks more like this:

*

*angry, 123

*enraged, 123

*furious, 123

*irritated, 123

*offended, 123
So how do you find synonyms for a word?
That's a simple process, but it's a two step* process:

*

*Look up the root key for the given word.  Say you want to find synonyms for "furious". You look it up and find the root is number 123.

*Look for all the words that have the same root key as your word, these are your synonyms.
The advantage of doing it this way is that it saves you a ton of data maintenance. You only have to maintain one record for each word, plus one for each group of synonyms.  That's a lot fewer than combinations of all synonyms, which is what you're looking at if you do this with an associative entity.
*Note: you don't actually have to do this in two steps. You can write a SQL which combines all of this into a single statement using a self join.

A: This is a classic case of where one would choose to use a linking table or Associative Entity in more technical language (also called bridging, joining or mapping tables inter alia). It is a bit unusual in that it requires a self-referencing linking table (which leads to complications re. constraint deferral - see below).
What I would do is something like this (see the fiddle here):
CREATE TABLE word
(
  word_id INTEGER NOT NULL AUTO_INCREMENT,
  the_word   VARCHAR (50) NOT NULL, -- I don't like having tables and columns with the same name
  pronunciation VARCHAR (50), -- allow NULLs for now - you can change it later
  CONSTRAINT word_pk PRIMARY KEY (word_id),
  CONSTRAINT word_the_word_uq UNIQUE (the_word)
    -- no duplicated words!
    -- although this is interesting, what about, say, bear, bear and bear, one is
    -- a large mammal, one is to carry and yet another is to tolerate something.
    -- I leave this up to you! Maybe another field for meaning? UNIQUE (the_word, meaning)?
);

Notice that already, with no programming done, you can constrain your data in all sorts of interesting ways - reducing the possibility of inconsistencies or errors creeping in.
Populate the table:
INSERT INTO word (the_word, pronunciation)
VALUES
('angry', 'ˈaNGgrē'), ('enraged', 'enˈrājd'), ('furious', NULL), ('irated', NULL),
('love', NULL), ('affection', NULL), ('passion', NULL), ('devotion', NULL);

Then:
CREATE TABLE synonym
(
  word_1 INTEGER NOT NULL,
  word_2 INTEGER NOT NULL,
  CONSTRAINT synonyms_not_match_ck CHECK (word_1 != word_2),
  CONSTRAINT synonyn_pk PRIMARY KEY (word_1, word_2),
  CONSTRAINT synonym_w1_fk FOREIGN KEY (word_1) REFERENCES word (word_id),
  CONSTRAINT synonym_w2_fk FOREIGN KEY (word_2) REFERENCES word (word_id)
);

Again, notice how much you can do with no coding.
Populate:
INSERT INTO synonym VALUES
(1, 2), (1, 3), (1, 4),
(2, 1), (2, 3), (2, 4),
(3, 1), (3, 2), (3, 4),
(4, 1), (4, 2), (4, 3);

In the fiddle, I've performed the same procedure for antonyms, but I won't put it here - too long!
To SELECT all the synonyms of 'enraged':
SELECT w.word_id, w.the_word, w.pronunciation
FROM word w
WHERE w.word_id IN
(
  SELECT word_2 FROM synonym
  WHERE word_1 =
  (
    SELECT word_id FROM word WHERE the_word = 'enraged'
  )
);

Result:
word_id the_word    pronunciation
      1    angry          ˈaNGgrē
      3  furious
      4   irated

DELETE the synonyms of 'enraged'
DELETE FROM synonym
WHERE word_1 = (SELECT word_id FROM word WHERE the_word = 'enraged')
OR    word_2 = (SELECT word_id FROM word WHERE the_word = 'enraged');

Check:
SELECT * FROM synonym; -- word_2 = 2 no longer exists, but it still exists in the word table

Result:
word_1  word_2
     3       1
     4       1
     1       3
     4       3
     1       4
     3       4

Then delete all reference to 'enraged' in the word table.
-- this now works because no FKs now point to it
DELETE FROM word where the_word = 'enraged';

And, from the fiddle, it's gone!
You might be better off using PostgreSQL which supports deferred constraints. They don't work on the fiddle for PostgreSQL, but you can experiment in your own environment if you are interested.
In future, please always include your MySQL version - it's important for every server, but particularly so for MySQL now (end 2019) because they have relatively recently introduced sophisticated features such Window functions and Common Table Expressions which not everybody is running, but can be crucial to solve certain problems!
p.s. welcome to the forum!
EDIT!
p.p.s Just for kicks, I tried to get PostgreSQL to do deletes in a single statement using cascading deletes with deferred constraints. I haven't been able to get it running yet, but in the meantime there's a  way of doing it in PostgreSQL that is quite neat.
From here (the accepted answer), in PostgreSQL, a single statement can be made up of several Common Table Expressions - AKA the WITH clause. So, we can do this (see fiddle here):
-- Works as a single statement
-- FROM here: https://stackoverflow.com/questions/50604838/deleting-with-self-referential-foreign-key-in-postgres
WITH cte1 AS
(
  DELETE FROM synonym
  WHERE word_1 = (SELECT word_id FROM word WHERE the_word = 'enraged')
  OR    word_2 = (SELECT word_id FROM word WHERE the_word = 'enraged')
),
cte2 AS
(
  DELETE FROM word WHERE the_word = 'enraged'
)
SELECT COALESCE(NULL, 'CTE succeeded') AS end_of_query;

Result:
end_of_query
CTE succeeded

Belt and braces:
-- Empty set. PostgreSQL really is the dog's!
-- 0 is impossible for word_1
SELECT word_1 AS x, CAST(word_2 AS TEXT) AS y FROM synonym WHERE word_1 = 2 OR word_2 = 2
UNION
SELECT word_id, the_word FROM word WHERE the_word = 'enraged';

Result:
x   y   <<==== Headers
        <<==== Nothing, i.e. empty set, i.e. desired result!

I still think that a single DELETE from word of the 'enraged' should delete all references to it using CASCADE - will try and figure it out tomorrow! MySQL doesn't have DEFERRED constraints and its CTEs won't let you do this either!

A: Schematically:
CREATE TABLE words ( id SERIAL PK,
                     word VARCHAR UNIQUE );

CREATE TABLE relation_type ( id SERIAL PK,
                             relation VARCHAR UNIQUE );

CREATE TABLE relations ( id SERIAL PK,
                         word_id BIGINT FK words (id),
                         related_id BIGINT FK words (id),
                         relation_type BIGINT FK relation_type (id) );


text:
Q: "sync source prob lem: 10278 dbclient error communicating with server" Problem
MONGODB v2.4.8 three node replica set.
"replSetGetStatus" from mgo2 reports:

mgo2 PRIMARY       sync source problem: 10278 dbclient error communicating mgo4
mgo3 SECONDARY     (blank)
mgo4 SECONDARY     (blank)

replSetGetStatus from mgo3 reports:

mgo2 PRIMARY      (blank)
mgo3 SECONDARY       syncing to: mgo2
mgo4 SECONDARY       syncing to: mgo2

replSetGetStatus from mgo4 reports:

mgo2 PRIMARY         (blank)
mgo3 SECONDARY       (blank)
mgo4 SECONDARY      syncing to: mgo2

Note the OPTIME is the same from all nodes for all nodes.
Questions
1) what does the error "sync source problem: 10278 dbclient error communicating mgo4" mean.
2) how do i troubleshoot it?
Thank you
Scott

A: MongoDB replica set members are constantly sending heartbeats (pings) to other members every two seconds. If a heartbeat doesn't return within 10 seconds, the other members mark that member as inaccessible.
The error you are getting is because there was a problem in communication between the primary and the secondary replica set members.
That could have been a temporary network problem or the server experienced a huge load and didn't respond in time.
You should check the logs on your servers to get a better insight about what went wrong.


text:
Q: jquery ajax call -- alternative to using session? I was asked not to use Session anywhere in my code. Currently, I'm authenticating the user to the web services interface and storing the access token (an object) in session and re-using it for subsequent requests. What would be a good place to store it on server-side? I don't want to send it to the client for security reasons.
Here's the code -
 var person;
    $.ajax({
        url: 'Default.aspx/LoadPerson',
        data: JSON.stringify({ id: 1 }),
        type: 'POST',
        contentType: 'application/json;',
        dataType: 'json',
        success: function (result) {
            person = result.d;
        }
    });

My Web service method looks something like this -
    [WebMethod]
    public static Person LoadPerson(int i)
    {
        var person = new Person();
        person.Name = "Bob";
        var userToken = SetupWebserviceUser();
        HttpContext.Current.Session["UserToken"] = userToken();
        // Call web service, get data.
        return person;
    }

A:
What would be a good place to store it on server-side?

There aren't too many options left, if you do not want to store the data in the client or in the seesion.
The only options that I can think of is a DataBase\static variable\ XML file.


text:
Q: Build ExtJS app in Laravel structure I want to build ExtJS (5.1.0) app in Laravel structure.

+project
++public
+++js
++++admin (built extjs app)
++++libs
+++++ext-5.1.0 (framework)
+project
++resources
+++views
++++admin
******index.blade.php

I ran CMD command (in project/public/js path):
sencha -sdk libs\ext-5.1.0 generate app MyApp admin

In app.json i set:
"indexHtmlPath": "../../../resources/views/admin/index.blade.php"

In index.blade.php i set:
<script id="microloader" type="text/javascript" src="/js/admin/bootstrap.js"></script>

After build the generated bootstrap.js contains:
Ext.manifest = Ext.manifest || "../../../public/js/admin/bootstrap.json";

And bootstrap.json has set all paths with "public" expression.
For example:
"Ext.app":"../../../public/js/admin/ext/packages/sencha-core/src/app"

"Ext.browser":"../../../public/js/admin/ext/packages/sencha-core/src/env/Browser.js"

Browser is looking for a
myapp.localhost/public/js/admin/bootstrap.js file, but real path is myapp.localhost/js/admin/bootstrap.js (without "public").
I have no idea how to build the app correctly.


text:
Q: Would a bar chart be a good way to show this type of data? I'm given around 15 data points, which are just numerical values.
The point of the graph is to show that all of these data points are under some maximum threshold. Would a bar chart be a good way to display this, with every bar as a separate data point?

A: I don't know your data, but theoretically it would work. It would be even better if you also plot the line of the maximum threshold to make it even clearer.
If you want a more "advanced" visualization, try some of these to show deviation from this maximum threshold.


text:
Q: What's the define difference between click and scroll events? I have this lack of code:

When i define click like this all ok:
jQuery('#selected-log').on('click', 'div', function() {
    console.log('click');
});

But when i trying to get event on scroll like this nothing happens:
jQuery('#selected-log').on('scroll', 'div', function() {
    console.log('scroll');
});

So is there some major difference between defining click and scroll?

A: Your code for scroll using .on() does not work because scroll event does not bubble up the DOM tree:
http://www.quirksmode.org/dom/events/scroll.html#t03


text:
Q: Positioning button inside leaflet layer control I'm using the leaflet styled layer control plug in to customize my map control.
I'm trying to add a button to the top right corner of my controls that closes the controls (primarily for mobile use).
I found this question and it works, but now I'm wondering how I can position this button. I want it to be in the top right corner of the control.
When I position the class "leaflet-control-close" it works (I tested with "position: relative; float: right;" and it did float right but stayed at the bottom), but if I give it an absolute position at the top of the page it seems to be appear behind my overlays.
I want it to push down the overlays a little bit so that it doesn't overlap.
EDIT: here is a jsfiddle showing what's happening. It's a little convoluted because the styled layer control files don't have a CDN so I just pasted in the CSS and javascript. I made a note where I add the button in the original Javascript, and below that JS is the JS to create the map and overlays.
I know the button on a desktop is kind of annoying because when you close the control with it, it immediately pops back open because your mouse is hovering. In my actual code I've set the display to none if the screen width is larger than tablet size, because that's the only time I feel like I need the button.
I customized the styled layer control javascript in order to include the button:
L.Control.StyledLayerControl = L.Control.Layers.extend({

    onAdd: function(map) {
        this._initLayout();
        this._update();
        this._addButton();

        map
            .on('layeradd', this._onLayerChange, this)
            .on('layerremove', this._onLayerChange, this);

        return this._container;
    },

    _addButton: function () {
      var elements = this._container.getElementsByClassName('leaflet-control-layers-list');
      var button = L.DomUtil.create('button', 'layer-control-close', elements[0]);
      button.innerText = 'Close control';
      L.DomEvent.on(button, 'click', function(e){
        L.DomEvent.stop(e);
        this._collapse();
      }, this);
    }
)};


text:
Q: Ajax request to the same jsp Pardon me if my terminologies are not exact. Here is my situation
1) I want to make an ajax request using a jQuery to the same jsp ( a.jsp)
Meaning a.jsp has the jQuery ajax calling the same a.jsp. Is this possible?
2) A function in my jsp outputs a JSON based on the context of the tool ( Portal).
Can the ajax request be made for this function on the page passing different parameters?
3) The idea is to do something like the "more info" meaning clicking more info will load the same jsp and pass different parameters to the function so that next set of results are fetched. Also I need to filter the results before being displayed.
Anyway I am not sure if I explained correct. Please give me some inputs


text:
Q: Cast exception Error in Delphi XE2 Getting the below Error when trying to assign a string to an AnsiString:

Error 'Implicit string cast with potential data loss from 'string' to
  'AnsiString' in Delphi XE2'

Code:
String1 := IntToStr(instance.CurrentSpeed);
UDPSocket1.Sendln(String1);

A: IntToStr() returns a String.  In Delphi 2009+, String maps to UnicodeString.  However, the TUdpSocket.Sendln() method takes an AnsiString instead.  Since you are passing a UnicodeString to Sendln(), a runtime conversion has to be performed, and converting Unicode data to Ansi is potentially lossy for Unicode characters > $007F.  That is what the compiler is warning you about.  The compiler cannot verify the result of such a conversion at compile-time.
To get rid of the warning, you need to use an explicit type-cast so the compiler knows you understand the risk and have accepted it (which in this case is OK, since IntToStr() returns only ASCII characters that are not lossy when converted to Ansi):
UDPSocket1.Sendln(AnsiString(String1));

A better solution is to stop using the TUdpSocket component in the first place.

*

*The Web.Win.Sockets unit was written back in the Kylix days when Borland was trying to implement its own cross-platform socket code (before ditching the effort and adopting Indy instead). The components in this unit are not written very well.  They cater to a lowest-common-denominator approach to socket APIs across platforms, so they don't have much functionality to them. They don't do error handling very well (if at all).  They are difficult to use in general. Etc.

*the Web.Win.Sockets unit was finally removed in XE6. Embarcadero doesn't support it anymore (and for good reason).
You really should stay away from the components in the Web.Win.Sockets unit altogether.
For instance, Indy 10 ships with Delphi.  It has a TIdUDPClient component that you can use instead, and it fully supports Unicode strings.  For example:
String1 := IntToStr(instance.CurrentSpeed);
// Send() supports an optional byte encoding when converting the string data to bytes
IdUDPClient1.Send('host', port, String1+EOL);

Or:
IdUDPClient1.Host := 'host';
IdUDPClient1.Port := port;
...
String1 := IntToStr(instance.CurrentSpeed);
// Send() supports an optional byte encoding when
// converting the string data to bytes for transmission
IdUDPClient1.Send(String1+EOL);


text:
Q: Error converting PDF to PNG Imagemagick: unable to create temporary file I have written a php script to programmatically create a PNG thumbnail for every PDF in a folder. I use imagemagick to do it, executing the following command:
exec('convert file.pdf[0] file.png');

Everything was working but suddenly I've started to get an error every time I try:

convert: unable to create temporary file file.pdf: ӓ?U|SvU?T???[U @
  error/pdf.c/ReadPDFImage/381. convert: missing an image filename
  file.png @ error/convert.c/ConvertImageCommand/2940.

Of course, I've tried directly in the command line and the same happens.
Any idea?
PS: I´m working with ImageMagick 6.6.0-4

A: I´ve seen that the temp directory is full of files previously created by imagemagick. I don´t know the reason why they are still there. But if i delete them, everything starts to work again.


text:
Q: bootstrap-datepicker to show in full screen I'm using the plugin: https://github.com/uxsolutions/bootstrap-datepicker
JSFiddle DEMO: https://jsfiddle.net/j3b089gr/
I'm showcasing the calendar with the HTML

first column

    <input class="datepicker" data-date-format="dd/mm/yyyy">

and the JS:
$('#datepicker').datepicker();

I would like to show the calendar in full screen but I'm unable to do this. It only shows in the col-7 area. How do I go about this?

A: You're using data-api to generate datepicker in your fiddle, so the js code is not being execute.
(
doc about data api

For most datepickers, simply set data-provide="datepicker" on the element you want to initialize, and it will be intialized lazily, in true bootstrap fashion.
  )

try to generate datepicker using js and add  'container' option, then you can write some custom style to make it full screen:

var widthPerDay = window.innerWidth / 7;
var heightPerDay = window.innerHeight / 6;

$('.datepicker').datepicker({container:'body',orientation:'auto bottom'}).on('show',function(){
$('.dropdown-menu').addClass('overlay'); // to position the datepicker, or just do it here
 $('.datepicker td').css( {"width":widthPerDay,"height":heightPerDay } ); // change the size of day elements to make the datepicker table resize.
  $('.datepicker th').css( {"width":widthPerDay,"height":heightPerDay } );

});
.dropdown-menu.overlay{
  left:0 !important;
}

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.8.0/css/bootstrap-datepicker.min.css" rel="stylesheet"/>

First Column

        <input class="datepicker" data-date-format="dd/mm/yyyy">


text:
Q: How to integrate external librarys (libs) into a grails project? I've a new grails 2.0 project and i want to integrate HtmlUnit-Libraries into it.
I just moved the HtmlUnit 2.9 libs into the "lib"-Folder of my grails project and used them in my grails-service. When i start my application, using intelliJ 11 IDE, it doesn't start because grails can't find the imports.
In my Service class i did:
 import com.gargoylesoftware.htmlunit.WebClient
 import com.gargoylesoftware.htmlunit.BrowserVersion

After starting the grails run-app script, i get the following exception:
/Users/whitenexx/Workspaces/sts-workspace/OMTool/grails-app/services/omtool/TestService.groovy: 4: unable to resolve class com.gargoylesoftware.htmlunit.BrowserVersion
@ line 4, column 1.
import com.gargoylesoftware.htmlunit.BrowserVersion^

How do I integrate java-libraries into an grails project?

A: Instead of copying the jar into the /lib directory, try specifying it in BuildConfig.groovy
grails.project.dependency.resolution = {

    // inherit Grails' default dependencies
    inherits("global") {
        // uncomment to disable ehcache
        // excludes 'ehcache'
    }
    log "error" // log level of Ivy resolver, either 'error', 'warn', 'info', 'debug' or 'verbose'
    checksums true // Whether to verify checksums on resolve

    repositories {
        inherits true // Whether to inherit repository definitions from plugins
        grailsPlugins()
        grailsHome()
        grailsCentral()

        mavenLocal()
        mavenCentral()

    }
    dependencies {
        // specify dependencies here under either 'build', 'compile', 'runtime', 'test' or 'provided' scopes eg.
        compile 'net.sourceforge.htmlunit:htmlunit:2.9'
    }
}

A: Did you add the jars to your buildpath?

A: I encountered the same problem,solved already. specifying it in BuildConfig.groovy.
dependencies {

    compile('net.sourceforge.htmlunit:htmlunit:2.9') {
        excludes 'xml-apis'
    }
}

if not take effect,you can clean your grails ivy-cache first and  try it again.


text:
Q: Importing module from diffrent custome package from the same project.... ModuleNotFoundError I have created 2 diffrent directories(Packages) in my project:
├── Package1
│   ├── __init__.py
│   └── database.py
│   └── crud.py
│   └── models.py
│   └── schemas.py
│   └── main.py
├── Package2
│   ├── __init_.py
│   └── code_file.py

In Package2.code_file.py I have import models from Package1 by adding the below line
from Package1 import models
When I'm trying to run the code_file.py from my CLI using
(venv) systemdetails:~project_location$ python3 Package2/code_file.py
I'm getting an error that states
Traceback (most recent call last):
  File "/project_location/Package2/code_file.py", line 12, in <module>
    from Package1 import models
ModuleNotFoundError: No module named 'Package1'

But when I run the file using the PyCharm => right-click => run 'code_file.py' it runs perfectly.
I'm unable to understand where the problem is...
Can anyone point me in write direction?
I have tried removing init.py in both the Packages.... Did not work


text:
Q: 'command not found' after 'npm test' in express, when i try to implement (cf. jest, supertest, env) I am trying to implement TESTCODE by jest and supertest in express.
but when i type npm test in vsc terminal, it made the following issue:
'.env' file already has private data. So it works when I try to signup and signin, but when i do npm test it made the issue.
I think it might because because jest(?) can't read .env. file properly.
vsc terminal
env-cmd ./.env jest --watch

./.env: line 1: DATABASE_USERNAME: command not found
./.env: line 2: DATABASE_PASSWORD: command not found
./.env: line 3: DATABASE_NAME: command not found
./.env: line 4: DATABASE_HOST: command not found
./.env: line 5: DATABASE_PORT: command not found
npm ERR! Test failed.  See above for more details.

package.json
{
  "name": "server",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "nodemon index.js",
    "test": "env-cmd ./.env jest --watch"
  },
  "jest": {
    "testEnvironment": "node"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "axios": "^0.21.0",
    "body-parser": "^1.19.0",
    "cors": "^2.8.5",
    "dotenv": "^8.2.0",
    "express": "~4.16.1",
    "express-validator": "^6.9.2",
    "i18n": "^0.13.2",
    "i18n-express": "^1.1.3",
    "jsonwebtoken": "^8.5.1",
    "morgan": "^1.10.0",
    "mysql2": "^2.1.0",
    "sequelize": "^6.3.5"
  },
  "devDependencies": {
    "babel-cli": "^6.26.0",
    "babel-preset-env": "^1.7.0",
    "dotenv": "^8.2.0",
    "jest": "^26.6.3",
    "nodemon": "^2.0.6",
    "sequelize-cli": "^6.2.0",
    "superagent": "^6.1.0",
    "supertest": "^6.1.1",
    "env-cmd": "^10.1.0"
  }
}

A: I ran your test script and it worked but make sure:

*

*Enough permission is granted for the project directory, run chmod -R a+rwx /your/project/path

*File structure is correct

*

*project

*

*.env

*package.json

A: Thank you for your advice.
My file structure is
project
    server
        .env
        package.json

First time when I type 'npm test' it made this result
=> spawn ./.env EACCES
So I typed 'chmod -R 777 server/ ', and 'npm test'
Then  it made this result
 > env-cmd ./.env jest --watch

./.env: line 1: DATABASE_USERNAME: command not found
./.env: line 2: DATABASE_PASSWORD: command not found
./.env: line 3: DATABASE_NAME: command not found
./.env: line 4: DATABASE_HOST: command not found
./.env: line 5: DATABASE_PORT: command not found
npm ERR! Test failed.  See above for more details.

Then I typed what you said 'chmod -R a+rwx server/', and 'npm test'
Then it made same result like up thing……….


text:
Q: Is there a way to filter out nested null values within an api - reactjs This is the api
I'm setting it in a state after calling within componentDidMount() with axios. If you take a look at the api some profile_path of the casts are null. Was wondering how can i remove them.
Here's a codesandbox example of my code i'm calling the api in MovieDetails.jsx

A: You can filter them:

const mov = {"id":848278,"cast":[{"adult":false,"gender":0,"id":3148142,"known_for_department":"Acting","name":"Courtney Loggins","original_name":"Courtney Loggins","popularity":1.899,"profile_path":null,"cast_id":2,"character":"Parker Zahn","credit_id":"60e49dde07faa200774ff88a","order":0},{"adult":false,"gender":2,"id":1186714,"known_for_department":"Acting","name":"Ruben Pla","original_name":"Ruben Pla","popularity":3.134,"profile_path":"/iYdAE5VrBd2HKMy0mHcZypsuRXG.jpg","cast_id":3,"character":"Torres","credit_id":"60e49de926dac1002362250b","order":1},{"adult":false,"gender":0,"id":1875337,"known_for_department":"Acting","name":"Tarkan Dospil","original_name":"Tarkan Dospil","popularity":1.15,"profile_path":null,"cast_id":6,"character":"Valentine","credit_id":"60e49e44b76cbb00461768f0","order":2},{"adult":false,"gender":0,"id":1299438,"known_for_department":"Acting","name":"Joston Theney","original_name":"Joston Theney","popularity":0.608,"profile_path":"/btnrSBONyzu7YNerSLhr2W4f9iA.jpg","cast_id":5,"character":"Lindon","credit_id":"60e49e09258823004727e8fa","order":3},{"adult":false,"gender":0,"id":2052540,"known_for_department":"Acting","name":"Antuone Torbert","original_name":"Antuone Torbert","popularity":0.766,"profile_path":null,"cast_id":4,"character":"Blackhawk","credit_id":"60e49df76bdec300460a3fd8","order":4}],"crew":[{"adult":false,"gender":0,"id":117168,"known_for_department":"Directing","name":"Hank Braxtan","original_name":"Hank Braxtan","popularity":1.969,"profile_path":null,"credit_id":"60e49d2aa3b5e6005d8f127e","department":"Directing","job":"Director"},{"adult":false,"gender":0,"id":1346332,"known_for_department":"Writing","name":"Jeffrey Giles","original_name":"Jeffrey Giles","popularity":1.313,"profile_path":null,"credit_id":"6123c736c439c00046280d4e","department":"Writing","job":"Writer"},{"adult":false,"gender":0,"id":2223180,"known_for_department":"Writing","name":"Jacoby Bancroft","original_name":"Jacoby Bancroft","popularity":0.608,"profile_path":null,"credit_id":"6123c723bbcae0002ba28ec9","department":"Writing","job":"Writer"}]}
const result = {...mov}
const temp = result.cast.filter(d => d.profile_path !== null)
result.cast = temp
console.log(result)


text:
Q: Hp Data Protector backup destination command line I'm using Hp DP ver. A.06.11 on HP-UX with 24 slots tape library.
On DP Gui, I'm able to specify backup destination. Is it possible to do it from the command line?
When I type the command
/opt/omni/bin/omnib -datalist "DAILY BACKUP" -mode full -load high

it will always use slot no. 21 but I have different tape for each day.

A: What's going on here is that the tape in slot 21 is in some tape pool (probably something like "Default LTO"). That pool is marked as "Appendable", which means that Data Protector will write to that tape until it is full. Then it will move on to the next-best tape.
The algorithm for choosing the "best" tape is: the tape with the fewest overwrites, and if there's a tie, the tape that was initialised first. If a tape isn't in the library and the pool is not marked as "Strict Allocation", then Data Protector will skip that tape.
A few thoughts:

*

*Usually people want backups written across different tapes each day  because they want to take tapes offsite -- which is a good idea. So take the tape out, and Data Protector will use another tape.

*You could change the pool to being Non-appendable, or Appendable for Incrementals Only.

*You could se the omnimm -move_medium command to take that tape out of the pool that it is in, and put it another. This will mean that that tape is not used for backup any more.
I think you also should be aware that Data Protector 6.1 went out of support many, many years ago, and that you are putting your organisation's backups at risk by continuing to use it. If you are on a support contract, it's a free upgrade to version 9. Then you would be able to ask the HP response centre these kinds of questions.
The sensible upgrade path would be to install Data Protector 9 on a Linux virtual machine to be the new cell manager, and then make this HP-UX box a client of that new cell. I've written about how to do this (and migrate backup history to it) in my book
http://store.data-protector.net/products/migrating-cloning-and-obsoleting-hp-data-protector-cell-managers


text:
Q: When i try to show dialog box it gives me FORCE CLOSE error Here is the code to show my dialog box activity. Whenever i try to open this intent my app get force close.so please tell me the mistakes in my code.And here is the logcat.

03-28 12:11:36.851: E/AndroidRuntime(681): FATAL EXCEPTION: main 03-28
  12:11:36.851: E/AndroidRuntime(681): java.lang.RuntimeException:
  Unable to start activity
  ComponentInfo{com.neelrazin.noteit/com.neelrazin.noteit.Password}:
  java.lang.NullPointerException 03-28 12:11:36.851:
  E/AndroidRuntime(681):    at
  android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
  03-28 12:11:36.851: E/AndroidRuntime(681):    at
  android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
  03-28 12:11:36.851: E/AndroidRuntime(681):    at
  android.app.ActivityThread.access$1500(ActivityThread.java:117) 03-28
  12:11:36.851: E/AndroidRuntime(681):  at
  android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
  03-28 12:11:36.851: E/AndroidRuntime(681):    at
  android.os.Handler.dispatchMessage(Handler.java:99) 03-28
  12:11:36.851: E/AndroidRuntime(681):  at
  android.os.Looper.loop(Looper.java:123) 03-28 12:11:36.851:
  E/AndroidRuntime(681):    at
  android.app.ActivityThread.main(ActivityThread.java:3683) 03-28
  12:11:36.851: E/AndroidRuntime(681):  at
  java.lang.reflect.Method.invokeNative(Native Method) 03-28
  12:11:36.851: E/AndroidRuntime(681):  at
  java.lang.reflect.Method.invoke(Method.java:507) 03-28 12:11:36.851:
  E/AndroidRuntime(681):    at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
  03-28 12:11:36.851: E/AndroidRuntime(681):    at
  com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597) 03-28
  12:11:36.851: E/AndroidRuntime(681):  at
  dalvik.system.NativeStart.main(Native Method) 03-28 12:11:36.851:
  E/AndroidRuntime(681): Caused by: java.lang.NullPointerException 03-28
  12:11:36.851: E/AndroidRuntime(681):  at
  com.neelrazin.noteit.Password.onCreate(Password.java:57) 03-28
  12:11:36.851: E/AndroidRuntime(681):  at
  android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
  03-28 12:11:36.851: E/AndroidRuntime(681):    at
  android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)

public class Password extends Activity {

    final Context context = this;
     public Long mRowId;
     private NotesDbAdapter mDbHelper;
     String password;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.password);

        mRowId = (savedInstanceState == null) ? null :
            (Long) savedInstanceState.getSerializable(NotesDbAdapter.KEY_ROWID);
        if (mRowId == null) {
            Bundle extras = getIntent().getExtras();
            mRowId = extras != null ? extras.getLong(NotesDbAdapter.KEY_ROWID)
                                    : null;
        }

         mDbHelper = new NotesDbAdapter(this);
            mDbHelper.open();
          Cursor notesC = mDbHelper. fetchNote( mRowId);
            startManagingCursor(notesC);
            final String pass = notesC.getString( notesC.getColumnIndex("passw") );

         // custom dialog
            final Dialog dialog = new Dialog(context);
            dialog.setContentView(R.layout.password);
            dialog.setTitle("Enter Password");

            final EditText enterpass = (EditText) dialog.findViewById(R.id.edtext);

            Button ok=(Button)findViewById(R.id.dialogButtonOK);
            ok.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    password= enterpass.getText().toString();
                    if(password.equals(pass.toString())){

                        Intent i= new Intent(getBaseContext(),NoteEditor.class);
                          i.putExtra(NotesDbAdapter.KEY_ROWID,mRowId);
                            startActivity(i);
                    }

                }
            });

            Button dialogButton = (Button)          dialog.findViewById(R.id.dialogButtonCANCEL);
            dialogButton.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    dialog.dismiss();
                }
            });
            dialog.show();
    }

A: In Here :
Button ok=(Button)findViewById(R.id.dialogButtonOK);//<<

you forget to call setContentView for Activity before accessing Views from it. set layout for Activity in onCreate of Activity as :
@Override
  protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main); //<<<
   .....

or if dialogButtonOK button is inside Dialog then use Dialog instance to initialize ok button as :
Button ok=(Button)dialog.findViewById(R.id.dialogButtonOK);

A: Seem error on Buttonok because initialization is done in a wrong way,
This way!:

Button ok=(Button)dialog.findViewById(R.id.dialogButtonOK);

Instead:

Button ok=(Button)findViewById(R.id.dialogButtonOK);


text:
Q: Django: render template based on request data with class-based views What I am trying to do:
generate page with some default input date values and generate some data based on those values.
When new data values are chosen, we generate updated data.
I am using class-based views considering structure of application which I would like to extend.
What is not working:
templates are rendered, but I can't get dynamically values of 'start' and 'end' to generate updated the data.
My question:
Is such structure correct and logical in terms of Django standard practices? Can you please point out where my code is incorrect?
My question is related to this topic. But I would like to keep all logic in the views.
Thank you very much.
Here is a bit simplified code:
index.html
   {% extends "base.html" %}
   {% block main %}
        {% include "_usage.html" %}
        {{ generated_data }}
        {{ table.render }}
    {% endblock %}

_usage.html

    From: <input id="id_start" name="start" type="text" value="{{ start }}">
    To: <input id="id_end" name="end" type="text" value="{{ end }}"
    <button class="name" type="submit">Submit</button>

urls.py
urlpatterns = patterns('',
    url(r'^$', GenericView.as_view(), name='index'),
)

views.py
from django.views.generic.base import View
from django.template.response import TemplateResponse

class UsageView(View):
    template_name = '_usage.html'
    default_start = '2014-01-01'
    default_end = '2014-01-02'

    def get(self, request):
        data_dict = {'start': self.default_start, 'end': self.default_end}
        response = TemplateResponse(request, self.template_name, data_dict)
        return response

class GenericView(UsageView):
    template_name = 'index.html'

    def get(self, request):
        super(GenericView, self).get(request)

        start_value = request.GET['start']
        end_value = request.GET['end']
        values = '1, 2, 3'

        data_dict = {'start': start_value, 'end': end_value, 'generated_data': values}

        response = TemplateResponse(request, self.template_name, data_dict)
        return response

A: There are a number of things wrong here.
Firstly, your super call in GenericView is pointless - you call the super function, but then throw the result away. But you couldn't actually do anything with that return value anyway, because it is returning a rendered response, rather than context values which you could then use to render the template.
Rather than subclassing View and overriding get, you should be overriding TemplateView and overriding get_context_data: then your method can simply be concerned with setting the relevant values, and the view itself will take care of rendering the template.
Secondly, you don't have an actual form element in _usage.html. That means the submit button won't do anything, so you won't ever receive your field values in request.GET. You need to wrap the fields with <form action="." method="GET"> ... </form>.


text:
Q: Bulk loading (BULK Insert) with multiple amounts of whitespace I'm trying to import a TXT file using the BULK INSERT function using SQL Server.
The data in the text file appears as such:
XDB          XDB_XTABNMSP        FLAGS        NUMBER       6
XDB          XDB_INDEX_DDL_CACHE       ROOT_TABLE_NAME       VARCHAR2       1
XDB          XDB_INDEX_DDL_CACHE       ROOT_TABLE_OWNER       VARCHAR2       2

All the values are separated by a "variable" amount of whitespaces. It could be separated by 5 spaces, sometimes 8 spaces, etc.
The code I'm using is as follows:
BULK INSERT MyTableName
FROM 'D:\MyTXTFileName.txt'
WITH (

  FIELDTERMINATOR = ' '
, ROWTERMINATOR = '\n'
, FIRSTROW=2
)

How can I set the column delimiter (FIELDTERMINATOR) so that it separates the values on ANY amount of whitespace?
Expected Result:
XDB XDB_XTABNMSP        FLAGS               NUMBER     6
XDB XDB_INDEX_DDL_CACHE ROOT_TABLE_NAME     VARCHAR2   1
XDB XDB_INDEX_DDL_CACHE ROOT_TABLE_OWNER    VARCHAR2   2


text:
Q: Flutter how to check if a debugger is attached to the application Security team wants me to use preventive techniques to prevent the debugger from connecting to the application.
For Android, it can be done using the isDebuggerConnected method of the android.os.Debug class.
For iOS, the use of PT_DENY_ATTACH can be implemented, which ensures that no debugger can be attached to the process called "ptrace".
The purpose is to terminate the application in case it is detected if there is a debugger attached to the application.
What I have tried, and I'm not really sure if its the right way to do it, is the following:
At least for Android, in the MainActivity file:
import io.flutter.embedding.android.FlutterActivity
import android.os.Debug
import android.util.Log

class MainActivity: FlutterActivity() {
    override fun onResume() {
        super.onResume()
        Log.i("Kotlin lifeCycle", "onResume")
        val isBeingDebugged: Boolean = android.os.Debug.isDebuggerConnected()
        Log.i("Kotlin lifeCycle onResume", "isBeingDebugged: " + isBeingDebugged)
    }
}

however I always get: isBeingDebugged: false
I have tried onCreate, onResume, lifecycle methods but these don't always get executed.
Is there a way to use this "android.os.Debug" class and its methods inside the Dart classes to do this check in a more controlled way?


text:
Q: Routing of incoming calls by called number I have two phone numbers registered with the same sip provider.  I would like Asterisk/PJSIP to route phone #1 (18005551212) differently than phone #2 (18005551313).
[sipprovider-18005551212]
type=registration
client_uri=sip:18005551212@sip.provider.com:5060

[sipprovider-18005551313]
type=registration
client_uri=sip:18005551313@sip.provider.com:5060

The Contact provided by Asterisk during registration is the same for both (using default extension 's').
Contact: <sip:s@10.1.1.1:5060>;expires=120

Can I do any of the following:
1)  When registering, provide an extension other than 's'?  Allowing inbound calls to hit unique extensions in the dialplan.
2) Route to unique context based on the To: Header on the INVITE?  (which holds the unique phone number called).  I have tried using 'context=' in the pjsip.conf endpoint block, but no luck; routing is either by IP (which is the same for both phone numbers), or by name (which is based on the From: Header).
Any help or pointers would be appreciated.

A: You could try this from my extensions.conf
[inbound-sip]
exten => 3215445,1,Goto(sip-in-1,s,1)
exten => 2544221,1,Goto(sip-in-2,s,1)

[sip-in-1]
exten => s,1,Goto(internal-ext,6881,1)

Calls then end up in the relevant context for further processing and alerting etc. sip-in-1 or sip-in-2 in this case.
In your sip.conf or pjsip.conf you need to specify the inbound context for both numbers you have - in this case context = inbound-sip

A: You should enable sip debug and see if calls have anything like destination number.
If it have no - you have no way get info which not present.
If you have, you should create extension s and parse number info using SIP_HEADER function from sip request body.


text:
Q: Excel "From xml data import" won't add new columns Excel 2010 has a fabulous feature under Data->"From Other Sources"->"From XML Data Import" to pull in XML from a web service, no coding required. Works great, but my service has now added a new column at the end. Refreshing the connection in Excel does not add the new column. In fact, creating a second connection to the exact same URL in the same spreadsheet won't show the new column, either (although doing the same thing on a different excel workbook will). Apparently, Excel is caching the columns somehow.
I found this link which describes a possible workaround by manually hacking the excel file; but that was 3 years ago. Surely, there's a better way now.
Any advice? You can replicate this by just saving the following XML as a text file, importing it to Excel, then editing the file and adding a new column.
<Table>
    <Row>
        <First>1</First>
        <Second>2</Second>
    </Row>
    <Row>
        <First>3</First>
        <Second>4</Second>
    </Row>
</Table>

A: Options:

*

*Excel 2010 Developer tab (see question Excel Add A Field To An Xml Map) (search)

*Excel 2007 (maybe others) A solution appears to have been developed using VBA in the forum
post: XML Question - Update Schema/Mapping (archive)(archive of the Programatically using XML Mapping Feature page that post references).  The VBA code is included below.

*Excel 2003 XML Toolbox for Excel 2003

*ALL: Workaround provided below which does not disturb formulas.

I have not tried the VBA code from the linked forum post and included below. I hope it works for you. However, the workaround below appears to be easy and non-disruptive to formulas referencing data inside the mapping.  Thus, I would use that, unless it does not work for you or if your mapping is complex, or you expect to need to semi-automatically update multiple times (although the workaround below takes very little time an effort).
There does not appear to be an official solution for Excel 2007. There appears to be two separate official solutions: one for Excel 2003 (add-on), and one for Excel 2010 (Developer tab).
The question Excel Add A Field To An Xml Map offered three methods which might work.

*

*The first was the XML Toolbox for Excel 2003 which can do this
in Excel 2003. A comment to that solution indicated that it has some
issues/problems and may, or may not, be functional for you. You may
have to use an older version on Excel, or even an older operating
system.

*The second is the "edit the .xls file" method.

*The third is to use the Excel 2010 Developer tab.

Additional options:

*

*Workaround provided below (probably my choice for simple one-off updates which are not expected to repeat and the mapping is simple).

*Save the worksheet as a XML Spreadsheet. Edit the schema recorded at the end of the file.  Given that it is XML it is entirely in text.  The schema is easy to understand. Adding a column is as simple as just copy and pasting (with modifications) a few lines of XML text.  If using this methd, it is probably easiest to make a duplicate of your worksheet, delete and re-create the map and mapping then cut and paste.  Example XML:

(SO-formatting required blank text)
<x2:Field x2:ID="Add-E-head">
 <x2:Range>RC[4]</x2:Range>
 <x2:XPath>Add-E-head</x2:XPath>
 <x2:XSDType>string</x2:XSDType>
 <ss:Cell>
 </ss:Cell>
 <x2:Aggregate>None</x2:Aggregate>
</x2:Field>

Workaround: [added/inserted/deleted column(s)] (easy for simple mappings, e.g. one large table):

*

*Make a backup copy of your worksheet.

*Delete the XML map. Not the mapping in the sheet. Just the XML map.

*Re-create the map. It will now have the new XML schema.

*If you have formula/data which would be overwritten by additional columns: Insert enough columns immediately to the right of the current area on the sheet which contains the XML mapped data.

*If there are any columns which have been inserted in between older columns then Insert a column in the sheet where they will go. Yes, this is right in the XML mapped data area and a generic column name will be temporarily assigned.

*Delete any columns which do not exist in the new XML.

*Drag-and-drop the elements from the newly mapped table to the top left corner of the current mapping (or otherwise recreate the mapping on the sheet directly over the mapping which you have not deleted).

*Manually change any headings that were updated (if your data was marked as having headings).

*Repeat steps 4 through 8 for all separate mappings you have in your workbook. Usually I just have one large mapping into which I reference as opposed to multiple small mappings.

*Refresh your XML data.

Your formulas should not have changed, and cell references into the XML mapped data should remain correct. For verification that you inserted any columns in step 3 correctly, you can, prior to making any other changes (i.e. at step 1a) create a row above the XML mapping and copy and paste just the values from the top row.  When you refresh the XML data in step 10 you can verify that the old row headings match the new placement.
Note: Steps 3 and 4 can alternately be done by making a more complicated mapping of the XML elements. I find it easier to just insert columns and keep a 1-1 correspondence with the XMl elements.
This worked on my machine through multiple trials and left the formulas referencing the area as correct. A file where you can experiment, called SO-XML mapping.xml is included in the example file linked below (and here)
Accounting for generic column changes in some data table obtained from a source (or using multiple sources interchangeably):
There are times when the data that you have is not dynamically provided by something like an XML map, or when you don't want to have to be fussy about remembering to account for inserted columns. The brute force workaround of accomplishing this is to create your own mapping of the data columns into a table(sheet) in your worksheet within which you control the column locations. You can do this by creating a table which indirectly references the data which you have imported/copied into a different sheet. using an indirect mapping like this can also be used to easily switch between two, or more, different data sets as input to whatever formulas you have set up.
The indirect mapping uses INDIRECT() to reference the the sheet containing the source data. All of your formulas then point to this indirect sheet instead of the source data. The contents of the columns in the indirect sheet are organized in fixed locations with the data pulled in from a column in the source data that matches the column heading specified. Then if a change is made to the organization of the columns within the source data you can just either create a new sheet with the alternately formatted data, or place it in the sheet where the original data used to be and change the column headings you are using for referencing. If switching between multiple data sets, you can then change the source data used completely by changing one cell.
This indirect mapping sheet allows the columns in your formulas (outside of the indirect sheet) to be fixed instead of having to worry about the possible reorganization of your source data.  Alternately, it permits you to have two, or more, data sets which are automatically converted into the same column organization when you switch between them. You can accomplish this even if the data sets have different headers used for the same actual data (just have a line of headers which is used when the alternate set(s) of data is(are) selected).
This is probably easier to show than to explain in a post like this. Thus, here is an example which selects data from five different sheets.
In that example, all your formulas would then reference the Indirect page. The example assumes all files are placed in the C:\ directory. Unfortunately, using XML mappings required a complete file path and C:\ is the highest probability location to exist on most machines running Excel.
VBA code from KMKfan on Nov 16th, 2009:
Posted in XML Question - Update Schema/Mapping (archive)(archive of the Programatically using XML Mapping Feature page that post references).
The comment in the post were:

Here is an update for this code. This code allows for multiple XML
  maps to update within the same workbook as long as the xsd and xml map
  have the same name (ie: the source map "MyMap" is based on MyMap.xsd.
  Should be very helpful if you are using XML to assist in reporting and
  decide to add a piece of data to capture. You can update the existing
  mapping automatically and only have to manually update the new data
  elements.

Dim r, c As Integer
Dim wb1, wb2 As Workbook
Dim StrMap, StrWS, StrRng, StrXPath As String
Dim nStrWS, nStrRng, nStrXPath As String
Dim nStrMap As XmlMap

Sub Update_XML()
    Call Get_XPath
    Call Add_NewMap
    Call Assign_Elements
End Sub

Sub Get_XPath()
'Gets Available XML Mappings (XPath) for current workbook and sends the text information to a temp file.
Set wb1 = ThisWorkbook
Set wb2 = Workbooks.Add
wb1.Activate
For Each Sheet In wb1.Sheets
Sheet.Select
    Range("A1").Select
    Selection.UnMerge
    For c = 1 To ActiveSheet.UsedRange.Columns.Count
        For r = 1 To ActiveSheet.UsedRange.Rows.Count
            If ActiveCell.Offset(r - 1, c - 1).XPath <> "" Then Call Send_XPath
            wb1.Activate
        Next r
    Next c
    Selection.Merge
Next Sheet

End Sub

Sub Send_XPath()
'Sends text information to a temporary workbook for use later.
    StrWS = ActiveSheet.Name
    StrRng = ActiveCell.Offset(r - 1, c - 1).Address
    StrXPath = ActiveCell.Offset(r - 1, c - 1).XPath
    StrMap = ActiveCell.Offset(r - 1, c - 1).XPath.Map.Name
    With wb2
        .Activate
        ActiveCell = StrMap
        ActiveCell.Offset(0, 1) = StrWS
        ActiveCell.Offset(0, 2) = StrRng
        ActiveCell.Offset(0, 3) = StrXPath
        ActiveCell.Offset(1, 0).Select
    End With
End Sub

Sub Add_NewMap()
'Delete the current XML map and add a new XML Map that has the same schema structure.
'XML Map and XSD schema must be named identically.  Only the .xsd extension should be different.
Dim MyPath, MyMap As String
MyPath = 'Path of .xsd file goes here
    For Each XmlMap In wb1.XmlMaps
        MyMap = XmlMap.Name
        wb1.XmlMaps(XmlMap.Name).Delete
        wb1.XmlMaps.Add(MyPath & "\" & MyMap & ".xsd").Name = MyMap
    Next XmlMap
End Sub

Sub Assign_Elements()
'Assign XPath of new XML Map to ranges based on the information in the temp workbook.  Close 2nd workbook w/o saving.
With wb2
    .Activate
    Application.Goto Range("$A$1")
End With
Do Until ActiveCell = ""
    Set nStrMap = wb1.XmlMaps(ActiveCell.Text)
    nStrWS = ActiveCell.Offset(0, 1)
    nStrRng = ActiveCell.Offset(0, 2)
    nStrXPath = ActiveCell.Offset(0, 3)
    With wb1
        .Activate
        Sheets(nStrWS).Select
        Range(nStrRng).XPath.SetValue nStrMap, nStrXPath
    End With
        wb2.Activate
        ActiveCell.Offset(1, 0).Select
Loop
    wb2.Close False
End Sub

A: Try this:
Highlight your imported data, and delete the rows they populate. Then, select the cell you want to insert the data and recreate the connection by going to Data -> From XML Data Import. When it recreates the connection, it should add your extra column. (If you try to refresh on top of the data table that's currently there, it won't append your column.)


text:
Q: setting path and alias to a particular python and pip version I have some python installations on my mac with M1 chip.
From the terminal, my situation is as follows:
LT-ichinen ~ % which python
python not found
LT-ichinen ~ % which python3
/opt/homebrew/bin/python3
LT-ichinen ~ % which pip
/usr/local/bin/pip
LT-ichinen ~ % which pip3
/opt/homebrew/bin/pip3

There are 2 goals here:

*

*I want python to point to python3

*I want pip to pip3 (i.e. /opt/homebrew/bin/pip3 instead of /usr/local/bin/pip).

I watched the following (https://www.youtube.com/watch?v=PUIE7CPANfo), and edited the .bash_profile as follows:
PATH="/opt/homebrew/bin:$PATH"
export PATH

alias python=python3
alias pip=pip3

I still get the same output as above (even after restarting the terminal and the whole computer).
I then looked for other Q&A, and trialed doing source ~/.bash_profile. I did get the behavior I wanted, but it does not last to the next time I restart the computer: If I restart the computer, and run source ~/.bash_profile, I do get the wanted behavior.
Question:
As far as I understood, the terminal should open ~/.bash_profile at each login, which for whatever reasons (maybe due to M1 chip, but this is only a guess) it is not doing. How can I get the wanted behavior without typing source ~/.bash_profile each time?