text:
Q: Linux split access (multiple internet connections w/ load balancing) Short story: I've got a faulty cisco 1811 on my hands. It's a dual wan fixed configuration router. I had it setup with route maps to do load balancing.
It works but every couple of hours it shits itself and needs rebooting. I need to take it out of it's current position on the network.
So what I've done (for temporary purposes) is built up a new box, installed debian, iproute2 and configured iptables.
I've got two internet connections, both on separate phone lines, both to separate linksys routers. The routers are in bridged mode.
The new box has 3 NICS (2 nics for connecting to each router in bridge mode) and one for internal network.
I've used pppoeconf to setup two new pppoe connections. That all works.
It seems to work when only one connection is up, but not when both are up. I have a feeling that it doesn't know which interface to process the packet on.
I've read many documents about split access and load balancing but I can't get it working.
gateway:~# ifconfig -a
eth1      Link encap:Ethernet  HWaddr 00:24:8c:4e:31:e7
         inet addr:192.168.5.254  Bcast:192.168.5.255  Mask:255.255.255.0
         inet6 addr: fe80::224:8cff:fe4e:31e7/64 Scope:Link
         UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
         RX packets:3494 errors:0 dropped:0 overruns:0 frame:0
         TX packets:3553 errors:0 dropped:0 overruns:0 carrier:1
         collisions:0 txqueuelen:1000
         RX bytes:633209 (618.3 KiB)  TX bytes:1668656 (1.5 MiB)
         Interrupt:219

eth2      Link encap:Ethernet  HWaddr 00:40:f4:ba:c4:41
         inet addr:192.168.1.2  Bcast:192.168.1.255  Mask:255.255.255.0
         inet6 addr: fe80::240:f4ff:feba:c441/64 Scope:Link
         UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
         RX packets:365 errors:0 dropped:0 overruns:0 frame:0
         TX packets:377 errors:0 dropped:0 overruns:0 carrier:0
         collisions:0 txqueuelen:1000
         RX bytes:57190 (55.8 KiB)  TX bytes:85824 (83.8 KiB)
         Interrupt:16 Base address:0xe800

eth3      Link encap:Ethernet  HWaddr 00:60:67:72:40:42
         inet addr:192.168.1.1  Bcast:192.168.1.255  Mask:255.255.255.0
         inet6 addr: fe80::260:67ff:fe72:4042/64 Scope:Link
         UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
         RX packets:2287 errors:0 dropped:0 overruns:0 frame:0
         TX packets:1971 errors:0 dropped:0 overruns:0 carrier:0
         collisions:0 txqueuelen:1000
         RX bytes:1414715 (1.3 MiB)  TX bytes:425185 (415.2 KiB)
         Interrupt:17 Base address:0xe400

lo        Link encap:Local Loopback
         inet addr:127.0.0.1  Mask:255.0.0.0
         inet6 addr: ::1/128 Scope:Host
         UP LOOPBACK RUNNING  MTU:16436  Metric:1
         RX packets:150 errors:0 dropped:0 overruns:0 frame:0
         TX packets:150 errors:0 dropped:0 overruns:0 carrier:0
         collisions:0 txqueuelen:0
         RX bytes:15596 (15.2 KiB)  TX bytes:15596 (15.2 KiB)

ppp0      Link encap:Point-to-Point Protocol
         inet addr:150.101.177.X  P-t-P:150.101.180.24  Mask:255.255.255.255
         UP POINTOPOINT RUNNING NOARP MULTICAST  MTU:1492  Metric:1
         RX packets:1955 errors:0 dropped:0 overruns:0 frame:0
         TX packets:1446 errors:0 dropped:0 overruns:0 carrier:0
         collisions:0 txqueuelen:3
         RX bytes:1344970 (1.2 MiB)  TX bytes:353725 (345.4 KiB)

ppp1      Link encap:Point-to-Point Protocol
         inet addr:150.101.179.X  P-t-P:150.101.180.143  Mask:255.255.255.255
         UP POINTOPOINT RUNNING NOARP MULTICAST  MTU:1492  Metric:1
         RX packets:28 errors:0 dropped:0 overruns:0 frame:0
         TX packets:37 errors:0 dropped:0 overruns:0 carrier:0
         collisions:0 txqueuelen:3
         RX bytes:6691 (6.5 KiB)  TX bytes:10285 (10.0 KiB)

I can dial both connections and they both answer and authenticate successfully.
gateway:~# cat /etc/network/interfaces
# This file describes the network interfaces available on your system
# and how to activate them. For more information, see interfaces(5).

# The loopback network interface
auto lo
iface lo inet loopback

# The primary network interface
allow-hotplug eth1
iface eth1 inet static
address 192.168.5.254
netmask 255.255.255.0
broadcast 192.168.5.255

auto eth3
allow-hotplug eth3
iface eth3 inet dhcp

auto eth2
allow-hotplug eth2
iface eth2 inet dhcp

auto dsl-provider1
iface dsl-provider1 inet ppp
pre-up /sbin/ifconfig eth3 up # line maintained by pppoeconf
#post-up ip route add 150.101.180.143 dev eth1 src 150.101.179.X table T2
#post-up ip route add default via 150.101.180.143 table T2
#post-up ip rule add from 150.101.179.X table T2
#post-down ip rule del from 150.101.179.X table T2
provider dsl-provider1

auto dsl-provider
iface dsl-provider inet ppp
pre-up /sbin/ifconfig eth2 up # line maintained by pppoeconf
#post-up ip route add 150.101.180.24 dev eth2 src 150.101.177.X table T1
#post-up ip route add default via 150.101.180.24 table T1
#post-up ip rule add from 150.101.177.X table T1
#post-down ip rule del from 150.101.177.X table T1
provider dsl-provider

gateway:~#

As you can see above I've commented out the post-up's and down's to set the ip routes
Should I be using ethX as the dev in ip route commands? or should it be pppX?
I also note that when any interface changes, the ip routes are refreshed and changes lost.
And here is my rt_tables file.
gateway:~# cat /etc/iproute2/rt_tables
#
# reserved values
#
255     local
254     main
253     default
0       unspec
#
# local
#
#1      inr.ruhep
200     uplink1
201     uplink2

100     T1
101     T2
gateway:~#

This is my ip tables script. I know it needs changing, (especially the default rules) but that aside: -
It works after one connection is up, and
#!/bin/sh
INTIF="eth1"

EXTIF="ppp0"
EXTIF2="ppp1"

EXTIP="`/sbin/ifconfig ppp0 | grep 'inet addr' | awk '{print $2}' | sed -e 's/.*://'`"
EXTIP2="`/sbin/ifconfig ppp1 | grep 'inet addr' | awk '{print $2}' | sed -e 's/.*://'`"

/sbin/depmod -a
/sbin/modprobe ip_tables
/sbin/modprobe ip_conntrack
/sbin/modprobe ip_conntrack_ftp
/sbin/modprobe ip_conntrack_irc
/sbin/modprobe iptable_nat
/sbin/modprobe ip_nat_ftp
echo "1" > /proc/sys/net/ipv4/ip_forward
echo "1" > /proc/sys/net/ipv4/ip_dynaddr
iptables -P INPUT ACCEPT
iptables -F INPUT
iptables -P OUTPUT ACCEPT
iptables -F OUTPUT
iptables -P FORWARD DROP
iptables -F FORWARD
iptables -t nat -F

iptables -A FORWARD -i $EXTIF -o $INTIF -m state --state ESTABLISHED,RELATED -j ACCEPT
iptables -A FORWARD -i $INTIF -o $EXTIF -j ACCEPT
iptables -t nat -A POSTROUTING -o $EXTIF -j MASQUERADE

iptables -A FORWARD -i $EXTIF2 -o $INTIF -m state --state ESTABLISHED,RELATED -j ACCEPT
iptables -A FORWARD -i $INTIF -o $EXTIF2 -j ACCEPT
iptables -t nat -A POSTROUTING -o $EXTIF2 -j MASQUERADE

#Transparent Proxy
iptables -t nat -A PREROUTING -i $INTIF -p tcp --dport 80 -j REDIRECT --to-port 3128

#Mail
iptables -A FORWARD -i $EXTIF -o $INTIF -d 192.168.5.4 -p tcp --dport 25 -j ACCEPT
iptables -t nat -A PREROUTING -i $EXTIF -d $EXTIP -p tcp --dport 25 -j DNAT --to 192.168.5.4
iptables -A FORWARD -i $EXTIF2 -o $INTIF -d 192.168.5.4 -p tcp --dport 25 -j ACCEPT
iptables -t nat -A PREROUTING -i $EXTIF2 -d $EXTIP2 -p tcp --dport 25 -j DNAT --to 192.168.5.4

#HTTPS (webmail)
iptables -A FORWARD -i $EXTIF -o $INTIF -d 192.168.5.4 -p tcp --dport 443 -j ACCEPT
iptables -t nat -A PREROUTING -i $EXTIF -d $EXTIP -p tcp --dport 443 -j DNAT --to 192.168.5.4
iptables -A FORWARD -i $EXTIF2 -o $INTIF -d 192.168.5.4 -p tcp --dport 443 -j ACCEPT
iptables -t nat -A PREROUTING -i $EXTIF2 -d $EXTIP2 -p tcp --dport 443 -j DNAT --to 192.168.5.4

#IMAPS
iptables -A FORWARD -i $EXTIF -o $INTIF -d 192.168.5.4 -p tcp --dport 993 -j ACCEPT
iptables -t nat -A PREROUTING -i $EXTIF -d $EXTIP -p tcp --dport 993 -j DNAT --to 192.168.5.4
iptables -A FORWARD -i $EXTIF2 -o $INTIF -d 192.168.5.4 -p tcp --dport 993 -j ACCEPT
iptables -t nat -A PREROUTING -i $EXTIF2 -d $EXTIP2 -p tcp --dport 993 -j DNAT --to 192.168.5.4

#POP3
iptables -A FORWARD -i $EXTIF -o $INTIF -d 192.168.5.4 -p tcp --dport 110 -j ACCEPT
iptables -t nat -A PREROUTING -i $EXTIF -d $EXTIP -p tcp --dport 110 -j DNAT --to 192.168.5.4
iptables -A FORWARD -i $EXTIF2 -o $INTIF -d 192.168.5.4 -p tcp --dport 110 -j ACCEPT
iptables -t nat -A PREROUTING -i $EXTIF2 -d $EXTIP2 -p tcp --dport 110 -j DNAT --to 192.168.5.4

#VPN
iptables -A FORWARD -i $EXTIF -o $INTIF -d 192.168.5.4 -p tcp --dport 1723 -j ACCEPT
iptables -t nat -A PREROUTING -i $EXTIF -d $EXTIP -p tcp --dport 1723 -j DNAT --to 192.168.5.4
iptables -A FORWARD -i $EXTIF2 -o $INTIF -d 192.168.5.4 -p tcp --dport 1723 -j ACCEPT
iptables -t nat -A PREROUTING -i $EXTIF2 -d $EXTIP2 -p tcp --dport 1723 -j DNAT --to 192.168.5.4

#HTTP
iptables -A FORWARD -i $EXTIF -o $INTIF -d 192.168.5.4 -p tcp --dport 80 -j ACCEPT
iptables -t nat -A PREROUTING -i $EXTIF -d $EXTIP -p tcp --dport 80 -j DNAT --to 192.168.5.4
iptables -A FORWARD -i $EXTIF2 -o $INTIF -d 192.168.5.4 -p tcp --dport 80 -j ACCEPT
iptables -t nat -A PREROUTING -i $EXTIF2 -d $EXTIP2 -p tcp --dport 80 -j DNAT --to 192.168.5.4

