Can I use OpenStack Rocky with a neoverse-n1?

Question: Situation: For now, I'm stuck on OpenStack Rocky on Ubuntu 18.04.6 and I have some beefy Neoverse-n1 hardware (aarch64, 64-core, 1TB memory) to integrate. Can I accomplish this with on my current OS cluster, or is this futile?
# qemu-system-aarch64 --version
QEMU emulator version 2.11.1(Debian 1:2.11+dfsg-1ubuntu7.41)
Copyright (c) 2003-2017 Fabrice Bellard and the QEMU Project developers
# virsh --version
4.0.0
# uname -r
5.4.0-137-generic

How Far I've gotten: I can create a VM from the command line like this:
qemu-system-aarch64 -nographic -cpu host  -machine virt,accel=kvm,gic-version=3  -m 8G -smp 4 ...

Problem:
I am struggling to integrating this with OpenStack Rocky.  I think the defaults for OpenStack/libvirt/qemu versions didn't account for this sort of hardware, so I'm expecting to do a lot of overrides.  I'm getting libvirt or qemu validation errors like:
libvirtError: XML error: memballoon unsupported with address type 'none'
qemu-system-aarch64: Unsupported NIC model: virtio-net
qemu-system-aarch64: Unsupported NIC model: lan9118

My current nova.conf contains:
[libvirt]
  virt_type = kvm
  cpu_mode = host-passthrough
  hw_machine_type = virt,accel=kvm,gic-version=3

More hardware info:
qemu-system-aarch64 -machine virt,gic-version=max -device \? |& grep virtio :
…
name "virtio-balloon-device", bus virtio-bus
name "virtio-balloon-pci", bus PCI, alias "virtio-balloon"
…
name "virtio-net-device", bus virtio-bus
name "virtio-net-pci", bus PCI, alias "virtio-net"

lspci:
    …
    0001:01:00.0 Ethernet controller: Intel Corporation Ethernet Controller 10G X550T (rev 01)
    0001:01:00.1 Ethernet controller: Intel Corporation Ethernet Controller 10G X550T (rev 01)
    …
    0003:02:00.0 Ethernet controller: Intel Corporation I350 Gigabit Network Connection (rev 01)
    0003:02:00.1 Ethernet controller: Intel Corporation I350 Gigabit Network Connection (rev 01)

Answer: Sorry, this is a really ugly long line, but this works for me:
/usr/bin/qemu-system-aarch64 -name guest=ol9-aarch64,debug-threads=on -S -object {"qom-type":"secret","id":"masterKey0","format":"raw","file":"/var/lib/libvirt/qemu/domain-58-ol9-aarch64/master-key.aes"} -blockdev {"driver":"file","filename":"/usr/share/edk2/aarch64/QEMU_EFI-silent-pflash.raw","node-name":"libvirt-pflash0-storage","auto-read-only":true,"discard":"unmap"} -blockdev {"node-name":"libvirt-pflash0-format","read-only":true,"driver":"raw","file":"libvirt-pflash0-storage"} -blockdev {"driver":"file","filename":"/var/lib/libvirt/qemu/nvram/ol9-aarch64_VARS.fd","node-name":"libvirt-pflash1-storage","auto-read-only":true,"discard":"unmap"} -blockdev {"node-name":"libvirt-pflash1-format","read-only":false,"driver":"raw","file":"libvirt-pflash1-storage"} -machine virt-7.2,usb=off,gic-version=2,dump-guest-core=off,memory-backend=mach-virt.ram,pflash0=libvirt-pflash0-format,pflash1=libvirt-pflash1-format -accel tcg -cpu neoverse-n1 -m 4096 -object {"qom-type":"memory-backend-ram","id":"mach-virt.ram","size":4294967296} -overcommit mem-lock=off -smp 2,sockets=2,cores=1,threads=1 -uuid bfe5ded2-a972-4464-a135-9c1dca08e155 -no-user-config -nodefaults -chardev socket,id=charmonitor,fd=81,server=on,wait=off -mon chardev=charmonitor,id=monitor,mode=control -rtc base=utc -no-shutdown -boot strict=on -device {"driver":"pcie-root-port","port":8,"chassis":1,"id":"pci.1","bus":"pcie.0","multifunction":true,"addr":"0x1"} -device {"driver":"pcie-root-port","port":9,"chassis":2,"id":"pci.2","bus":"pcie.0","addr":"0x1.0x1"} -device {"driver":"pcie-root-port","port":10,"chassis":3,"id":"pci.3","bus":"pcie.0","addr":"0x1.0x2"} -device {"driver":"pcie-root-port","port":11,"chassis":4,"id":"pci.4","bus":"pcie.0","addr":"0x1.0x3"} -device {"driver":"pcie-root-port","port":12,"chassis":5,"id":"pci.5","bus":"pcie.0","addr":"0x1.0x4"} -device {"driver":"pcie-root-port","port":13,"chassis":6,"id":"pci.6","bus":"pcie.0","addr":"0x1.0x5"} -device {"driver":"pcie-root-port","port":14,"chassis":7,"id":"pci.7","bus":"pcie.0","addr":"0x1.0x6"} -device {"driver":"pcie-root-port","port":15,"chassis":8,"id":"pci.8","bus":"pcie.0","addr":"0x1.0x7"} -device {"driver":"pcie-root-port","port":16,"chassis":9,"id":"pci.9","bus":"pcie.0","multifunction":true,"addr":"0x2"} -device {"driver":"pcie-root-port","port":17,"chassis":10,"id":"pci.10","bus":"pcie.0","addr":"0x2.0x1"} -device {"driver":"pcie-root-port","port":18,"chassis":11,"id":"pci.11","bus":"pcie.0","addr":"0x2.0x2"} -device {"driver":"pcie-root-port","port":19,"chassis":12,"id":"pci.12","bus":"pcie.0","addr":"0x2.0x3"} -device {"driver":"pcie-root-port","port":20,"chassis":13,"id":"pci.13","bus":"pcie.0","addr":"0x2.0x4"} -device {"driver":"pcie-root-port","port":21,"chassis":14,"id":"pci.14","bus":"pcie.0","addr":"0x2.0x5"} -device {"driver":"pcie-root-port","port":22,"chassis":15,"id":"pci.15","bus":"pcie.0","addr":"0x2.0x6"} -device {"driver":"pcie-pci-bridge","id":"pci.16","bus":"pci.7","addr":"0x0"} -device {"driver":"qemu-xhci","p2":15,"p3":15,"id":"usb","bus":"pci.2","addr":"0x0"} -device {"driver":"virtio-scsi-pci","id":"scsi0","bus":"pci.3","addr":"0x0"} -device {"driver":"virtio-serial-pci","id":"virtio-serial0","bus":"pci.4","addr":"0x0"} -blockdev {"driver":"file","filename":"/var/lib/zhive/shared/isos/OracleLinux-R8-U6-aarch64-dvd.iso","node-name":"libvirt-2-storage","auto-read-only":true,"discard":"unmap"} -blockdev {"node-name":"libvirt-2-format","read-only":true,"driver":"raw","file":"libvirt-2-storage"} -device {"driver":"scsi-cd","bus":"scsi0.0","channel":0,"scsi-id":0,"lun":0,"device_id":"drive-scsi0-0-0-0","drive":"libvirt-2-format","id":"scsi0-0-0-0","bootindex":1} -blockdev {"driver":"host_device","filename":"/dev/vg0/mydisk","aio":"native","node-name":"libvirt-1-storage","cache":{"direct":true,"no-flush":false},"auto-read-only":true,"discard":"unmap"} -blockdev {"node-name":"libvirt-1-format","read-only":false,"discard":"unmap","cache":{"direct":true,"no-flush":false},"driver":"raw","file":"libvirt-1-storage"} -device {"driver":"scsi-hd","bus":"scsi0.0","channel":0,"scsi-id":0,"lun":1,"device_id":"drive-scsi0-0-0-1","drive":"libvirt-1-format","id":"scsi0-0-0-1","write-cache":"on"} -netdev {"type":"tap","fd":"82","id":"hostnet0"} -device {"driver":"virtio-net-pci","netdev":"hostnet0","id":"net0","mac":"52:54:00:52:6b:1a","bus":"pci.1","addr":"0x0"} -chardev pty,id=charserial0 -serial chardev:charserial0 -chardev socket,id=charchannel0,fd=73,server=on,wait=off -device {"driver":"virtserialport","bus":"virtio-serial0.0","nr":1,"chardev":"charchannel0","id":"channel0","name":"org.qemu.guest_agent.0"} -chardev socket,id=chrtpm,path=/run/libvirt/qemu/swtpm/58-ol9-aarch64-swtpm.sock -tpmdev emulator,id=tpm-tpm0,chardev=chrtpm -device {"driver":"tpm-tis-device","tpmdev":"tpm-tpm0","id":"tpm0"} -device {"driver":"usb-tablet","id":"input0","bus":"usb.0","port":"1"} -audiodev {"id":"audio1","driver":"none"} -vnc 127.0.0.1:19,audiodev=audio1 -device {"driver":"VGA","id":"video0","vgamem_mb":16,"bus":"pci.16","addr":"0x1"} -device {"driver":"virtio-balloon-pci","id":"balloon0","bus":"pci.5","addr":"0x0"} -object {"qom-type":"rng-random","id":"objrng0","filename":"/dev/urandom"} -device {"driver":"virtio-rng-pci","rng":"objrng0","id":"rng0","bus":"pci.6","addr":"0x0"} -sandbox on,obsolete=deny,elevateprivileges=deny,spawn=deny,resourcecontrol=deny -msg timestamp=on

