Docker 1.5 on IPv6 only host

Question: I have problems with routing traffic from Docker (version 1.5.0) container on IPv6 only host. nc -w 10 2a00:1450:4010:c07::71 80 outputs nc: connect to 2a00:1450:4010:c07::71 port 80 (tcp) timed out: Operation now in progress.
Following this documentation ifconfig eth0; ifconfig docker0; ip -6 route show shows:
eth0      Link encap:Ethernet  HWaddr fa:16:3e:74:4a:b9
          inet6 addr: fe80::f816:3eff:fe74:4ab9/64 Scope:Link
          inet6 addr: 2a02:6b8:0:1a71::2329/64 Scope:Global
          inet6 addr: 2a02:6b8:0:1a71:f816:3eff:fe74:4ab9/64 Scope:Global
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:78994 errors:0 dropped:0 overruns:0 frame:0
          TX packets:20269 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:55503363 (55.5 MB)  TX bytes:1945660 (1.9 MB)

docker0   Link encap:Ethernet  HWaddr 56:84:7a:fe:97:99
          inet addr:172.17.42.1  Bcast:0.0.0.0  Mask:255.255.0.0
          inet6 addr: fe80::5484:7aff:fefe:9799/64 Scope:Link
          inet6 addr: fe80::1/64 Scope:Link
          UP BROADCAST MULTICAST  MTU:1500  Metric:1
          RX packets:90 errors:0 dropped:0 overruns:0 frame:0
          TX packets:28 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:6528 (6.5 KB)  TX bytes:2840 (2.8 KB)

2001:db8:0:2::/64 dev docker0  metric 1024
2a02:6b8:0:1a71::/64 dev eth0  proto kernel  metric 256
fe80::/64 dev eth0  proto kernel  metric 256
fe80::/64 dev docker0  proto kernel  metric 256
default via 2a02:6b8:0:1a71::1 dev eth0  metric 2048  mtu 1450 advmss 1390
default via fe80::1 dev eth0  metric 2049  mtu 1450 advmss 1390

And ifconfig eth0; ip -6 route show within container:
eth0      Link encap:Ethernet  HWaddr 02:42:ac:11:00:09
          inet addr:172.17.0.9  Bcast:0.0.0.0  Mask:255.255.0.0
          inet6 addr: fe80::42:acff:fe11:9/64 Scope:Link
          inet6 addr: 2001:db8:0:2:0:242:ac11:9/64 Scope:Global
          UP BROADCAST  MTU:1500  Metric:1
          RX packets:1 errors:0 dropped:0 overruns:0 frame:0
          TX packets:1 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:110 (110.0 B)  TX bytes:90 (90.0 B)

2001:db8:0:2::/64 dev eth0  proto kernel  metric 256
fe80::/64 dev eth0  proto kernel  metric 256
default via fe80::1 dev eth0  metric 1024

IPv6 and IPv4 routing is enabled (cat /proc/sys/net/ipv6/conf/default/forwarding gives 1 and cat /proc/sys/net/ipv6/conf/all/forwarding gives 1).
Seems like I need add route from docker0 bridged IPv6 traffic to eth0, but have no idea what exactly to do.
Please halp!
Answer: It is not recommended to do any kind of NAT in IPv6 environment, that defeats the purpose of IPv6.
You can accomplish access to the container through IPv6 using pipework.
Pipework allows more flexible network configuration:
sudo docker run -t -i --name myimage <image id from `sudo docker images`> /bin/bash

sudo pipework br4 -i eth1 <container id from `sudo docker ps`> 2001:db8:44::1/24@2001:db8:44::ff

sudo ip a a 2001:db8:44::FF/64 dev br4

To be able to reach your container from Internet, you will need to assign an IPv6 address from a subnet of your public IPv6.
By assigning IPv6 address to a new interface in the container (eth1), the IPv4 default route is removed and the new IPv6 default route will point to the new IPv6 default gateway via eth1.

Container interfaces before applying pipework:
root@a0b5f4937c42:/# ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host
       valid_lft forever preferred_lft forever
494: eth0: <BROADCAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default
    link/ether 02:42:ac:11:00:49 brd ff:ff:ff:ff:ff:ff
    inet 172.17.0.73/16 scope global eth0
       valid_lft forever preferred_lft forever
    inet6 fe80::42:acff:fe11:49/64 scope link
       valid_lft forever preferred_lft forever
root@a0b5f4937c42:/#

Container interfaces After applying pipework: (eth1)
root@9c8372c70ddc:/# ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host
       valid_lft forever preferred_lft forever
498: eth0: <BROADCAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default
    link/ether 02:42:ac:11:00:4a brd ff:ff:ff:ff:ff:ff
    inet 172.17.0.74/16 scope global eth0
       valid_lft forever preferred_lft forever
    inet6 fe80::42:acff:fe11:4a/64 scope link
       valid_lft forever preferred_lft forever
500: eth1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    link/ether 1e:0a:3f:b3:15:43 brd ff:ff:ff:ff:ff:ff
    inet6 2001:db8:44:0:1c0a:3fff:feb3:1543/64 scope global dynamic
       valid_lft 2591994sec preferred_lft 604794sec
    inet6 2001:db8:44::1/24 scope global
       valid_lft forever preferred_lft forever
    inet6 fe80::1c0a:3fff:feb3:1543/64 scope link
       valid_lft forever preferred_lft forever
root@9c8372c70ddc:/# route
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
172.17.0.0      *               255.255.0.0     U     0      0        0 eth0
root@9c8372c70ddc:/# route -6
Kernel IPv6 routing table
Destination                    Next Hop                   Flag Met Ref Use If
2001:db8:44::/64               ::                         UAe  256 0     0 eth1
2001:d00::/24                  ::                         U    256 0     0 eth1
fe80::/64                      ::                         U    256 0     0 eth0
fe80::/64                      ::                         U    256 0     0 eth1
::/0                           2001:db8:44::ff            UG   1024 0     0 eth1
::/0                           fe80::a8bb:ccff:fe00:100   UGDAe 1024 0     0 eth1
::/0                           ::                         !n   -1  1     3 lo
::1/128                        ::                         Un   0   1     0 lo
2001:db8:44::1/128             ::                         Un   0   1     0 lo
2001:db8:44:0:1c0a:3fff:feb3:1543/128 ::                         Un   0   1     0 lo
fe80::42:acff:fe11:4a/128      ::                         Un   0   1     0 lo
fe80::1c0a:3fff:feb3:1543/128  ::                         Un   0   1     0 lo
ff00::/8                       ::                         U    256 2     0 eth0
ff00::/8                       ::                         U    256 6     0 eth1
::/0                           ::                         !n   -1  1     3 lo
root@9c8372c70ddc:/#

From container to docker host::
root@9c8372c70ddc:/# ping6 2001:db8:44::ff
PING 2001:db8:44::ff(2001:db8:44::ff) 56 data bytes
64 bytes from 2001:db8:44::ff: icmp_seq=1 ttl=64 time=0.134 ms
64 bytes from 2001:db8:44::ff: icmp_seq=2 ttl=64 time=0.062 ms
64 bytes from 2001:db8:44::ff: icmp_seq=3 ttl=64 time=0.061 ms
^C
--- 2001:db8:44::ff ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 1998ms
rtt min/avg/max/mdev = 0.061/0.085/0.134/0.035 ms
root@9c8372c70ddc:/#

From docker host to container:
ping6 2001:db8:44::1
PING 2001:db8:44::1(2001:db8:44::1) 56 data bytes
64 bytes from 2001:db8:44::1: icmp_seq=1 ttl=64 time=0.092 ms
64 bytes from 2001:db8:44::1: icmp_seq=2 ttl=64 time=0.072 ms
64 bytes from 2001:db8:44::1: icmp_seq=3 ttl=64 time=0.074 ms
64 bytes from 2001:db8:44::1: icmp_seq=4 ttl=64 time=0.075 ms
^C
--- 2001:db8:44::1 ping statistics ---
4 packets transmitted, 4 received, 0% packet loss, time 2997ms
rtt min/avg/max/mdev = 0.072/0.078/0.092/0.010 ms
ajn:~/docker/dockergit$

Answer: Here is solution with NAT:
ip6tables -t nat -A POSTROUTING -s 2001:db8:0:2::/64 ! -o docker0 -j MASQUERADE

This will enable routing from docker subnetwork to wide world.
Comment: @SanderSteffann yep, changed it to workaround. Do you now how to get things working without it?
Comment: Sorry, no. I don't have any experience with docker yet. With virtual machines you either route an IPv6 prefix to your box and use that to route to the different VMs or you bridge your LAN to the VMs. No idea how docker does thinks though.
Comment: @SanderSteffann I have strong feeling, that without routed IPv6 segment (like in my case `2001:db8`) there is no solution with route tables, so NAT is the only solution (as in IPv4 case for docker).

Docker 1.5 on IPv6 only host


Upgrading from Ubuntu 14.04 to 14.04.1

Question: Will I be given an option to upgrade to Ubuntu 14.04.1 from 14.04 when I bootup from a cd or usb drive? Or do I need to do a complete new install?
Thank you.
Comment: I believe it's just a normal update. I did a fresh install from a 14.04 disk the day before .1 was released and the next day, after an update I had 14.04.1
Answer: If you have been doing regular updates, you may already have 14.04.1.
check $lsb_release -a
Answer: If you have 14.04 and you have been allowing it to install all the updates, you will already have all the updates included in 14.04.1.
The "point releases" like this are a way of bundling all the updates that have been released so far so that people installing 14.04 "fresh" (eg from a DVD) won't need to download so many updates immediately after installation.  It may also allow a smoother installation process because the version being installed will benefit from any new hardware support in those updates.
But if you already have a 14.04 system you'll already have those updates.
Answer: If lsb_release -a shows that you are running 14.04 try sudo apt-get update && sudo apt-get -y dist-upgrade && sudo shutdown -r now
After the reboot you should be running Ubuntu 14.04.1

Upgrading from Ubuntu 14.04 to 14.04.1


Copy-Item -Recurse skips Creation of one sub-directory

Question: I want to copy all files with all subdirectories to another machine (using a WinRM session) and the copy part of my script looks like this:
$sourceDir = "C:\Build\Application1"
$targetDir = "C:\Install\Application1"
Copy-Item -ToSession $session -Path $sourceDir\* -Destination $targetDir -Recurse -Force

$sourceDir contains two subdirectories:
C:\Build\Application1 (3 files)
             |
             +--- Application Files (empty)
                         |
                         +--- Application_2016_12_10_2 (10 files)

Scenario 1
If the folder Application1 does not exist yet in C:\Install, the destination folder structure looks like this after executing my script:
C:\Install\Application1 (3 files)
             |
             +--- Application_2016_12_10_2 (10 files)

Scenario 2
If the folder Application1 already exists in C:\Install, the destination folder structure looks like this as expected:
C:\Install\Application1 (3 files)
             |
             +--- Application Files (empty)
                         |
                         +--- Application_2016_12_10_2 (10 files)

Why is my script not creating the folder Application Files in the first scenario? Can someone clarify?
I'm using Powershell 5
Answer: See the issue what you are facing is because you are telling powershell to copy the items from the sourcedir\* . As a result, it is looking for the content of it.
So just use this directly and it will work :
$sourceDir = "C:\Build\Application1"
$targetDir = "C:\Install\Application1"
Copy-Item -ToSession $session -Path $sourceDir -Destination $targetDir -Recurse -Force