#Bridgit
iptables -A FORWARD -i $EXTIF -o $INTIF -d 192.168.5.4 -p tcp --dport 8080 -j ACCEPT
iptables -t nat -A PREROUTING -i $EXTIF -d $EXTIP -p tcp --dport 8080 -j DNAT --to 192.168.5.4
iptables -A FORWARD -i $EXTIF2 -o $INTIF -d 192.168.5.4 -p tcp --dport 8080 -j ACCEPT
iptables -t nat -A PREROUTING -i $EXTIF2 -d $EXTIP2 -p tcp --dport 8080 -j DNAT --to 192.168.5.4

#GATEWAY2="150.101.180.143"
#GATEWAY="150.101.180.24"

#ip route add $GATEWAY dev $EXTIF src $EXTIP table T1
#ip route add default via $GATEWAY table T1
#ip route add $GATEWAY2 dev $EXTIF2 src $EXTIP2 table T2
#ip route add default via $GATEWAY2 table T2

#ip rule add from $EXTIP table T1
#ip rule add from $EXTIP2 table T2

#ip route add default scope global nexthop via $GATEWAY dev $EXTIF weight 1 nexthop via $GATEWAY2 dev $EXTIF2 weight 1

Any ideas would be fantastic.
Thanks,
Mike
EDIT: Here is the requested commands and output which were requested from the comments on this question. Thanks!
Explanation: I've turned on the machine with both interfaces automatically coming up on bootup (ppp dials and connects automatically). You can see as soon as I turn off one interface it works.
login as: root
root@192.168.5.254's password:
Linux gateway 2.6.26-2-686 #1 SMP Thu Sep 16 19:35:51 UTC 2010 i686

The programs included with the Debian GNU/Linux system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.

Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent
permitted by applicable law.
Last login: Wed Nov  3 04:07:28 2010 from 192.168.5.38
gateway:~# ping google.com
ping: unknown host google.com
gateway:~# ip route
150.101.180.24 dev ppp0  proto kernel  scope link  src 150.101.179.XXX
150.101.180.24 dev ppp1  proto kernel  scope link  src 150.101.177.XXX
192.168.5.0/24 dev eth1  proto kernel  scope link  src 192.168.5.254
192.168.1.0/24 dev eth2  proto kernel  scope link  src 192.168.1.2
192.168.1.0/24 dev eth3  proto kernel  scope link  src 192.168.1.3
default via 192.168.1.254 dev eth3
default via 192.168.1.254 dev eth2
default dev ppp1  scope link
default dev ppp0  scope link
gateway:~# ip link show
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 16436 qdisc noqueue state UNKNOWN
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
2: eth1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 10                                                                                00
    link/ether 00:24:8c:4e:31:e7 brd ff:ff:ff:ff:ff:ff
3: eth2: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UNKNOWN ql                                                                                en 1000
    link/ether 00:40:f4:ba:c4:41 brd ff:ff:ff:ff:ff:ff
4: eth3: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UNKNOWN ql                                                                                en 1000
    link/ether 00:60:67:72:40:42 brd ff:ff:ff:ff:ff:ff
5: ppp0: <POINTOPOINT,MULTICAST,NOARP,UP,LOWER_UP> mtu 1492 qdisc pfifo_fast state UN                                                                                KNOWN qlen 3
    link/ppp
6: ppp1: <POINTOPOINT,MULTICAST,NOARP,UP,LOWER_UP> mtu 1492 qdisc pfifo_fast state UN                                                                                KNOWN qlen 3
    link/ppp
gateway:~# clear
gateway:~# ip link show
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 16436 qdisc noqueue state UNKNOWN
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
2: eth1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
    link/ether 00:24:8c:4e:31:e7 brd ff:ff:ff:ff:ff:ff
3: eth2: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UNKNOWN qlen 1000
    link/ether 00:40:f4:ba:c4:41 brd ff:ff:ff:ff:ff:ff
4: eth3: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UNKNOWN qlen 1000
    link/ether 00:60:67:72:40:42 brd ff:ff:ff:ff:ff:ff
5: ppp0: <POINTOPOINT,MULTICAST,NOARP,UP,LOWER_UP> mtu 1492 qdisc pfifo_fast state UNKNOWN qlen 3
    link/ppp
6: ppp1: <POINTOPOINT,MULTICAST,NOARP,UP,LOWER_UP> mtu 1492 qdisc pfifo_fast state UNKNOWN qlen 3
    link/ppp
gateway:~# ip neigh show
192.168.5.38 dev eth1 lladdr 00:1d:60:0a:cb:23 DELAY
192.168.1.254 dev eth3 lladdr 00:04:ed:a9:07:81 REACHABLE
192.168.1.254 dev eth2 lladdr 00:04:ed:aa:cd:45 REACHABLE
192.168.5.43 dev eth1 lladdr 00:08:5d:03:b3:3f STALE
192.168.5.4 dev eth1 lladdr 00:1e:0b:1c:4e:60 STALE
gateway:~# ip route get 5.5.5.5
5.5.5.5 via 192.168.1.254 dev eth3  src 192.168.1.3
    cache  mtu 1500 advmss 1460 hoplimit 64
gateway:~# ping google.com
ping: unknown host google.com
gateway:~# ping 4.2.2.2
PING 4.2.2.2 (4.2.2.2) 56(84) bytes of data.
From 192.168.1.254 icmp_seq=1 Destination Net Unreachable
From 192.168.1.254 icmp_seq=2 Destination Net Unreachable
^C
--- 4.2.2.2 ping statistics ---
2 packets transmitted, 0 received, +2 errors, 100% packet loss, time 1003ms

gateway:~# ifconfig -a
eth1      Link encap:Ethernet  HWaddr 00:24:8c:4e:31:e7
          inet addr:192.168.5.254  Bcast:192.168.5.255  Mask:255.255.255.0
          inet6 addr: fe80::224:8cff:fe4e:31e7/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:739 errors:0 dropped:0 overruns:0 frame:0
          TX packets:303 errors:0 dropped:0 overruns:0 carrier:2
          collisions:0 txqueuelen:1000
          RX bytes:59730 (58.3 KiB)  TX bytes:35821 (34.9 KiB)
          Interrupt:219

eth2      Link encap:Ethernet  HWaddr 00:40:f4:ba:c4:41
          inet addr:192.168.1.2  Bcast:192.168.1.255  Mask:255.255.255.0
          inet6 addr: fe80::240:f4ff:feba:c441/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:152 errors:0 dropped:0 overruns:0 frame:0
          TX packets:119 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:15328 (14.9 KiB)  TX bytes:8207 (8.0 KiB)
          Interrupt:16 Base address:0xe800

eth3      Link encap:Ethernet  HWaddr 00:60:67:72:40:42
          inet addr:192.168.1.3  Bcast:192.168.1.255  Mask:255.255.255.0
          inet6 addr: fe80::260:67ff:fe72:4042/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:521 errors:0 dropped:0 overruns:0 frame:0
          TX packets:758 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:48899 (47.7 KiB)  TX bytes:57096 (55.7 KiB)
          Interrupt:17 Base address:0xe400

lo        Link encap:Local Loopback
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:16436  Metric:1
          RX packets:20 errors:0 dropped:0 overruns:0 frame:0
          TX packets:20 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:1160 (1.1 KiB)  TX bytes:1160 (1.1 KiB)

ppp0      Link encap:Point-to-Point Protocol
          inet addr:150.101.179.XXX  P-t-P:150.101.180.24  Mask:255.255.255.255
          UP POINTOPOINT RUNNING NOARP MULTICAST  MTU:1492  Metric:1
          RX packets:61 errors:0 dropped:0 overruns:0 frame:0
          TX packets:3 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:3
          RX bytes:7454 (7.2 KiB)  TX bytes:54 (54.0 B)

ppp1      Link encap:Point-to-Point Protocol
          inet addr:150.101.177.XXX  P-t-P:150.101.180.24  Mask:255.255.255.255
          UP POINTOPOINT RUNNING NOARP MULTICAST  MTU:1492  Metric:1
          RX packets:127 errors:0 dropped:0 overruns:0 frame:0
          TX packets:3 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:3
          RX bytes:6278 (6.1 KiB)  TX bytes:54 (54.0 B)

gateway:~# ifdown eth2
There is already a pid file /var/run/dhclient.eth2.pid with pid 2217
killed old client process, removed PID file
Internet Systems Consortium DHCP Client V3.1.1
Copyright 2004-2008 Internet Systems Consortium.
All rights reserved.
For info, please visit http://www.isc.org/sw/dhcp/

Listening on LPF/eth2/00:40:f4:ba:c4:41
Sending on   LPF/eth2/00:40:f4:ba:c4:41
Sending on   Socket/fallback
DHCPRELEASE on eth2 to 192.168.1.254 port 67
gateway:~# ping google.com
PING google.com (66.102.11.104) 56(84) bytes of data.
64 bytes from syd01s01-in-f104.1e100.net (66.102.11.104): icmp_seq=1 ttl=58 time=32.8 ms
64 bytes from syd01s01-in-f104.1e100.net (66.102.11.104): icmp_seq=2 ttl=58 time=32.7 ms
64 bytes from syd01s01-in-f104.1e100.net (66.102.11.104): icmp_seq=3 ttl=58 time=32.9 ms
64 bytes from syd01s01-in-f104.1e100.net (66.102.11.104): icmp_seq=4 ttl=57 time=33.3 ms
64 bytes from syd01s01-in-f104.1e100.net (66.102.11.104): icmp_seq=5 ttl=57 time=32.6 ms
^C
--- google.com ping statistics ---
5 packets transmitted, 5 received, 0% packet loss, time 4017ms
rtt min/avg/max/mdev = 32.694/32.923/33.373/0.263 ms
gateway:~# ifup eth2
Internet Systems Consortium DHCP Client V3.1.1
Copyright 2004-2008 Internet Systems Consortium.
All rights reserved.
For info, please visit http://www.isc.org/sw/dhcp/

Listening on LPF/eth2/00:40:f4:ba:c4:41
Sending on   LPF/eth2/00:40:f4:ba:c4:41
Sending on   Socket/fallback
DHCPDISCOVER on eth2 to 255.255.255.255 port 67 interval 8
DHCPOFFER from 192.168.1.254
DHCPREQUEST on eth2 to 255.255.255.255 port 67
DHCPACK from 192.168.1.254
bound to 192.168.1.2 -- renewal in 20576 seconds.
if-up.d/mountnfs[eth2]: waiting for interface dsl-provider1 before doing NFS mounts (warning).
if-up.d/mountnfs[eth2]: waiting for interface dsl-provider before doing NFS mounts (warning).
gateway:~# ping google.com
PING google.com (66.102.11.104) 56(84) bytes of data.
^C
--- google.com ping statistics ---
5 packets transmitted, 0 received, 100% packet loss, time 4013ms

gateway:~# ifdown eth3
There is already a pid file /var/run/dhclient.eth3.pid with pid 2523
killed old client process, removed PID file
Internet Systems Consortium DHCP Client V3.1.1
Copyright 2004-2008 Internet Systems Consortium.
All rights reserved.
For info, please visit http://www.isc.org/sw/dhcp/