and this is the libvirt xml that generated it:
<domain type='qemu'>
  <name>ol9-aarch64</name>
  <uuid>bfe5ded2-a972-4464-a135-9c1dca08e155</uuid>
  <metadata>
    <libosinfo:libosinfo xmlns:libosinfo="http://libosinfo.org/xmlns/libvirt/domain/1.0">
      <libosinfo:os id="http://oracle.com/ol/9"/>
    </libosinfo:libosinfo>
  </metadata>
  <memory unit='KiB'>4194304</memory>
  <currentMemory unit='KiB'>4194304</currentMemory>
  <vcpu placement='static'>2</vcpu>
  <os firmware='efi'>
    <type arch='aarch64' machine='virt-7.2'>hvm</type>
    <boot dev='cdrom'/>
  </os>
  <features>
    <acpi/>
    <gic version='2'/>
  </features>
  <cpu mode='custom' match='exact' check='none'>
    <model fallback='allow'>neoverse-n1</model>
  </cpu>
  <clock offset='utc'/>
  <on_poweroff>destroy</on_poweroff>
  <on_reboot>restart</on_reboot>
  <on_crash>destroy</on_crash>
  <devices>
    <emulator>/usr/bin/qemu-system-aarch64</emulator>
    <disk type='file' device='cdrom'>
      <driver name='qemu' type='raw'/>
      <source file='/var/lib/zhive/shared/isos/OracleLinux-R8-U6-aarch64-dvd.iso'/>
      <target dev='sda' bus='scsi'/>
      <readonly/>
      <address type='drive' controller='0' bus='0' target='0' unit='0'/>
    </disk>
    <disk type='block' device='disk'>
      <driver name='qemu' type='raw' cache='none' io='native' discard='unmap'/>
      <source dev='/dev/vg0/mydisk'/>
      <target dev='sdb' bus='scsi'/>
      <address type='drive' controller='0' bus='0' target='0' unit='1'/>
    </disk>
    <controller type='usb' index='0' model='qemu-xhci' ports='15'>
      <address type='pci' domain='0x0000' bus='0x02' slot='0x00' function='0x0'/>
    </controller>
    <controller type='scsi' index='0' model='virtio-scsi'>
      <address type='pci' domain='0x0000' bus='0x03' slot='0x00' function='0x0'/>
    </controller>
    <controller type='pci' index='0' model='pcie-root'/>
    <controller type='pci' index='1' model='pcie-root-port'>
      <model name='pcie-root-port'/>
      <target chassis='1' port='0x8'/>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x01' function='0x0' multifunction='on'/>
    </controller>
    <controller type='pci' index='2' model='pcie-root-port'>
      <model name='pcie-root-port'/>
      <target chassis='2' port='0x9'/>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x01' function='0x1'/>
    </controller>
    <controller type='pci' index='3' model='pcie-root-port'>
      <model name='pcie-root-port'/>
      <target chassis='3' port='0xa'/>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x01' function='0x2'/>
    </controller>
    <controller type='pci' index='4' model='pcie-root-port'>
      <model name='pcie-root-port'/>
      <target chassis='4' port='0xb'/>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x01' function='0x3'/>
    </controller>
    <controller type='pci' index='5' model='pcie-root-port'>
      <model name='pcie-root-port'/>
      <target chassis='5' port='0xc'/>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x01' function='0x4'/>
    </controller>
    <controller type='pci' index='6' model='pcie-root-port'>
      <model name='pcie-root-port'/>
      <target chassis='6' port='0xd'/>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x01' function='0x5'/>
    </controller>
    <controller type='pci' index='7' model='pcie-root-port'>
      <model name='pcie-root-port'/>
      <target chassis='7' port='0xe'/>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x01' function='0x6'/>
    </controller>
    <controller type='pci' index='8' model='pcie-root-port'>
      <model name='pcie-root-port'/>
      <target chassis='8' port='0xf'/>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x01' function='0x7'/>
    </controller>
    <controller type='pci' index='9' model='pcie-root-port'>
      <model name='pcie-root-port'/>
      <target chassis='9' port='0x10'/>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x02' function='0x0' multifunction='on'/>
    </controller>
    <controller type='pci' index='10' model='pcie-root-port'>
      <model name='pcie-root-port'/>
      <target chassis='10' port='0x11'/>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x02' function='0x1'/>
    </controller>
    <controller type='pci' index='11' model='pcie-root-port'>
      <model name='pcie-root-port'/>
      <target chassis='11' port='0x12'/>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x02' function='0x2'/>
    </controller>
    <controller type='pci' index='12' model='pcie-root-port'>
      <model name='pcie-root-port'/>
      <target chassis='12' port='0x13'/>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x02' function='0x3'/>
    </controller>
    <controller type='pci' index='13' model='pcie-root-port'>
      <model name='pcie-root-port'/>
      <target chassis='13' port='0x14'/>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x02' function='0x4'/>
    </controller>
    <controller type='pci' index='14' model='pcie-root-port'>
      <model name='pcie-root-port'/>
      <target chassis='14' port='0x15'/>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x02' function='0x5'/>
    </controller>
    <controller type='pci' index='15' model='pcie-root-port'>
      <model name='pcie-root-port'/>
      <target chassis='15' port='0x16'/>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x02' function='0x6'/>
    </controller>
    <controller type='pci' index='16' model='pcie-to-pci-bridge'>
      <model name='pcie-pci-bridge'/>
      <address type='pci' domain='0x0000' bus='0x07' slot='0x00' function='0x0'/>
    </controller>
    <controller type='virtio-serial' index='0'>
      <address type='pci' domain='0x0000' bus='0x04' slot='0x00' function='0x0'/>
    </controller>
    <interface type='bridge'>
      <mac address='52:54:00:52:6b:1a'/>
      <source bridge='vlanbr88'/>
      <model type='virtio'/>
      <address type='pci' domain='0x0000' bus='0x01' slot='0x00' function='0x0'/>
    </interface>
    <serial type='pty'>
      <target type='system-serial' port='0'>
        <model name='pl011'/>
      </target>
    </serial>
    <console type='pty'>
      <target type='serial' port='0'/>
    </console>
    <channel type='unix'>
      <target type='virtio' name='org.qemu.guest_agent.0'/>
      <address type='virtio-serial' controller='0' bus='0' port='1'/>
    </channel>
    <input type='tablet' bus='usb'>
      <address type='usb' bus='0' port='1'/>
    </input>
    <input type='keyboard' bus='usb'>
      <address type='usb' bus='0' port='2'/>
    </input>
    <tpm model='tpm-tis'>
      <backend type='emulator' version='2.0'/>
    </tpm>
    <graphics type='vnc' port='-1' autoport='yes'>
      <listen type='address'/>
    </graphics>
    <audio id='1' type='none'/>
    <video>
      <model type='vga' vram='16384' heads='1' primary='yes'/>
      <address type='pci' domain='0x0000' bus='0x10' slot='0x01' function='0x0'/>
    </video>
    <memballoon model='virtio'>
      <address type='pci' domain='0x0000' bus='0x05' slot='0x00' function='0x0'/>
    </memballoon>
    <rng model='virtio'>
      <backend model='random'>/dev/urandom</backend>
      <address type='pci' domain='0x0000' bus='0x06' slot='0x00' function='0x0'/>
    </rng>
  </devices>
</domain>


Variation of a functional

Question: I have to find the variation of the following functional:

There are two conditions a > 0 and b > 0.
The question is "find the differential equation with respect to x(t), so that the functional is minimized".
Answer: Set $y(\tau) = x(\tau) + \varepsilon \eta(\tau)$ where $\eta(\tau)$ is an arbitrary but twice differentiable function.  Then
$$
S[y(\tau)]=\int_0^t a \left(\dot{x}(\tau)+\varepsilon \dot{\eta}(\tau)\right)^2 + b\left(\ddot{x}(\tau)+\varepsilon \ddot{\eta}(\tau)\right)^2 + c(x(\tau)+\varepsilon \eta(\tau))^4 d\tau.
$$
Take the derivative wrt to $\varepsilon$ and let $\varepsilon \rightarrow 0$, yielding
$$
\nabla_\eta S[x(\tau)] = \int_0^t 2a\dot{x}(\tau)\dot{\eta}(\tau) + 2 b \ddot{x}(\tau)\ddot{\eta}(\tau) + 4 c x(\tau)^3\eta(\tau) d\tau.
$$
This is the directional/Gateaux derivative of $S[]$ wrt $\eta$ evaluated at $x$.
Are you optimizing the functional?  The idea is that if you are at $x$ and take a step $\varepsilon$ in the direction $\eta$ in the appropriate space of functions, you are evaluating the value of moving from $x$ towards $y$. Setting $\nabla_\eta S[x^*]=0$ means that there are no directions away from $x^*$ that locally improve $S$.  Do you have initial conditions, or other constraints?
Comment: What sign is $c$?  If $c>0$, it feels like $x(\tau) = 0$ must be the solution, which achieves a global value of zero. Any other twice-differentiable $x$ will given strictly positive values of one or more of the terms of the integrand.
Comment: If $c<0$, just take $x(\tau)$ to be an arbitrary and positive constant $\bar{x}$.  The dot and double dot terms are zero, so you get $tc\bar{x}<0$, and you can make the functional as negative as you want, meaning the problem is unbounded below and a minimizer does not exist.
Comment: The question is "find the differential equation with respect to x(t), so that the functional is minimized"
Answer: Calling
$$
x_1 = x\\
x_2 = \dot x\\
x_3 = \ddot x
$$
$X = (x_1,x_2,x_3)$ we have
$$
S = \int _0^t (a x_2^2+b x_3^2+c x_1^4)d\tau\ \ \ \text{s. t.}\ \ \ \dot X = A X
$$
with $A = \left(\begin{array}{ccc}0 & 1 & 0\\ 0 & 0 & 1\\\end{array}\right)$
Now considering the lagrangian
$$
L = \int _0^t (a x_2^2+b x_3^2+c x_1^4+\lambda_1(t)(\dot x_1-x_2)+\lambda_2(t)(\dot x_2-x_3))d\tau
$$
and using the Euler-Lagrange equations we get at
$$
\cases{\dot\lambda_1 = 4cx_1^3\\ \dot\lambda_2 +\lambda_1 = 2 a x_2\\ \lambda_2=2bx_3}
$$
and after substitution we obtain the following differential equation:
$$
bx''''-a x''+2c x^3=0
$$
Comment: They are Lagrange multipliers.

Variation of a functional


Java: Where can I find advanced file manipulation source/libraries?

Question: I'm writing arbitrary byte arrays (mock virus signatures of 32 bytes) into arbitrary files, and I need code to overwrite a specific file given an offset into the file. My specific question is: is there source code/libraries that I can use to perform this particular task?
I've had this problem with Python file manipulation as well. I'm looking for a set of functions that can kill a line, cut/copy/paste, etc. My assumptions are that these are extremely common tasks, and I couldn't find it in the Java API nor my google searches.
Sorry for not RTFM well; I haven't come across any information, and I've been looking for a while now.
Comment: How big are the files?  You might want to look at FileChannel (http://java.sun.com/javase/6/docs/api/java/nio/channels/FileChannel.html) and other parts of NIO.
Answer: Maybe you are looking for something like the RandomAccessFile class in the standard Java JDK. It supports reads and writes at some offset, as well as byte arrays.
Comment: Yup, that's amazing. That's exactly what I want.
Answer: Java's RandomAccessFile is exactly what you want.
It includes methods like seek(long) that allow you to move wherever you need in the file.  It also allows for reading and writing at the same time.
Comment: RandomAccessFile might serve as a basis (personally I'd use a FileChannel), but there's a lot of work necessary to be able to remove or insert data in the middle of a file.
Answer: As far as I know, Java has primarily lower level functions for manipulating files directly. Here is the best I've come up with

The actions you describe are standard in the Swing world, and for text comes down to manipulating a Document object.  These act on data in memory.  The class java.nio.channels.FileChannel has similar methods that act directly on a file.   Neither fine the end of lines automatically, but other classes in java.io and java.nio do.
Apache Commons has a sandbox library called Flatfile which looks like it does what you want. The problem is that no code has been released yet.  You may, however, want to talk to people working on it to get some more ideas.  I didn't do a general check on libraries.
Answer: Have you looked into File/FileReader/FileWriter/BufferedReader?  You can get the contents of the files and manipulate it as you like, you can search the data in the files, you can overwrite files, create new, append to an existing....
I am not sure this is exactly what you are asking for but I use these APIs all the time for logging, RTF editors, text file creation for email, and many other things.
As far as cut/copy/past goes, I have not come across the ability to do that directly, however, you can output the contents of the file and "copy" what part of it you want and "paste" it into a new file, or append it to an existing.
Answer: While writing a byte array to a file is a common task, writing to a give file 32-bytes byte array just once is just not something you are going to find in java.io  :)
To get started, would the below method and comments look reasonable to you?  I bet someone here, maybe even myself, could whip it out quick like.
public static void writeFauxVirusSignature(File file, byte[] bytes, long offset) {
    //open file
    //move to offset
    //write bytes
    //close file
}

Questions:

How big could the potential target files be?
Do you need performance?

I ask because clean, easy to read code would use Apache Commons lib's, but large file writes in a performance sensitive environment will necessitate using java.nio libraries


Testing for a root larger than 1 in AR(p)

Question: My question is the following:
How to test for a root larger than 1 in AR(p) process from its observations.
Thanks in advance.
Answer: In unit root larger than 1, do you mean higher integration order than one ($I(1)$ which is a unit root)? If you suspect a process is integrated of order two, $I(2)$, you can run the unit root test on the differenced series. If the differenced series also have a unit root, the integration order is higher than one.
Comment: NO. I am asking for a test than can tell if there is a root(s) greater than 1 in the AR(p) process. I am not asking for integration order.


embedding multiple Twitter buttons in one page?

Question: I'm using Drupal and I have a list of items (View with many nodes) in one page.
I want to add a Twitter button for each of these items in the list, however I'm only able to create a tweet button for the page and not for each item
http://twitter.com/about/resources/tweetbutton
Any idea how to embed multiple Twitter buttons in one page ?
Answer: I had this issue when i wanted to tweet dynamic ajax text but could work out how to just tweet specific text or in your case, a list item. Follow this tutorial: http://blog.twostepmedia.co.uk/dynamic-jquery-twitter-status/
Comment: Similar to my code but this: http://www.kimwoodbridge.com/how-to-create-your-one-facebook-share-url/
Comment: @benhowdle89 hey, in the demo you passed, if I'm not wrong, they always use the same url for all snippets loaded with ajax. I actually would like to generate a different url for each article of the list, otherwise it doesn't work. Right ?
Comment: Absolutely, but on this line: window.open('http://twitter.com/home?status=' + url + '...http://bit.ly/h2yqcx', 'Tweet', 'width=750,height=500 the bit.ly url is the url of my blog post, you could jQuery/javascript to change this to a variable containing your unique urls
Comment: @benhowdle89 Thanks, I think I can actually solve it by generating my url and using "#" selector on a specific div inside my page. What about facebook button?
Comment: @benhowdle89 ok cool. One last thing: do you maybe know where I can get a facebook "Share" button sprite ? I mean multiple button status shots in one single picture
Comment: Googled around, cant really find one, you will have to hit Photoshop :)


C++ Why is the output of this code 3? (structs)

Question: Can someone help me understand step-by-step why the following C++ code outputs a 3?
#include <iostream>
using namespace std;

struct sct
{
    int t[2];
};

struct str
{
    sct t[2];
};

int main() {
    str t[2] = { {0,2,4,6}, {1,3,5,7} };
    std::cout << t[1].t[0].t[1];
}

Comment: @cal223 it may help you to think of `str t[2] = { {0,2,4,6}, {1,3,5,7} };` as `str t[2] = { { {0,2}, {4,6} }, { {1,3}, {5,7} } };` instead, because that is basically what it is really doing.
Comment: first t[1] is {1,3,5,7}, second t[0] is {1,3}, third t[1] is 3.
Comment: This appears to be some [assessment question](https://www.ccna7.com/cpa-programming-essentials-in-c/cpa-chapter-2-assessment-answers-100/)?  Do you understand any of this code?  Where are you lost?
Comment: What do you think it should output?
Comment: I am confused on the t[0] part. Does the sct structure put the first two integers {1,3} from the array {1,3,5,7} selected by the first t[1] into it's array?
Comment: I suggest you rename the members of the structs, to make it easier to read.
Comment: Thank you, I understand it now after renaming.
Answer: t[1] is {1,3,5,7}.
str is represented in memory as four integers back-to-back, organized into 2 sct structures. In this case, the first one has the values 1 and 3, while the second contains 5 and 7.
Thus, t[1].t[0] is {1,3}, so t[1].t[0].t[1] is 3.
Answer: str t[2] = { {0,2,4,6}, {1,3,5,7} };

This means we are an array of two str values {0,2,4,6} at 0 index and {1,3,5,7} at index 1.
cout<<t[0]  //gives 0,2,4,6
cout<<t[1]  //gives 1,3,5,7

Now, when in question cout << t[1].t[0].t[1]; we see what is in t[1] i.e (1,3,5,7), and with that we go inside the str block to assign t[1] to a variable of type stc. Inside it there, we find another variable t[2] of type stc. Here we divide our previous value as t[1].t[0]=1,3 and t[1].t[1]=5,7.
Now, when in question cout << t[1].t[0].t[1]; we see what is in t[1].t[0]=1,3, and with that we go inside the stc block to assign t[1].t[0] to a variable of type int. Inside it there, we find another variable t[2] of type int. Here we divide our previous value as t[1].t[0].t[0]=1 and t[1].t[0].t[1]=3.
Now, when in question cout << t[1].t[0].t[1]; we see what is in t[1].t[0].t[1]=3, and then it gets printed due to cout!!!!!


Using #states to disable a field collection field

Question: I am trying to disable a date field's second value, inside a field collection, but it isn't working.
My hook_form_alter has this:
  $form['field_certification']['und'][0]['field_validity']['und'][0]['#states'] = array(
        'disabled' => array(
          'input[name="field_certification[und][0][field_auto_calculate_validity][und]"]' => array('checked' => TRUE),
        ),
      );

The HTML for the date field is here:
<input class="date-clear form-text hasDatepicker date-popup-init" type="text" id="edit-field-certification-und-0-field-validity-und-0-value2-datepicker-popup-0" name="field_certification[und][0][field_validity][und][0][value2][date]" value="07/23/2014" size="20" maxlength="30">

The checkbox is here:
<input type="checkbox" id="edit-field-certification-und-0-field-auto-calculate-validity-und" name="field_certification[und][0][field_auto_calculate_validity][und]" value="1" class="form-checkbox">

Could it be because I'm not specifically selecting the (second) value of the date field?
Comment: By 'disable a date field collection field's second value', do you mean to prevent the display of the second form element within that collection?
Comment: I have a field collection, and I have a date field inside of that field collection. That date field has both start and end dates (or to and from dates, whatever you want to call them). I want to disable the second one when a given checkbox is checked.
Comment: I missed the relevance of the checkbox. I guess you would need to do this with javascript/jquery (adding a click event to the checkbox to disable the field), though maybe Drupal's AHAH functionality could be of use: https://www.drupal.org/node/331941
Comment: updated solution, hope helps
Answer: My original answer totally missed the point (apologies), this is updated version:
I do not think you can use Drupal's form api #state property to accomplish what you would like. States can be used to hide, reveal and disable whole form elements, such as a fieldset, text input or date field, but you aim to disable one part of a single (contrib) element (ie the second value of a date_combo field provided by the date module).
There are two possible solutions:

load your own jquery when the form is loaded, and add a change() function to disable the relevant date field component
separate the start/end dates into separate date fields and use the drupal #states functionality (as above) to disable the (whole) second date field:
$form['field_certification']['und'][0]['field_validity']['#states'] = array(
'disabled' => array(
    ':input[name="field_certification[und][0][field_auto_calculate_validity][und]"]' => array(
        'checked' => true
    ),
)

);

I hope this helps, I played around with it on a blank d7 install, and this was the only way I could get your intended functionality to work.
Comment: apologies for repeated updates
Comment: No, I can get it to disable the date field generally, but I want only the second date value to be grayed out. And yes, I corrected the lack of : in my code.
Comment: I will try to replicate your issue.


Maintaining Object state in javascript DOJO

Question: I have the following code to call an function on each button in a page.
       dojo.query('.btn').forEach(function(item){
        Obj =   new MyClass(item); // class calls the ajax request on error of each btn click I have to handle some functionality in below function showError
        dojo.connect(Obj, 'showError', dojo.hitch(Obj, function(errors){
            console.log(Obj + 'came');
        }));

Here I tried using dojo.hitch to maintain state of each object Obj, But it is not maintaining.Only first Obj is firing.For second Button also, the first Obj is firing.Is there anything I am missing here.
Comment: Have you checked if your forEachLoop submits the correct items? That it loops through the hole bunch of Buttons you made or does it break at the first one?
Answer: Obj is declared as a global variable. Try putting a var in front of it. For example:
var Obj = new MyClass(item);

If you don't provide the var, it will create a globally accessible variable called Obj. This means that each time you loop, you refer to the same global variable. The result of this is that each one is connected to the same Obj (and that's why both buttons are connected to the same object).
Also, read this question on StackOverflow to get a more detailed view about declaring variables and the global scope.


Tensor product of simple $sl_2$ modules

Question: I am working on the following problem:
Let $M(n)$ be the finite-dimensional, simple $\mathfrak{sl}_2(\mathbb{C})$-module with highest weight $n\in\mathbb{N}_0$. Show that the module $M(l)\otimes_{\mathbb{C}} M(k)$ is cyclic for $l,k\in\mathbb{N}_0$.
I am familiar with the Clebsch-Gordan statement. Hence, I am puzzled by how the dimension of the tensor product can be 1:
$$M(l)\otimes M(k)\cong M(l+k)\oplus M(l+k-2) \oplus … M(|l-k|)$$
for $k\geq l$. What am I overlooking? Any help is greatly appreciated!
Comment: Note the last one should be $M(|l-k|)$ it doesn't really matter which way round you put $l$ and $k$
Comment: @MarianoSuárez-Álvarez Thank you for your clarification! But the following question arised: I know that each summand $M(l)$ of the direct sum is $l+1$ dimensional. Furthermore, it holds that $M(l)=\langle v_0,...,v_m\rangle$, where $v_0$ is the highest weight vector and $v_i=\frac{1}{i!}f^i.v_0$ holds. How does considering the sum of highest weight vectors help me?
Comment: @MarianoSuárez-Álvarez Please post answers in answers, not in comments. See **[How do comments work](https://meta.stackexchange.com/questions/19756/how-do-comments-work)** for more information.
Answer: Assume $k\ge\ell$ for simplicity. For all $j$, $0\le j\le \ell$, let $v_j$ be the highest weight vector of the summand $M(\ell+k-2j)$. Following Mariano's suggestion, consider the vector
$$
v=v_0+v_1+\cdots+v_\ell.
$$
Let $W$ be the submodule generated by $v$. I will show that $W=M(\ell)\otimes M(k)$. Cyclicity follows immediately.
Let $x$ be the raising operator, $y$ the lowering operator, and $h=[x,y]$. Because the vectors $v_j$ are all weight vectors, we have $h\cdot v_j=(k+\ell-2j)v_j$ for all $j$. It follows that for all exponents $m\in\Bbb{N}$ we have
$$
h^m\cdot v_j=(k+\ell-2j)^mv_j.
$$
Here I abbreviated the $m$-fold operation by $h^m\cdot v_j=h\cdot(h\cdot(\cdots (h\cdot v)\cdots)$ (if you are familiar with the universal enveloping algebra, this is exactly how it acts).
So for all $m$, $0\le m\le \ell$, we have
$$
h^m\cdot v=\sum_{j=0}^\ell(k+\ell-2j)^m v_j.
$$
Observe that for all $m$ we have $h^m\cdot v\in W$. We can further extend the idea, and let any polynomials $P(h)$ of $h$ act on the module $W$ in the obvious way. Here $P[T]\in\Bbb{C}[T]$ is the polynomial ring.
Claim. For all $i, 0\le i\le\ell$, the vector $v_i\in W$.
Proof. Consider the span $V$ of the vectors $v_0,v_1,\ldots,v_\ell$.
The element $h$ acts on $V$ via the diagonal matrix with elements $\lambda_j=k+\ell-2j$, $0\le j\le \ell$ along the diagonal. Consider the interpolation polynomial
$$
P_i(h)=\prod_{0\le j\le\ell, j\neq i}(h-\lambda_j).
$$
We clearly have $P_i(h)\cdot v \in W$, and $P_i(h)$ acts as the diagonal matrix with entries $P_i(\lambda_j)$, $0\le j\le\ell$. By design $P_i(\lambda_j)=0$ for all $j\neq i$, but $P_i(\lambda_i)\neq0$. Therefore $P_i(h)\cdot v=z_iv_i$ for some non-zero constant $z_i\in\Bbb{C}$. QED
But $v_j$ generates the summand $M(k+\ell-2j)$ (you only need to apply the lowering operator to it a sufficient number of times). Therefore all the summands $M(k+\ell-2j)\subseteq W$, and we are done.
Comment: @john_psl1298 Sorry about using possibly confusing words (I have been editing the answer heavily). The elements $x,y,h$ are the usual matrices in $\mathfrak{sl}_2$. It turned out that I only really need $h$. Ok, I do need $y$ at the end also :-)
Comment: Thank you for this great answer! But I have never heard of the raising (lowering) operator. I read the Wikipedia article but I do not understand how these operators work here.
Comment: A nice argument @Mariano. I think it can be made to work even more generally. When there are two isomorphic summands, we need to modify the choice of a generating element, and use a pair of components of unequal weights. By applying a suitable number of a ladder operator we can annihilate one component but not the other etc.
Comment: @Mariano I, too, was surprised about that. For it would lead to a conclusion that all finite dimensional modules are cyclic, which should not be true. Ok, the argument fails for the sum of two trivial modules, because we cannot find distinct weights. What about $M(1)\oplus M(1)$? If $v_0,v_1$ are weight vectors of the former summand (of weights $\pm1$) and $w_0,w_1$ of the latter. Then $v=v_0+w_1$ seems to generate it all. For we have $h\cdot v=v_0-w_1$. Hence $v_0$ and $w_1$ would both be in there. I don't see the error :-)
Comment: @Mariano That makes more sense! There had to be something :-)
Answer: The dimension of $M(\ell)$ is $\ell+1$. Thus the dimension of the left-hand side is $(\ell+1)(k+1)$, and the dimension of the right hand side is
$$(\ell+k+1)+\cdots+(\ell-k+1)=\sum_{i=1}^{k+1}(\ell-k+2i-1)=(\ell-k)(k+1)+(k+1)^2=(\ell+1)(k+1),$$
and they are compatible.
Comment: @MarianoSuárez-Álvarez I disagree, the OP finds what seems like a contradiction with the Clebsch-Gordan based off of the dimensions on both sides. I explain why this is not actually a contradiction.

Tensor product of simple $sl_2$ modules


Extract file from .apk?

Question: in my android app I'm using an own java library that extracts a .db-file from jar. In Java desktop it works well, but when I try to do it on android, the inputstream blocks forever. The copy method looks like this:
InputStream in = classloader.getResourceAsStream(...);
OutputStream out = new FileOutputStream(new File(...));
try {
  while ((read = in.read()) != -1) {
    out.write(read);
  }
} finally {
  try {
    in.close();
  } catch (final Exception e) {
    LOGGER.debug("Error", e);
  }

  try {
    out.close();
  } catch (final Exception e) {
    LOGGER.debug("Error", e);
  }
}

I want to copy this file to the external files dir and android.permission.WRITE_EXTERNAL_STORAGE is granted.
Is there a way to access the file in /data/app/...apk? If not, how can I detect that it can not be accessed without blocking forever?
Comment: Is this about shipping your app with a filled database?
Comment: Yes, the app should contain a filled database. On first start, the database should be extracted and updated.
Answer: You should put the database-file in the /assets-folder and copy it to the /databases-folder on first run. A tutorial on this can be found here.
However, if you only want to create the tables and some sample-entry's, you might want to use the onCreate()-method from the SQLiteOpenHelper to do so.
Comment: I will try that. But I want to copy the file to the external storage.
Comment: You can do that, too (if you have the "Write External Storage"-permission).
Answer: Maybe you should store your data in the raw folder, you access it then :)
http://developer.android.com/guide/topics/resources/index.html
Answer: Answering to the question : we can  only extract the class files from the apk that we have got, we will not get the layout/xml files or any other files.
There are ways by which we can extract the class files from the apk.

Extract file from .apk?


Combine the bar graph and line graph

Question: I'm trying to draw a graph as following :

I tried many libraries like afreechart, charts4j, aiChart and many more. I want to this type of graph,
Is it possible? Which library is useful for that? or any other solution for that?
Answer: AChartEngine library supports combined charts also..
You can download source from here which fits your requirememnt.
For more reference refer here
Comment: Thanks CRUSADER.. But line graphs point should be center of bar graph and from the all points it becomes line graph.
Comment: It will be center of bar graph, hmm,... I think you got confused in ref link provide, In there line corresponds to income and bar corresponds to expense, so you see the difference, but in your case both values are same so you get the desired graph you wanted.

Combine the bar graph and line graph


Ocultar rows de uma pickerview quando selecionado um item de outra pickerview - Swift

Question: Criei um pickerview utilizando um array multidimensional, precisaria ocultar alguns itens do picker4 depois que eu selecionasse o primeiro item do picker3.
class ViewControllerEspessuras: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {

    var data = [["1.50","1.60","1.67","1.74"],
                ["-10.00 Esf.","-9.00 Esf.","-8.00 Esf.","-7.00 Esf.","-6.00 Esf.","-5.00 Esf.","-4.00 Esf.","-3.00 Esf.","-2.00 Esf.","-1.00 Esf.","Plano","+1.00 Esf.","+2.00 Esf.","+3.00 Esf.","+4.00 Esf.","+5.00 Esf.","+6.00 Esf.","+7.00 Esf.","+8.00 Esf.","+9.00 Esf.","+10.00 Esf."],
                ["1.50","1.60","1.67","1.74"],
                ["-10.00 Esf.","-9.00 Esf.","-8.00 Esf.","-7.00 Esf.","-6.00 Esf.","-5.00 Esf.","-4.00 Esf.","-3.00 Esf.","-2.00 Esf.","-1.00 Esf.","Plano","+1.00 Esf.","+2.00 Esf.","+3.00 Esf.","+4.00 Esf.","+5.00 Esf.","+6.00 Esf.","+7.00 Esf.","+8.00 Esf.","+9.00 Esf.","+10.00 Esf."]]
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
        return 4
    }
    func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return data[component].count
    }
    func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return data[component][row]
    }
    func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        let picker1 = data[0][pickerView.selectedRowInComponent(0)]
        let picker2 = data[1][pickerView.selectedRowInComponent(1)]
        let picker3 = data[2][pickerView.selectedRowInComponent(2)]
        let picker4 = data[3][pickerView.selectedRowInComponent(3)]
    }
}

Answer: Você deve alterar seu numberOfRowsInComponent e titleForRow forComponent para que eles levem em consideração a seleção do terceiro.
Feito isso é só chamar reloadComponent do último quando o terceiro muda.
Referências podem ser encontradas nessa resposta do SO (em inglês)


Dirichlet process mixture modelling for a Gaussian likelihood

Question: Let $\mathcal{Y} = (\mathbf{y}_1, \dots, \mathbf{y}_N)$ be data observed, such that each $\mathbf{y}_i \in \mathbb{R}^2$. Now conditional on unobserved cluster centres (means) $\mathcal{X} = (\mathbf{x}_1, \dots, \mathbf{x}_K)$, where $K >>0, K \in [1,\infty)$ is also unknown, we have
$$L(\mathcal{Y}|\mathcal{X}, \mathcal{C}, \Sigma,K) = \prod_{i =1}^N \prod_{j=1}^K [\mathcal{N}_2(\mathbf{y}_i;\mathbf{x}_j,\Sigma)]^{\mathcal{C}_{ij}},$$
where $\Sigma$ is a known covariance matrix and $\mathcal{C}_{ij} = 1$ if observation $i$ belongs to cluster $j$ and is zero otherwise.
Now, denote the number of observations per cluster as $S_1, \dots S_K$. We have that $S_j = \sum_{i =1}^{N} \mathcal{C}_{ij}$ for each $j = 1, \dots, K.$ The distribution of each $S_j$ follows $S_j \sim p(S)$ independently and identically, and while it is not multinomial, it is known.
I would like to infer $K$ and $\mathcal{X}$ given the above set-up. Since $K$ in this application is typically quite large (and can be infinite), I was hoping to use some theory in Bayesian nonparametrics, specifically from Dirichlet mixture models. However, since I do not have a typical Gaussian Mixture Model, I am unsure how to set this up.
Any help or pointers to specific papers which outline the theory that I need would be very kindly appreciated. Thanks!
Comment: You mention that you need to infer $X$ -- which is unobserved. How do you have a distribution conditioned on an unobserved variable? Usually when there is $P(Y \mid X  = x)$, you are estimating a conditional distribution based on an observed variable $X = x$, where $x$ is an instance of the random variable $X$.
Comment: Your question confuses me a little. E.g. take a random sample $Y_i \sim  \mathcal{N}(\mu,1)$ iid $i =1, \dots, n$, with $\mu$ unknown. Then the likelihood of $y_1, \dots, y_n$ given $\mu$ is $L(y_1, \dots, y_n| \mu) = \prod_i \mathcal{N}(y_i|\mu)$. To infer $\mu$ in Bayesian setting, note that from Bayes' theorem $f(\mu|y_1, \dots, y_n) \propto L(y_1, \dots, y_n| \mu) \pi(\mu)$, where $\pi(\mu)$ denotes some prior over $\mu$. Taking the MAP value of this posterior gives an estimate for $\mu$. Above, I have described my likelihood. Priors can be chosen to make sampling from posteriors easier.
Comment: In the above eqn. is X referring to the mean?
Comment: Yes, I'll change my question if this is unclear.
Comment: Thanks. I will try to answer your question.
Answer: Chinese restaurant process
Let's define this problem using the Chinese Restaurant Process (CRP) formulation of the Dirichlet Process (DP), which can be summarized as follows (from Gershman et al., emphasis mine):

Imagine a restaurant with an infinite number of tables, and imagine a sequence of customers entering the restaurant and sitting down. The first customer enters and sits at the first table. The second customer enters and sits at the first table with probability $\frac{1}{1+\alpha}$, and the second table with probability $\frac{\alpha}{1+\alpha}$, where $\alpha$ is a positive real. When the $n^{th}$ customer enters the restaurant, she sits at each of the occupied tables with probability proportional to the number of previous customers sitting there, and at the next unoccupied table with probability proportional to $\alpha$.

Using the following analogy, one can formulate an infinite-GMM problem:

infinite number of tables $\equiv$ infinite number of clusters i.e. unknown number of clusters.
customers sitting at a table $\equiv$ observations belonging to a cluster.
table parameters $\equiv$ cluster parameters i.e. mean $x_k$, covariance $\Sigma$.

Infinite-GMM
Now that we have a background on CRP, lets look at the data generation process using infinite-GMM with a CRP prior:

First we need to choose a cluster assignment, $z_i$ for each observation, $y_i$. Using a Chinese restaurant process, we assume that there are currently $K$ clusters, but we also have a probability to assign an observation to a new cluster $K+1$. This way we do not need to fix $K$ a priori,

$$
\begin{equation}\tag{1}\label{eqn1}
  P(z_i=k\mid \alpha) =
    \begin{cases}
      \frac{S_k}{S+\alpha-1} & , k \in [1, K]\\
      \frac{\alpha}{S+\alpha-1} & , k = k_{new}=K+1\\
    \end{cases}
\end{equation}
$$

Given a cluster assignment, we can generate an observation from the corresponding Gaussian with parameters: $y_i \sim \mathcal{N}(x_k, \Sigma)$

where, $S_k$ are the number of observations assigned to the $k^{th}$ cluster, exclusing the $i^{th}$ observation, and $S$ are the total number of observations.
Implementation
The infinite-GMM problem can be solved using a Gibbs sampler, which alternatively samples $z_i$ and the model parameters $\mu_k, \Sigma$. Here are some resources for that:

Yee Whye Teh's MATLAB implementation of infinite-GMM is here.
More details on the Math can be found here
Comment: Thanks so much for your time and effort into this response! :) I'll take a look at your formulation. Btw, I'm assuming that $S = \sum_{k = 1}^{K+1} S_k$?
Comment: Yes. $S$ is the total number of observations and $S_k$ are the observations assigned to the $k^{th}$ cluster.


How to update the colour of minColor and maxColor when data is changed in high charts' solid gauge in ReactJS?

Question: Basically, I want to implement https://www.highcharts.com/demo/gauge-solid in ReactJS. I set minColor and maxColor in config, which is if the speed is between 40 and 60 showing green and otherwise showing red. The charts show normally in the right colour initially. I also setInterval to update the chart in function _testSoloution. The figure changed but the colour isn't updated. How to update the colour?

import React, {Component} from "react";
import ReactHighcharts from 'react-highcharts';
import Highcharts from "highcharts";
import HighchartsMore from 'highcharts/highcharts-more';
import SolidGauge from 'highcharts/modules/solid-gauge';

const gaugeSetting = (data) => {
    return {
        chart: {
            type: 'solidgauge'
        },
        title: null,
        pane: {
            center: ['50%', '85%'],
            size: '140%',
            startAngle: -90,
            endAngle: 90,
            background: {
                backgroundColor: (Highcharts.theme && Highcharts.theme.background2) || '#EEE',
                innerRadius: '60%',
                outerRadius: '100%',
                shape: 'arc'
            }
        },
        tooltip: {
            enabled: false
        },
        yAxis: {
            minColor: data >= 40 && data < 60 ? 'green' : 'red',
            maxColor: data >= 60 || data <= 40 ? 'red' : 'green',
            lineWidth: 0,
            minorTickInterval: null,
            tickPixelInterval: 400,
            tickWidth: 0,
            title: {
                y: -70
            },
            labels: {
                y: 16
            },
            min: 0,
            max: 100,
        },
        plotOptions: {
            solidgauge: {
                dataLabels: {
                    y: -30,
                    borderWidth: 0,
                    useHTML: true
                }
            }
        },
        credits: {
            enabled: false
        },
        series: [{
            name: 'Speed',
            data: [data],
            dataLabels: {
                format: '
{y}
' +
                '°C
'
            },
            tooltip: {
                valueSuffix: ' km/h'
            }
        }]
    }
}
export default class Chart extends Component{
    constructor() {
        super();
        this.state = {
            cars: [
                {
                    name: 'Car1',
                    speed: 30,
                },
                {
                    name: 'Car2',
                    speed: 50,
                },
            ]
        }
    }
    componentDidMount() {
        HighchartsMore(Highcharts);
        SolidGauge(Highcharts);
        this.charts = this.state.cars.map((car, index) => {
            return Highcharts.chart(this.refs[car.name], gaugeSetting(car.speed));
        })
        this.timerID = setInterval(() => {
            this._testSoloution(0);

        }, 1000);
        console.log(this.refs.chart);
    }

    _testSoloution = (index) => {
        point = chartSpeed.series[0].points[0];
        inc = Math.round((Math.random() - 0.5) * 100);
        newVal = point.y + inc;

        if (newVal < 0 || newVal > 200) {
            newVal = point.y - inc;
        }

        point.update(newVal);

        this.setState({
            cars: [
                ...this.state.cars.slice(0,index),
                {
                    ...this.state.cars[index],
                    speed: newVal
                },
                ...this.state.cars.slice(index + 1),
            ]
        })

    }
    _showGuage = () => (
        this.state.cars.map(car => (

            )
        )
    )

    render() {
        return (

                {this._showGuage()}

        )
    }
}

Comment: where do you try to change the color?
Comment: I set the criteria in yAxis.minColor, and yAxis.maxColor in gaugeSetting, and then in function _testSoloution, I invoke point.update(newVal) when a new value come. The color should change when the new value falls out of the criteria.
Comment: newVal is just the y co-ordinate and point must expect both x and y. There is something fishy there.
Comment: According to the example, https://www.highcharts.com/demo/gauge-solid, newValue makes the figure change and the color change.
Answer: Highcharts supports only hex colors when it comes to some numerical operations on them, so colors like red or green won't work in this case. Use #FF0000 and #008000 instead.
API reference: https://api.highcharts.com/class-reference/global.html#ColorString
Doc reference: https://www.highcharts.com/docs/chart-design-and-style/colors


Conics definition from Lens formula

Question: Starting with Lens formula directly
$$ \frac1u + \frac1u = \frac1f $$
or in its Gauss form:
$$ (u-f)(v-f) = f^2, $$
how to recast this into the conics form using definition of eccentricity
$$ \frac{PF}{PD} = e\,, $$
at least as an approximation, using geometric optics where $PF,PD$ are focal and directrix distances of the conics curve ?
Edit1:
My query in other words is for finding relations between $(u,FD),(v,FP), (e, f, \mu) $ including any constants and linear approximations.
$$ \frac{ \sin i}{\sin r } = \mu ,\, \mu  >1, =1$$  respectively for Snell Law refraction/reflection.
The formulas unify reflection and refraction swapping sign of $f$ or changing $\mu$ with above and corroborated by Fermat principle minimum optical path lengths.
Question is motivated on assumption of a valid unified derivation for conic shaped reflectors and refractors. It is a geometric optics question.
Answer: In Gaussian Optics (paraxial optics), the lens formula relates object distance and image distance with the focal length of the refracting (reflecting) surface. This focal length is related with the curvature of the surface and it has only meaning in that approximation. This means that even a conic has a focal length in the paraxial approximation. However, it only depends on the curvature of the surface despite this has eccentricity. I mean, the eccentricity has no role in the determination of the surface focal length.
If you think in the focal length as the distance for which a collimated light beam focus perfectly after refracting (reflecting) in the surface, then you should work with the optical path length definition along the bundle of rays belonging to the beam of light. This treatment expand the Gaussian Optics approximation and it is risky to talk about parameters defined and meaningful only within it.
Maybe I am missing something in your question.
Comment: Thanks for the reply. Scope of query extended as above.

Conics definition from Lens formula


Desmarcar CheckBox Somente Com Senha

Question: Tenho um sistema e em uma parte preciso que somente membros do suporte possam desmarcar um checkbox.
Já Tentei diversos códigos mas sempre ocorre o mesmo problema : O CheckBox por padrão quando clicado ele é marcado ou desmarcado e eu não consegui achar uma maneira de parar esse processo e somente dar continuidade com a senha.
Último Código que tentei :
procedure TFEncerramentoPeriodo.CBFinanceiroClick(Sender: TObject);
var senha,senhad : String;
begin
senha := '328Cont';
 if CBFinanceiro.Checked = true then
 begin
   if not(InputQuery('Digite a Senha', 'Senha', Senhad))
  then
  exit;

    if (SenhaD=Senha) then
    begin
      CBFinanceiro.Checked := False;
    end
    else
    begin
      ShowMessage('Senha Incorreta! Somente Membros do Suporte Podem Desmarcar Essa Opção!');
      CBFinanceiro.Checked := True;
    end;
 end

Pesquisei em vários locais e inclusive aqui no SO e não achei ninguém com a mesma duvida ou problema igual ou parecido.
Comment: Independente da senha, num código convencional, como você faz para o checkbox ser somente leitura?
Comment: propriedade Enabled....
Comment: o que acontece é o seguinte, eu quero que o usuário possa habilitar o check box, mas nao possa desabilitá-lo sem antes contatar o suporte. Pois com esse formulário provocara uma reação em cadeia em outros formulários, alterando a maneira de como eles funcionarão
Comment: Bom, nada impede de habilitar se estiver unchecked, e desabilitar ao checar. Se tiver sucesso, poste como resposta no campo abaixo. Lembre-se que vc pode [edit] o post para melhorar. Aprender a fazer um [mcve] é importante também. Este link pode ajudar no melhor aproveitamento do site: [Guia de sobrevivência do Stack Overflow em Português](https://pt.meta.stackoverflow.com/q/8045/70)
Comment: okay, vou bolar um esquemaa! obrigado pelas dicas!
Answer: Consegui fazer com este código, utilizando os eventos OnMouseDown e OnKeyDown do CheckBox:
procedure TForm3.CheckBox1MouseDown(Sender: TObject; Button: TMouseButton;
  Shift: TShiftState; X, Y: Integer);
var
  senha, senhad: string;
  b: boolean;
begin
  senha := '328Cont';
  if CheckBox1.Checked then
  begin
    b := InputQuery('Digite a senha', 'Senha', Senhad);
    CheckBox1.Checked := not (b and (senhad = senha));
  end;
end;

procedure TForm3.CheckBox1KeyDown(Sender: TObject; var Key: Word;
  Shift: TShiftState);
var
  senha, senhad: string;
  b: boolean;
begin
  if Key <> VK_SPACE then
    exit;
  Key := 0;
  senha := '328Cont';
  if CheckBox1.Checked then
  begin
    b := InputQuery('Digite a senha', 'Senha', Senhad);
    CheckBox1.Checked := not (b and (senhad = senha));
  end;
end;

Answer: Parece-me que está a fazer o IF errado para a combo.
Quando tem a combo checkada e lá clica, ela entra nesse método já com o checked=false e nao checked=true. Assim o seu codigo funciona se alterar para
if CBFinanceiro.Checked = false then
begin
  if not(InputQuery('Digite a Senha', 'Senha', Senhad)) then
     CBFinanceiro.Checked := true;

A unica coisa menos boa é que a caixa aparece unchecked quando a prompt aparece, mas depois fica bem... nao sei se é problema.

Desmarcar CheckBox Somente Com Senha


Templated dict keys in ansible YAML

Question: I am trying to use a dict in an Ansible task, which is defined like this:
in vars/main.yml file:
username: user1
userpass: pass1
users:
  "{{ username }}":
    pass: "{{ userpass }}"

This doesn't work in Ansible 2.9: Ansible seems to not interpolate the value for "{{ username }}"
IIRC this worked fine around Ansible 2.5
What has changed? How should I rewrite my roles and playbooks now?
Comment: FYI, I was not able to make your above var definition display your expected result with ansible version 2.4 and 2.5. Anslble only expands jinja2 template expressions in values, not in hash keys
Answer: The play
- hosts: localhost
  vars:
    username: user1
    userpass: pass1
    users: "{{ {username: {'pass': userpass}} }}"
  tasks:
    - debug:
        var: users

gives:
"users": {
    "user1": {
        "pass": "pass1"
    }
}

Is this what you're looking for?

Templated dict keys in ansible YAML


In Javascript, given value, find value and filter on the specific value from Object literal

Question: I should note I am not the best with Javascript/ajax/jquery. Anyway, I am in need of some assistance when it comes to checking an object to see if it contains a certain value based on an object literal. I am using the JavaScript InfoVis Toolkit for a project I am working on. The library visualization I am using isn't using a true json object, but more of a javascript object literal. I'm having a hard time seeing if an item exists in my object.
I tried the best answer provided after making changes to fit my code, however, it does not seem to work properly.
I've also tried a for..in loop which I know is frowned upon (plus I didn't get this to work as expected either)
Here is the object and its structure:
 myObj = {
    id: "190_0",
    name: "Pearl Jam",
    children: [{
        id: "306208_1",
        name: "Pearl Jam & Cypress Hill",
        children: [{
            id: "84_2",
            name: "Cypress Hill",
            children: []
        },
        {
            id: "306208_3",
            name: "Alex"
        }]
    }]
};

[EDIT]
I am trying to get to "Alex" in this example, but everything I've attempted fails. I'd need it to look through the entire structure, so I can't have hard-coded selections (myObj.children[0].name....)
The end goal for my project is to be able to search for users whom have a specific skill set. So for example:
I want to search for the skillset C++, then show all the children of C++ (which would be people's names).
[/EDIT]
Thank you in advance for any help.
Comment: @BenjaminGruenbaum since this is specific to searching an object literal for data, I don't think searching the prototype is appropriate. I'd imagine this is data extraction for the sake of displaying something for the end user, and I doubt they care about the inner workings of the object.
Comment: How are you trying to find alex? Like are you trying to find any object with `name=x` or any object with a property with value `x`
Comment: It should be `myObj.children[0].children[1].name`. Whether that answers your question I have no idea.
Comment: *I am trying to get to "Alex"*. This is not well defined. What if there are more than one "Alex"? Do you want to explore all tree of descendants? What if the object is recursive (some node has an ancestor as a child)?
Comment: This is just an example that I am trying to use. What I will actually be attempting to filter on in my implementation is a specific skill set.

For example, down the line I would want to search on C++ and then show all entries / objects under the C++ node.
Comment: You want to detect if the value appears _anywhere_ in the object?
Comment: @BenjaminGruenbaum - Yes
Comment: for..in is only frowned upon when used to iterate over an array. It is the proper syntax to use to iterate over an object. The problem when using it with an array is, depending on the browser, it will also iterate over the prototype.
Comment: @Deadron finding it on the prototype is totally legit imo. It's still there if it's on the prototype.
Comment: Many of us come from languages where you can use a foreach on any collection/array so it is confusing, especially when it works in FF/Chrome.  I wasn't trying to suggest it was or was not legit though, it just merely is.
Comment: @Bubbles It's a perfectly fine use case to read data from the prototype. `var a = {x:3,y:6};var b = Object.create(a);` - if you ask me it seems perfectly reasonable to say `b` has a property with the value 6 even though it's in its prototype. Also, I'm sorry if my comment on my answer came off as harsh and I don't understand why you deleted your comment and answer (it _was_ missing a `return false` to terminate the `$.each` in the `if` but that's nothing major).
Comment: It seems to me that you might want to pre-process your objects before you use them. Maybe even separate the children into a different data structure. Ending up with [something like this](http://jsfiddle.net/QcKfg/) isn't a bad plan.
Answer: After the clarification here is a recursive way to check that:
Here is a small implementation
function contains(obj,what){
    if(obj === what){
        return true;
    }
    if(typeof obj!== "object" || obj === null){
        return false;
    }
    for(var i in obj){
        if(contains(obj[i],what)){
            return true;
        }
    }
   return false;
}

This works in all browsers new and old and has no dependencies. Once again annotated:
function contains(obj,what){
    if(obj === what){ // if the object is what we're looking for - return it
        return true;
    }
    // if it's not what we're looking for and it's not an object return it
    if(typeof obj!== "object" || obj === null){
        return false;
    }
    for(var i in obj){ // check if it's any of its properties
        if(contains(obj[i],what)){
            return true; // found it in a child
        }
    }
   return false; // did not find it anywhere.
}

Also, obligatory one liner:
function contains(obj,what){
    return (obj === what)||((typeof obj === "object" && obj !== null) &&  Object.keys(obj).some(function(el){return contains(obj[el],what);}));
}

Comment: @Bubbles Seriously? Look at your jQuery code and look at my native one?  Even if we ignore the one line golfed version which is shorter. The Native JS version is _a lot_ more readable than the jQuery one, it's more reusable. I don't buy the "aweful type system" bit - if you code in a language you _have_ to know it, lack of knowledge of the language typesystem is not an excuse for including an 80K LoC library. Learn the language instead.


$\mu $ ergodic $\iff \mathcal{O}^{+}_{\phi}(x)\cap A\neq\emptyset$

Question: Let $\mathcal{A}$ be a $\sigma$-Algebra on $X$ and $\phi: X\rightarrow X$ measurable (i.e. $\phi^{-1}(A)\in\mathcal{A}$) .
Let $\mu:\mathcal{A}\rightarrow[0,1]$ be probability measure which is $\phi$-invariant (i.e. $\mu(\phi^{-1}(A))=\mu(A)\thinspace \forall A\in\mathcal{A}$).

To prove:
$\mu$ is ergodic $\iff$$\forall A\in \mathcal{A}$ with $\mu(A)>0 \colon\qquad\mathcal{O}^{+}_{\phi}(x)\cap A\neq\emptyset$ for almost all $x\in X $
Has anyone an idea how to start both ways ? Maybe the fact that $\mathcal{O}^{+}_\phi(x)\subseteq X $ for an invariant $\phi$ could help. I've tried the facts that $\mu(\mathcal{O}^{+}_\phi(x)\cup A) = \mu(\mathcal{O}^{+}_\phi(x))+\mu(A)-\mu(\mathcal{O}^{+}_\phi(x)\cap A)$. and $\mathcal{O}^{+}_\phi(x)$ is countable  $\mu(\mathcal{O}^{+}_\phi(x))=0$
I'm thankful for any tips
Comment: Here's an odd LaTeXnicality: \mu:\mathcal{A} \rightarrow[0,1] and \mu\colon\mathcal{A} \rightarrow[0,1] yield conspicuously different results in MathJax as used here, and in LaTeX yield visibly but not as conspicuously different results: $$ \begin{align} & \mu:\mathcal{A}\rightarrow [0,1] \\ & \mu\colon\mathcal{A}\rightarrow [0,1] \end{align} $$
Comment: What is $\mathcal{O}_{\phi}^{+}(x)$?
Comment: the forward Orbit of $x$ i.e. $\mathcal{O^{+}_\phi(x)}=\{\phi^{t}(x)\colon t\in\mathbb{Z}^+\}$
Comment: Presumably you want to use "ergodic" somewhere.
Answer: For all $A \in \mathcal{A}$, let $x \in \phi^{-n}(A)$ iff $\phi^n(x) \in F$. Then, $O_\phi(x) \cap A \neq \emptyset$ a.s. iff $\mu(\cup_{n=1}^\infty\phi^{-n}(A))=1$.
($\Rightarrow$) Suppose that $\mu$ is ergodic and let $\mu(A)>0$.
Let $F_n = \bigcup_{k=n}^\infty \phi^{-k}(A)$ and note that $F_{n+1} \subset F_n$ and $\phi^{-1}(F_n) = F_{n+1}$. By $\phi$-invariance, $\mu(F_n) = \mu(F_{n+1})$. Let $F = \bigcap_{n=1}^\infty F_n$ and note that $\phi^{-1}(F)=F$.
By ergodicity, $\mu(F) = 0$ or $1$. But $F_n \downarrow F$ and $\mu(F_n) = \mu(F_1)$ imply that $\mu(F_1)=0$ or $1$.
To finish, then, it suffices to show that $\mu(F_1)>0$. Simply observe that $\phi^{-1}(A) \subset F_1$ and use $\phi$-invariance once more to get $\mu(F_1) \geq \mu(\phi^{-1}(A)) = \mu(A)>0$.
($\Leftarrow$) For the converse assume that $\mu$ is not ergodic and let $A$ be a witness to this fact. Then, $\phi^{-1}(A)=A$, and $0 < \mu(A)<1$. By induction $\phi^{-n}(A)=A$ for all $n$, hence $$\mu(\cup_{n=1}^\infty\phi^{-n}(A)) = \mu(A) < 1.$$
Comment: @ThomasMuller $F$ is the set of points that visit $A$ infinitely many times. The explanation of why $\mu(\cup_n \phi^{-n}(A))=1$ is just the proof of ($\Rightarrow$); note that $F_1 = \cup_n \phi^{-n}(A)$. I'm not sure what else to say. (If you are asking about the second sentence, note that I'm not asserting $\mu(\cup_n \phi^{-n}(A))=1$ there, I'm just pointing out that it's equivalent to $O_\phi(x) \cap A \neq \emptyset$ a.s.)
Comment: @ThomasMuller That's not a proof by contradiction. I argued directly that [$\mu$ not ergodic] $\implies \mu(\cup_n \phi^{-n}(A))<1$, which is equivalent to $ \mu(\cup_n \phi^{-n}(A))=1 \implies$ [$\mu$ is ergodic].
Comment: thanks ! But can you explain $F $ and why $\mu(\bigcup\phi^{-n}(A))=1$ ?
Comment: ah okay. my last question: why is $\mu(A)<1$ a contradiction ? we assumed that $\mu $ is not ergodic.
Comment: great answer ! thank a lot


Comando makemigrations no Django (1.9) não reconhece Blank = True num campo boolean

Question: Eu tenho o seguinte modelo:
class Site(models.Model):
    """
    Model for a site entry
    @author: Leonardo Pessoa
    @since: 05/09/2016
    """
    from decimal import Decimal

    consolidated_financials     = models.BooleanField(blank=True)
    type                        = models.ForeignKey(Type)
    tier1_business              = models.ForeignKey(Business, limit_choices_to = {'tier': 1}, related_name='%(class)s_tier1')

Note que o campo consolidated_financials agora tem o parâmetro blank=True que não existia na primeira versão do modelo. Quando eu executo o makemigrations, o Django não reconhece a mudança, mas quando adiciono em outro campo que não o BooleanField, sim. Existe alguma restrição com este campo em específico?
Answer: O campo BooleanField não toma como parâmetro null=True. Ao invés disso, use NullBooleanField.
Tem uma ótima resposta no Programmers.se do Jacob Maristany que diz:

Se permitir a utilização do null, você está transformando um campo binário (true/false) em ternário (true/false/null), onde suas entradas 'null' são indeterminadas.

Para a discussão completa, veja: Should I store False as Null in a boolean field database?


Proper name for this distribution type

Question: I need help in defining the type of distribution used in software so that I could use some standard distribution library for this purpose. I apologize for not using proper terms. It takes "center" value and an alpha parameter (0 to 1) and produces N values within a given range, so that values are "clustered" around this "center" value. The less alpha the less they are "centered".
For example, if I feed a range of 1-5 with center at 4, alpha=0.5 and ask for 20 values the result will look something like this:
1:1 times
2:3 times
3:4 times
4:7 times
5:5 times

You get the idea. Thanks!
P.S. In case it might help, I provided some extracts from code
The code for probability density function:
private function assessProbabilityDensityFunction(){
        $probabilityDensityFunction=array();
        for ($i = 0; $i < $this->valueRange->getNumberOfValues(); $i++)
            $probabilityDensityFunction[$i] = $this->probabilityFunction() * $this->probabilityCenteredCoefficient($i);
        return $probabilityDensityFunction;
    }

private function probabilityFunction(){
        return (1 - $this->settings->getAlpha()) / (1 - pow($this->settings->getAlpha(), $this->valueRange->getNumberOfValues() - $this->CentralValueSerialNumber() + 1) + $this->settings->getAlpha() - pow($this->settings->getAlpha(), $this->CentralValueSerialNumber()));
    }
private double centerBasedCoefficient(int valueIndex) {
            return Math.pow(parameters.alpha, distanceFromCenter(valueIndex)+1);
        }

private function distanceFromCentralValue($serialNumber){
        return abs($this->CentralValueSerialNumber() - $serialNumber - 1);
    }

And here's the cumulative function code
private function assessCumulativeDistributionFunction(){
    $cumulativeDistributionFunction = array();
    $cumulativeDistributionFunction[0] = $this->probabilityFunction->getValue(0);
    for ($i = 1; $i < $this->getValueRange()->getNumberOfValues(); $i++)
        $cumulativeDistributionFunction[$i] = $cumulativeDistributionFunction[$i - 1] + $this->probabilityFunction->getValue($i);
    return $cumulativeDistributionFunction;
}

And here's how we get distributed values
public function getValue(){
   return  $this->multinomialDistribution()+$this->cumulativeFunction->getValueRange()->getFromValue();
}

private function multinomialDistribution(){
   $rnd= lcg_value(); // random (0,1)
   for ($i=0; $i<$this->cumulativeFunction->getValueRange()->getNumberOfValues(); $i++)
     if ($this->cumulativeFunction->getValue($i) > $rnd) return $i;
   throw new Exception("Should always return a value");
}

Comment: It would be a lot easier if, in place of the code, you'd provide the math.
Comment: I am close to figuring out the math from the code, but the definition of the `probabilityCenteredCoefficient` function is missing.
Comment: Sorry, I've updated code with this function. Its a short one
Answer: The code is a bit confusing (comments would be nice). My guess is that you're trying to generate something like a discrete Beta distribution. I'm not sure what that would be though...
Comment: A discrete gamma won't be confined to a finite range, but a discrete beta will do the trick.  (A discrete gamma generalizes the geometric distribution, which itself is just a discrete exponential.)
Comment: Right! I've edited my answer.

Proper name for this distribution type


CMake errors when building cpprestsdk

Question: I'm trying to build cpprestsdk (https://github.com/Microsoft/cpprestsdk) under MSYS2. With pacman I installed the required dependencies:

boost
openssl

But I get the following output:
$ cmake -G "MSYS Makefiles" .. -DCMAKE_BUILD_TYPE=Release
-- Setting gcc options
-- Added test library httpclient_test
-- Added test library httplistener_test
-- Added test library json_test
-- Added test library pplx_test
-- Added test library streams_test
-- Added test library uri_test
-- Added test library utils_test
-- Added test library websocketclient_test CMake Error: The following variables are used in this project, but they are set to NOTFOUND.
Please set them or make sure they are set and tested correctly in the
CMake files:
C:/cpprestsdk/Release/src/Boost_INCLUDE_DIR
used as include directory in directory
C:/cpprestsdk/Release/src
C:/cpprestsdk/Release/tests/functional/streams/Boost_INCLUDE_DIR
used as include directory in directory
C:/cpprestsdk/Release/tests/functional/streams
C:/cpprestsdk/Release/tests/functional/websockets/Boost_INCLUDE_DIR
used as include directory in directory
C:/cpprestsdk/Release/tests/functional/websockets

-- Configuring incomplete, errors occurred! See also "C:/cpprestsdk/Release/build.release/CMakeFiles/CMakeOutput.log".

I have difficulties to understand what those errors actually mean.
I tried to inspect the log output but I didn't find anything so obvious...
Am I missing some other dependencies?
UPDATE
After the good suggestion of @Some programmer dude, I fixed the cmake errors setting the Boost_INCLUDE_DIR in CMakelist.txt.
BUT now I have this one when I issue the make command:
$ make
Scanning dependencies of target cpprest
[  0%] Building CXX object src/CMakeFiles/cpprest.dir/http/client/http_client.cpp.obj
cc1plus.exe: error: /mingw32/include/boost: No such file or directory [-Werror=missing-include-dirs]

It says it cannot find /mingw32/include/boost but it actually exists:
$ ls /mingw32/include/boost/
accumulators             context                       fusion                  make_unique.hpp                predef                         spirit
algorithm                convert                       generator_iterator.hpp  math                           predef.h                       spirit.hpp
align                    convert.hpp                   geometry                math_fwd.hpp                   preprocessor                   statechart
align.hpp                core                          geometry.hpp            mem_fn.hpp                     preprocessor.hpp               static_assert.hpp
aligned_storage.hpp      coroutine                     get_pointer.hpp         memory_order.hpp               program_options                swap.hpp
any.hpp                  coroutine2                    gil                     metaparse                      program_options.hpp            system
...

I don't open another question because I'm afraid the issue is related to the previous one - not completely fixed.
Comment: There might be a bug where the CMakeLists.txt file doesn't check for Boost or its location? What happens if you manually set `Boost_INCLUDE_DIR` to the location of the Boost header files? Have you tried reporting it to the project maintainers (by adding an [issue on github](https://github.com/Microsoft/cpprestsdk/issues))?
Comment: How to set the variable? I tried to export it: `export Boost_INCLUDE_DIR=/mingw32/include/boost/` but nothing has changed
Comment: The same way you set `CMAKE_BUILD_TYPE`. Please spend some time to read [the CMake documentation](https://cmake.org/cmake/help/v3.8/) (for example how to use [the `cmake` command](https://cmake.org/cmake/help/v3.8/manual/cmake.1.html)).
Comment: Solved adding `set(Boost_INCLUDE_DIR "/mingw32/include/boost/")` in CMakeLists.txt. If you change your comment as an answer I will accept it. Thanks
Answer: If you're looking to modify either the OpenSSL or Boost locations, you should modify the files:
cpprest_find_boost.cmake
cpprest_find_openssl.cmake
You can see the different ways it is managed for different platforms. I've modified for iOS to use static libs versus the framework solution they are using.
Both require pouting the right includes and right library paths for each respective library.

CMake errors when building cpprestsdk


Why can't I define nat in Isabelle?

Question: I was following the tutorial for Isabelle, and typed in the following example from section 2.2.2:
theory FailedBasicAdditionProof
  imports Main
begin

datatype nat = 0 | Suc nat

fun add :: "nat ⇒ nat ⇒ nat" where
"add 0 n = n" |
"add (Suc m) n = Suc(add m n)"

lemma add_02: "add m 0 = m"
apply(induction m)
apply(auto)
  done
end

but got the error
Legacy feature! Bad name binding: "nat.0"⌂
Legacy feature! Bad name binding: "nat.0"⌂
Bad name: "nat.0"

What am I doing wrong?
Answer: If you happen to look at the datatype docs, the exact same example is done, except with the word Zero instead of the number 0.
If you replace 0 with Zero, the example should work. I think this is a naming convention that was probably changed or added later.
The correct example is here:
theory CorrectBasicAdditionProof
  imports Main
begin

datatype nat = Zero | Suc nat

fun add :: "nat ⇒ nat ⇒ nat" where
"add Zero n = n" |
"add (Suc m) n = Suc(add m n)"

lemma add_02: "add m Zero = m"
apply(induction m)
apply(auto)
  done
end

Why can't I define nat in Isabelle?


Por que as chamadas de atributos não definidos na classe é possível?

Question: Não sei se isso é um comportamento padrão em POO, mas pelo que tenho estudado, quando coloco o objeto.metodo_ou_atributo deveria chamar algum método ou atributo que foi definido na classe previamente, mas no trecho do código abaixo há a classe Pessoa e dentro dessa classe só está definido o atributo nome. Ao instanciar essa classe p1 = Pessoa("João") o nome "João" vai para o atributo self.nome. Até ai tudo bem.
Mas por que p1.outra_coisa = "Carlos" é aceito, se outra_coisa não está definido como atributo da classe Pessoa? Estou criando algum atributo temporário no objeto ou algo do tipo? Isso é alguma má pratica que deve ser evitada?
class Pessoa:
    def __init__(self, nome: str):
        self.nome = nome

p1 = Pessoa("João")
p1.outra_coisa = "Carlos"

print(p1.outra_coisa)
print(p1.nome)

Answer: Quase nada é um comportamento de POO. Orientação a objeto é algo secundário da programação e não tem o valor que algumas pessoas acham que tem. OO é aprendido errado pela maioria das pessoas, se é que pode-se chamar de aprender.
O comportamento mostrado é definido pela qualidade da tipagem de Python que é definida como dinâmica. Veja mais, e também.
Em tipagem dinâmica os objetos não tem uma forma muito definida, eles são o que são. Então a classe de Python é só uma dica do que você espera que o objeto tenha e realize, mas nada impede do objeto criado com base nela seja modificado e fique diferente do que a classe projetou. Fica a cargo do programador não abusar disto.
É um mecanismo que dá alguma vantagem, mas perde-se a robustez. Por isso Python não é uma linguagem adequada para grandes projetos, apenas para scripts, mesmo que muitas pessoas usem:

O ideal é evitar esse tipo de coisa sim.
Classes em Python na verdade são dicionários um pouco modificados, então é só colocar uma chave nova e é aceito. Dá até para apagar certas partes e jogar fora todo contrato, afinal Python, por definição, não respeita contratos (tem outras formas mas não vem ao caso). Então se você disse que quer colocar algo na classe, é aceito.
É assim com todas linguagens de tipagem dinâmica. Se quer contratos fortes precisa procurar linguagens com tipagem estática e forte com bom nível de soundness. Se precisa de liberdade para fazer o que bem entender no código (não confundir com o resultado final) então Python é uma boa escolha.


Most Efficient way to compare a value in a table to another set of values

Question: I am in the middle of a project where i need to be able to get a value (phone number) from one table then compare it to another set of numbers (phone number rates) that are in another table and i was wondering what the most efficient way to do this would be?
I would be using PHP and then calling SQL from that but which is most efficient way to search a table to compare
for example would it be quicker/slower if my rates table was from smallest to largest or visa versa?
0
00
000
or
000
00
0
And how would i code this to make it as quick as possible as i am comparing around 60k lines per time i run this script
Please see below for example of the two tables:
Table 1: Phone Numbers

Date, CLID, DNID, Duration
10/3/14, 01344883333, 01344883321, 60
10/3/14, 01344883333, 07839451009, 60
10/3/14, 01344883333, 07767045933, 60

Table 2: Rates

prefix, description, cost
44, UK - Local, 0.005
07760, UK - Mobile - Vodafone, 0.05
07760,UK - Mobile - Vodafone,0.05
07765,UK - Mobile - Vodafone,0.05
07766,UK - Mobile - Vodafone,0.05
077670,UK - Mobile - Vodafone,0.05
077671,UK - Mobile - Vodafone,0.05
077672,UK - Mobile - Vodafone,0.05
077673,UK - Mobile - Vodafone,0.05
077674,UK - Mobile - Vodafone,0.05
077675,UK - Mobile - Vodafone,0.05
077676,UK - Mobile - Vodafone,0.05
077677,UK - Mobile - Vodafone,0.05
077678,UK - Mobile - Vodafone,0.05
077679,UK - Mobile - Vodafone,0.05
07768,UK - Mobile - Vodafone,0.05

Comment: Give us a little more detail about what your search process would look like.  For example, what does your key (the thing you are using to look up a rate with) look like?  Is it an area code?
Comment: increased the amount of detail
Comment: So it's just rates by prefix?  Put the rates into an [array](http://php.net/manual/en/language.types.array.php) (prefix -> key, rate -> value), and look them up by key.
Comment: there is 46,000 rates surely thats not the quickest or most memory efficient way?
Comment: If you're looking up a rate by prefix, a map data structure of some sort (using either a hash table or BST) is absolutely the best and fastest way to retrieve the rate.  Or, y'know, just put the rates in a SQL Database table, and index the prefix.
Comment: do you have any examples or info on map's? i am not familiar with them
Comment: http://www.bowdoin.edu/~ltoma/teaching/cs210/fall09/Slides/Maps.pdf
Answer: You could get this down from 60K lines per search (I assume that's the number of rows in your Rates table), down to the max length - min length of any prefix by running one query at a time until you got your answer like this:
If the max length of any prefix is 6 characters, and you're searching for the rate for the phone number '07767045933', then search for the rate like this:
SELECT *
FROM Rates r
WHERE r.prefix = LEFT('07767045933', 6)

If no result, then search for:
SELECT *
FROM Rates r
WHERE r.prefix = LEFT('07767045933', 5)

etc., down to your minimum prefix size.
Equality searches like this can utilize an index. Ensure that there is an index on Rates(prefix).
Or course, you could extract the substring from the phone number in PHP instead of SQL. Using a prepared statement, there would be little overhead in switching out the string until you found the rate.


Removing VLAN 1 traffic from a port

Question: If I look at this page for Xen Server VLANs, it says

"Configuring the XenServer management interface on a VLAN network is
not supported"

So then the Server must be on 'VLAN1' yes, my problem is that VLAN 1 traffic is enabled untagged on all switch ports (on my tp-link switches at least), so it seems using VLAN 1 as a management port means that all this traffic is on the wire for all ports. This seems kinda derp regarding the point of VLANs
edit: who are the trolls who downvote questions without being able to answer them?
Answer: I think there are a couple of things to understand here that might help clarify.
In a switched network, traffic will only be sent to a physical port if the destination is on that port, or it is broadcast traffic. For example if you have PC1 plugged into gi0/0, PC2 plugged into gi0/1, and PC3 plugged into gi0/2, any traffic between PC1 and PC2 will not be seen by PC3. You can test this out by plugging two computers in and running wireshark on one of them, while the other pings google. Do you see the traffic? So even if all the ports are natively set to VLAN1 (I'd be surprised if you couldn't change it), they are only going to see the data they should see.
As you stated, the XenServer documentation says VLAN is not supported for the management interface. I believe they actually mean VLAN tagging and trunked interfaces are not supported for the management interface. If you look at their example, they set the VLAN on the switch port for the management interface to be 181, meaning they set a VLAN on the port the host management interface is on, but the port is set in access mode.
Trunked ports with native VLANs have been known to cause issues with all kinds of software and hardware, so it's no surprise Citrix tell you to keep the management interface off of that configuration. Last thing you want is somebody typoing adding a VLAN to the allowed list and removing all the others causing your host to drop.
Comment: I will add as a note, I did a quick look and tp-link switches will allow you to remove an interface from vlan 1 as long as it's a member of another vlan first. The faq does say that all ports are members of vlan 1 by default, but not that you cannot remove them.
Comment: ahh yup, thanks for clarifying, so it may be a TP-Link thing. In this image https://i.imgur.com/oj4Nukw.png it shows that VLAN1 cannot be selected to remove untagged ports. In my case I am using an intel NUC with Xen, with only 1 internal NIC. This issue arose actually when I was trying to troubleshoot a VLAN which had a Xen VM on it, where I noticed traffic from the management LAN on the wire.. perhaps there is no easy solution for this, besides VLAN hosts have a VLAN VPID which I believe prevents them from connecting into to VLAN1

Removing VLAN 1 traffic from a port


Popup Dialogs in web applications

Question: Are popup dialogs a good thing as far as web application usability is concerned? I know they break the back button. Are they worth using or should they be used only when you cant avoid?
Answer: If you are talking about window popups then sure they are considered bad usabiltiy practice. A user feels that he is about to view an advertisement and closes it all sudden. Also it doesnt falls into seamless view of site. Popups are sure a distraction we have currently been working on a project where we use Lightbox modalbox from jQuery to avoid usage of popups which have been very well recieved by users. See
http://colorpowered.com/colorbox/ for examples of Lightboxes.
I always like to read http://www.useit.com/alertbox/990530.html for usability concerns.
Answer: You may not count this as the answer you wanted, but I have used CSS dialog popups with great effect in some of my web apps.
See here: CSS Message Boxes with Different Types
Answer: With the arrival of Web 2.0, it is better to use dialog boxes like jQuery UI

Popup Dialogs in web applications


What are some examples influences from external cultures on the development of Western classical music?

Question: So, I think it's largely safe to presume that the core of Western musical theory developed almost entirely within Europe -- Greece in its very early history, mainly Italy and also the Franco-Flemish regions during the middle ages and Renaissance, and perhaps a little after that elsewhere.
There are however notable exceptions. Spain's role in the development of classical music cannot be understated, I think. While we may not remember many famous early Spanish composers, I have heard that they were instrumental (no pun intended) in developing various forms of classical composition, perhaps bringing some in from the Middle-Eastern and North Africans musical traditions.
So here are a few of my proposals to start us off:

Some compositional forms popular in the Renaissance and Baroque, e.g. sarabande and passacaglia, are suggested to have originated in the Middle East/Arabia, in some loose stylistic sense.
The horse-travelling nomads of Central Asia are rumoured to have invented and indeed introduced the first bowed string instruments to Europe, which the Italians adopted and improved by way of the Byzantines. (Early examples of harps and lyres were of course found in Ancient Greece and indeed ancient Celtic regions for the former.)

Does anyone else have some suggestions, tentative or well-supported, to share?
Answer: Let's look at the last 100 or 125 years of Western classical music.
1) American jazz has had a huge influence on 20th-century Western classical music. American jazz originated outside of 20th-century Western classical music. But now its harmonic and rhythmic vocabulary have permanently influenced Western classical music.
2) Minimalism, a la Steve Reich and Philip Glass, came from a conscious attempt to incorporate polyrhythms and repetitive rhythmic and melodic phrases into Western classical music. The concepts behind these polyrhythms and phrases come from studying traditional African drumming. So sub-Saharan African music now influences modern Western classical music.
In my opinion the overriding characteristic of post-modern Western classical music is its emphasis on percussion instruments, on the one hand, and rhythmic complexity in general on the other.
3) Film and the motion picture industry has tremendously re-shaped Western classical music. This started in the 1920s with composers being commissioned to write accompaniment music for live orchestras to play in sync with silent movies. Then when motion picture technology incorporated sound recording, filmmakers the world over enlisted composers to compose and record soundtracks. Writing music to motion pictures has changed compositional techniques significantly, as a practical consideration.
4) Bartok and Stravinsky, among others, championed the use of frequently-changing odd-time signatures, and the impetus for this seems to be various Eastern-European and Middle-Eastern folk music traditions--although 20th century composers took these compositional devices much further. Frequently-changing odd-time signatures are now used in all kinds of classical music, not the least of which are film scores, where phrasing, meters, and tempos shift constantly so the music can follow and accentuate the action on the screen.
5) Charles Ives, Aaron Copland and others incorporated Appalacian folk music and other folk music from the United States of America. This did not have as heavy an implication as what others were doing with jazz, but it is an influence nonetheless.
6) I must also mention Caribbean and South American popular music, not the least of which comes from Brazil. Along with this comes the fertile cross-over of New World classical guitar music (Leo Brouwer in Cuba, etc.)
Comment: There's some precedent for (4) in Chopin, Liszt, Debussy, and even Brahms. Etudes in particular are prone to time changes. Perhaps the 20th-c. composers were merely *developing* a previously-tapped source.
Comment: _Let's look at the last 100 or 125 years of Western classical music_ | +1 for good research, but IMO you are severely limiting the scope of this question by focusing only on relatively recent history. Folk traditions have permeated and often been the sources and inspirations for 'classical' music from the earliest times. Music comes from all people, not just composers sitting in their studios.
Answer: The turkish motives and joining russians to mainstream western music.
Gypsy people is the powerful steering power bringing music from one place to another.
Squeeze-boxes together with harmonicas seems to be originated in China.
Xylophones are very old and not of european origin also.
Answer: Here is just a very brief list of well-known and prominent examples. Virtually all classical composers - Josef Haydn drew material from German folk tunes - and particularly in the Romantic and Modern Eras, drew from the folk musical traditions they were surrounded with. They by no means lived or worked in some sort of classical/academic musical isolation.

In his youth, Brahms worked with a Hungarian violinist, Eduard Remenyi, who introduced him to Hungarian and Gypsy folk music, which was very influential in his compositions. Among many other things, he later wrote a famous collection of Hungarian Dances (Brahms) .
Here is what appears to be a good article on the subject:
Brahms: The Hungarian Connection explores the composer's love of folk music from the country

Debussy, among the most notable of many, was deeply affected by
Javanese Gamelan Music :
Gamelan - Influence on Western music
The gamelan has been appreciated by several western composers of classical music, most famously Claude Debussy who heard a Javanese gamelan in the premiere of Louis-Albert Bourgault-Ducoudray's Rhapsodie Cambodgienne at the Paris Exposition of 1889 (World's Fair). The work had been written seven years earlier in 1882, but received its premiere only in 1889. The gamelan Debussy heard in it was in the slendro scale and was played by Central Javanese musicians.
Despite his enthusiasm, direct citations of gamelan scales, melodies, rhythms, or ensemble textures have not been located in any of Debussy's own compositions. However, the equal-tempered whole tone scale appears in his music of this time and afterward,[28] and a Javanese gamelan-like heterophonic texture is emulated on occasion, particularly in "Pagodes", from Estampes (solo piano, 1903), in which the great gong's cyclic punctuation is symbolized by a prominent perfect fifth.
The composer Erik Satie, an influential contemporary of Debussy, also heard the Javanese gamelan play at the Paris Exposition of 1889. The repetitively hypnotic effects of the gamelan were incorporated into Satie's exotic Gnossienne set for piano.
Direct homages to gamelan music are to be found in works for western instruments by John Cage, particularly his prepared piano pieces, Colin McPhee, Lou Harrison, Béla Bartók, Francis Poulenc, Olivier Messiaen, Pierre Boulez, Bronislaw Kaper and Benjamin Britten. In more recent times, American composers such as Henry Brant, Steve Reich, Philip Glass, Dennis Murphy, Loren Nerell, Michael Tenzer, Evan Ziporyn, Daniel James Wolf and Jody Diamond as well as Australian composers such as Peter Sculthorpe, Andrew Schultz and Ross Edwards have written several works with parts for gamelan instruments or full gamelan ensembles. I Nyoman Windha is among contemporary Indonesian composers that have written compositions using western instruments along with Gamelan. Hungarian composer György Ligeti wrote a piano étude called Galamb Borong influenced by gamelan. Avant-garde composer Harry Partch, one of America's most idiosyncratic composers, was also influenced by Gamelan, both in his microtonal compositions and the instruments he built for their performance...

Bella Bartok, credited by many as the first to seriously engage in ethnomusicology, was deeply influenced by the folk music of Hungary and Eastern Europe, from quite a young age:
Bartok - Early musical career (1899–1908)
In 1908, he [Bartok] and Kodály traveled into the countryside to collect and research old Magyar folk melodies. Their growing interest in folk music coincided with a contemporary social interest in traditional national culture. They made some surprising discoveries. Magyar folk music had previously been categorised as Gypsy music. The classic example is Franz Liszt's famous Hungarian Rhapsodies for piano, which he based on popular art songs performed by Romani bands of the time.
In contrast, Bartók and Kodály discovered that the old Magyar folk melodies were based on pentatonic scales, similar to those in Asian folk traditions, such as those of Central Asia, Anatolia and Siberia. Bartók and Kodály quickly set about incorporating elements of such Magyar peasant music into their compositions. They both frequently quoted folk song melodies verbatim and wrote pieces derived entirely from authentic songs. An example is his two volumes entitled For Children for solo piano, containing 80 folk tunes to which he wrote accompaniment. Bartók's style in his art music compositions was a synthesis of folk music, classicism, and modernism. His melodic and harmonic sense was profoundly influenced by the folk music of Hungary, Romania, and other nations. He was especially fond of the asymmetrical dance rhythms and pungent harmonies found in Bulgarian music. Most of his early compositions offer a blend of nationalist and late Romanticism elements.
In his later years in the USA, Bartok actually received a research fellowship from Columbia University to study Serbian and Croatian folk songs.
Bartók World War II and last years in America (1940–45)
Having first sent his manuscripts out of the country, Bartók reluctantly emigrated to the U.S. with his wife Ditta in October that year. They settled in New York City after arriving on the night of October 29–30, 1940 via a steamer from Lisbon... Supported by a research fellowship from Columbia University, for several years, Bartók and Ditta worked on a large collection of Serbian and Croatian folk songs in Columbia's libraries. Bartók's economic difficulties during his first years in America were mitigated by publication royalties, teaching and performance tours. While his finances were always precarious, he did not live and die in poverty as was the common myth. He had enough friends and supporters to ensure that there was sufficient money and work available for him to live on. Bartók was a proud man and did not easily accept charity. Despite being short on cash at times, he often refused money that his friends offered him out of their own pockets. Although he was not a member of the ASCAP, the society paid for any medical care he needed during his last two years. Bartók reluctantly accepted this (Chalmers 1995, 196–203).

As mentioned by @user1044 in their answer, many 20th Century American composers, such as Ives, Copland, Gershwin and Bernstein, incorporated jazz, blues and other 'folk music' genres into their compositions.
Answer: I read somewhere that polyphonic music and counterpoint were introduced to Europe by Irish monks at the invitation of Charlemagne. Until then, it was all unisons and octaves (no chords!).
Comment: You seem to be conflating a few different ideas: If you have nothing but unisons and octaves, it's essentially a monotone - not music as we know it - all "A's" or all "C's", etc - no melody. Polyphony means more than one melody line. Before the development of polyphony there was monophony - one melody line but potentially using all the notes of various scales and modes, not just octaves and unisons.  The development and use of chords is something else entirely that came quite a bit later - early Renaissance I believe, as the concepts of harmony and polyphony were developed further.
Answer: The twentieth century influences of world music on classical music are numerous, but there are also some notable earlier examples:
Classical music inspired by Middle Eastern music is common.  For instance, Mozart's wonderful "Rondo alla turca" (c.1783), and all the various "Arabesques".  As mentioned in the question, Spanish classical music, in particular, is as closely related to Middle Eastern music as European, doubtlessly due to Spain's proximity to, onetime colonization by, and otherwise intimate history with the Middle East.
Von Weber was influenced by Chinese music in his 1804 opera Turandot.
Saint-Saëns wrote several pieces inspired by African music, including one called "Africa" (1891).
Early twentieth century classical composer Samuel Coleridge-Taylor (named, somewhat confusingly, after the poet Samuel Taylor Coleridge) was part African himself, and composed popular and critically acclaimed works based both on African and on Native American musical themes.