Hope it helps
Comment: That was the Problem. Thanks a lot!
Comment: Thanks @Marc.. Happy to help :)


How can I send the stdout of one process to multiple processes using (preferably unnamed) pipes in Unix (or Windows)?

Question: I'd like to redirect the stdout of process proc1 to two processes proc2 and proc3:
         proc2 -> stdout
       /
 proc1
       \
         proc3 -> stdout

I tried
 proc1 | (proc2 & proc3)

but it doesn't seem to work, i.e.
 echo 123 | (tr 1 a & tr 1 b)

writes
 b23

to stdout instead of
 a23
 b23

Answer: Editor's note:
 - >(…) is a process substitution that is a nonstandard shell feature of some POSIX-compatible shells: bash, ksh, zsh.
 - This answer accidentally sends the output process substitution's output through the pipeline too: echo 123 | tee >(tr 1 a) | tr 1 b.
 - Output from the process substitutions will be unpredictably interleaved, and, except in zsh, the pipeline may terminate before the commands inside >(…) do.
In unix (or on a mac), use the tee command:
$ echo 123 | tee >(tr 1 a) >(tr 1 b) >/dev/null
b23
a23

Usually you would use tee to redirect output to multiple files, but using >(...) you can
redirect to another process. So, in general,
$ proc1 | tee >(proc2) ... >(procN-1) >(procN) >/dev/null

will do what you want.
Under windows, I don't think the built-in shell has an equivalent. Microsoft's Windows PowerShell has a tee command though.
Comment: This doesn't do exactly what @secr requested.  `tee` will append the output of a process redirection onto `stdout` before sending it through the pipe, which is distinctly different than piping the same instance of `stdout` to multiple commands.  @dF, for example, `echo 123 | tee >(tr 1 a)  | tr 2 b` will result in `1b3 ab3`, which makes no sense in the context of the original question.
Comment: While very handy, be aware that the commands started inside >(...) are dissociated from the original shell, and you can't easily determine when they finish; the _tee_ will finish after writing everything, but the substituted processes will still be consuming the data from various buffers in the kernel and file I/O, plus whatever time is taken by their internal handling of data. You can encounter race conditions if your outer shell then goes on to rely on anything produced by the sub-processes.
Comment: This is not a POSIX construct and requires bash or ksh.
You're out of luck with tcsh and dash etc.
Comment: @Dejay Clayton: You can discard the original input by using `inproc | tee >(outproc1) >(outproc2) > /dev/null | outproc`. outproc will see only the output produced by outproc1 and outproc2. The original input is 'gone'.
Comment: @pixelbeat: …but it can be broken down to POSIX constructs (see my answer :)
Comment: Adding to the above: This works because process substitution happens before redirection (undocumented AFAICT), so `outproc1` and `outproc2` get what used to be `tee`'s 'own' stdout before it gets redirected to the bit bucket.
Comment: Thank you very much. That >(...) - concept is new to me.

Note: It doesn't seem to work under Window's cmd, PowerShell and not even cygwin's bash.
Comment: I'm not sure how to do it in PowerShell... It doesn't work in cygwin's bash for me either, I wonder whether it's a known limitation or a bug!
Comment: I tried applying this where one of the destinations is standard output. I came up with this: "command | tee >(cat - > ./log.txt)". I wonder if there is a better way.
Comment: @Harvey If I understand your question: you could use `command | tee log.txt` and it will send output to stdout and log.txt. `tee` writes to stdout and files, the `>()` trick is to send to a process.
Comment: Doesn't work when I tried it with a bigger example:  cat /usr/share/dict/words | tee >(head -1)  | tail -1
tee: /dev/fd/63: Broken pipe
ZZZ
Answer: Like dF said, bash allows to use the >(…) construct running a command in place of a filename. (There is also the <(…) construct to substitute the output of another command in place of a filename, but that is irrelevant now, I mention it just for completeness).
If you don't have bash, or running on a system with an older version of bash, you can do manually what bash does, by making use of FIFO files.
The generic way to achieve what you want, is:

decide how many processes should receive the output of your command, and create as many FIFOs, preferably on a global temporary folder:

    subprocesses="a b c d"
    mypid=$$
    for i in $subprocesses # this way we are compatible with all sh-derived shells
    do
        mkfifo /tmp/pipe.$mypid.$i
    done

start all your subprocesses waiting input from the FIFOs:

    for i in $subprocesses
    do
        tr 1 $i </tmp/pipe.$mypid.$i & # background!
    done

execute your command teeing to the FIFOs:

    proc1 | tee $(for i in $subprocesses; do echo /tmp/pipe.$mypid.$i; done)

finally, remove the FIFOs:

    for i in $subprocesses; do rm /tmp/pipe.$mypid.$i; done

NOTE: for compatibility reasons, I would do the $(…) with backquotes, but I couldn't do it writing this answer (the backquote is used in SO). Normally, the $(…) is old enough to work even in old versions of ksh, but if it doesn't, enclose the … part in backquotes.
Comment: ++ for a great approach, but you should use `mkfifo` rather than `mknod`, because only the former is POSIX-compliant. Also, the use of unquoted command substitutions is brittle, and there's potential for using globbing for efficiency.
I took the liberty of implementing a more robust solution - albeit `bash`-based - in my answer.
Note that `$(…)` has been part of POSIX for a long time now, so I'd stay away from the less predictable `\`…\`` (and SO definitely allows use of `\`` in code blocks and even in-line code spans (at least now :)).
Comment: It seems the write-side will block if one of the read-side processes stops consuming (i.e. fails to start, dies, etc).  Something to consider when thinking about the necessary resilience of your solution.
Answer: Unix (bash, ksh, zsh)
dF.'s answer contains the seed of an answer based on tee and output process substitutions
(>(...)) that may or may not work, depending on your requirements:
Note that process substitutions are a nonstandard feature that (mostly)
 POSIX-features-only shells such as dash (which acts as /bin/sh on Ubuntu,
 for instance), do not support. Shell scripts targeting /bin/sh should not rely on them.
echo 123 | tee >(tr 1 a) >(tr 1 b) >/dev/null

The pitfalls of this approach are:

unpredictable, asynchronous output behavior:  the output streams from the commands inside the output process substitutions >(...) interleave in unpredictable ways.
In bash and ksh (as opposed to zsh - but see exception below):

output may  arrive after the command has finished.
subsequent commands may start executing before the commands in the process substitutions have finished - bash and ksh do not wait for the output process substitution-spawned processes to finish, at least by default.
jmb puts it well in a comment on dF.'s answer:

be aware that the commands started inside >(...) are dissociated from the original shell, and you can't easily determine when they finish; the tee will finish after writing everything, but the substituted processes will still be consuming the data from various buffers in the kernel and file I/O, plus whatever time is taken by their internal handling of data. You can encounter race conditions if your outer shell then goes on to rely on anything produced by the sub-processes.

zsh is the only shell that does by default wait for the processes run in the output process substitutions to finish, except if it is stderr that is redirected to one (2> >(...)).
ksh (at least as of version 93u+) allows use of argument-less wait to wait for the output process substitution-spawned processes to finish.
Note that in an interactive session that could result in waiting for any pending background jobs too, however.
bash v4.4+ can wait for the most recently launched output process substitution with wait $!, but argument-less wait does not work, making this unsuitable for a command with multiple output process substitutions.
However, bash and ksh can be forced to wait by piping the command to | cat, but note that this makes the command run in a subshell. Caveats:

ksh (as of ksh 93u+) doesn't support sending stderr to an output process substitution (2> >(...)); such an attempt is silently ignored.
While zsh is (commendably) synchronous by default with the (far more common) stdout output process substitutions, even the | cat technique cannot make them synchronous with stderr output process substitutions (2> >(...)).

However, even if you ensure synchronous execution, the problem of unpredictably interleaved output remains.

The following command, when run in bash or ksh, illustrates the problematic behaviors (you may have to run it several times to see both symptoms): The AFTER will typically print before output from the output substitutions, and the output from the latter can be interleaved unpredictably.
printf 'line %s\n' {1..30} | tee >(cat -n) >(cat -n) >/dev/null; echo AFTER

In short:

Guaranteeing a particular per-command output sequence:

Neither bash nor ksh nor zsh support that.

Synchronous execution:

Doable, except with stderr-sourced output process substitutions:

In zsh, they're invariably asynchronous.
In ksh, they don't work at all.

If you can live with these limitations, using output process substitutions is a viable option (e.g., if all of them write to separate output files).

Note that tzot's much more cumbersome, but potentially POSIX-compliant solution also exhibits unpredictable output behavior; however, by using wait you can ensure that subsequent commands do not start executing until all background processes have finished.
See bottom for a more robust, synchronous, serialized-output implementation.

The only straightforward bash solution with predictable output behavior is the following, which, however, is prohibitively slow with large input sets, because shell loops are inherently slow.
Also note that this alternates the output lines from the target commands.
while IFS= read -r line; do
  tr 1 a <<<"$line"
  tr 1 b <<<"$line"
done < <(echo '123')

Unix (using GNU Parallel)
Installing GNU parallel enables a robust solution with serialized (per-command) output that additionally allows parallel execution:
$ echo '123' | parallel --pipe --tee {} ::: 'tr 1 a' 'tr 1 b'
a23
b23

parallel by default ensures that output from the different commands doesn't interleave (this behavior can be modified - see man parallel).
Note: Some Linux distros come with a different parallel utility, which won't work with the command above; use parallel --version to determine which one, if any, you have.

Windows
Jay Bazuzi's helpful answer shows how to do it in PowerShell. That said: his answer is the analog of the looping bash answer above, it will be prohibitively slow with large input sets and also alternates the output lines from the target commands.

bash-based, but otherwise portable Unix solution with synchronous execution and output serialization
The following is a simple, but reasonably robust implementation of the approach presented in tzot's answer that additionally provides:

synchronous execution
serialized (grouped) output

While not strictly POSIX compliant, because it is a bash script, it should be portable to any Unix platform that has bash.
Note: You can find a more full-fledged implementation released under the MIT license in this Gist.
If you save the code below as script fanout, make it executable and put int your PATH, the command from the question would work as follows:
$ echo 123 | fanout 'tr 1 a' 'tr 1 b'
# tr 1 a
a23
# tr 1 b
b23

fanout script source code:
#!/usr/bin/env bash

# The commands to pipe to, passed as a single string each.
aCmds=( "$@" )

# Create a temp. directory to hold all FIFOs and captured output.
tmpDir="${TMPDIR:-/tmp}/$kTHIS_NAME-$$-$(date +%s)-$RANDOM"
mkdir "$tmpDir" || exit
# Set up a trap that automatically removes the temp dir. when this script
# exits.
trap 'rm -rf "$tmpDir"' EXIT