Listening on LPF/eth3/00:60:67:72:40:42
Sending on   LPF/eth3/00:60:67:72:40:42
Sending on   Socket/fallback
DHCPRELEASE on eth3 to 192.168.1.254 port 67
gateway:~# ping google.com
ping: unknown host google.com
gateway:~# ping 4.2.2.2
connect: Network is unreachable
gateway:~# ping 4.2.2.2
connect: Network is unreachable
gateway:~# ip route
150.101.180.24 dev ppp0  proto kernel  scope link  src 150.101.179.XXX
192.168.5.0/24 dev eth1  proto kernel  scope link  src 192.168.5.254
192.168.1.0/24 dev eth2  proto kernel  scope link  src 192.168.1.2
gateway:~# route
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
150.101.180.24  *               255.255.255.255 UH    0      0        0 ppp0
192.168.5.0     *               255.255.255.0   U     0      0        0 eth1
192.168.1.0     *               255.255.255.0   U     0      0        0 eth2
gateway:~# ping google.com
ping: unknown host google.com
gateway:~# plog
Nov 11 17:17:07 gateway pppd[2139]: sendPacket: send: Network is down
Nov 11 17:17:07 gateway pppd[2139]: Exit.
gateway:~# poff -a
gateway:~# pon dsl-provider
Plugin rp-pppoe.so loaded.
gateway:~# pon dsl-provider1
Plugin rp-pppoe.so loaded.
gateway:~# ping google.com
PING google.com (66.102.11.104) 56(84) bytes of data.
64 bytes from syd01s01-in-f104.1e100.net (66.102.11.104): icmp_seq=1 ttl=57 time=32.8 ms
64 bytes from syd01s01-in-f104.1e100.net (66.102.11.104): icmp_seq=2 ttl=58 time=32.5 ms
64 bytes from syd01s01-in-f104.1e100.net (66.102.11.104): icmp_seq=3 ttl=57 time=32.9 ms
64 bytes from syd01s01-in-f104.1e100.net (66.102.11.104): icmp_seq=4 ttl=57 time=32.3 ms
^C
--- google.com ping statistics ---
4 packets transmitted, 4 received, 0% packet loss, time 3008ms
rtt min/avg/max/mdev = 32.373/32.657/32.906/0.218 ms
gateway:~#
gateway:~# ip route get 5.5.5.5
5.5.5.5 dev ppp0  src 150.101.179.XXX
    cache  mtu 1492 advmss 1452 hoplimit 64
gateway:~#

A: As you can see here
  gateway:~# ip route
  150.101.180.24 dev ppp0  proto kernel  scope link  src 150.101.179.XXX
  150.101.180.24 dev ppp1  proto kernel  scope link  src 150.101.177.XXX
  192.168.5.0/24 dev eth1  proto kernel  scope link  src 192.168.5.254
  192.168.1.0/24 dev eth2  proto kernel  scope link  src 192.168.1.2
  192.168.1.0/24 dev eth3  proto kernel  scope link  src 192.168.1.3
> default via 192.168.1.254 dev eth3
> default via 192.168.1.254 dev eth2
> default dev ppp1  scope link
> default dev ppp0  scope link

you have 4 default routes. When you're trying to reach a non-local host, one of these 4 is chosen:
gateway:~# ip route get 5.5.5.5
5.5.5.5 via 192.168.1.254 dev eth3  src 192.168.1.3
    cache  mtu 1500 advmss 1460 hoplimit 64

In this case eth3, which doesn't get you to the desired destination. The gateway you're asking to forward your packets (192.168.1.254) truthfully responds, that it has no path to the destination network:
gateway:~# ping 4.2.2.2
PING 4.2.2.2 (4.2.2.2) 56(84) bytes of data.
From 192.168.1.254 icmp_seq=1 Destination Net Unreachable

I don't know where those default routes via ethX originate from, but you need to get rid of them:
ip route del default via 192.168.1.254 dev eth3
ip route del default via 192.168.1.254 dev eth2

If your setup is not working as intended after that, the output of ip rule show will probably be helpful for further debugging.


text:
Q: Is there a simple way to transform an array based on a dimension table? I have two tables:

*

*One with a column with is an array of identifiers.

*Another which is a dimension table of that map these identifiers to another value

I'm looking to transform the column of the first table using the dimension table.
Example:
Table 1:
Column A  | Column B
 'Bob'      |  ['a', 'b', 'c']
 'Terry'      |  ['a']
Dimension Table:
Column C  | Column D
 'a'      |  1
 'b'      |  2
 'c'      |  3

Expected Output:
Column A  | Column B
 'Bob'      |  [1,2,3]
 'Terry'      |  [1]
Is there a way to do this (preferably in Presto) without exploding and re-aggregating the array column ?

A: i guess you would be able to do this without exploding and re-aggregation by using transform_keys, not sure this is easier though.
SELECT map_keys(transform_keys(MAP(ARRAY['a','c'], ARRAY[null,null]),
                      (k, v) -> MAP(ARRAY['a', 'b', 'c', 'd'], ARRAY[1,2,3,4])[k]));

I guess it requires that the dimension table is not "too big".

redpajama_set_name: RedPajamaStackExchange


text:
Q: Calculator app is not working - Java I am making a text based calculator that can do addition, subtraction, division, multiplication and powers. The code I have written so far seems to work, but when it reaches the section where it determines if the inputed text is a +, -, /, *, or a ^, it endlessly loops and doesn't recognize the input.
    double inputX;  // Used for input 2
    double inputY;  // Used for input 1
    double output;  // Used for math purposes

    String inputS;  // Used for string input

    String subt;   // Store the - in a string
    subt = "-";

    boolean corrInput = true;
    boolean repeat = true;

    while (repeat == true){

        System.out.print("Please enter a number: ");

        inputX = TextIO.getlnDouble();  // Retrieves inputX

        System.out.println("x: " + inputX + "\n");

        System.out.print("Please enter a number: ");

        inputY = TextIO.getlnDouble();  // Retrieves inputY

        System.out.println("y: " + inputY + "\n");

        while (corrInput == true){
            System.out.println("Choose an operation: +, -, *, /, ^.");
            inputS = TextIO.getlnString();  // Retrieves a strings input

            // Calculator logic

            if (inputS == subt){
                output = inputX - inputY;   // X minus Y

                System.out.println("Calculatorator says that " + inputX + " - " + inputY
                    + " = " + output);
            }

            else if (inputS == "+"){
                output = inputX - inputY;   // X plus Y

                System.out.println("Calculatorator says that " + inputX + " + " + inputY
                    + " = " + output);
            }

            else if (inputS == "*"){
                output = inputX * inputY;   // X multiplied by Y

                System.out.println("Calculatorator says that " + inputX + " * " + inputY
                    + " = " + output);
            }

            else if (inputS == "/"){
                output = inputX / inputY;   // X divided by Y

                System.out.println("Calculatorator says that " + inputX + " / " + inputY
                    + " = " + output);
            }

            else if (inputS == "^"){
                output = Math.pow(inputX, inputY);  // X to the power of Y

                System.out.println("Calculatorator says that " + inputX + " ^ " + inputY
                    + " = " + output);
            }

            else {
                System.out.println("Please provide a valid input. '" + inputS
                    + "' is not valid input");
            }

        }

        System.out.println("Want to do another Calculatoration?");
        repeat = TextIO.getBoolean();   // Retrieves input as a boolean

    }

    System.out.println("Thank you for using my calculator!");

The solution is most likely obvious, but I am not

A: You are never changing corrInput value to false, so it won't never exit the nested while.
corrInput = false;

You may also want to use str1.equals(str2) to compare strings instead of ==.