# Determine the number padding for the sequential FIFO / output-capture names,
# so that *alphabetic* sorting, as done by *globbing* is equivalent to
# *numerical* sorting.
maxNdx=$(( $# - 1 ))
fmtString="%0${#maxNdx}d"

# Create the FIFO and output-capture filename arrays
aFifos=() aOutFiles=()
for (( i = 0; i <= maxNdx; ++i )); do
  printf -v suffix "$fmtString" $i
  aFifos[i]="$tmpDir/fifo-$suffix"
  aOutFiles[i]="$tmpDir/out-$suffix"
done

# Create the FIFOs.
mkfifo "${aFifos[@]}" || exit

# Start all commands in the background, each reading from a dedicated FIFO.
for (( i = 0; i <= maxNdx; ++i )); do
  fifo=${aFifos[i]}
  outFile=${aOutFiles[i]}
  cmd=${aCmds[i]}
  printf '# %s\n' "$cmd" > "$outFile"
  eval "$cmd" < "$fifo" >> "$outFile" &
done

# Now tee stdin to all FIFOs.
tee "${aFifos[@]}" >/dev/null || exit

# Wait for all background processes to finish.
wait

# Print all captured stdout output, grouped by target command, in sequences.
cat "${aOutFiles[@]}"

Answer: Since @dF: mentioned that PowerShell has tee, I thought I'd show a way to do this in PowerShell.
PS > "123" | % {
    $_.Replace( "1", "a"),
    $_.Replace( "2", "b" )
}

a23
1b3

Note that each object coming out of the first command is processed before the next object is created.  This can allow scaling to very large inputs.
Comment: Yes, but this is the equivalent of doing `while IFS= read -r line; do tr 1 a <<<"$line"; tr 1 b <<<"$line"; done < <(echo '123')` in Bash, which scales well _memory-wise_, but not _performance-wise_.
Answer: You can also save the output in a variable and use that for the other processes:
out=$(proc1); echo "$out" | proc2; echo "$out" | proc3

However, that works only if

proc1 terminates at some point :-)
proc1 doesn't produce too much output (don't know what the limits are there but it's probably your RAM)

But it is easy to remember and leaves you with more options on the output you get from the processes you spawned there, e. g.:
out=$(proc1); echo $(echo "$out" | proc2) / $(echo "$out" | proc3) | bc

I had difficulties doing something like that with the | tee >(proc2) >(proc3) >/dev/null approach.
Answer: another way to do would be,
 eval `echo '&& echo 123 |'{'tr 1 a','tr 1 b'} | sed -n 's/^&&//gp'`

output:
a23
b23

no need to create a subshell here
Comment: What shell does this work on?  All it does it eval `echo 123 |{tr 1 a,tr 1 b}` which complains that `{tr` doesn't exist and if you put in extra spaces it waits for extra input because of the comma and if you change the comma to a semicolon or ampersand you get just the first one printed - not both.
Comment: @JerryJeremiah: It works in shells that brace expansion (`bash`, `ksh`, `zsh`) by creating the command line `echo '&& echo 123 |'{'tr 1 a','tr 1 b'} | sed -n 's/^&&//gp'` in a _string_ and then passing that string to `eval`. That said, it (a) creates 3 subshells in the process of constructing the string (1 for the `\`...\``, and 2 for the segments of the embedded pipeline, and (b), more importantly, it _duplicates_ the input command so that a separate copy is run for each target `tr` command. Aside from inefficiency, the same command run twice doesn't necessarily yield the same output twice.


How to generate a dynamic image grid with vue.js?

Question:     <template>
      <q-page class="page bg-brown-2 q-pa-lg">

            <q-img :src="require('../assets/Pictures/' + getImageId(x,y) + '.png')"></q-img>

      </q-page>
    </template>

So i want to generate an image grid with rows and columns to display a large image composed of many smaller images of the same size in vue.js. First i loop through the rows and create 15 of them (the whole picture is 15x24 pictures) with v-for, while having the x counter to iterate. Inside i use another v-for to fill every row with 24 columns. If i just give y inside the url as number, it renders the same row 15 times but it works. When i try to use a simple function getImageId(rows, columns) then it doesn´t render anything and the whole site stays blank. The calculations on the Image Id´s is based on a 0 - 359 count but in reverse to get the right line-up of the pictures. I subtract from 359 the rows minus 1, because the range starts with 1 from what i found out, times 24 to get the start index of each row. After that i add the current column index to count incrementally down from 359 to 0 from row to row and column to column. I guess the problem lies in my usage of the vue syntax and structure, since im not too well accustomed to it. Any help is welcome.
Comment: I found out, that the site tries to load the picture with the id of 360 but it is not present and i designed the whole function for the id´s to not get above 359 in any way, so i don´t know why....
Answer: I found out, that the site tries to load the picture with the id of 360 but it is not present and i designed the whole function for the id´s to not get above 359 in any way, so i don´t know why...
You did not design the function that way. With 1 and 2 you get that result..
If you want all images from 359 to 0, why don't just fetch them and then show them in order?

console.log(test(1,1)) // 359
console.log(test(1,2)) // 360

function test(row, col) {
  return 359 - ((row - 1) * 24) + (col - 1)
}
Comment: I forgot the parenthesis around everything that is subtracted. Thx for showing me my mistake but i already implemented it another way by generating a structure that i iterate through instead of actual numbers


Why do Ubuntu LTS releases provide 5 years of support? What happens during the lifecycle of an LTS release on a production server to need 5 years?

Question: Also, what do IT teams of production servers do to prepare for end of support and transition from an older LTS release to a newer one?
Comment: We start planning for the upgrade at the beginning of the 5 years (and we don't wait until the End-Of-Life, just until the next LTS is a available) . We identify our own critical programs and services and the shared libraries and the build tools and the connections and ... whatever is "critical". Prepare a test environment, set up automatic testing. Install early versions of the next LTS, test, resolve problems,, lather, repeat.
Comment: The questions you asked in the title are easy. Where's the practicality in constantly changing operating system versions if you need a stable release? The 5 years of support are necessary in order to recitfy any security issues or other bugs, and no potentially system-breaking changes are introduced. It also gives the server managers plenty of time to prepare for the next release, and anticipate any major kernel changes, etc. It's just common sense really
Comment: For many companies, 5 years isn't long enough, which Ubuntu caters for as the five years you mention refers to *standard* support, which can be extended using ESM. Your question though is vague & varies on industry/purpose of the machine, let alone organizations.vary in skills etc... and any answer will be opinion (off-topic on this site) & specific to certain organizations/jurisdictions that may differ to others.
Answer: Each LTS that Canonical (a for-profit company which is NOT AskUbuntu) or AskUbuntu supports requires a certain set of resources (the people familiar with old releases, the hardware to run it on, ...).
As you look at older and older releases, you'll find that they differ more and more from the current release in that they support a smaller variety of hardware and software, and they do some system management tasks differently. This makes "support" more difficult.
That Canonical supports LTS releases for 5 years, and releases new LTS releases every 2 years is their business decision.
What this means is that, 2 years into your 5 year window, a new LTS release is available for testing, and eventual migration. You have 3 years for testing.


Illuminate \ Database \ QueryException (42S22) SQLSTATE[42S22]

Question: Please help me with this. I want to delete, refresh and reset my migration and my db but still stuck with this error.
Column not found: 1054 Unknown column 'posts.user_id' in 'where clause' (SQL: select * from `posts` where `posts`.`user_id` = 1 and `posts`.`user_id` is not null)

Comment: Better check the `posts` table has `user_id`
Comment: Does this issue occur when migrating? If so, it would be a good idea to show the migration that's not working.
Comment: @IjasAmeenudeen You might as well make your comment as an answer. I saw you beat me by about 9 hours.
Comment: @YahyaUddin Sure ;)
Answer: It clearly says user_id column is not in posts table. Check if it is available in the posts table.
If you have that column and still throwing an error, please update your question with the posts table migrations and the Eloquent query you are trying to execute.


convergence or divergence of $\sum_{n=0}^∞ \frac{(\ln(n)+5)}{n^2}$

Question: Determine whether the following series is convergent or divergent
$$\sum_{n=0}^∞ \frac{(\ln(n)+5)}{n^2}$$
I tried using comparison test and p-test:
$$\frac{\ln(n)+5}{n^2}$$<=$$\frac{1}{n^2}$$
And since 1/n^2 is convergent by p-test, the series is convergent. But i am not sure if my solution is correct especially the part on determining the upper bound of $$\frac{\ln(n)+5}{n^2}$$
Answer: Note that$$\frac{\ln(n)+5}{n^2}\leqslant\frac1{n^{3/2}}\iff\ln(n)+5\leqslant\sqrt n,$$and this last statement holds, if $n\gg1$. So, since the series $\sum_{n=1}^\infty\frac1{n^{3/2}}$ converges, so does your series.
Answer: You can't use this comparison, because $$\lim\frac{\frac{\ln n+5}{n^2}}{\frac{1}{n^2}}=\infty$$
(You would have to have finite nonzero limit to get what you want from this test)
The fastest test to apply here, is the condensation test:
$$
\sum 2^n\frac{\ln (2^n)+5}{(2^n)^2}=\sum\frac{n\ln 2+5}{2^n}<\infty
$$
($\sum\frac{n}{2^n}$ converges by Cauchy: $\sqrt[n]{\frac{n}{2^n}}\to\frac{1}{2}<1$) so your series converges by condensation test.
Answer: Hint: apply Cauchy's condensation test on the general term of the series.
$$2^k \cdot \frac{\ln(2^k) + 5}{(2^k)^2} = \frac{k\ln2 + 5}{2^{k}}$$
It's clear that the above series converge.


Problem with apt-get upgrade and dependencies

Question: Im trying to upgrade my system but when I execute the command this happens:
plex@plex-server:~$ sudo apt-get upgrade
[sudo] password for plex:
Reading package lists...
Building dependency tree
Reading state information... Done
You may want to run 'apt --fix-broken install' to fix it.
The following packages have unmet dependencies:
  libgail-3-0 : Depends: libgtk-3-0 (=3.22.30-1ubuntu4) but 3.22.30-1ubuntu1 is installed
  libgtk-3-bin : Depends: libgtk-3-0 (>= 3.22.30-1ubuntu4) but 3.22.30-1ubuntu1 is installed
E: Unmet dependencies. Run 'apt --fix-broken install' without packages (or specify a solution).

I have done update before and I've tried autoclean, autoremove, --fix-missing but it still doesn't work.
EDIT
This is what I have in my sources.list file:
#deb cdrom:[Ubuntu 18.04 LTS _Bionic Beaver_ - Release amd64 (20180426)]/
bionic main restricted

# See http://help.ubuntu.com/community/UpgradeNotes for how to upgrade to
# newer versions of the distribution.
deb http://es.archive.ubuntu.com/ubuntu/ bionic main restricted
# deb-src http://es.archive.ubuntu.com/ubuntu/ bionic main restricted

## Major bug fix updates produced after the final release of the
## distribution.
deb http://es.archive.ubuntu.com/ubuntu/ bionic-updates main restricted
# deb-src http://es.archive.ubuntu.com/ubuntu/ bionic-updates main
restricted

## N.B. software from this repository is ENTIRELY UNSUPPORTED by the
Ubuntu                                             ## team. Also, please
note that software in universe WILL NOT receive any
## review or updates from the Ubuntu security team.
deb http://es.archive.ubuntu.com/ubuntu/ bionic universe
# deb-src http://es.archive.ubuntu.com/ubuntu/ bionic universe
deb http://es.archive.ubuntu.com/ubuntu/ bionic-updates universe
# deb-src http://es.archive.ubuntu.com/ubuntu/ bionic-updates universe

## N.B. software from this repository is ENTIRELY UNSUPPORTED by the
Ubuntu
## team, and may not be under a free licence. Please satisfy yourself as
to
## your rights to use the software. Also, please note that software in
## multiverse WILL NOT receive any review or updates from the Ubuntu
## security team.
deb http://es.archive.ubuntu.com/ubuntu/ bionic multiverse
# deb-src http://es.archive.ubuntu.com/ubuntu/ bionic multiverse
deb http://es.archive.ubuntu.com/ubuntu/ bionic-updates multiverse
# deb-src http://es.archive.ubuntu.com/ubuntu/ bionic-updates multiverse

## N.B. software from this repository may not have been tested as
## extensively as that contained in the main release, although it
includes
## newer versions of some applications which may provide useful features.
## Also, please note that software in backports WILL NOT receive any
review
## or updates from the Ubuntu security team.
deb http://es.archive.ubuntu.com/ubuntu/ bionic-backports main restricted
universe multiverse
# deb-src http://es.archive.ubuntu.com/ubuntu/ bionic-backports main
restricted universe multiverse

## Uncomment the following two lines to add software from Canonical's
## 'partner' repository.
## This software is not part of Ubuntu, but is offered by Canonical and
the
## respective vendors as a service to Ubuntu users.
# deb http://archive.canonical.com/ubuntu bionic partner
# deb-src http://archive.canonical.com/ubuntu bionic partner

deb http://security.ubuntu.com/ubuntu bionic-security main restricted
# deb-src http://security.ubuntu.com/ubuntu bionic-security main
restricted
deb http://security.ubuntu.com/ubuntu bionic-security universe
# deb-src http://security.ubuntu.com/ubuntu bionic-security universe
deb http://security.ubuntu.com/ubuntu bionic-security multiverse
# deb-src http://security.ubuntu.com/ubuntu bionic-security multiverse

Comment: Next time please use the code formatting and not the quote, since here all the line breaks are missing. Did you try what it suggests `sudo apt --fix-broken install`? Post its output here please
Answer: Let's take a look at the key part of the error message:
Los siguientes paquetes tienen dependencias incumplidas:
  libgail-3-0 : Depende: libgtk-3-0 (=3.22.30-1ubuntu4) pero 3.22.30-1ubuntu1 está instalado
  libgtk-3-bin : Depende: libgtk-3-0 (>= 3.22.30-1ubuntu4) pero 3.22.30-1ubuntu1 está instalado

It says that you are trying to upgrade newer packages with older versions. Read it again, playing close attention to the difference between the version numbers.
Let's use a handy apt tool to see which repository these packages came from:
$ apt cache madison libgtk-3-bin
libgtk-3-bin | 3.22.30-1ubuntu1 | http://us.archive.ubuntu.com/ubuntu bionic/main amd64 Packages
libgtk-3-bin | 3.22.30-1ubuntu4 | http://us.archive.ubuntu.com/ubuntu bionic-updates/main amd64 Packages

Oh look, BOTH packages are listed. One is in bionic, the other in bionic-updates.
So the system is complaining that it NEEDS the version from bionic-updates, but cannot install it.
Time to look at your sources in your Software & Updates control panel (or in /etc/apt/sources.list). Ensure that the repo for bionic-updates is present and enabled.
Comment: This is what I have in my sources.list. If I'm not wrong, bionic-updates should be enabled (I've deleted comented lines).
deb http://es.archive.ubuntu.com/ubuntu/ bionic main restricted
deb http://es.archive.ubuntu.com/ubuntu/ bionic-updates main restricted
deb http://es.archive.ubuntu.com/ubuntu/ bionic universe
deb http://es.archive.ubuntu.com/ubuntu/ bionic-updates universe
Comment: Please add new information to your original question, formatted properly, instead of burying it in comments.
Comment: Did you remember to run `sudo apt- update` before `upgrade`? If so, did you get any `update` errors?
Comment: Yes I updated before with no errors.
Answer: First try this command:
apt --fix-broken install

And then:
sudo apt update


Distinguish tr in dynamic table form for serializing jQuery

Question: I have a dynamic table with same names of form parameters.
I need to get the parameters as separate rows for insertion in database using $_POST in PHP page.
HTML

        <form>

                    <select id="selectcs" name="selectcs[]">
 *--value options --*
                    </select>

                    <select id="selectprts" name="selectprts[]">
 *--value options--*
                    </select>

                    <select id="selectnds" name="selectnds[]">
 *--value options --*
                    </select>

                    <input type="text" name="lcl[]" value="0">
                    <input type="text" name="ucl[]" value="0">

        </form>

The jQuery below appends tr id to each row, but it actually does not help to get the POST values as separate rows.
Is there any solution to get these values for database insertion in PHP page?
jQuery
          formData = $("#table_params_form").serialize();

         $('#table_params').find('tr').each(function(){
           formData += '&' + this.id + '=row'+(i+1);
           i++;
          });

        $.post("saveParams.ajax.php",(formData ))

Comment: Given that all the controls have the same name, surely you can figure out which row is which by the index of the resulting arrays?
Answer: You don't need that ID. form.serialize is enough. You can loop data like:
foreach ($i = 0; $i < count($_POST['selectcs']); $i++) {
    var_dump($_POST['selectcs'][$i]);
    var_dump($_POST['selectprts'][$i]);
    var_dump($_POST['selectnds'][$i]);
    var_dump($_POST['lcl'][$i]);
    var_dump($_POST['ucl'][$i]);
}


Coordinate geometry: find a circle given two points and a tangent

Question: I have to find the equation of the circle which passes through the points $A(-2,2)$ and $B(5,-5)$ and has the line $3x-4y=35$ as a tangent at the point $B(5,-5)$.
I tried forming the tangent in a third equation using $(-g,-f)$. With the two points on the circle I used them to form an equation in the form $x^2+y^2+2gx+2fy+c$. I don't know how to go further.
Answer: The equation of the line perpendicular to the given tangent at $B (5,-5)$ can be found to be $4x + 3y = 5$. The centre of the circle must lie on this line. The centre must also lie on the perpendicular bisector of the line joining $A$ and $B$. The equation of this perpendicular can be found by using the fact that it passes through the mid point of $AB$ and perpendicular to $AB$. The equation of this line will be $x - y = 3$. Solving the linear equation gives the centre as $(2,-1)$. The radius is $\sqrt{4^2+(-3)^2} = 5$.
So the equation of circle is $(x-2)^2 +(y+1)^2 = 25$ which can be expressed in standard form as  $x^2 + y^2 - 4x + 2y -20 = 0$. This is the answer.
Answer: The centre of such a circle must lie on the perpendicular bisector of $AB$, i.e. on the line $y=x-3$, and on the perpendicular to $3x-4y=35$ through $B$, i.e. on the line $4x+3y=5$. It follows that the centre of the circle lies at $\left(\frac{14}{13},-\frac{25}{13}\right)$. Can you finish from there?
Comment: Yes thank you .
Answer: Hint. Find the equation of every circles passing through $A$ and $B$. Then find the one whose intersection with the line yields only one solution. Since this is a second degree equation, the discriminant needs to be 0.
Answer: Hint.  The center of the circle is on the perpendicular to the tangent line.  Find the equation to the perpendicular to the tangent line and you can then express the y-coordinate of the center in terms of the x-coordinate (or vice versa).  Then you can express the circle in terms of just the x-coordinates and point (-2, 2) and in terms of the x-coordinate and point (5, -5).  This is two quadratic equations with one variable and should be straightforward to solve for the x-coordinate.  The y-coordinate and radius follow easily.
Comment: d'oh!  The center is also on the perpendicular bisector of AB. Which gives us both coordinates of the center and a lot simpler equations to solve.  d'oh!
Answer: Slope of AB $m_1 = -7/7 = -1$ , slope of tangent at $ B= m_2=3/4$
tan ( angle between chord AB and tangent at $B $
$$= \dfrac{3/4-(-1)}{1+(-1)(3/4)} = 7 = \tan \gamma;\,  \cos \gamma =\frac{1}{\sqrt{50}} $$
We can use a property of circle: Angle in the alternate segment equals that between tangent at B and chord AB.
Let a point on circle be C(x,y).
Equate the cosine of the angle of above given known vectors to $\cos \gamma$ inside segment angles between  vectors AC and BC ( vector dot product/product of vector absolute  values).
$$ AC: (x+2)i + (y-2) j ;\,\, BC (x-5) i + (y+5) j ;\,$$


How can I drill conduit hole through plywood firestop I can't reach?

Question: I'm trying to run a 3/4" conduit (1" OD) from unfinished basement utility room A to unfinished utility room B, through the ceiling of finished room C.
There are several floor trusses which are easy to bypass, but about 6 feet from the edge of the wall is a plywood firestop (red) that already has holes for Pex plumbing, black iron gas piping, and ventilation duct. From room A, I can get within about 4 feet of the firestop but I can't reach it to drill a hole.
I spoke with a contractor who said the easy method would be to cut a big piece out of the ceiling of room C, right next to the firestop (green) and then replace it when done - but I don't want to do this if I can avoid it since I won't be able to match the ceiling texture and paint afterward.
Will a flex drill bit extension (50" or so) allow me to drill the 1" hole I need? Is there another easy solution I'm missing that doesn't involve cutting a hole in the ceiling?
Comment: The flex fish bit is perfect for this.  I just used one for a project.
Comment: Awesome drawing! Made the question extremely clear. I'd go with a flex or rigid bit extension.
Comment: I would make a 1" drill 50" long - pipe and drill and welding...
Comment: Whatever method you go with - put in 3 while you do it so you don't go through the same grief in a few years time...
Answer: When I come across problems like this I go in from the floor boards above. It can be the same amount of work but leaves the finish and colours of the existing ceiling as you mentioned wanting.
Answer: The flex auger bit is one good way to drill a hole several feet away.
Another option is a drill bit or hole saw extension. These might come in handy again in the future, whereas a 50 inch flex bit might not. The problem is that these extensions are offered only in short lengths (12-18 inch) so you'd have to stack several of them. That'll make it hard to aim, create some wobble as it spins, cost the same as the long flex bit, and if they work themselves loose there's a risk of the extensions separating as you try to pull them back after drilling the hole.
Extra points if you're using metal conduit and you form teeth in the end of the pipe to make a very deep hole saw/core drilling tool. ;-)
Comment: While I like the "toothed metal conduit" idea, I ended up using a flex auger bit and only had a little bit of trouble with the conduit couplers as they're larger diameter than the conduit and auger diameter.


Why APT Preferences doesn't work as expect

Question: I want to install puppet which version higher than 2.7.11 on Ubuntu, but the origin source version is 2.7.11, so I add the puppetlabs's source:
echo "deb http://apt.puppetlabs.com precise devel" > /etc/apt/sources.list.d/puppetlabs.list

then I use apt-get and then find the latest version is already 3.0.0 .But I just want to use 2.7.19 .So I edit the /etc/apt/preferences:
package:puppet
Pin: release  v=2.7.19*, o= "http://apt.puppetlabs.com/"
Pin-Priority: 1001

then I use apt-cache policy puppet ,but it seems this does not works as I expect:
puppet:
Installed: 3.0.0-0.1rc6puppetlabs1
Candidate: 3.0.0-0.1rc6puppetlabs1
Package pin: (not found)
Version table:
*** 3.0.0-0.1rc6puppetlabs1 1001
    500 http://apt.puppetlabs.com/ precise/devel amd64 Packages
    100 /var/lib/dpkg/status
 2.7.19-0.1rc3puppetlabs1 1001
    500 http://apt.puppetlabs.com/ precise/devel amd64 Packages

I have read the man 5 apt_preferences, but still can't make it works right.
Comment: I would suggest unix&linux instead, since this isn't specific to Ubuntu.
Comment: This question belongs in http://askubuntu.com/.
Answer: Read the file here
The "o=" means the Origin in the Release file.
If you want to use http  (as the source in sources.list)... you should write:
Pin: origin "http..."

Check at man apt_preferences to get more help about it!
Comment: How can I set version 2.7.19 to the 1001 ,adn keep other version in the 500 at the same time?


How does gcc link static library?

Question: I have a simple program use static library for control pci device. I have got some examples. But i want to make myself some examples but i can't link static libraries.
I have 3 file: led.cpp main.cpp main.h
gcc -c led.cpp -I../utils -I../driver -o led.o
gcc -c main.cpp -I../utils -I../driver -o main.o

it' s ok. Succesfuly creating main.o and led.o object files.
But when linking state, its broken. 24dsi20c500k_utils.a and 24dsi20c500k_dsl.a static libraries.
gcc led.o main.o ../utils/24dsi20c500k_utils.a ../docsrc/24dsi20c500k_dsl.a -o led

Output is shown:
led.o: In function `led_tests(int)':
led.cpp:(.text+0x18): undefined reference to `gsc_label(char const*)'
led.cpp:(.text+0x31): undefined reference to `dsi20c500k_initialize(int, int)'
led.cpp:(.text+0x39): undefined reference to `gsc_label_level_inc()'
led.cpp:(.text+0x5b): undefined reference to `dsi20c500k_led(int, int, int, int*)'
led.cpp:(.text+0x81): undefined reference to `dsi20c500k_led(int, int, int, int*)'
led.cpp:(.text+0xa2): undefined reference to `gsc_label_level_dec()'
led.cpp:(.text+0xb1): undefined reference to `dsi20c500k_initialize(int, int)'
main.o: In function `_perform_tests(int)':
main.cpp:(.text+0x3a1): undefined reference to `gsc_label(char const*)'
main.cpp:(.text+0x3c6): undefined reference to `gsc_id_driver(int, char const*)'
main.o: In function `main':
main.cpp:(.text+0x42c): undefined reference to `gsc_label_init(int)'
main.cpp:(.text+0x49a): undefined reference to `gsc_id_host()'
main.cpp:(.text+0x4a4): undefined reference to `gsc_count_boards(char const*)'
main.cpp:(.text+0x4b6): undefined reference to `gsc_select_1_board(int, int*)'
main.cpp:(.text+0x4d7): undefined reference to `gsc_label(char const*)'
main.cpp:(.text+0x500): undefined reference to `gsc_dev_open(unsigned int, char const*)'
main.cpp:(.text+0x54f): undefined reference to `gsc_dev_close(unsigned int, int)'
collect2: ld returned 1 exit status
make: *** [led] Error 1

if i rename cpp files to c files compilation succesfull. What is the problem?
Comment: see: http://stackoverflow.com/a/173007/14065
Answer: gcc -c main.cpp will compile your code as C++ code.
What likely happens then, is that your main.cpp includes other header files, that are not meant to be compiled as C++. This means that when including these header files in a C++ program , gcc will assume all the stuff the header files declares are C++.
And if they're not, you get linker errors if you try to link to C code that the compiler assumed was C++.
You can remedy this by stating that those header files are C. e.g. in your main.cpp you'd do
extern "C" {
#include "some_c_lib.h"
}

Comment: My problem solved with this solution. Some header files added to extern "C" scope. Thank you.
Answer: You probably didn't use extern "C".

if i rename cpp files to c files compilation succesfull. What is the
  problem?

How does gcc link static library?


How can I import numpy correctly?

Question: I am using qiskit (I am an absolute beginner with some experience with Java and know basic python) but when I tried to run an example code which uses numpy it gave me this error. I tried reinstalling it but it gave me the same error.
I have tried installing and reinstalling it but it didnt work
import numpy as np
from cqc.pythonLib import CQCConnection, qubit
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute
from qiskit.tools.visualization import circuit_drawer
from qiskit.quantum_info import state_fidelity
from qiskit import BasicAer

Traceback (most recent call last):
  File "/home/nikhil/.local/lib/python3.6/site-packages/numpy/core/__init__.py", line 40, in <module>
    from . import multiarray
  File "/home/nikhil/.local/lib/python3.6/site-packages/numpy/core/multiarray.py", line 12, in <module>
    from . import overrides
  File "/home/nikhil/.local/lib/python3.6/site-packages/numpy/core/overrides.py", line 6, in <module>
    from numpy.core._multiarray_umath import (
ModuleNotFoundError: No module named 'numpy.core._multiarray_umath'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/nikhil/.local/lib/python3.6/site-packages/fghjkl.py", line 1, in <module>
    import numpy as np
  File "/home/nikhil/.local/lib/python3.6/site-packages/numpy/__init__.py", line 142, in <module>
    from . import core
  File "/home/nikhil/.local/lib/python3.6/site-packages/numpy/core/__init__.py", line 71, in <module>
    raise ImportError(msg)
ImportError:

IMPORTANT: PLEASE READ THIS FOR ADVICE ON HOW TO SOLVE THIS ISSUE!

Importing the multiarray numpy extension module failed.  Most
likely you are trying to import a failed build of numpy.
Here is how to proceed:
- If you're working with a numpy git repository, try `git clean -xdf`
  (removes all files not under version control) and rebuild numpy.
- If you are simply trying to use the numpy version that you have installed:
  your installation is broken - please reinstall numpy.
- If you have already reinstalled and that did not fix the problem, then:
  1. Check that you are using the Python you expect (you're using /usr/bin/python3.7),
     and that you have no directories in your PATH or PYTHONPATH that can
     interfere with the Python and numpy versions you're trying to use.
  2. If (1) looks fine, you can open a new issue at
     https://github.com/numpy/numpy/issues.  Please include details on:
     - how you installed Python
     - how you installed numpy
     - your operating system
     - whether or not you have multiple versions of Python installed
     - if you built from source, your compiler versions and ideally a build log

     Note: this error has many possible causes, so please don't comment on
     an existing issue about this - open a new one instead.

Original error was: No module named 'numpy.core._multiarray_umath'

Comment: @VictorRuiz Got the mistake, Pycharm was using 3.7 as the project interpreter, changed it to 3.6. This fixed the previous problem. Thank you so much for helping!
Comment: Run  ```python --version``` and ```pip freeze | grep numpy``` to get the versions of python and numpy. You installed it via pip install?
Comment: Also did you follow the instructions in the error message?
Comment: Did you follow all the instructions in the "PLEASE READ THIS FOR ADVICE ON HOW TO SOLVE THIS ISSUE" message? The part about checking which Python you're using and checking your PATH and PYTHONPATH seems relevant. Particularly, it says you're using Python 3.7, but the stack trace shows Python trying to import from Python 3.6 directories.
Comment: Execute the next command: ```python -c "import sys; print(sys.path)"``` Check that .../python3.7/site-packages is on the sys.path
Comment: If you are going to reinstall the packages, I'd suggest first doing 'numpy' and testing it alone.  The do `qiskit` etc.  Some times packages require older `numpy` versions, and that can cause conflicts.
Comment: Yes I have been using Python 3.6 directories as the modules I want to use are there. Using 3.7 gives me error. How can I configure numpy according to 3.6?
Comment: @VictorRuiz I tried that command with both python and python3, I had python 2.7 and python 3.6 with each of the following. Why isnt is showing 3.7 when I use python3?
Comment: Create a virtualenv with version 3.6: ```virtualenv --python=python3.6 test```. Then print again sys.path and try to install and import numpy
Comment: @VictorRuiz Hi! I changed the virtualenv and its still showing it to be python 3.6 instead of 3.7, I tried installing numpy but it says that it is already in the directory of 3.6 (Requirement already satisfied: numpy in ./.local/lib/python3.6/site-packages). Is importing numpy giving a problem because its looking for it in 3.7 instead of 3.6?
Comment: before installing numpy and excute your script, make sure to activate the virtualenv: ```./test/bin/activate``` (the virtualenv you created should have python 3.6 version). Check it with ```python3 --version```
Answer: Try to upgrade the numpy:
pip install --upgrade numpy

or uninstall it and reinstall it again:
pip uninstall numpy
pip install numpy

Comment: @invalidexplorer then I suggest to check the numpy's Github issues for similar problems

How can I import numpy correctly?


Acceptable image resolution relative to native display resolution on high-PPI displays?

Question: I'm wondering if there are any studies - or even anecdotal evidence - on what the acceptable resolution of images is on high-resolution screens (e.g. phones and tablets).
Obviously, an image that's only 50% of a display's native resolution will look noticeably upscaled and blurry, and one that's 100% or above will look as crisp as possible.
But between those two cases, there are diminishing returns when increasing the image's resolution. An image that's 98% of native resolution will still look pretty darn crisp, despite the minor upscaling.
(Granted, the image's motif matters: Line art will likely show signs of scaling much more readily than a nature photograph or portrait.)
In my case, I'm dealing with an iOS/Android app that needs to show a lot of thumbnails and full-size images (all photographs; no line art), which are downloaded from a server. Obviously, the less there is to download the better, and the fewer separate resolutions the server has to prepare the better.
The server can of course just prepare, say, 4 different resolutions of an image, and just serve whichever resolution is exactly as large or larger than the native resolution of the client (the apps report their native resolution to the server when fetching content, so the server decides what resolution to send back).
But intentionally serving too-large images to mobile clients seems pretty inelegant and increases load times. What I'd like to be able to do is have the server send images that are at least X% of native resolution, where X% is whatever's "acceptable".
So I'm wondering if there's a rule of any sort for what is considered "near-enough" to native resolution. For instance, if an image is only 80% of native resolution, will it be noticeable enough to hurt the user experience? Can it be smaller? Should it be larger?
I'm well aware that it may be dependent on way too many factors to have a hard and fast rule, but I'm curious if anyone's tested it.
Comment: What type of app is this? Specifically, what are users going to be doing with the images? Are they going to be simply viewing them, or will they be downloading them for some other use (wallpaper, sending, etc.) For what it's worth, Imgix (https://www.imgix.com) essentially solves this problem... for a price, of course.
Comment: @Brian It's an informational app for a large public aquarium. The images are mainly illustrations of the different species (in the typical very detailed style of textbooks) with transparent backgrounds. Users will only be viewing them, nothing more. Thanks for the link; that's noted for future reference, since swapping out the entire image-serving part of the CMS is no-go right now.
Answer: When I worked for a newspaper I know we had rules around how far you could push an image beyond it's native resolution, 20% larger was the threshold if I recall correctly.
However it depended on the size of the image and subject matter to an extent. I was told that the smaller the image the more a person has to concentrate on the image and more likely they will notice imperfections.
Also if the image was of a compelling news event, the rule book went out the window completely, such as mobile phone photos being used as full page images on the front page after the 7/7 bombings in London.
Whilst working on websites at different stages, I've found people's opinions on image JPEG quality very subjective, where some users didn't notice the difference between a 30% and 80% quality image, whilst others picked up on the slight artefacts in 90%+ images.
Recently I've used Cloudinary to serve images dynamically dependent on resolution on websites, whilst this is JS based, I'm it could be ported to a native environment.
If your app needs to be available offline, perhaps it could detect the resolution of the device after installing, then download the appropriately sized image media for that device and save locally. That way you don't need to include every image size for every device or maintain different app versions.
Comment: I know, but at this point replacing all image handling isn't really an option, unfortunately. Besides, everything is working quite well as-is - it just struck me as an area where a very minor change could potentially save a lot of bandwidth over time, and make the app load things faster, use less space on the device, etc. etc., all at the cost of some minor upscaling. Maybe.
Comment: Interesting. That sort of "rule of thumb" from your newspaper career is the kind of thing I'm curious about. By the way, the app already downloads only the right resolution for the device's native res, and it's stored locally. It's not meant to be fully offline-capable, but it does try to be a little clever about things. Still, if no perfect match for its resolution is available on the server, it has to pick the next best thing, and that's where the "acceptable upscaling" could be relevant. Currently it errs on the side of downloading too-large images.
Comment: Thanks. If you were using something like Cloudinary (or Imgix probably), you can load the exact dimensions you need and set the weighting for the crop as needed. These would be dynamically generate images on the fly, meaning you wouldn't need the rule of thumb approach.


How do I set a time delay between 2 screenshot-desktop calls?

Question: screenshot-desktop is a promise based npm API which takes the desktop screenshot and stores it when called.
However, I need to call the function thrice and set a delay of 5 secs between each call.
Since this is a promise API, their execution takes place instantly. Can I create a delay between my calls?
const screenshot = require('screenshot-desktop');
screenshot({filename:'a.jpg'});
//need delay of 5 secs here
screenshot({filename:'b.jpg'});
//another delay of 5 secs needed here
screenshot({filename:'c.jpg'});

Obviously, setTimeout and setInterval functions do not work with these promise-based APIs.
Answer: I advise you to use promises in the following way:
const screenshot = require('screenshot-desktop');
const delay = (ms = 100) => new Promise(resolve => setTimeout(resolve, ms))

async function init() {
    screenshot({filename:'a.jpg'});
    await delay(5000);
    screenshot({filename:'b.jpg'});
    await delay(5000);
    screenshot({filename:'c.jpg'});
}

init();

With asyncronous functions you can use await to stop processing until a given condition or event is met. In this case the "event" is a timer that takes 5000 milliseconds to finish.
If an asyncronous function throw an error, you can catch it by using the catch method or the second argument of the then method like so:
init().then(function(result) {
    console.log("The async function finished sucessfully and returned the following:");
    console.log(result);
}, function (err) {
    console.log("The async function failed with the following error:");
    console.log(err);
});


Why does ruby stop me from capitalizing an argument in a rake task?

Question: I've got a rake task that renames a bunch of stuff in various files.  So, if someone at the cmd terminal writes this
 rename:namechange[funk]

the code below should perform the necessary find/replace.  My problem is that I can't get this line to work.
args[:new_name.capitalize]

Any idea why?
namespace :rename do

    desc 'changes the name of the app'
    task :changename, :new_name do |task, args|
      args[:new_name.capitalize]
      # change any instances of the term "framework" to the new name of the app
      #for testing, just change these: file_names = ['config/environment.rb'] #['config/environments/test.rb', 'config/environments/production.rb', 'config/environment.rb']
      file_names = ['app/helpers/application_helper.rb', 'app/views/pages/home.html.erb', 'rakefile', 'config/application.rb', 'config.ru', 'config/database.yml',
                    'config/environments/development.rb', 'config/environments/test.rb', 'config/environments/production.rb',
                    'config/environment.rb', 'config/initializers/secret_token.rb', 'config/initializers/session_store.rb', 'config/routes.rb',
                    'spec/controllers/pages_controller_spec.rb']
      file_names.each do |file_name|
        text = File.read(file_name)
        File.open(file_name, "w") { |file| file << text.gsub("Framework", args[:new_name]) }
      end
    end
end

UPDATE: I had trouble with ".capitalize" because it automatically put any character after the first as a lowercase letter.  Ultimately, I arrived at this:
      args[:new_name][0] =  args[:new_name].capitalize[0]

Comment: I edited your title. This is place for adults and professionals.
Comment: What are you trying to achieve with this?
Answer: args[:new_name.capitalize]

Will just call capitalize on the :new_name symbol returning :New_name and will use that as a key in the args hash. You want to use
args[:new_name].capitalize!

Which will access :new_name in the args hash and capitalize it in place
Comment: symbols have a #capitalize method http://ruby-doc.org/core-1.9.3/Symbol.html#method-i-capitalize
Comment: actually, Symbols don't even have a #capitalize method.
Comment: ah, okay, added in 1.9.x, wasn't there in 1.8.7. Weird, I don't know why you'd ever want to do that to a Symbol
Answer: Did you mean to write one of these:
args[:new_name].capitalize!
args[:new_name] = args[:new_name].capitalize


how to set color Gradient for carbonTabSwipeNavigation CarbonKit Cocoapods

Question: I am new to iOS.I want to apply gradient colors on CarbonTabSwipeNavigation.I tried to apply the gradient to the toolbar of CarbonTabSwipeNavigation, but it is not happening
I have tried with Static Colore Code
carbonTabSwipeNavigation.toolbar.isTranslucent = true
var color1 = hexStringToUIColor(hex: "#00275E")
carbonTabSwipeNavigation.carbonSegmentedControl?.backgroundColor = color1
carbonTabSwipeNavigation.setIndicatorColor(UIColor.white) //tabBar font
carbonTabSwipeNavigation.setSelectedColor(UIColor.white, font: UIFont.boldSystemFont(ofSize: 14))

Comment: Consider marking an answer as correct to expand the visibility of the question: [stackoverflow.com/help/someone-answers](https://stackoverflow.com/help/someone-answers)
Answer: First, add these extensions in your project.
extension UINavigationBar {

    func setGradientBackground(colors: [UIColor]) {

        var updatedFrame = bounds
        updatedFrame.size.height += self.frame.origin.y
        let gradientLayer = CAGradientLayer(frame: updatedFrame, colors: colors)

        setBackgroundImage(gradientLayer.createGradientImage(), for: UIBarMetrics.default)
    }
}

extension UIView {

    func setGradientBackgroundOnView(colors: [UIColor]) {

        var updatedFrame = bounds
        //    updatedFrame.size.height += self.frame.origin.y
        let gradientLayer = CAGradientLayer(frame: updatedFrame, colors: colors)
        self.layer.insertSublayer(gradientLayer, at: 0)
    }
}

extension CAGradientLayer {

    convenience init(frame: CGRect, colors: [UIColor]) {
        self.init()
        self.frame = frame
        self.colors = []
        for color in colors {
            self.colors?.append(color.cgColor)
        }
        startPoint = CGPoint(x: 0, y: 1)
        endPoint = CGPoint(x: 1, y: 1)
    }

    func createGradientImage() -> UIImage? {

        var image: UIImage? = nil
        UIGraphicsBeginImageContext(bounds.size)
        if let context = UIGraphicsGetCurrentContext() {
            render(in: context)
            image = UIGraphicsGetImageFromCurrentImageContext()
        }
        UIGraphicsEndImageContext()
        return image
    }

}

Then call this method as your requirement.
Example:- If you want to set a gradient color on navigationbar of your app then call use this
self.navigationController?.navigationBar.setGradientBackground(colors: [UIColor.black, UIColor.red])


Resize Div whilst maintaining ratio

Question: I'm trying to create a page where a centrally placed div resizes to fit in the page both horizontally and vertically whilst retaining the ratio.
Currently I'm using a combination of JS and CSS although I'm not sure it's particularly efficient - it also seems a little hacky.
How would I either clean up this code or rewrite it to achieve this?
Javascript
function changesize(){

var $width = $(".aspectwrapper").height();
var $changewidth = $width * 1.5;
var $doc = $(document).width();
var $height;

if ($doc <= $changewidth){ $changewidth = ( $doc - 100 );
$height = ( ($doc - 100) / 1.5 );
$(".aspectwrapper").css('height', "" + $height + "");
};

$(".content").css('width', "" + $changewidth + "");
$(".aspectwrapper").css('width', "" + $changewidth + "");
};

$(document).ready(function(e) {

 $(changesize);

});

$(window).resize(function(e) {

$(changesize);

});

CSS
html, body {
width: 100%;
height: 100%;
padding: 0;
margin: 0;
}
.aspectwrapper {
display: inline-block;
position: relative;
margin: 0 auto;
height: 90%;
border: #F00 1px solid;
background-color: #F00;
}
.content {
position: absolute;
top: 0;
bottom: 0;
right: 0;
margin-top: 60px;
outline: thin dashed green;
overflow: hidden;
background-color: #09C;
}
#wrapper {
width: 100%;
height: 100%;
text-align: center;
background-color: #0F3;
float: left;
}

HTML

 CONTENT GOES HERE

Answer: I'd personally position my center div horizontally and vertically using positioning/margin combinations with a specific liquid width and height. It would resize based on page width without the use of javascript. Here's an example.
http://jsfiddle.net/9Aw2Y/
Comment: Whilst this does resize the div based on browser size, I need to maintain the same ratio of the size of the DIV, specifically 1:1.5 height to width - the css method does not keep this ratio.
Comment: In that case, I'd use jQuery to adjust the CSS on document load. I'd send the height of the div to a variable and change the `.css()` of the element for the width (i.e. `.css('width','x*1.5');`) as well as the length of the margin-left for the element (`.css('left','-x*.75');`).

Resize Div whilst maintaining ratio


Block IP access to specific page only

Question: I need to block access from a certain IP address to one page of a website only, not the entire website.
Here's what I have, but doesn't seem to be working (I switch out offending IP to mine and am still abel to access after refresh/cache dump etc)
<Files specificpage.php>
    order deny,allow
    deny from XX.XXX.XXX.XX
</Files>

Is there a better way of doing this or does anything jump out here?
thx
Answer: You can actually mod_rewrite rules for finer control here. Place this in your root .htaccess:
RewriteEngine On

RewriteCond %{REMOTE_ADDR} =XX.XXX.XXX.XX
RewriteRule ^specificpage\.php$ - [F,NC]

Comment: Yes this is no doubt better than using `` as it gives lot more features than `Files` directive.

Block IP access to specific page only


Can I repair hairline cracks in a solid wood exterior door with clear silicone caulk?

Question: My front doors have several small hairline cracks around the door panels. I would like to seal them. Can I use clear silicone caulking without damage to the stained surface? Do I need to clean or prep the wood surface for better adhesion?
Answer: I don't see any reason why you couldn't use silicon caulking or why it would damage the surface.  Just know that you will not be able to stain over it again.  Some caulk is listed as paintable which might be a better bet as at least you can paint it down the road if you choose.
If you are going to want to stain the door at a later date, a wood filler product would probably work best as it will blend in well and accept the stain.
As for cleaning the door, you definitely want to remove any dirt and debris from the area you are going to fix. You will want to scrape off and remove any previous caulking that may be present too.
Comment: I agree, especially about wood filler, but urge that, if you use sealant, use a paintable version such as [this](http://www.homedepot.com/h_d1/N-5yc1v/R-202097444/h_d2/ProductDisplay?catalogId=10053&langId=-1&keyword=paintable+seal&storeId=10051). It will let you finish over it, which regular silicon sealant will not.


Event of multiple checkboxes using onCheckedChanged

Question: I have a problem with login checkboxes
First, I`m going to make 3 checkboxes and created change listener for each
public class MainActivity extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener {

private CheckBox main_id_saver;
private CheckBox main_pw_saver;
private CheckBox main_auto_login;

and allocate ID of wigets for each too in onCreate(xml file is skipped)
main_id_saver = (CheckBox) findViewById(R.id.main_id_saver);
main_pw_saver = (CheckBox) findViewById(R.id.main_pw_saver);
main_auto_login = (CheckBox) findViewById(R.id.main_auto_login);

main_id_saver.setOnCheckedChangeListener(this);
main_pw_saver.setOnCheckedChangeListener(this);
main_auto_login.setOnCheckedChangeListener(this);

and I want to set a click event for checkboxes which satisfies below

If ID, PW checkboxes is checked, then auto login checkboxes are checked automatically
cannot check PW checkbox only
If auto login is checked, then ID, PW are checked automatically
If any checkbox is clicked in status of all checkboxes are checked, then all checkboxes are unchecked

I made some tries and below is that
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
    if (main_auto_login.isChecked()){
        if(!main_id_saver.isChecked() || !main_pw_saver.isChecked()) {
            main_id_saver.setChecked(true);
            main_pw_saver.setChecked(true);
            return;
        } else if (main_id_saver.isChecked()&&main_pw_saver.isChecked()&&main_auto_login.isChecked()){
            main_auto_login.setChecked(false);
            main_id_saver.setChecked(false);
            main_pw_saver.setChecked(false);
            return;
        }
    } else if(main_pw_saver.isChecked()){
        if(main_id_saver.isChecked()){
            main_auto_login.setChecked(true);
            return;
        } else if(!main_id_saver.isChecked()){
            Toast.makeText(MainActivity.this, "CANNOT REMEMBER PASSWORD BUT FOR ID",Toast.LENGTH_SHORT).show();
            main_pw_saver.setChecked(false);
            return;
        }
    }
    return;
}

but it doesn`t work as I have thought
what is the best code for this problem?
In my arrogant opinion, making onChangedLinster event separately is the best answer but I cannot make it...
Comment: where is `onCheckedChanged` of remaining 2 checkboxes
Comment: Try setting an instance field like `dontFire = false;` and then in the event
`if(dontFire) return;
dontFire = true;
.
.
dontFire = false;`
When you call `setChecked` the event is called again and I guess this messes things up.
Comment: @Redman is it onCheckedChanged is applied for all checkbox changing?
Comment: @alfoks setting boolean type variable is the only way to deal with this? ok thank you sir
Comment: @timedeveloper that's how I handle calling `setChecked` inside the event itself. See the answer of Ekrem for simplifying your code, but still you'll need to stop the event being called again.
Comment: @alfoks ah yeah I got what you mean sir. That setChecked function recalls sanother setChecked again and again. Seems like smart compiler has stopped this horrible loop for newbie coder...
Answer: chk.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            switch (buttonView.getId()){
                case R.id.checkbox1:
                    if(isChecked)
                        //Do something
                    else
                        //Do something
                    break;
                case R.id.checkBox2:
                    if(isChecked)
                    //Do something
                    else
                    //Do something
                    break;

            }
        }
    });

Comment: Ah, that`s what I wanted. Thank you sir
Comment: What's `chk`? Is it some sort of grouping component?
Comment: chk is CheckBox.


Selenium webdriver - keep user logged in (java)

Question: I'm trying to do a simple Selenium test using webdriver (firefox).

Steps:
1. Open login page
2. Log in
3. Open subpage

My problem is that when a subpage is loaded user is no longer logged in. Thanks in advance for tips how to solve this.
public class Test  {
  public static void main(String[] args) {

    WebDriver driver = new FirefoxDriver();

    driver.get("https://example.com/login");

    WebElement login = driver.findElement(By.id("login_username"));
    WebElement pass = driver.findElement(By.id("login_password"));
    WebElement loginButton = driver.findElement(By.id("auth-login-submit"));

    login.sendKeys("login");
    pass.sendKeys("pass");
    loginButton.click();

    driver.get("https://example.com/subpage");
  }
}

Comment: it *may* be calling `driver.get()` too fast.. maybe you should wait until it says `You are now logged in as X`
Comment: Thanks a lot, it helped. I use Thread.sleep(5000) in try/catch. Is there a better way?
Comment: Better way is add expected condition instead of `Thread.sleep()` and wait until text `You are now logged in as X` is displayed. http://stackoverflow.com/questions/19908296/fluent-wait-and-webdriver-wait-differences
Answer:
Thanks a lot, it helped. I use Thread.sleep(5000) in try/catch. Is
  there a better way? –  aponski Mar 28 at 9:00

Implicit waits as the best choice
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

An implicit wait is to tell WebDriver to poll the DOM for a certain
  amount of time when trying to find an element or elements if they are
  not immediately available. The default setting is 0. Once set, the
  implicit wait is set for the life of the WebDriver object instance.

This is just one-time configuration
Source: http://docs.seleniumhq.org/docs/04_webdriver_advanced.jsp


Linked list with function resulting in infinite loop

Question: I am trying to make a simple linked list, only with a function and two pointers.
#include <stdio.h>
#include <stdlib.h>

typedef struct leonor{
    int x;
    struct leonor * next;
}leo;

For purpose of practice I always look for the end of the list to add the last new node I created. The function (add) is as follows :
void add(leo **ad)
{
    int i;
    leo *current, *new, **previous; /*Previous points on the pointer NEXT
                                     *of an element*/

    new=malloc(sizeof(*new));

    for (i=0;i<3;i++)
    {
        printf("x : ");
        scanf("%d",&new->x);
        new->next=NULL;

        previous = ad; /*'previous' receives adresse of head of list*/
        current = *previous;

        while(current != NULL) /*Look for last element of list*/
        {
            previous = &(current->next);
            current = current->next;
        }

        new->next = *previous;
        *previous = new;
    }
}

The rest of the code :
void display_(leo *hl)
{
    while (hl)
    {
        printf("%d -> ",hl->x);
        hl=hl->next;
    }
}
int main()
{
    leo * head;
    head = NULL;
    add(&head);
    display_(head);
    return 0;
}

The problem is after creating linked list (list of 3 integers in here) it always contains only the number typed last. And when displaying the result is a infinite loop of the same said number. Would appreciate help.
Comment: You have too many variables to take care of. In particular: `previous = ad;` you don't need the previous variable, instead you could use (and assign to) ad.
Answer: You're only allocating one struct leo and using the same one for each element you add. You need to allocate a new one for each element you put on the list.
Comment: Man It's been hours I'm compiling and compiling again! Hug thanks!
Answer: You seem to trying to combine your link entry information with specific data information/types. Do the link list stuff generically. Then the actual interrogation code will be easy to write. And code using your link lists to create lists will be easy.
Your link list entry structure should look like this (by the book):
typedef struct{
    void* prev;
    void* data;
    void* next;
}link_entry;

Build your code about that structure - it will make life much easier. You will need to a cast each time you want to interrogate data but it will make your code much, much easier.
typedef struct
{
   void* first;
   void* last;
   int n;
} LLst;

Some simple functions:
LList create()
{
   return(calloc(sizeof(LList));
}

list_entry* add_entry(LList* list, void* data)
{
   list_entry* entry = malloc(sizeof(list_entry);
   entry->prev = list->last;
   entry->data = data;
   entry->next = NULL;
   list->last=entry;
   if(!list->first) list->first=list->last;
   list->n++;
   return entry;
}

void del_entry(LList* list, list_entry* entry)
{
   /* you may wish to add a free data client procedure to free the data as     well */
   list->last=entry->prev;
   if(entry) free(entry);
   list->n--;
   if(!list->n) list->first=list->last=NULL;
   return entry;
}

Comment: Thanks for the effort.
Comment: No problem. Probably more than what you needed but might be useful for some future reference. Thanks for the question.


A notation $H$ on top of matrices

Question: Could anyone tell me what the $H$ notation generally used on the top of some matrices is meant to be in this paper by Schmidt? The first usage is in equation 2.9 on page 9. Does it mean to be Hermitian?
Thank you.
Answer: Conjugate transpose. Also denoted $A^*$ or $A^\dagger$. But I prefer to at least change the font somehow like $A^{\rm H}$ or $A^{\sf H}$ so it doesn't get confused with exponentiation.
Comment: Generally, Physics people use $A^{\dagger}$, I will stick to $A^{\star}$. Thank you.

A notation $H$ on top of matrices


How to manage two different intent filter for android deeplink/applink?

Question: I have already an intent filter for my applink/deeplink. Sample code :
<activity android:name="com.XXXX.XXXX.XXXXXXXXXXXXActivity"
            android:enabled="true"
            android:excludeFromRecents="true"
            android:noHistory="true"
            android:theme="@android:style/Theme.Translucent"
            android:launchMode="singleInstance">
            <intent-filter android:autoVerify="true">
                <data android:scheme="http" />
                <data android:scheme="https" />
                <data android:host="www.xxxxxx.com" />
                <action android:name="android.intent.action.VIEW" />
                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />
            </intent-filter>
</activity>

This intent filter does not make any link redirection from web browser to app because we don't have any path or pathPattern. We what our behaviour like that only. But for a new saml signin use case, we have to open saml sign in page in the web browser(not in app webview) and once signed in redirect back to app. So we want to use a pathPattern now. Now the problem starts. We have the same scheme and host. So if I create a new intent filter under the same activity with same scheme and host with pathPattern browser making all url redirection to app which I don't want at all. Sample code :
<activity android:name="com.XXXX.XXXX.XXXXXXXXXXXXActivity"
            android:enabled="true"
            android:excludeFromRecents="true"
            android:noHistory="true"
            android:theme="@android:style/Theme.Translucent"
            android:launchMode="singleInstance">
            <intent-filter android:autoVerify="true">
                <data android:scheme="http" />
                <data android:scheme="https" />
                <data android:host="www.xxxxxx.com" />
                <action android:name="android.intent.action.VIEW" />
                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />
            </intent-filter>
                <data android:scheme="http" />
                <data android:scheme="https" />
                <data android:host="www.xxxxxx.com" />

                <data android:pathPattern="/ap/signin.*" />

                <action android:name="android.intent.action.VIEW" />
                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />
            </intent-filter>
</activity>

I have tried with a new activity and used the second intent filter there, but still the same problem. All the urls starts redirecting from the browser to app instead only /ap/signin url.
When I am only using the 2nd intent filter and removed the 1st intent filter, /ap/signin url only redirects from the browser to app, but all other deeplink/applink url stops working. This is kind of known to me.
Does anyone have a proper solution of this? With out breaking the existing flow how can I introduce a new pathPattern ?
Answer: You need to use "pathPrefix" so only ap/signin will open in your app
    <intent-filter>
            <data android:scheme="http" />
            <data android:scheme="https" />
            <data android:host="xxxxxx.com" />

            <data android:pathPrefix="/ap/signin/" />

            <action android:name="android.intent.action.VIEW" />
            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />
        </intent-filter>

Comment: Should I use 2 different intent filter and in the 2nd intent filter use the same code or should I change the existing intent filter like this?
Comment: No It does not work. Same experience I am getting what was I was getting with pathPattern
Comment: Check that you open a new intent filter tag
Comment: No it is not working. If I create a new intent filter or a new activity with a different intent filter, after sign in to the saml url, the first redirection url with my host name get open in the app which is not the pathPrefix I have given. pathPrefix url comes after url redirect for this post request url. Same thing is happening with pathPatterns too. My expected result should be from browser only /ap/signin... url should be redirected to app and all other url should be deeplink/applink when clicking on the url from mobile but not in browser.
Comment: Example: if I click https://www.xxxxx.com/bb/feature/sso.. link from mobile message/email it should be deeplinked/applinked but if the urls are opening in browser, it should not applinked or deeplinked. From browser only /ap/signin... should be redirected to app or deeplinked/applinked. But currently what I am experiencing:             1. on click app links are deeplinkced/applinked from message/email which is expected.  2. From app I have started a flow which opens in brwoser. I signed in the browser, then url redirection happens which redirect to /bb/feature/sso... which is a post call.
Comment: /bb/feature/sso.. url get deeplicked/applinked from my browser to app which I don't want.  3. From /bb/feature/sso... url, another url redirection happens if I stays in browser is /ap/signin.. which I want to deeplink/applink which is a get request. But as /bb/feature/sso... is getting deeplinked and it is a post url, workflow breaks. Is there anyway ehich can make all url from my host as applink/deeplink and at the same time other than /ap/signin.. url no other url will be redirected to app from browser.


Simple cURL script doesn't retrieve data

Question: I'm just starting to learn cURL and now I simply try all kind of things to get used to the options that cURL give me.Here is a simple script which I use to connect and retrieve data from a current site
<?php

      $ch=curl_init();
      $header[] = "Cache-Control: max-age=0";
      $header[] = "Connection: keep-alive";
      $header[] = "Keep-Alive: 300";
      $header[] = "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7";
      $header[] = "Accept-Language: en-us,en;q=0.5";
      $header[] = "Pragma: "; // browsers keep this blank.
      curl_setopt($ch, CURLOPT_URL, "http://img2.somesite.net/bitbucket/");
      curl_setopt($ch, CURLOPT_HEADER, $header);
      curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
      $a=curl_exec($ch);
      curl_close($ch);
      echo $a;

?>

I want to get the images stored there, but obviously I miss something.I'm not sure how it should be done.When you write http://img2.somesite.net/bitbucket/pic.jpg the image is loaded.I want to get the name of all files that are there, or maybe I should trigger a command which will download the images and then check them on the PC...I don't know is this possible with cURL and hwo could be done?
  Also when I leave it
http://somesite.net/

I get the resource back, so basicly this works...
Thanks
Leron
Comment: Ops, I want to do it via cURL
Comment: Well, just for the sake of it i tried and : `failed to open stream: HTTP request failed! HTTP/1.0 404 Not Found in C:\Program Files...`
Comment: `failed to open stream: HTTP request failed! HTTP/1.0 404 Not Found in C:\Program Files` - this
Comment: does the page you are requesting exists?
Comment: yes, when I use the script below and leave http://somesite.net/ it works, but it's mentioned in my original post
Answer: Try setting a User-Agent, as Some sites block requests without a user agent.
Also, download Tamper Data for firefox and see the Headers being sent to the Server when you initiate the download from your browser. Imitiate all the Headers from curl and that will do it.
Thats how i do it.
Comment: Nice, still way from making an workin cURL script but hope this program will help
Comment: If you would give the actual URL then maybe we can help more, but without that, Tamper Data is all i can think of for you.
Answer: CURLOPT_HEADER is a boolean value determining whether it should return the requests' headers.
To pass headers to cURL, you should use CURLOPT_HTTPHEADER.
This should work just fine:
<?php
      $ch=curl_init();
      $header[] = "Cache-Control: max-age=0";
      $header[] = "Connection: keep-alive";
      $header[] = "Keep-Alive: 300";
      $header[] = "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7";
      $header[] = "Accept-Language: en-us,en;q=0.5";
      $header[] = "Pragma: "; // browsers keep this blank.
      curl_setopt($ch, CURLOPT_URL, "http://img2.somesite.net/bitbucket/");
      curl_setopt($ch, CURLOPT_HEADER, false);
      curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
      curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
      $a=curl_exec($ch);
      curl_close($ch);
      echo $a;
?>

Comment: That exact code returns 404 - Not Found, as my riginal one, maybe I really should be more specific about the browser headers.


How do I know when I'll fight Akuma/Gouken at the end of Arcade mode?

Question: Occasionally at the end of Arcade mode, I'll be able to fight Akuma/Gouken in the extra stage after the boss battle (with Seth).
Unfortunately, this doesn't quite so often. I've played through Arcade Mode, only for the character cutscene to trigger right after the Seth boss battle fight, and sometimes getting to Akuma.  I've only fought Gouken once, and I have no idea how I was able to fight him.
How can I tell when I'll fight Akuma/Gouken at the end? Is there a requirement I need to do (take minimal damage, combos, etc.?) to actually fight them?
Answer: There are actually 4 secret bosses (in SSFIV AE and USFIV). Assuming you have selected Arade mode with 1 round per game you need to meet the following requirements to be able to fight them:

Akuma

No Continues
1 Perfect

Evil Ryu

No Continues
1 Perfect
defeat Seth with Super/Ultra

Gouken

No Continues
1 Perfect
5 First Strikes
3 x Super/Ultra Finishes

Oni

No Continues
1 Perfect
5 First Strikes
3 x Super/Ultra Finishes
defeat Seth with Super/Ultra

These requirements increase once you choose multiple rounds per game.
You can only fight the boss if he is a member of the cast for your game. This means you cannot fight Oni or Evil Ryu in Street Fighter IV or Super Street Fighter IV. Here is a list of all bosses in the different versions:

Street Fighter 4: Akuma, Gouken
Super Street Fighter 4: Akuma, Gouken
Super Street Fighter 4 Arcade Edition (201X): Akuma, Gouken, Evil Ryu, Oni
Ultra Street Fighter 4: Akuma, Gouken, Evil Ryu, Oni

TIP: You can use the second controller as a last resort. If you miss your Super/Ultra on Seth you can press Start and you will enter a 2 player game. Once you win you can resume Arcade mode and fight against Seth again. This is not counted as a loss.
Source: http://www.xboxachievements.com/forum/showthread.php?t=314180
Comment: so... the answer is the same for all of Super Street Fighter 4, Street Fighter 4 and Ultra Street Fighter 4?
Comment: @badp And SF4 AE. The vast majority of questions will be, see the meta here: http://meta.gaming.stackexchange.com/questions/5554/lets-merge-tagstreet-fighter-4-and-tagsuper-street-fighter-4-to-tagstree
Comment: If the hidden boss is your rival, what will happen? For example: the rival of evil ryu is Gouken, then if we meet the requirements for Gouken, will we fight Gouken again?


Maximum Sub-Set Sum

Question: I'm trying to solve a slightly different variation of the Maximum Sub-Set Sum problem. Instead of consecutive elements, I want to find the elements that gives you the largest sum in the array. For example, given the following array:
{1,-3,-5,3,2,-7,1} the output should be 7 ( the sub-array with largest sum is {1,3,2,1} ).
Here the code I use to calculate the max sum:
    int max(int a, int b)
    {
        if (a >= b)

            return a;

        return b;
    }

    int func(List<Integer> l, int idx, int sum)
    {
        if (idx < 0)

            return sum;

        return max ( func(l,idx - 1, sum+l.get(idx)), func(l,idx-1,sum) );

    }

    public static void main(String[] args) {

        List<Integer> l = new LinkedList<Integer>();
        l.add(-2);
        l.add(-1);
        l.add(-3);
        l.add(-4);
        l.add(-1);
        l.add(-2);
        l.add(-1);
        l.add(-5);
        System.out.println(func(l,l.size()-1,0));
    }

It works when I use positive and negative numbers together in the same array. However, the problem starts when I use only negative numbers - the output always is 0. I guess it happens because I send 0 as the sum at the very first time when I call the function. Can someone tell me how should I change my function so it will work with only negative numbers as well.
Comment: Your task does not make sense. It will be always a an array of all positive elements from your original array.  No need for any calculations.
Comment: If it's all positive then you're are right. But when it has negative and positive together - then you need to calculate.
Comment: No, you do not. It will **always** be - all positive numbers, assuming there is at least one.
Comment: I see what you mean, you are right! Thanks for pointing it !
Comment: In order to make it algorithm-worthy you need a constraint.  That's what "*consecutive numbers*" requirement was for.
Comment: The problem could be equivalently worded as "find the sum of the subset containing all positive integers of the input". Which obviously leads to the answer 0 / empty subset, if only negative parameters are input. The major issue with your code is the non-polynomial runtime of `O(n^2)`, which is simply a waste of computational power. Most important question: why would 0 be an incorrect output in the first place?
Answer: Your solution is unnecessarily complicated and inefficient (it has an O(2^n) time complexity).
Here's a simple and efficient (O(N) time, O(1) extra space) way to do it:

If there's at least one non-negative number in the list, return the sum of all positive numbers.
Return the largest element in the list otherwise.

Here's some code:
def get_max_non_empty_subset_sum(xs):
     max_elem = max(xs)
     if max_elem < 0:
          return max_elem
     return sum(x for x in xs if x > 0)

Answer: The special case would be when all elements are negative. In this case find the least negative number. That would be your answer. This can be done in O(N) time complexity.
PSEUDO CODE
ALLNEG=true
LEAST_NEG= -INFINITY
for number in list:
    if number>=0
        ALLNEG=false
        break
    else if number>LEAST_NEG
        LEAST_NEG=number
if ALLNEG==true
    answer=LEAST_NEG
else
    ...

Comment: @Dukeling the question just asked about the special case of all negative numbers.
Comment: Thank you! I didn't think about this approach.
Comment: Though your question might be slightly incorrectly framed. I think you are looking for maximum subset sum . Sub array means contiguous elements only.
Comment: What do you mean by `answer=LEAST_NEG`?
Comment: @PM77-1 The special case in this problem is when all numbers in the list are negative. In this case the answer will be the least negative number. LEAST_NEG holds the value of that number, provided that all numbers in the list are negative.
Comment: @PM77-1 , the variable answer is the required solution. If all numbers are negative, the least negative number is the answer.
Comment: No, if all numbers are negative - then the minimum of all numbers is the answer.  For {-1; -2} the answer is {-1}.
Comment: @PM77-1 by least negative , I mean the number closest to 0.
Comment: In your example the minimum is actually -2, if all the numbers are negative, then the solution should be the maximum number - the least negative one.
Comment: @Keselme  I hope you understand the solution. To the best of my knowledge it is correct.
Comment: `LEAST_NEG= -INFINITY` - does it mean closest to 0?
Comment: @PM77-1 That is the initial value to ensure that when we are inside the loops, the if conditions make LEAST_NEG the minimum value. This will not happen if it is initialized with 0.
Comment: It is a PSEUDOCODE @PM77-1
Comment: I see what you mean now. You may want to expand your answer a bit.

Maximum Sub-Set Sum


How to remove this title bar off window from gnome-shell?

Question: How can I remove this title-bar  Ubuntu Start Page - Mozilla Firefox like thing off browser/window from gnome-shell?
Answer: Simply add this extension to get rid of the title bar and reclaim your screen space:
https://extensions.gnome.org/extension/723/pixel-saver/
It has the added benefit that you still get maximise/minimise buttons but these are now stowed away in the top panel.