text:
Q: using chatterbean AIML interpeter to make alice bot whenever i try to load the Alice aiml files i get various errors about the tags not being found, but when i fix thos errors i get an error i dont know how to fix. the aiml thing not being implemented, but wehen i look at the aiml class it is impementing it :?
my code:
public static String input()
{
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    //System.out.println("you say>");
    String input = "";
    try
    {
        input = in.readLine();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return input;
}

public static void main(String[] args) throws Exception
{
     Chat ch=new Chat();
     AliceBotMother mother = new AliceBotMother();
     mother.setUp();
     AliceBot bot = mother.newInstance();
     System.err.println(bot.respond("welcome"));
 while(true)
 {
     String input = Chat.input();
         // while the user saying 'bye'
         if(Chat.END.equalsIgnoreCase(input))
             break;
         // do some respond..
         System.err.println("Alice>" + bot.respond(input));
 }

A: Chatterbean is an old Java program that is no longer supported.  You should the newer Java AIML 2.0 library Program AB at https://code.google.com/p/program-ab/


text:
Q: xcode, ios, Can't move buttons around screen The Output on Console:

2015-07-02 17:31:49.105 Make Maths Fun[15079:90b] but_1.center.x =
  155.000000 but_1.center.y = 90.000000
2015-07-02 17:31:49.105 Make Maths Fun[15079:90b] but_2.center.x =
  155.000000 but_2.center.y = 140.000000

The Code:
but_1.center = CGPointMake(155, 90);
but_2.center = CGPointMake(155, 140);

Screenshot:

The Output says that it is at that x and y but when I run the program they are where I had them on the viewcontroller

A: Try this
Disable your Use Auto Layout option and then try again.
Hope it helps.

A: If you are using AutoLayouts then setting the postion of button from code do not work. So you have two options

*

*Disable the Autolayouts from story board and then set the
position from code.

*If you using autoLayouts then you have to make the IBOutlet of
constraint, you can use anyone Leading Space Constraint of Trailing
space constraint outlet. And then set the constant of that
constraint (the constraint of which you make IBOutlet) at the run
time from code to get desired position.


text:
Q: Crouch speed is faster than Movement Speed In short, when I click the CTRL key, my player goes down but it goes faster than when it moves normally, why?
public float movementSpeed = 10.0f;
public float crouchSpeed = 2.0f;

if (Input.GetKey(KeyCode.LeftControl))
{
    isCrouching = true;
}

if (isCrouching == true)
{
    controller.height = crouchingHeight;
    float curSpeedX = canMove ? (isCrouching ? crouchSpeed : movementSpeed) * Input.GetAxis("Vertical") : 0;
    float curSpeedY = canMove ? (isCrouching ? crouchSpeed : movementSpeed) * Input.GetAxis("Horizontal") : 0;
    movement *= crouchingMulitplier;
    float movementY = movement.y;
    movement = (transform.forward * curSpeedX) + (transform.right * curSpeedY);
}


text:
Q: mysql mixed privileges I am trying to create a separate set of privileges for a database that contains both "read only" tables and "read write" tables. To be more specific, the database contains 10 tables that I want the user to only read from (i.e. select only). It also contains around 30 tables which the user is free to read and write to and from. Lastly, I would also like the user to be able to create/drop/alter tables created by him thus granting him full access to his own tables under the same database.
Is something like this possible? I have tried to think of the ways I can use GRANT but my head is getting stuck.
Thanks

A: What you want is possible except I'm not sure about the last sentence. I don't think mySQL tables have "owners" as such, but you can limit access to tables with certain prefixes. Maybe that is a way to go.

*

*Obligatory manual reference: 12.4.1.3. GRANT Syntax

*I recommend using a GUI like HeidiSQL (for Windows) to point-and-click the required privilege rules. It produces proper SQL to look at and learn from as well. Here is a screen shot of its excellent user manager.


text:
Q: Is there any way to use varargs with boost::format? I'm kinda loathe to use a fixed-sized buffer and the vnsprintf usual suspects.
Would something like this work to have boost::format work with a variable argument list?
Sadly, I cannot use anything from C++11.
void formatIt(const char* msg, ...) {
        va_list args;
        va_start(args, msg);
        boost::format f(msg);
        for loop somehow {
          f % va_arg(args, const char *);   //does this work?
        }
        va_end(args);
}

A: I use this:
inline static std::string FormatStringRecurse(boost::format& message)
{
    return message.str();
}

template <typename TValue, typename... TArgs>
std::string FormatStringRecurse(boost::format& message, TValue&& arg, TArgs&&... args)
{
   message % std::forward<TValue>(arg);
   return FormatStringRecurse(message, std::forward<TArgs>(args)...);
}

template <typename... TArgs>
std::string FormatString(const char* fmt, TArgs&&... args)
{
    using namespace boost::io;
    boost::format message(fmt);
    return FormatStringRecurse(message, std::forward<TArgs>(args)...);
}

A: I used to use this:
inline static std::string FormatString()
{
    return std::string();
}

inline static std::string FormatString(const char* szMessage)
{
    return szMessage;
}

template<typename Type1>
static std::string FormatString(const char* formatString, const Type1& arg1)
{
    using namespace boost::io;
    boost::format formatter(formatString);
    formatter % arg1;
    return boost::str( formatter );
}

template<typename Type1, typename Type2>
static std::string FormatString(const char* formatString, const Type1& arg1, const Type2& arg2)
{
    using namespace boost::io;
    boost::format formatter(formatString);
    formatter % arg1 % arg2;
    return boost::str( formatter );
}

template<typename Type1, typename Type2, typename Type3>
static std::string FormatString(const char* formatString, const Type1& arg1, const Type2& arg2, const Type3& arg3)
{
    using namespace boost::io;
    boost::format formatter(formatString);
    formatter % arg1 % arg2 % arg3;
    return boost::str( formatter );
}

/// etc up to 10 args

I guess it doesn't use varargs as you requested, but do you often need to go above 10 or so arguments? There may be some macro magic that would make what you wanted happen, but err... that's magic, so you may be better off with just writing out all the versions.


text:
Q: ASTER DEMs multidirectional hillshades I am trying to produce a multidirectional hillshade from ASTER DEMs in QGIS. basically I am trying to achieve something similar to this

which is a screenshot from this layer https://services.arcgisonline.com/arcgis/rest/services/Elevation/World_Hillshade/MapServer
but there the problem is that I can not print maps in the high resolution I need.
so i thought i do it myself but when I
apply these settings

that work for other DEMs very nicely I get a terrible image for Aster.

I kind of suspect it has to do with the fact that I can not apply the scale correction factor of 111120 (in the Scale ratio vert. units to horiz. box) which I usually do for aster.
any thoughts for how I can make this work?


text:
Q: Cannot install pip with pypy: "Fatal RPython error: UnicodeDecodeError" I'm using Windows 10 (64bit, zh-cn) with pypy (2.4 32bit based on python 3.2.5).
When trying to install pip from pypy,
  > pypy get-pip.py

after a short delay, the pypy.exe would stop response and then the following logging shows in the command prompt:
  Fatal RPython error: UnicodeDecodeError

Does anyone know how to fix it? Thanks in advance.

A: there is bug in the version.... try to change the display language, Location and Format in "Region and language" to English... this might solve your issue


text:
Q: linked list printf("%d\n",tasks_head->head->tid) Segmatation fault I have this code and i want to print the tid of each node. I have segmatation fault in this for loop
printf("%d\n",tasks_head->head->tid); And i am not sure if the task_count[] works as i want. I want to save a counter++ in each position of the array.
struct Tasks
{

    int tid;
    int difficulty;
    struct Tasks *next;
};

struct Head_GL
{

    int tasks_count[3];
    struct Tasks *head;
};

struct Head_GL *tasks_head=NULL;

int num=0;

int insert_task(int tid, int difficulty){

    num++;
    struct Tasks *prev=NULL;
    struct Tasks *temp=NULL;
    struct Tasks *new=(struct Tasks*)malloc(sizeof(struct Tasks));

    tasks_head=(struct Head_GL*)malloc(sizeof(struct Head_GL));
    tasks_head->head=(struct Tasks*)malloc(sizeof(struct Tasks));

    tasks_head->tasks_count[0]=0;
    tasks_head->tasks_count[1]=0;
    tasks_head->tasks_count[2]=0;
    tasks_head->head->difficulty=0;
    tasks_head->head->tid=0;
    tasks_head->head->next=NULL;

    if(new==NULL)
        return 0;
    new->tid = tid;
    new->difficulty = difficulty;
    new->next = NULL;

    if(difficulty==1)
        tasks_head->tasks_count[0]++;
    else if(difficulty==2)
        tasks_head->tasks_count[1]++;
    else
        tasks_head->tasks_count[2]++;

    if(tasks_head==NULL){
        tasks_head->head = new;
        return 1;
    }
    if( tasks_head->head->difficulty > difficulty){
        new->next = tasks_head->head;
        tasks_head->head= new;
        return 1;
    }
    else{
        prev = tasks_head->head;
        temp = tasks_head->head->next;
        while(temp != NULL && temp->difficulty < difficulty){
            prev = temp;
            temp = temp->next;
        }
        if(temp==NULL){
            prev->next = new;
            return 1;
        }
        else{
            new->next = temp;
            prev->next = new;
            return 1;
        }
    }
}

int main(){

    printf("hello1\n");

    if(1==insert_task(1,1))
        printf("alo");

    if(1==insert_task(4,1))
        printf("alo");

    if(1==insert_task(3,2))
        printf("alo\n");

    printf("%d\n",num);

    for(int i=0; i<num; i++){
        printf("%d\n",tasks_head->head->tid);
        tasks_head->head=tasks_head->head->next;
    }
/*

    for(int i=0; i<3; i++){
        printf("%d",tasks_head->tasks_count[i]);
    }*/
    return 0;
}

A: There are a few problems with this code, but the most important is how you are affecting tasks_head.
At present you are malloc'ing a new tasks_head each time you enter insert_task, and recreating the head element, with these two lines:-
tasks_head=(struct Head_GL*)malloc(sizeof(struct Head_GL));
tasks_head->head=(struct Tasks*)malloc(sizeof(struct Tasks));

Normally you would either do this once, in a separate call to an initialisation function, or you can do it within insert_task by checking if it has already been performed.
You don't really need to create "head" separately, as the head will be the first "new" when you initialise the tasks_head global variable. So if you move this section of code down to below the creation of the "new" task, then you can assign it directly to the head.
If we look at the code where you are inserting the item into the linked list based upon its difficulty, then you can see that you are already doing this:-
if(tasks_head==NULL){
    tasks_head->head = new;
    return 1;
}

So the creation of a separate "head" is totally unnecessary.
The check here, by the way is exactly the check you would want to perform the once-off initialisation of "tasks_head", so if we take your code from above and move it into this section, then you will not keep reseting your global.
The downside of moving the initialisation, however, is that you've already tried to adjust the task difficulty count, so this also needs to come below, and we'll need to add an equivalent for the init case.
If you put all of those changes together you get the following:-
int insert_task(int tid, int difficulty){
    num++;
    struct Tasks *prev=NULL;
    struct Tasks *temp=NULL;
    struct Tasks *new=(struct Tasks*)malloc(sizeof(struct Tasks));

    if(new==NULL)
        return 0;

    new->tid = tid;
    new->difficulty = difficulty;
    new->next = NULL;

    if(tasks_head==NULL){
        tasks_head=(struct Head_GL*)malloc(sizeof(struct Head_GL));
        tasks_head->head=(struct Tasks*)malloc(sizeof(struct Tasks));
        tasks_head->tasks_count[(difficulty != 1 && difficulty != 2)?2:difficulty-1]=1;
        tasks_head->head = new;
        return 1;
    }

    if(difficulty==1)
        tasks_head->tasks_count[0]++;
    else if(difficulty==2)
        tasks_head->tasks_count[1]++;
    else
        tasks_head->tasks_count[2]++;

    if( tasks_head->head->difficulty > difficulty){
        new->next = tasks_head->head;
        tasks_head->head = new;
        return 1;
    }
    else{
        prev = tasks_head->head;
        temp = tasks_head->head->next;
        while(temp != NULL && temp->difficulty < difficulty){
            prev = temp;
            temp = temp->next;
        }
        if(temp==NULL){
            prev->next = new;
            return 1;
        }
        else{
            new->next = temp;
            prev->next = new;
            return 1;
        }
    }
}

The task_count difficulty mapping looks a little odd but I've tried to replicate your current behaviour, where a task of difficulty 1 is set to 0 and 2 is set to 1 and everything else is set to 2. I've done that with this slightly funky line using a tenery operator:
tasks_head->tasks_count[(difficulty != 1 && difficulty != 2)?2:difficulty-1]=1;

But it might just be that you want:
tasks_head->tasks_count[difficulty-1]=1;

if your task difficulty is only in the range 1-3.
Lastly we need to look at your loops in your main method which are currently modifying the global variable while trying to traverse the linked list.
for(int i=0; i<num; i++){
    printf("%d\n",tasks_head->head->tid);
    tasks_head->head=tasks_head->head->next;
}

I think you want to think about using a pointer to traverse this like the following:-
for(struct Tasks *p = tasks_head->head; p != NULL; p = p->next){
    printf("%d\n", p->tid);
}

I'll leave you to think about the second loop to work out how you might wish to do something similar.


text:
Q: Extracting data from another workbook, without mentioning the sheet name I have two workbook. Source workbook and destination workbook.
I would like to extract all the data from my source workbook, depending on the header of my destination workbook.
For this, I have the below code. I would like to know, if it is possible, just to mention workbook name without mentioning the sheet name? Every time I save a new excel file, the sheet saves as sheet1, sheet2. I get an subscript error due to this change in sheet name.
Could any one help, how I can extract data from the sheet without mentioning the sheet name. In most cases, in my workbook, I have only one sheet.
Sub Extract()
Dim DestinationWB As Workbook
    Dim OriginWB As Workbook
    Dim path1 As String
    Dim FileWithPath As String
    Dim Lastrow As Long, i As Long, LastCol As Long
    Dim TheHeader As String
    Dim cell As Range
    Set DestinationWB = ThisWorkbook

    ' get the path of this workbook
    path1 = DestinationWB.Path
    FileWithPath = path1 & "\Downloads\Sourcg.xlsx"
    Set OriginWB = Workbooks.Open(filename:=FileWithPath)

    'get the count of last row and column
     Lastrow = OriginWB.Worksheets("1").Cells(Rows.count, 1).End(xlUp).Row
    LastCol = OriginWB.Worksheets("1").Cells(1, Columns.count).End(xlToLeft).Column

    For i = 1 To LastCol
        'get the name of the field (names are in row 1)
        TheHeader = OriginWB.Worksheets("1").Cells(1, i).Value

        With DestinationWB.Worksheets("S").Range("A4:L4")
            'Find the name of the field (TheHeader) in the destination (in row 4)
            Set cell = .Find(TheHeader, LookIn:=xlValues)
        End With

        If Not cell Is Nothing Then
            OriginWB.Worksheets("1").Range(Cells(2, i), Cells(Lastrow, i)).Copy Destination:=DestinationWB.Worksheets("S_APQP").Cells(5, cell.Column)
        Else
            'handle the error
        End If
    Next i

    OriginWB.Close SaveChanges:=False
End Sub

A: Mikz, you use property Worksheets of Workbook. This property contains an ordinary VBA Excel collection (of worksheets). You can access members of any collection by it's position (integer) or by it's key (string). You use key in your code, since you use a string value. If you have the only one worksheet in your workbook, you definitely should use position value, which is 1 - OriginWB.Worksheets(1). And it will work regardless of name of the sheet.
If you have more than 1 worksheet, you can traverse through the collection usingFOR EACH aWorksheet IN OriginWB.Worksheets
BTW - I would recommend you to use WITH operator for OriginWB.Worksheets("1")IMHO it will help you to make shorter and more readable code. You can use nested WITH operators.


text:
Q: Silent Windows Installer installer without rebooting automatically Currently I have an MSI which performs a major upgrade, and it is launched as:
msiexec.exe /i installer.msi /qn REBOOT=ReallySuppress

My question is regarding that particular property REBOOT=ReallySuppress: does this mean it will not restart the system but will do proper changes (if applied) when user reboot her system manually? Or will it simply ignore those things that require to restart the system?

A: The installer performs all the operations. The value ReallySuppress of REBOOT property, or /norestart option, simply suppress system restart, if it's needed. And msiexec.exe exit code would be 3010 (ERROR_SUCCESS_REBOOT_REQUIRED) to indicate to the calling application that system restart is required.
The files that were in use during installation will have been moved out of the way and will be permanently deleted when system restarts. It is recommended to restart the system as soon as possible because until then some processes will be using the old (locked) files whereas new processes will be using the new, updated files, so there is room for ambiguity, especially since there may be registry changes as well. As such the /noreboot option is useful when you have several packages to install and you want to reboot after the last one, but only if it's absolutely necessary. Just ignoring the reboot prompt is not a good way to go.


text:
Q: Spring aop: advice never reached I've create this pointcut:
@Pointcut(value = "execution(* net.space.service.RepositoryService.createDocumentFromBytes(..))")
public void groupBytesMethod() {
}

and this advice:
@Around("groupBytesMethod()")
public Object groupMetrics(ProceedingJoinPoint point) throws Throwable {
    Object result = point.proceed();
}

I've set a breakpoint, but it's never reached.
package net.space.service;

@Service
public class RepositoryService {
    private Reference createDocumentFromBytes(String id, byte[] content) throws IOException {...}
    public Reference groupDocuments(@NotNull RepositoryGroupForm groupForm) {
        return this.createDocumentFromBytes("id", new byte[10]);
    }
}

A: There are many ways to make this work, I would suggest use an annotation,something like :
@Documented
@Target(ElementType.METHOD)
@Inherited
@Retention(RetentionPolicy.RUNTIME)
public @interface GroupBytesMethod {
}

Then
@Aspect
@Component
public class MyAspect {

    @Around("@annotation(GroupBytesMethod)") // use full package name of annotation
    public Object groupMetrics(ProceedingJoinPoint point) throws Throwable {
        // do something before
        Object result = null;
        try {
          result = point.proceed();
        }
        catch (Throwable t) {
          // handle an exception
        }
        // do something after
        return result;
    }
}

Example here


text:
Q: Pandas: extract and select data from columns using a pattern My data contains a structure similar to this (reduced to 2 elements, but there are tens):
Variable        elem_1_pre    elem_1_post   elem_2_pre    elem_2_post
Observation1    present       absent        absent        present
Observation2    absent        present       present       absent

The ultimate objective is to select observations (and possibly the associated column names) that are present in pre but absent in post and vice versa.
In other words, an operation like (pseudocode)
("present" in *_pre and "absent" in *_post) or
("present" in *_post and "absent" in *_pre)

I'm thinking groupby could be used for this. Is such a thing possible with pandas?

A: You wondered if groupby could be used here, so I'll mention how it can be.  Short version, although I'd probably write this in two lines for clarity:
(df == 'present').groupby(lambda x: x.rsplit("_", 1)[0], axis=1).sum() == 1

First, we can start from an example dataframe, compliments of @unutbu (NOTE: this is different from yours, so that the output isn't all True):
>>> import pandas as pd
>>> df = pd.DataFrame(['present absent absent absent'.split(),
                   'present present present absent'.split()],
                  columns='elem_1_pre elem_1_post elem_2_pre elem_2_post'.split(),
                  index='Observation1 Observation2'.split(),)
>>> df
             elem_1_pre elem_1_post elem_2_pre elem_2_post
Observation1    present      absent     absent      absent
Observation2    present     present    present      absent

We can determine which of these are present:
>>> p = df == "present"
>>> p
             elem_1_pre elem_1_post elem_2_pre elem_2_post
Observation1       True       False      False       False
Observation2       True        True       True       False

Then, what we really want to do is group the columns into the "elem_1" bits.  You can use string methods or regular expressions or even the indexes if they're ordered.  I like using string methods, so we'll split the column name by the first _ on the right.  To group over the columns, we use axis=1:
>>> for k, g in p.groupby(lambda x: x.rsplit("_", 1)[0], axis=1):
    print 'group key:', k
    print g
...
group key: elem_1
             elem_1_pre elem_1_post
Observation1       True       False
Observation2       True        True
group key: elem_2
             elem_2_pre elem_2_post
Observation1      False       False
Observation2       True       False

We want to count the True values in a row and see if there's only one.  True ~ 1 and False ~ 0, so we can use sum:
>>> p.groupby(lambda x: x.rsplit("_", 1)[0], axis=1).sum()
              elem_1  elem_2
Observation1       1       0
Observation2       2       1

and then
>>> p.groupby(lambda x: x.rsplit("_", 1)[0], axis=1).sum() == 1
             elem_1 elem_2
Observation1   True  False
Observation2  False   True

Or, putting it all together:
>>> grouped = (df == "present").groupby(lambda x: x.rsplit("_", 1)[0], axis=1)
>>> answer = grouped.sum() == 1
>>> answer
             elem_1 elem_2
Observation1   True  False
Observation2  False   True

A: If the values in your DataFrame are exactly the strings 'present' and 'absent', then you could convert the string values to boolean values with
In [17]: df.values == 'present'
Out[17]:
array([[ True, False, False,  True],
       [False,  True,  True, False]], dtype=bool)

Once you have boolean values, you can use the NumPy XOR logical operator, ^, to combine two columns into the desired value:
import pandas as pd
df = pd.DataFrame(['present absent absent present'.split(),
                   'absent present present absent'.split()],
                  columns='elem_1_pre elem_1_post elem_2_pre elem_2_post'.split(),
                  index='Observation1 Observation2'.split(),)
df = pd.DataFrame(df.values == 'present',
                  columns=df.columns,
                  index=df.index)
print(df)
#              elem_1_pre elem_1_post elem_2_pre elem_2_post
# Observation1       True       False      False        True
# Observation2      False        True       True       False

for i in range(1,3):
    elem = ['elem_{i}_{s}'.format(i=i, s=suf) for suf in ('pre', 'post')]
    change = 'elem_{i}_change'.format(i=i)
    df[change] = df[elem[0]] ^ df[elem[1]]
print(df.ix[:, 'elem_1_change elem_2_change'.split()])

yields
             elem_1_change elem_2_change
Observation1          True          True
Observation2          True          True


text:
Q: Angular 2: Override Router navigate method I want to override the Router::navigate and execute some code directly in a Router class (log for example)
export const routes: Routes = [
    {
        path: '',
        redirectTo: '/home',
        pathMatch: 'full'
    }
];

export function routerFactory(rootComponentType: Type<any> | null, urlSerializer: UrlSerializer,
                   rootContexts: ChildrenOutletContexts, location: Location,
                   injector: Injector, loader: NgModuleFactoryLoader,
                   compiler: Compiler, config: Router): Router {

  return new MyRouter(
      rootComponentType,
      urlSerializer,
      rootContexts,
      location,
      injector,
      loader,
      compiler,
      config
  );
}

@NgModule({
  declarations: [
    AppComponent,
    ...
  ],
  imports: [
    routing,
    ...
  ],
  providers: [
    ...
    {
      provide: Router,
      useFactory: routerFactory,
      deps: [Type, UrlSerializer, ChildrenOutletContexts, Location, Injector,
             NgModuleFactoryLoader, Compiler, router]
    }
  ],
  bootstrap: [AppComponent]
})

With that code, i have the error:
Error: Can't resolve all parameters for routerFactory: (
[object Object],
[object Object],
[object Object],
[object Object],
[object Object],
[object Object],
[object Object],
?)

Did i miss something ? Can i override with factory the Router component ?
Why angular can't inject my routes ?

A: I managed to override the default angular Router.navigate function using the below code (Angular v6.0.3):
export class MyRouter extends Router {
  constructor(rootComponentType: Type<any>, urlSerializer: UrlSerializer,
    rootContexts: ChildrenOutletContexts, location: Location, injector: Injector,
    loader: NgModuleFactoryLoader, compiler: Compiler, config: Routes) {
    super(rootComponentType, urlSerializer, rootContexts, location, injector, loader, compiler, config);
  }
  navigate(commands: any[], extras: NavigationExtras = { skipLocationChange: false }): Promise<boolean> {
    ...
    return super.navigate(commands, extras);
  }
}

function flatten<T>(arr: T[][]): T[] {
  return Array.prototype.concat.apply([], arr);
}

export function routerFactory(rootComponentType: Type<any>, urlSerializer: UrlSerializer,
  rootContexts: ChildrenOutletContexts, location: Location, injector: Injector,
  loader: NgModuleFactoryLoader, compiler: Compiler, config: Route[][]): Router {
  return new MyRouter(
    rootComponentType,
    urlSerializer,
    rootContexts,
    location,
    injector,
    loader,
    compiler,
    flatten(config)
  );
}

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    RouterModule.forRoot([]),
    ...
  ],
  providers: [
    {
      provide: Router,
      useFactory: routerFactory,
      deps: [ApplicationRef, UrlSerializer, ChildrenOutletContexts, Location, Injector,
        NgModuleFactoryLoader, Compiler, ROUTES]
    },
    ...
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }


text:
Q: Conductivity of an Ideal Gas I'm currently going through the derivation of heat flow equation of an ideal gas in the An Introduction to Thermal Physics book by Schroeder and had some trouble understanding it. It uses the setup below:

The diagram above represents a small region within a container of gas. The temperature increases in the positive $x$ direction but does not vary in the vertical direction. $l$ is the mean free path of the molecules in the two boxes. $\Delta t=l/v_{rms}$ is the average time between collisions where $v_{rms}$ is the RMS velocity of all the molecules in the two boxes. The two boxes each have a length of $l$. $U_{1}$ is the total internal energy of particles in Box 1 and $U_2$ is the total internal energy in Box 2. The boxes are intended to be imaginary separations and not actual physical separations.
During the time interval $\Delta t$, the book states that the energy crossing the dotted line from Box 1 is equal to $U_{1}/2$ since half of the particles in Box 1 will have a positive velocity in the $x$ direction. In other words, half of the molecules in Box 1 will cross the dotted line during $\Delta t$. By the same logic, the energy crossing the dotted line from Box 2 to the left is equal to $U_{2}/2$. Then, the net heat energy $Q$ that crosses the dotted line is:
$$Q = \frac{1}{2} (U_1-U_2) = -\frac{1}{2} (U_2-U_1) = -\frac{1}{2} C_V (T_2-T_1) = -\frac{1}{2}C_V l \frac{\text{d}T}{\text{d}x}$$
But my problem with this derivation is that $\Delta t$ is the time taken to travel one mean free path $l$ the mean free path averaged over all of the molecules in both boxes. That is, since the temperature in Box 1 is smaller than the average temperature of the two boxes (and hence the average velocity of molecules in Box 1 are smaller than $v_{rms}$), the molecules in Box 1 will not travel the entire distance $l$ during $\Delta t$. This implies that less than half of the molecules in Box 1 will cross the dotted line and hence the energy crossing the dotted line from Box 1 should be less than $U_{1}/2$. Is there something incorrect with my reasoning or is the book skipping over the details?

A: Since $l$ is very small, the difference of temperatures of Box 1 and Box 2 are also small hence we can ignore the difference of the average speeds of molecules in the two boxes.


text:
Q: How do I make multiple if statements more concise? I am trying to make this script more concise, since I will be adding on more statements in the future.
x = Math.floor((Math.random() * 9) + 1);
var one = document.getElementById("test");

if(x === 1) {
  one.style.backgroundColor = "red";
}
if(x === 2) {
  one.style.backgroundColor = "blue";
}
if(x === 3) {
  one.style.backgroundColor = "yellow";
}

A: You can store the properties and values in a plain object
const o = {1:'a',2:'b',3:'c'}
one.style.backgroundColor = o[x]

A: If you do not need the random value for other purpose, you could take an array and check if you got a truthy value for setting the color.

var x = ['red', 'blue', 'yellow'][Math.floor(Math.random() * 9)],
    one = document.getElementById("test");

if (x) one.style.backgroundColor = x;

test

A: Another solution could be creating a Map between ids and colors. Note this enable the possibility of define values for non-consecutive indexes. Also, you could, for example, assign multiple mappings to some color to give they more probability.

let bgColor = new Map();
bgColor.set(1, {bg:"red", c:"black"});
bgColor.set(2, {bg:"blue", c:"white"});
bgColor.set(3, {bg:"green", c:"red"});
bgColor.set(4, {bg:"skyblue", c:"black"});
bgColor.set(5, {bg:"maroon", c:"white"});
bgColor.set(6, {bg:"red",c:"black"});
bgColor.set(7, {bg:"red",c:"black"});
bgColor.set(8, {bg:"BlueViolet", c:"white"});

var one = document.getElementById("test");

setInterval(function()
{
    let x = Math.floor((Math.random() * 9) + 1);
    let {bg, c} = bgColor.get(x) || {};
    console.log(x, bg, c);

    if (bg)
    {
        one.style.backgroundColor = bg;
        one.style.color = c;
    }
}, 1000);

I'm Gonna be Iron Like a Lion in Zion

A: Another possibility, if your end goal is to simply randomly select between a number  of equally-weighted values is to write a simple function that accepts those values, and either returns one or returns a function, which when called returns one.  Here's the second version:

const randomChoice = (vals) => () => vals[Math.floor(vals.length * Math.random())]
const randomColor = randomChoice(['red', 'blue', 'yellow'])

document.body.style.backgroundColor = randomColor()

Here randomChoice is a utility function that might be stored elsewhere, and randomColor generates one of the items you need.
This might not meet your needs.  But if the three branches were just placeholders, and you would eventually need the nine the code suggests, then this might be the easiest to keep up-to-date.
This could be expanded to handle unequal weightings, but it would be more complex.  There are plenty of places where this sort of random choice could be useful.

A: Another way of doing it would be by implementing a simple weight system.

const colors = [
  { color: 'skyblue', weight: 1 },
  { color: 'orangered', weight: 2 },
  { color: 'black', weight: 1 },
  { color: 'teal', weight: 3 }
].reduce((res, {color, weight}) => [...res, ...Array(weight).fill(color)],[]);

const randomColor = () => colors[Math.floor(colors.length * Math.random())];

// Demo
Array(50).fill().forEach(() => {
  const el = document.createElement('div');
  const color = randomColor();
  el.innerText = color;
  el.style.backgroundColor = color;
  document.body.append(el);
});


text:
Q: Hide or not to hide the system tray in a Windows Phone 7 application? I am debating whether to hide or not to hide the system tray in a Windows Phone 7 application. I've not found any general suggestions on this issue -the official Windows Phone design guidelines don't address this issue at all - except for Jeff Wilcox's blog post who suggested that he personally likes to see the system tray in applications. I'd like some general advice on this issue from other Windows Phone developers.
Some reasons for showing the system tray are

*

*Doesn't take up that much space

*Users may want to see it at times

Reasons for hiding it are

*

*You can't control its background: unless you're using PhoneBackgroundBrush as the background the top row will stand out

*Lots of widely used / official apps already hide it: all games as well as the official Facebook and Twitter app.

I'd appreciate all advice on this.

A: I would say it depends on the application/game you are writing
If the app needs a network connection or if you will be in the application for a long period of time show it so the user can keep an eye on network and battery.
If you need the extra screen space (for a game?), and you rarely need network hide it.
Or... I guess you leave it up-to the user and give them a setting to programatically hide/show it.

A: I think its best to use the tray in applications that are tools or utilities. Typically these users would prefer more info than less when they're using applications on the phone (battery, network, time).
Also adding the tray in there tends to make the application look more native on the phone (according to me and others I've asked), which is a big plus because the user associates your app as if it was built with the phone OS.
But if the application is a game, media, etc. type of application I recommend you take it off, especially on panorama because it takes away from the intended design. Also these types of applications focus on the content and seeing multiple little icons at the top can take away from the experience.
Really to me the space it occupies isn't really THAT much, so that shouldn't be too much of an issue. But rather the purpose of the app as stated above.
I do like the suggestions that have been given as far as giving the user the choice. Check out this code:
        bool ShowTray;

        //ASK USER WHAT THEY WANT
        //ShowTray = true or false;

        SystemTray.IsVisible = ShowTray;

A: I've been reluctantly hiding, at least on any view where I have a background image; otherwise it looks too strange to me. I've been considering a setting in my app that would allow the user to choose, and persisting that to isolated storage.
Also considering maybe having the top of the screen in phone background brush color and have it fade / blend into another color or background image. Not sure how well that would turn out but as long as it is not a cheesy looking gradient effect, perhaps.
I'm hoping eventually MS will soon add support for transparency in the system tray or otherwise help address this issue. As a user I wish that I could force the system tray to always be visible across all apps, but as a developer I realize that the visual effect often doesn't look good.
Perhaps if the community came up with a new UX metaphor where maybe double-tapping in the system tray area would toggle whether it is visible. A single tap could perhaps start to animate / pop / hint at the system tray...

A: Transparency and colors are now possible with Mango by setting its BackgroundColor and Opacity :
shell:SystemTray.IsVisible="True"
shell:SystemTray.BackgroundColor="Transparent"
shell:SystemTray.Opacity="0"

I would say by default show it unless it really gets in the way in a way you can't workaround, especially if its an app and not a game.


text:
Q: I don't understand the problem that the error want to tell me. i copied the error message #include <iostream>;

using namespace std;

int main()

{

    int  total_of_seconds;

cout << "please inter the total of seconds \n";

cin >> total_of_seconds ;

int seconds_per_day = 24* 60 *60 ;

int seconds_per_hours = 60 * 60 ;

int seconds_per_minutes= 60 ;

int number_of_days = floor (total_of_seconds/seconds_per_day) ;

int s = total_of_seconds % seconds_per_day ;

int number_of_hours=  floor (s/seconds_per_hours ) ;

int s %= seconds_per_hours;

int number_of_minutes= floor (s/seconds_per_minutes) ;

int s %= seconds_per_minutes;

int number_of_seconds = s;

cout << number_of_days <<":" << number_of_hours <<":" << number_of_minutes<< ":" << number_of_seconds<<endl ;

return 0;

}

/tmp/uGTkaIpa1f.cpp:11:22: error: 'floor' was not declared in this scope
   11 | int number_of_days = floor (total_of_seconds/seconds_per_day) ;
      |                      ^~~~~
/tmp/uGTkaIpa1f.cpp:14:7: error: expected initializer before '%=' token
   14 | int s %= seconds_per_hours;
      |       ^~

A: You have declared your variable at

int s = total_of_seconds % seconds_per_day ;

and you're trying to re-declare it at

int s %= seconds_per_hours;

remove the int declaration
P.S. include the cmath for using floor


text:
Q: Use .bashrc without breaking sftp My problem is that I need to set a few variables, and output a few lines every time I login to the ssh shell, and at the same time I have to be able to use sftp to tarnsfer files via Filezilla.
Now, as per the openssh FAQ at http://www.openssh.org/faq.html, if your startup scripts echo any kind of output, it messes up with sftp. So it either delays indefinitely, or errors out with a "Connection closed by server with exit code 128".
I have tried solutions like moving .bashrc to .bash_profile, or using the following code in .bashrc:
if [ "$TERM" != "dumb" ]
then
   source .bashc_real
fi

And:
if [ "$TERM" = "xterm" ]
then
   source .bashc_real
fi

However, nothing works. My shell terminal is bash, and I connect to sftp with filezilla.

A: If you're using csh:
if ($?prompt)
  ... interactive stuff ...

And if it's bash:
if [[ $- == *i* ]]; then
  ... interactive stuff ...
fi

or alternatively using bash regular expressions:
if [[ $- =~ i ]]; then
  ... interactive stuff ...
fi

These lines should precede lines where you ouput/echo something back.

A: Try doing this instead
if [ "$SSH_TTY" ]
then
   source .bashc_real
fi

A: Mike's answer will probably work.  But it's worth pointing out that you can accomplish this carefully selecting which startup files to put the verbose stuff in.  From the bash man page:

When  bash is invoked as an interactive login shell, or as a non-interactive shell with the --login option, it first reads and executes  commands  from  the file /etc/profile, if that file exists.  After reading that file, it looks for ~/.bash_profile, ~/.bash_login, and ~/.profile, in  that order, and reads and executes commands from the first one that exists and is readable.  The --noprofile option may be  used  when  the shell is started to inhibit this behavior.
When an interactive shell that is not a login shell  is  started,  bash reads
and executes commands from ~/.bashrc, if that file exists.  This may be
inhibited by using the --norc option.  The --rcfile file  option will  force
bash  to  read  and  execute commands from file instead of ~/.bashrc.

The sftp/scp tools start an interactive non-login shell, so .bashrc will be sourced.  Many distributions source .bashrc from .bash_profile or vice versa, so it can get confusing.  A good trick for testing the cleanliness of your login environment is to ssh in with a command, which simulates the same way scp/sftp connect.  For example: ssh myhost /bin/true will show you exactly what scp/sftp sees when they connect.
A simple demo:
insyte@mazer:~$ echo "echo Hello from .profile" > .profile
insyte@mazer:~$ echo "echo Hello from .bashrc" > .bashrc

sazerac:~ insyte$ ssh mazer /bin/true
Hello from .bashrc
sazerac:~ insyte$

insyte@mazer:~$ rm .bashrc

sazerac:~ insyte$ ssh mazer /bin/true
sazerac:~ insyte$

The first test will cause scp/sftp/rsync etc. to break.  The second version will work just fine.

A: Mike's solution worked for me as well. But since my default shell is TCSH, I had to slightly edit the fix as follows (in .tcshrc):
if ( $?SSH_TTY ) then
    exec /bin/bash
endif

Just thought I would share for everyone's benefit.

A: Here are the first lines of my (default) .bashrc file:
# ~/.bashrc: executed by bash(1) for non-login shells.
# see /usr/share/doc/bash/examples/startup-files (in the package bash-doc)
# for examples

# If not running interactively, don't do anything
case $- in
    *i*) ;;
      *) return;;
esac

The check for an interactive session avoids messing up with SCP, SFTP or ssh remote-host command mode.
Without this, if your file .bashrc uses echo or some other stuff printing on stdout, you may get this kind of errors:

*

*SFTP : Received message too long 168435779

*SCP : protocol error: unexpected <newline>

A: I like some of the other solutions mentioned here better, but I thought I throw out the solution that I currently use on my bash and csh VMs to prevent SFTP disconnects due to echo commands in my startup scripts, just in case anyone finds the information helpful.
In BASH:
if [ $TERM == "xterm" ] || [ $TERM == "xterm-256color" ]; then
  echo "Xterm display identified: echo enabled"
  echo_disable="0"
else
  echo_disable="1"
fi

# Use the following for all subsequent echo commands
if [ $echo_disable == 0 ]; then
 echo "Safe to display on Xterm"
fi

In csh:
if ($TERM == "xterm") then
  echo "Xterm display identified: echo enabled"
  set echo_disable = "0"
else
  set echo_disable = "1"
endif

# Use the following for all subsequent echo commands
if !( "$echo_disable" ) echo "Safe to display on Xterm"

It's a bit brute force, but it does work.


text:
Q: How to add friends to specific list on facebook? I am searching for a way to select all friends that attended to an event, and add them to a specific list.
This should have been implemented in facebook already, as they are blocking profiles for doing massive event invites, without providing tools for massively organize these friends per categories. There should be a way to select all the friends that joined an event, add them to a list, and invite this list for events that will interest the list.
This JS code helps to massive invite all friends. Does anybody know how to modify this in order to add these selected profiles to a list? I have searched the API and didnt find anything that could work so far.
javascript:elms=document.getElementsByName("checkableitems[]");for (i=0;i<elms.length;i++){if (elms[i].type="checkbox" )elms[i].click()};

Any help would be appreciated. Thanks!


text:
Q: Read IR Sensor in python I'm working on a project on python and Arduino. And I have a /possibly/ silly question. How I can read an IR Sensor in python for two different conditions depends on the sensor's state. Like:
import serial
Arduino = ('COMx', 96000, timeout=x)

If Sensor is LOW:
//do something
else:
// do another thing.

I want to move a stepper motor and if one detects IR Sensor, change the direction and if detects another one, reset the loop. But, in this moment I want to know how I can read the sensor in python


text:
Q: How to prevent other phone/mobile numbers to send SMS command to Arduino? INTRO:
I'm a novice when it comes to Arduino programming and using AT commands. I already tried to search the whole internet and asked on Arduino forum, but I have no luck and nobody seems to give me a clear idea about it there.
PROBLEM:
So, I have this code where an SMS command can switch on and off the light and it will response to a specific phone number only. My problem is, the program response even when I'm using different phone numbers. I hope there's a way which it can only whitelist a specific number so no one can prank the program without the owner's knowledge.
FOR EXAMPLE:

*

*The owner's phone number is +631234567890

*Some random phone number: +63xxxxxxxxxx

The owner can switch on and off the light. [YES]
But supposedly, the random phone number CAN NOT and will never have the authority to switch the lights on and off. Only the owner can.
HERE'S MY CURRENT CODE: CCTO
#include <SoftwareSerial.h>
SoftwareSerial GPRS(10, 11);
String textMessage;
String lampState;
const int relay = 12;

void setup() {
  pinMode(relay, OUTPUT);
  digitalWrite(relay, HIGH);

  Serial.begin(9600);
  GPRS.begin(9600);
  delay(5000);
  Serial.print("GPRS ready...\r\n");
  GPRS.print("AT+CMGF=1\r\n");
  delay(1000);
  GPRS.print("AT+CNMI=2,2,0,0,0\r\n");
  delay(1000);
}

void loop(){
  if(GPRS.available()>0){
    textMessage = GPRS.readString();
    Serial.print(textMessage);
    delay(10);
  }
  if(textMessage.indexOf("ON")>=0){
    // Turn on relay and save current state
    digitalWrite(relay, HIGH);
    lampState = "ON";
    Serial.println("Lamp set to ON\r\n");
    textMessage = "";
    GPRS.println("AT+CMGS=\"+631234567890\"");
    delay(500);
    GPRS.print("Lamp was finally switched ON.\r");
    GPRS.write( 0x1a );
    delay(1000);
  }
  if(textMessage.indexOf("OFF")>=0){
    // Turn off relay and save current state
    digitalWrite(relay, LOW);
    lampState = "OFF";
    Serial.println("Lamp set to OFF\r\n");
    textMessage = "";
    GPRS.println("AT+CMGS=\"+631234567890\"");
    delay(500);
    GPRS.print("Lamp was finally switched OFF.\r");
    GPRS.write( 0x1a );
    delay(1000);
  }
  if(textMessage.indexOf("STATUS")>=0){
    String message = "Lamp is " + lampState;
    GPRS.print("AT+CMGF=1");
    delay(1000);
    Serial.println("Lamp state resquest");
    textMessage = "";
    GPRS.println("AT+CMGS=\"+631234567890\"");
    delay(500);
    GPRS.print("Lamp is currently ");
    GPRS.println(lampState ? "ON" : "OFF");
    GPRS.write( 0x1a );
    delay(1000);
  }
}

How can I do that?

A: Your textMessage must contain an information about sender and time of the message. Something like this:

+CMGL: 2,"REC UNREAD","+63xxxxxxxxxx",,"07/02/18,00:07:22+32" A simple demo of SMS text messaging.

So, you need to extract the phone number at compare it with the authorized one.

A: You can define the desired phone number in the code and compare it with the number assigned to the incoming SMS. If the number matches the one in your code, proceed with the algorithm. Otherwise, ignore the message.
Got this code from the official Arduino Forum, which you can check out from the link given at the end. You can code out these two functions:

String CellNumtemp;
String CellNum;

// check if there are incoming SMS
void ricezione(){
  Serial.println ("controllo ricezione SMS");
  // AT command to set mySerial to SMS mode
  mySerial.print("AT+CMGF=1\r");
  delay(100);
  // Read the first SMS saved in the sim
  mySerial.print("AT+CMGR=1\r");
  delay(10);
  if(mySerial.available()>0){
    textMessage = mySerial.readString();
    Serial.print(textMessage);
    delay(10);
  }
  // check if the SMS is "STATO"
  if(textMessage.indexOf("STATO")>=0){
    Serial.println("Invio info stato arnia");
    //save the phone number of the senders in a string (this works with italian region you must adapt to   yours)
    CellNumtemp = textMessage.substring(textMessage.indexOf("+39"));
    CellNum = CellNumtemp.substring(0,13);
    smsstato();
    CellNumtemp = "";
    textMessage = "";
  }
  mySerial.print("AT+CMGD=1\r");
  delay(100);
  mySerial.print("AT+CMGD=2\r");
  delay(100);
}

// Send sms with all the information to the number stored
void smsstato(){
  // delete the first SMS
  mySerial.print("AT+CMGD=1\r");
  delay(100);
  mySerial.print("AT+CMGF=1\r");
  delay(1000);
  mySerial.print("AT+CMGS=\"");
  mySerial.print(CellNum);
  mySerial.print("\"\r");
  delay(1000);
  //The text of the message to be sent.
  mySerial.print("INFO: Latitudine: ");
  mySerial.print(latitude);
  mySerial.print(", Longitudine: ");
  mySerial.print(logitude);
  mySerial.print(", Ampere: ");
  mySerial.print(consumotemp);
  delay(1000);
  mySerial.write(0x1A);
  delay(1000);
  Serial.println("sms stato");
}```

Thanks to the user ilteo85 on the https://forum.arduino.cc.
Check this out for reference: https://forum.arduino.cc/index.php?topic=637264.0

A: you could just use the whitelisting function in gsm module
the cmd is
AT+CWHITELIST=mode,index,number
Parameters

0 Disable
1 Enable only call white list
2 Enable only SMS white list
3 Enable call and SMS white list

The index of phone number, scope: 1-30

Phone number to be set
example
AT+CWHITELIST=2,1,+9198xxxxxxx


text:
Q: Test Coverage for Batch Class I have the following Batch class which operates on a custom object (Sample__c) and the default Contact object. My test class goal was to create a list of Samples which I know satisfy the batch's query , insert those and then run the batch with an assert on all the created Samples which tests what the batch should have modified. Right now my test is failing and I'm getting 0% coverage on the batch class. Any help would be appreciated, thank you.
global class SampleSurveyEmailHandler implements Database.Batchable<sObject>{

NPS_Survey_Date_Window__c window = NPS_Survey_Date_Window__c.getInstance();
Date minimum = Date.today().addDays(window.Minimum__c.intValue());
Date maximum = Date.today().addDays(window.Maximum__c.intValue());
Set<String> productCodes = new Set<String>{'WISDOMUK_IN', 'WISDOM_IN', 'Wisdom_PB', 'Wisdom_DD'};
List<String> emailsNotUsed = new List<String>{'bev@mirandalambert.com', 'annbelles@aol.com', 'feragen.at'
    ,'dna-worldwide.co.uk', 'vetgen.com', 'blackdogdna.com', 'canix-dna.com', 'dna-worldwide', 'mss.effem.com',
    'anidom.de', 'whatbreedismydog', 'info@canix-dna.com', 'customercare@marsveterinary.com', 'wisdom@wisdompanel.com',
    'info@anidom.de', 'info@blackdogdna.com', '4dogs@caninelifetimehealth.org', 'program@searchdogfoundation.org'};
Integer sixMonths = 180;
Integer surveySentDifference =0;
public String query = 'SELECT Id,Product_Code__c,Consumer_Email__c, Consumer__r.NPS_Email_Sent_On__c FROM Sample__c WHERE'+
    ' Survey_Mail_Sent__c = false AND' +
    ' RGS_Report_Regenerated_On__c = NULL AND'+
    ' Financial_State__c = NULL AND'+
    ' Has_Escalated_Case__c = false AND'+
    ' RGS_Report_Ready_On__c >:' + maximum +
    ' AND RGS_Report_Ready_On__c <:' + minimum;

//retrieved from custom setting so we can stop the process and re-run with
//other settings if need be

public SampleSurveyEmailHandler(){
}

global Database.QueryLocator start(Database.BatchableContext BC)
{

    return Database.getQueryLocator(query);
}

global void execute(Database.BatchableContext BC, List<Sample__c> scope)
{
    // we really just need the Id from this object so we can send the correct template for every environment
    EmailTemplate template = [SELECT Id, Name FROM EmailTemplate WHERE Name = 'NPS_Customer_Survey'];
    // We'd like to send a customer another survey if they purchase samples more than 180 days apart
     for(Sample__c sample : scope){
        boolean validEmail = true;
        for( String key : emailsNotUsed){
            if(sample.Consumer_Email__c.contains(key)){
                validEmail = false;
                break;
            }
        }
        if(sample.Consumer__r.NPS_Email_Sent_On__c == NULL){
            //this consumer hasn't received a Survey Email so we want to force one through
            surveySentDifference = 181;
            }
        else{
            surveySentDifference = date.valueof(sample.RGS_Report_Ready_On__c).daysBetween(sample.Consumer__r.NPS_Email_Sent_On__c);
        }

        if(productCodes.contains(sample.Product_Code__c) && validEmail == true && surveySentDifference > sixMonths){
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            mail.setTargetObjectId(sample.Consumer__r.Id);
            mail.setTemplateId(template.Id);
            Messaging.sendEmail(new Messaging.SingleEmailMessage[] {mail});
            sample.Survey_Mail_Sent__c = true;
            sample.Consumer__r.Survey_Email_Sent__c = true;
            sample.Consumer__r.NPS_Email_Sent_On__c = Date.today();
            }

     }
     update scope;
}
global void finish(Database.BatchableContext BC){}

}
    @isTest
private class TestClass_SampleSurveyEmailHandler {

  static testMethod void unitTest(){
    List<Sample__c> samples = MSS_TestData.createSampleRecords(20);
    Date twoWeeksAgo = Date.today().addDays(-15);
    Contact cont = new Contact();
    cont.Email = 'sam.vanryssegem@mss.effem.com';
    List<Id> sampleIds = new List<Id>{};
    for(Sample__c sample : samples){
      sample.RGS_Report_Ready_On__c = twoWeeksAgo;
      sample.Consumer__r = cont;
      sample.Product_Code__c = 'WISDOM_IN';
      sampleIds.add(sample.Id);

    }
  String query = 'SELECT Id,Product_Code__c,Consumer_Email__c, Consumer__r.NPS_Email_Sent_On__c FROM Sample__c WHERE'+
        ' Id IN ' + sampleIds;
    insert samples;

    Test.startTest();
    List<Sample__c> queriedSamples = [SELECT Id,Product_Code__c,Consumer_Email__c, Consumer__r.NPS_Email_Sent_On__c FROM Sample__c WHERE Id IN :sampleIds];
    System.assert(queriedSamples.size() >0);
    SampleSurveyEmailHandler handler = new SampleSurveyEmailHandler();
    handler.query = query;
    Database.executeBatch(handler);
    for(Sample__c sample : samples){
      System.assert(sample.Consumer__r.NPS_Email_Sent_On__c != NULL);
    }
    Test.stopTest();

  }
}

A: One problem is that the query you are using in your test case is just appending the list of IDs to the query string which will not include the necessary braces or quotes.
Instead you need something like this:
String inTerm = '(\'' + String.join(sampleIds, '\',\'') + '\')';

and append that to your two query strings.
Invalid SOQL syntax would stop your batchable code ever being reached.
Your test will need to requery the Sample__c object after the Test.stopTest() call to meaningfully assert the NPS_Email_Sent_On__c value.
(I also suggest it would be better to not change the query used in the batchable in the test but rather to create objects in the test case that result in matches from the query.)

A: Try changing your test class code for start and stoptest() location:
List<Sample__c> queriedSamples = [SELECT Id,Product_Code__c,Consumer_Email__c, Consumer__r.NPS_Email_Sent_On__c FROM Sample__c WHERE Id IN :sampleIds];
System.assert(queriedSamples.size() >0);
Test.startTest();
SampleSurveyEmailHandler handler = new SampleSurveyEmailHandler();
handler.query = query;
Database.executeBatch(handler);
Test.stopTest();
List<Sample__c> lstSamples = [SELECT sample.Consumer__r.NPS_Email_Sent_On__c FROM Sample__c];
for(Sample__c sample : lstSamples){
  System.assert(sample.Consumer__r.NPS_Email_Sent_On__c != NULL);
}


text:
Q: Atualizar definições de colunas e tabelas com Hibernate Boa tarde.
Gostaria de saber e confirmar se tem alguma maneira de atualizar definições de tabela e coluna em cada schema utilizando o Hibernate.
Por enquanto, o que vi até agora foi que o Hibernate apenas cria tabelas e colunas, mas não deleta ou modifica as suas definições, como, por exemplo, o tamanho de um campo.
Já implementei o Flyway no aplicação e o mesmo está funcionando corretamente, porém a ideia é que isto seja feito sem criar um script SQL para percorrer os schemas e que o Hibernate identifique as definições que precisam ser alteradas, tabelas e campos que precisam ser criados e que aplique no banco para cada schema.
Agradeço desde já.

A: Dentro do persistence.xml (ou hibernate.cfg.xml ou algum outro mecanismo equivalente) você pode definir a seguinte propriedade:
<property name="hibernate.hbm2ddl.auto" value="update" />

*

*O valor "update" altera a estrutura do banco de dados para refletir as suas entidades Java.

*O valor "validate" não altera o banco de dados, apenas verifica se ele coincide com o especificado nas entidades. Caso não coincidir, uma exceção será lançada na inicialização.

*O valor "create" recria o banco de dados do zero, perdendo as informações lá existentes.

*O valor "create-drop" recria o banco de dados do zero, perdendo as informações lá existentes e também apaga tudo ao terminar de executar.

Portanto, me parece que o que lhe interessa é o "update". Mas devo avisar que não é recomendável utilizar-se isso em produção devido aos riscos inerentes de fazer-se modificações estruturais em tabelas sem o acompanhemento e planejamento manual e detalhado disso. Em ambiente de produção é recomendado usar apenas o "validate".


text:
Q: Do we receive hat notifications on the Android mobile app? I know hats are not enabled in the Android app, but is there a way to receive notifications when you have earned one? Similar to when you get a comment or other notification, just for hats, or has the app been left entirely normal this year?

A: Well, apparently the Android App hates hats, and with Winter Bash notifications being in their own little snowflake menu, the answer is "nope".
(posted from my Android phone)


text:
Q: Download data from webmap made with leaflet Can I download the data from a webmap made available from leaflet? I am referring to these dataset (https://www.vectorbase.org/popbio/map/), for which I wish to download the data for Europe? Is there a way to import these data into QGIS providing the link of the website?

A: In general, yes, in theory, yes, in practice, yes with a bit of work. There's no general general solution because you can't know how the data is coming from the server. The solution involves looking at the underlying Javascript and seeing what it does. Chances are it will be an AJAX call to a server that returns a geoJSON data set, but it could literally be anything. If AJAX and geoJSON mean nothing to you then I doubt you'll be able to write something to do it for any given site.
That said, the site you reference has a big fat "Downloads" button which is clearly the recommended way to get the data you want rather than trying to reverse engineer their web map system. Use that.

A: I would complete (although it can still be known how data come from the server) Spacedman's answer by saying that reverse-engineering the AJAX call to retrieve data with the finest granularity (at the level of each point) would give nothing but an important coding/development stage to accomplish first. Indeed, data aggregation (averaging and so on) is  server-sidely performed. Furthermore, no geoJSON format specification adopted here. An example of call being :
https://www.vectorbase.org/popbio/map/asolr/solr/vb_popbio/smplGeoclust?q=*&fq=geo_coords:[44.731125592643274,-18.9404296875%20TO%2055.26659815231191,22.873535156249996]&stats.facet=geohash_3&facet.pivot=geohash_3,species_category&json.wrf=jQuery110206188232152791343_1464644641028&callback=?&_=1464644641034

May be you should try to contact them ?


text:
Q: get Sum of values in column from sqlDataSource I have a SqlDataSource dsDetails that selects from the DB table.
<asp:SqlDataSource ID="dsDetails" runat="server" SelectCommand="spGetDetails"
OnSelected="dsDetails_Selected" SelectCommandType="StoredProcedure">
<SelectParameters>
    <asp:QueryStringParameter Name="mode" QueryStringField="mode" Type="String" DefaultValue="NULL" />
</SelectParameters>
</asp:SqlDataSource>

The result is bound to gridview in the aspx page
<asp:GridView  CssClass="content" ID="gridDetails" runat="server" DataSourceID="dsDetails" AllowSorting="True" AllowPaging="True" PagerSettings-Position ="TopAndBottom" DataKeyNames="ID" AutoGenerateColumns="False" >
        <PagerSettings Position="TopAndBottom" Mode="NumericFirstLast" />
        <EmptyDataTemplate>
            <b>There are no records to display.</b>
        </EmptyDataTemplate>
        <Columns>
            <asp:BoundField DataField="empNum" HeaderText="Employee Number" SortExpression="empnum" ApplyFormatInEditMode="True" HtmlEncode="False" ReadOnly="True" />
            <asp:BoundField DataField="empName" HeaderText="Emplopyee Name" SortExpression="empname" ApplyFormatInEditMode="True" HtmlEncode="False" ReadOnly="True" />
            <asp:BoundField DataField="empDoj" HeaderText="Emplopyee Date of joining" SortExpression="empdoj" ApplyFormatInEditMode="True" HtmlEncode="False" ReadOnly="True" />
            <asp:TemplateField HeaderText="Salary" SortExpression="sal">
                <EditItemTemplate>
                    <asp:TextBox ID="txtSal" runat="server" Text='<%# Eval("sal", "{0:F}") %>'></asp:TextBox>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="Label4" runat="server" Text='<%# Eval("sal", "{0:C2}") %>'></asp:Label>--%>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField>
                <EditItemTemplate>
                    <asp:Button ID="btnSave" runat="server" CausesValidation="True" CommandName="cmdSave"
                        Text="Save" />
                    <asp:Button ID="btnCancel" runat="server" CausesValidation="False" CommandName="cmdCancel"
                        Text="Cancel" />
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Button ID="btnApprove" runat="server" CausesValidation="False" CommandName="cmdApprove"
                        Text="Approve" />
                    <asp:Button ID="btnEdit" runat="server" CausesValidation="False" CommandName="cmdEdit"
                        Text="Edit" />
                    <asp:Button ID="btnDelete" runat="server" CausesValidation="false" CommandName="cmdDelete"
                        Text="Delete" />
                    <ajaxToolkit:ConfirmButtonExtender ID="cbeDelete" runat="server"
                        TargetControlID="btnDelete"
                        ConfirmText="Are you sure?" />
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>

Now what i have to achieve is Find the Sum of the Salary Column of the grid view. How to achieve this using the Data Source in the page load method? I have to get the sum of Salary for the entire result set (avg records returned 60-80)
Iterating through the rows and computing the sum in gridDetails_RowDataBound wont be effective since the rows.count will be max of 10 since the page size is 10. When the result set has more than 10 records say 55, It will compute the sum for the current gridview page alone (first 10 records). I have to get the sum for all 55 records and display it in a label in the pageload method.
Please provide suggestion..

A: The SQLDataSource provides a Selected event that fires after data retrieval has finished.  See SqlDataSource.Selected Event.  You should be able to do a sum on the rows in the grid in this event.

A: This worked for me
In PageLoad method add
dvSql = DirectCast(dsDetails.Select(DataSourceSelectArguments.Empty), DataView)
                    For Each drvSql As DataRowView In dvSql
                        amtSum += CDbl(drvSql("sal"))
                    Next
                    lblTotalAmt.Text = CStr(recoveryAmtSum)

In dsDetails_Selected method add this line
e.Command.Parameters("@approvaltype").Value = mode


text:
Q: Detecting if an element is visible on the page with JavaScript or Puppeteer I'm building a framework that crawls websites hosted on our infrastructure to verify there is nothing against our policies. If there is content prohibited, we are taking a screenshot of it among other details.
Obviously, you can't take screenshot if the element is not visible due to being inside of an overflow: hidden parent or because there is an absolute element positioned above it.
Is there a way in 2019 to know if an element can be visible to the human eye?
Since it's inside Puppeteer I can use either native Puppeteer API or whatever JavaScript library needed since I can inject it to the page.
Example of the problem:

$('#above').html(`You can see green: ${$('#below').is(':visible')}. But can you really?`)
#above {
  width: 600px;
  height: 600px;
  position: absolute;
  background-color: red;
  text-align: center;
  font-size: 30px;
  padding: 30px;
}

#below {
  width: 440;
  height: 200;
  background-color: red;
}

(Yes, I saw this question was asked, but it was 7 years ago and much was changed since and I can also use puppeteer which in his case was not possible).

A: I never did this, but the hover function will fail if the element is not visible or "hoverable". You could do something like this:
let error = null;
await page.hover('yourSelector').catch(e => error = e);
if (!error) {
   //The element should be visible here.
}

A: I found a way (thanks @hardkoded for planting the idea in my head...)
I didn't test it on all edge cases, but it does seem to work on my example.
Basically I'm adding an eventListener for mouseover event that sets a boolean flag and then calling puppeteer's hover function that moves the mouse to the center of the element.
If the flag is set, the element is visible.
await page.goto('c:/temp/code.html')
const el = await page.$('#below')
await page.evaluate(el => {
  el.addEventListener('mouseover', function () {
    this.setAttribute('mouseover-worked', 'true')
    console.log('hovered!!!')
  })
}, el)
await el.hover()
const hovering_works = await page.evaluate(el => el.getAttribute('mouseover-worked'), el)
console.log(hovering_works)

If someone finds a flaw, please let me know...

A: There is an easy way built into the puppeteer library to check this. You can give a { visible: false } option to the page.waitForSelector function that will check or actually wait until an element is visible:
const element = await page.waitForSelector('#selector', { visible: true });

This will do a decent check. See the full code of the function here. It will check the following:

*

*Does the element exist?

*Is the element not hidden (style.visibility !== 'hidden') according to window.getComputedStyle?

*Has the element a height/width/top/bottom greater than 0 according to element.getBoundingClientRect()?

The latter case would also cover your example code as the #below element should be having a height of 0. So it's a decent check but you will always be able to construct cases in which the code does not work. If you want to cover more edge cases, you can also expand the approach of the puppeteer devs.
Full code sample
As the function will not resolve if the element does not exist, you have to use a small helper Promise to timeout the check:
const element = await Promise.race([
    new Promise(resolve => setTimeout(() => resolve(), 200)), // resolves without value after 200ms
    page.waitForSelector('#selector', { visible: true })
]);
if (element) {
    // element is visible
}

A: Maybe you can using elementHandle.boundingBox()
It will return a Promise that show a bounding box of the element (relative to the main frame), or null if the element is not visible.
The snippet example:
      const loadMoreButton = await getDataPage.$(
        'button.ao-tour-reviews__load-more-cta.js-ao-tour-reviews__load-more-cta'
      );

      const buttonVisible = await loadMoreButton.boundingBox();

      if (buttonVisible) {
        await loadMoreButton.click().catch((e) => {
          console.log(': ' + e)
        });
      }