BASH: Newline or HR after long command output

Question: Is there any way to configure Bash to print a newline or horizontal line after commands that provided more than N lines of output? For instance, after a simple cd I don't need a newline or horizontal line, but after a long cat a visual indication of the end of each command's output would be great when I am comparing the output of various commands.
Comment: Maybe, I did not understand you well. If you want to add a newline, you can just use `echo` after each command.
Answer: This cannot be done in bash. The program's output to the terminal does not pass through shell (bash), so there is no way for bash to determine how many lines were printed.
Personally I just manually hit enter once or twice in case when I need visual separation. If you would like to have a newline on every command, the best way is to export PS1='\n'"$PS1"
Comment: Thank you kubanczyk. I actually do currently have a newline character there but seeing a new line after every command is a real waste of screen space. It drives me nuts like source code with the opening bracket on a line to itself.
Answer: Actually you could use a wrapper script like the one below:
#!/bin/bash

CMD="$*"
N=10
IFS=:

i=0;
eval $CMD | while read line; do
    echo "$line"
    i=$((i+1))
    if [ $((i % $N)) -eq 0 ]; then
        echo '================================================================';
    fi
done

Save it in your homedir, lets say as a ~/wrapper.sh. Make alias for it in your .bashrc file:
alias wrap="~/wrapper.sh "

Now you can invoke command of your choice with 'wrap' prefix:
wrap cat veryLongFile

stdout from your command will be post-processed by the wrapper.sh (I'm adding horizontal line after each 1o lines)
Comment: That is great! Is there any way to have _all_ commands automatically wrapped?


PHP: mapa de localização dos usuários através de IP com geolocalização

Question: Boa Noite , eu tenho no banco de dados da minha empresa com varios endereços de IP ( em formato de histórico ) e o IP atual do usuário que acessa o meu site.
Gostaria de saber sé consigo com esse dados montar um mapa do acesso , mostrando quais países eu tenho o maior fluxo de usuários .
O sistema automaticamente já determina a sigla do país através do php e de um banco de dados de GeoIp que configurei , gostaria de saber então como organizar esses dados em um mapa.
Comment: Pode usar uma API pronta: http://www.infosniper.net/services.php
Comment: aqui no próprio Stack Overflow em português você tem a resposta. [Clique aqui](https://pt.stackoverflow.com/questions/34958/como-determinar-a-localiza%C3%A7%C3%A3o-aproximada-do-usu%C3%A1rio-pelo-ip).
Comment: @RpgBoss , ela consegue montar os mapas de calor?Pelo que vi ela me retorna dados que já possuo.
Comment: @MarceloÁgil a localização eu ja tenho , quero montar um mapa com ela.
Comment: Ah tah, você quer montar um mapa igual ao do WordPress.
Comment: Eu nunca vi esse do Wordpress , eu quero montar algo eficiente porque são 3 mil usuários , 3 mil IPS , então fica ruim puxar os dados .
Comment: O Wordpress tem uma menu no painel de controle, onde você pode analisar as visitas do dia, da semana, do mês ou geral (desde o início do registro), e ele distribui no mapa mundi com níveis de cores (Quanto mais vermelho mais visitas) dos países pra ver qual a maior frequência de visitas. Não é dificil fazer, mas leva algum tempo, por isso sugerir baixar uma API pronta. https://i.stack.imgur.com/9J8Ko.png
Answer: Se você ja tem o país que o usuário está você pode fazer de diversas formas, entre elas:
1 - usar a API do Google Maps e usar o mapa de calor
https://developers.google.com/maps/documentation/javascript/examples/layer-heatmap?hl=pt-br
2 - Você pode montar o mapa mundi em SVG (no google tem varios sites para fazer download) e criar uma coleção de cores e conforme a quantidade de acessos você usa a cor para pintar aquele país.
Comment: OI amigo , eu consigo montar esse mapa sem utilização de APIs?
Comment: Quando conseguir vai praticamente ter criado uma API sem perceber :)
Comment: Eu digo API como da Google .
Comment: olá, você ja tem as siglas dos paises em sua base de dados...então você consegue criar um degrade conforme a quantidade num range que voce determinar. Feito isso, basta pegar os SVGs do mapa mundo e colorir conforme esse degrade.
Comment: Sim , isso é o facil amigo o problema é na horar de gerar e comparar os IPs com o da base de dados do GEOIP.
Comment: Torna-se custoso pro servidor  , o mysql fica em 100% de uso da CPU com 2 mil ips.
Comment: acho que o melhor é vc criar um processo a parte que faz essa comparação do IP com a base de dados e atualiza a tabela já com o valor certo. Deixa esse processo em paralelo rodando de hora em hora pegando os novos IPs dentro desse range de hora... ou seja, vc vai ter um delay de 1h para mostrar as infos.


Problemas com Drag and Drop em JavaScript puro

Question: Estou com problemas com a minha função de Drag e Drop em JavaScript, o funcionamento do drag and drop está perfeito, porém quando troco algumas imagens, elas fazem a troca incorreta. Por exemplo: tenho as imagens x,y e z, e quando troco z e y, a troca ocorre em y e x e z fica no mesmo local.

<code>//esta função irá pegar o ID das imagens, para fazer a troca das imagens de acordo com o id delas

function pegaId(obj) {
var idCorreto = obj.getAttribute('id');
return idCorreto;
}

function drag(obj) {
 var zIndexImg = 0;
 // com a var id, eu detecto qual imagem está sendo arrastada
 var id = obj.getAttribute('id');

 var img = document.getElementById(id);
 var imgPositionLeft = img.offsetLeft;
 var imgPositionTop = img.offsetTop;

 img.ondragstart = function() {
  return false;
 };

 function dropImage(e) {
  img.style.transition = "";
  img.style.zIndex = zIndexImg++;

  // faço o drag das imagens
  img.style.top = e.clientY - imgPositionTop + 'px';
  img.style.left = e.clientX - imgPositionLeft + 'px';

  console.log(e.clientX - imgPositionLeft);
 }

 function change(id1, id2, div1, div2) {
  // esta função realizara a troca das imagens
  img.removeAttribute('style');

  // atribuo as imagens e as divs em que estao guardadas em variaveis
  var imgDiv = document.getElementById(div1);
  var imgDiv_2 = document.getElementById(div2);
  var imgId = document.getElementById(id1);
  var imgId2 = document.getElementById(id2);

  // pego o id de ambas imagens
  var getId = imgId.getAttribute('id');
  var getId2 = imgId2.getAttribute('id');

  // faço a troca dos ids
  imgId.setAttribute('id', getId2);
  imgId2.setAttribute('id', getId);

  // e sobreponho as imagens nas divs, fazendo a troca
  imgDiv.innerHTML = imgId2.cloneNode().outerHTML;
  imgDiv_2.innerHTML = imgId.cloneNode().outerHTML;
 }

 function drop(e) {
  // esta função é para quando soltar as imagens
  dropImage(e);
  // removo os eventos adicionados
  document.removeEventListener('mousemove', dropImage);
  document.removeEventListener('mouseup', drop);

  // descubro qual a imagem clicada para fazer a troca
  if (img.style.left >= '90px' && img.style.left <= '130px') {
   // pego o ID para saber qual a imagem
   if (pegaId(obj) == 'teste1') {

    // e faço a troca com a função change
    change("teste1", "teste2", "img1", "img2");

   } else if (pegaId(obj) == 'teste2') {
    change("teste2", "teste3", "img2", "img3");
   }

  }

  if (img.style.left >= '230px' && img.style.left <= '250px') {
   change("teste1", "teste3", "img1", "img3");

  }
  if (img.style.left >= '-115px' && img.style.left <= '-130px') {

   if (pegaId(obj) == 'teste3') {
    change("teste2", "teste3", "img2", "img3");
   } else if (pegaId(obj) == 'teste2') {
    change("teste2", "teste1", "img2", "img1");
   }
  }

  if (img.style.left >= '-225px' && img.style.left <= '-250px') {
   change("teste1", "teste3", "img1", "img3");
  }

  // reseto os valores após soltar a imagem
  img.style.left = '0px';
  img.style.top = '0px';
 }

 // adiciono os eventos novamente após clicar nas imagens
 img.addEventListener('mousedown', function() {
  document.addEventListener('mousemove', dropImage);
  document.addEventListener('mouseup', drop);
 });
}</code>

http://jsfiddle.net/v1u1xnwj/11/
Comment: Queres que a imagem arrastada troque de posição com a que está fixa ou inserir a arrastada e afastar as outras para o lado?
Comment: @Sergio reinseri o jsFiddle !
Comment: Desculpe por ter removido o link @anuseranother
Comment: @re22 Sem problemas, também não havia notado, acontece.
Comment: Quero que a que está sendo arrastada troque de lugar com a que está fixa no momento, porém gostaria de manter puro JavaScript sem jQuery...
Answer: Identifiquei que o meu problema ocorreu pois a mesma função que trocava as imagens estava trocando os ids, ocasionando nessa confusão em algumas trocas. Fiz a troca do ID em outra função e o problema deixou de existir, assim:
<code>//função que troca as imagens de lugar
            function change(id1,id2,div1,div2){

                img.removeAttribute('style');

                var imgDiv = document.getElementById(div1);
                var imgDiv_2 = document.getElementById(div2);
                var imgId = document.getElementById(id1);
                var imgId2 = document.getElementById(id2);

                imgDiv.innerHTML = imgId2.cloneNode().outerHTML;
                imgDiv_2.innerHTML = imgId.cloneNode().outerHTML;
}

//função que troca o id das imagens
            function trocaId(id1,id2){
                var id_1 = document.getElementById(id1);
                var id_2 = document.getElementById(id2);

                    id_1.setAttribute('id',id2);
                    id_2.setAttribute('id',id1);
                }

//fazendo a troca

            if(img.style.left >= '250px' && img.style.left <= '290px'){
                if(pegaId(obj) == 'teste1'){
                    change("teste1","teste2","img1","img2");
                    trocaId("teste1","teste2");
                }else if(pegaId(obj) == 'teste2'){
                    change("teste2","teste3","img2","img3");
                    trocaId("teste2","teste3");
                }
</code>
http://jsfiddle.net/v1u1xnwj/10/


VLANs and Access Point

Question: I have all my network (wired and WiFi) in the same VLAN. I just bought a new Access Point, and am trying to set WiFi Clients to be in VLAN 2.
On the AP, I set it to assign VLAN 2 to the clients, and on my pfSense firewall, I configured a VLAN for WiFi on the same NIC where the LAN is. I also enabled DHCP for the WIFI VLAN, using a different subnet (192.168.2.0/24) than the existing LAN (192.168.0.0/24).
When I connect with a client to WiFi, my client doesn't get an IP address.
The AP is connected to a switch, which is connected to the LAN NIC of the pfSense. As far as I know, those are untagged for VLAN.
I tried restarting pfSense, as I read adding VLANs might require it, but the issue persisted.
My network has two switches. A Baseline Switch 2250-SFP Plus and a Baseline Switch 2226-SFP Plus.
pfSense is plugged to the 2250 in port 3, and port 49 is used to cascade to port 25 of the 2226. The UniFi is plugged to port 17 of the 2226.
I've created the VLAN 2 in both the 2250 and the 2226, and added ports 3 and 49 of the 2250 and 17 and 25 of the 2226 as VLAN 2 tagged.
The UniFi gets its IP address though DHCP, and is only getting an IP address of the wired subnet (which I believe is ok).
I can connect to WiFi just fine, but I can't get an IP address.
Comment: You might want to add the model number of your manageable vlan-capable switch, and its settings for the ports to the AP and pfsense.
Comment: @AlexStragies just added more details on the VLAN configuration.
Answer: You need to set the port on the switch to accept tagged packets. This is usually accomplished by changing the port mode to trunk.
On the firewall, you also need to set up packets for that subnet to be tagged as VLAN 2, and you will need to set the switch port mode to trunk. On some firewalls, you actually create a new virtual interface for the VLAN. I have no experience with pfSense, so I can't help you there.

VLANs and Access Point


adicionar itens de um loop while em uma ArrayList, Java

Question: Preciso adicionar as entradas de um loop que o usuário fizer e armazenar em uma lista, do jeito que eu fiz está salvando somente o ultimo número, preciso que armazene todos.
System.out.println("Digite quantos pontos o cliente possui. ");
Scanner entrada1 = new Scanner(System.in);
ArrayList bancoEntradas = new ArrayList();
<code>                pontos = entrada1.nextInt();
                while (contador != pontos) {
                    System.out.println("Digite as composição dos pontos, 3,4,5 ou 7 são permitidos ");
                    System.out.println("Pontos em análise " + pontos + "  Somátorio dos pontos inseridos  " + contador);
                    Scanner entrada4 = new Scanner(System.in);
                    pontoinserido = entrada4.nextInt();
                    bancoEntradas.add(pontoinserido);

                    while (pontoinserido != 3 && pontoinserido != 4 && pontoinserido != 5 && pontoinserido != 7) {

                        System.out.println("Resposta incorreta. Digite as composição dos pontos, 3,4,5 ou 7 são permitidos.");
                        pontoinserido = entrada4.nextInt();
                        if (pontoinserido < pontos) {
                            //pontoinserido = entrada4.nextInt();
                            continue;
                        }

                    }

                    contador = pontoinserido + contador;
</code>
Answer: <code>pontos = entrada1.nextInt();
                while (contador != pontos) {
                    System.out.println("Digite as composição dos pontos, 3,4,5 ou 7 são permitidos ");
                    System.out.println("Pontos em análise " + pontos + "  Somátorio dos pontos inseridos  " + contador);
                    Scanner entrada4 = new Scanner(System.in);
                    pontoinserido = entrada4.nextInt();
                    bancoEntradas.add(pontoinserido);

                    while (pontoinserido != 3 && pontoinserido != 4 && pontoinserido != 5 && pontoinserido != 7) {

                        System.out.println("Resposta incorreta. Digite as composição dos pontos, 3,4,5 ou 7 são permitidos.");
                        pontoinserido = entrada4.nextInt();
                        if (pontoinserido < pontos) {
                            //pontoinserido = entrada4.nextInt();
                            continue;
                        }

                        bancoEntradas.add(pontoinserido); // so faltou adicionar novamente na lista

                    }

                    contador = pontoinserido + contador;
</code>


Google Ads API does not return disabled campaigns

Question: I am migrating our API ingestion from googleads to google-ads in python and I noticed that the campaign resource only returns entities that have status "ENABLED". In the googleads version, it returns all entities by default when you request for it.
I tried modifying the GAQL to include filtering like where campaign.status != 'ENABLED' and I get no results back from the API.
Is there a way to get entities with all status like "PAUSED", "REMOVED" etc? Also, is there a place to run the GAQL in the web UI? (They have the GAQL validator but it doesn't let me run it)
Answer: you can add in WHERE clause
campaign.status IN ('ENABLED', 'PAUSED', 'REMOVED', 'UNKNOWN')


Command line program to test DHCP service

Question: Is there a simple ping-like command to test whether a DHCP service is running on a network? ...on Linux
Answer: Based on this answer, assuming you have installed nmap (sudo apt install nmap):
sudo nmap --script broadcast-dhcp-discover

Add the -e $interface option if you have more than one network interface. (For example: nmap --script broadcast-dhcp-discover -e eth0)
Sample output:
Starting Nmap 7.01 ( https://nmap.org ) at 2017-09-27 17:40 CEST
Pre-scan script results:
| broadcast-dhcp-discover:
|   Response 1 of 1:
|     IP Offered: 192.168.81.94
|     DHCP Message Type: DHCPOFFER
|     Server Identifier: 192.168.81.2
|     IP Address Lease Time: 5m00s
|     Subnet Mask: 255.255.255.0
|     Router: 192.168.81.2
|     Domain Name Server: 192.168.81.2
|     Domain Name: example.lan
|     NTP Servers: 192.168.81.10, 192.168.81.2
|     NetBIOS Name Server: 192.168.81.10
|_    NetBIOS Node Type: 8
WARNING: No targets were specified, so 0 hosts scanned.
Nmap done: 0 IP addresses (0 hosts up) scanned in 0.66 seconds

Or this output on a different network, with nmap v. 6 :
Starting Nmap 6.00 ( http://nmap.org ) at 2017-09-27 17:42 CEST
Pre-scan script results:
| broadcast-dhcp-discover:
|   IP Offered: 192.168.4.101
|   DHCP Message Type: DHCPOFFER
|   Server Identifier: 192.168.4.1
|   IP Address Lease Time: 7 days, 0:00:00
|   Subnet Mask: 255.255.255.0
|   Time Offset: 7200
|   Router: 192.168.4.1
|   Domain Name Server: 18.104.22.168, 184.108.40.206
|   Renewal Time Value: 3 days, 12:00:00
|_  Rebinding Time Value: 6 days, 3:00:00
WARNING: No targets were specified, so 0 hosts scanned.
Nmap done: 0 IP addresses (0 hosts up) scanned in 1.15 seconds

Comment: Note that [this script](https://github.com/nmap/nmap/blob/master/scripts/broadcast-dhcp-discover.nse) uses a fixed MAC address (`DE:AD:CO:DE:CA:FE`) and therefore will not work if your DHCP server is configured with a whitelist.
Comment: @Bob An option has been added. `--script-args mac=XX:XX:XX:XX:XX:XX`. It hasn't been released yet though.
Comment: For DHCPv6 there's `sudo nmap -6 --script broadcast-dhcp6-discover`
Comment: this didn't find my DHCP server.- must be something wrong with my pc... ethernet works, just not that.
Answer: Even if you don't use a Nagios monitoring server, you can grep the check_dhcp binary or compile it from source and use the check to test a DHCP-Server. E.g.
./check_dhcp -v -s <dhcp_server_address> -r <expected_ip_address> -m <mac_address_touse>

Answer: or you can try dhcpcd in test mode:
dhcpcd -T eth0

Comment: Use `dhcpcd -T eth0 -t 2` to timeout after 2 seconds
Comment: a dhcp server needs to see a packet on the network from a host requesting a dhcp configuration message.
therefore we need to mimic a dhcp request,, and this tool will do that and print the response, which will be an ip address, netwmask, default router, and optionally dns resolvers, ntp servers etc.
Comment: not all distros seem to have the dhcpcd program, so you'll have to try the dhclient program in test mode, as discussed elsewhere on this page.
Comment: Could you please expand on why should this command detect DHCP servers on your network and what kind of output should we expect when someone will be detected?
Answer: dhcpdump is good for sniffing and displaying DHCP packets on the network.
E.g.
# dhcpdump -i eth0
---------------------------------------------------------------------------

  TIME: 2015-11-27 11:41:37.379
    IP: 0.0.0.0 (0:11:b9:5:0:b8) > 255.255.255.255 (ff:ff:ff:ff:ff:ff)
    OP: 1 (BOOTPREQUEST)
 HTYPE: 1 (Ethernet)
  HLEN: 6
  HOPS: 0
   XID: abce9327
  SECS: 0
 FLAGS: 0
CIADDR: 0.0.0.0
YIADDR: 0.0.0.0
SIADDR: 0.0.0.0
GIADDR: 0.0.0.0
CHADDR: 00:11:b9:05:00:b8:00:00:00:00:00:00:00:00:00:00
 SNAME: .
 FNAME: .
OPTION:  53 (  1) DHCP message type         1 (DHCPDISCOVER)
OPTION:  57 (  2) Maximum DHCP message size 576
OPTION:  55 (  4) Parameter Request List      1 (Subnet mask)
                          3 (Routers)
                         28 (Broadcast address)
                          6 (DNS server)

---------------------------------------------------------------------------

You can use it in conjunction with another tool to do DHCP requests, or just use it to watch PCs/devices query DHCP.
Comment: @KenSharp Why? Yes. dhcpdump will only show something when a client on the network requests a dhcp address. If you don't want to wait and don't want to send a dhcp request yourself but only see which machine would answer what IF there were a request, then this is not the solution.
Comment: Also available for macOS thru `brew install dhcpdump`.
Comment: This seems to only only work if there is actual dhcp traffic on the network.
Comment: This is what I'd recommend for anyone trying to diagnose TFTP problems. Knowing the thin client wasn't even requesting the field my router UI exposes as "TFTP Server IP/hostname" and just assumes the DHCP and TFTP will be on the same box would have saved me an entire afternoon.
Answer: Why not just make a DHCP request?
dhclient

For verbose output use:
dhclient -v
Comment: Probably because that will make your system *use* the IP assigned by the DHCP server which is not what one wants when e.g. trying to find out if there are rogue DHCP servers in his network.
Comment: -n option helps here?
Comment: I don't think `-n` does what you think it does.
Comment: Option `-n` seems to be broken on ISC DHCP Client v4.2.4 on Ubuntu 14 LTS?
Comment: https://explainshell.com/explain?cmd=dhclient+-n: "Do not configure any interfaces.  This is most likely to be useful in combination with the -w flag."
Answer: I wrote a DHCP test client program a while ago, works on Windows and POSIX:
https://github.com/CyberShadow/dhcptest
Comment: Written in D... It seems possible (with `ldc2`) to get static binaries with `ldc2 -link-defaultlib-shared=false -static -L=-lphobos2-ldc -L=-lz dhcptest.d`
Answer: There is a program called dhcping (with just one p)
Answer: if you use nagios you could monitor it with check_dhcp
Answer: On Debian-Ubuntu systems:
dhcpd -f

gives good feedback and tests the configuration.
On RH systems try:
/etc/rc.d/init.d/dhcpd configtest

Comment: That test is run on the dhcp server to check its configuration, it doesn't tell you if a device on the network will actually see a working server


Using integrals to evaluate the O(n) of sums

Question: Taking an unusual approach to finding the big O notation of a sum:
$$f(n)=\sum_{k=0}^{n}k$$
Then let $g(n) = \int_{0}^{n}xdx $. Could we then say that because $g(n)\simeq f(n)$, that $f(n)\in O(g)$.
Now evaluating $g(n)$,
$$g(n) = \int_{0}^{n}xdx = \left[ \frac{1}{2}x^2 \right]_{0}^{n} = \frac{1}{2}n^2$$
$\therefore g(n)\in O(n^2)$ and $f(n) \in O(n^2)$
Does this logic stack up? and is it possibly useful for more complex sums. I am aware of other ways to find the big O of $f(n)$, however this was my first instinct. Id be grateful for any insight.
Comment: what is the definition of $g(x)\simeq f(x)$?
Answer: Your approach to finding the big O notation of the sum function $f(n)=\sum_{k=0}^{n}k$ is interesting. However, I would like to point out that your conclusion that $f(n)\in O(g(n))$ based on the approximation $g(n)\simeq f(n)$ is not valid.
To see why, consider the definition of big O notation: $f(n)\in O(g(n))$ if there exist positive constants $C$ and $n_0$ such that $|f(n)|\leq C|g(n)|$ for all $n\geq n_0$. Your approximation $g(n)\simeq f(n)$ does not give you a precise upper bound on $f(n)$ in terms of $g(n)$. In other words, you cannot conclude that $f(n)\leq Cg(n)$ for some constant $C$.
However, you can still use your approach to find the big O notation of $f(n)$ by comparing it to a known function that grows at the same rate. In this case, you correctly calculated that $g(n)\in O(n^2)$, so we can conclude that $f(n)\in O(n^2)$ as well.
To see why, note that $f(n)=\sum_{k=0}^{n}k=\frac{n(n+1)}{2}$, which is a quadratic function of $n$. Therefore, we can write $f(n)=an^2+bn+c$ for some constants $a$, $b$, and $c$. Since $f(n)$ is a quadratic function and $g(n)\in O(n^2)$, we can conclude that $f(n)\in O(n^2)$ as well.
In summary, your approach of approximating the sum function with an integral and then comparing it to a known function can be a useful technique for finding the big O notation of more complex sums. However, it is important to remember that the approximation does not give a precise upper bound, so you still need to verify that the function you compare it to is indeed a tight upper bound.


MikroTik. NAT forwarding is not working for local network

Question: I try to access my external IP address from the local network, but instead of reaching my webserver behind NAT - the webfig page shows up.
NAT forwarding is working when accessing from the internet.
EDIT: This is my current nat config
[admin@MikroTik] > ip firewall nat print
Flags: X - disabled, I - invalid, D - dynamic
 0    ;;; defconf: masquerade
      chain=srcnat action=masquerade out-interface-list=WAN ipsec-policy=out,none

 1    chain=dstnat action=dst-nat to-addresses=<server's ip> to-ports=80 protocol=tcp in-interface=ether1 dst-port=80

Comment: Look up "Hairping NAT" on the documentation. It is not trivial to set up but that is what is missing - your traffic is not being NAT's because it is  bypassing the NAT.
Comment: Yup. That worked well. Thanks!
Answer: To achieve this, you need to use Internal NAT Hairpin. You can configure it in a few commands.
Let's assume that 188.8.131.52 is our external IP address, 192.168.1.0/24 is our local network, and 192.168.1.128 is a webserver.
Then, you need to add these NAT rules:
/ip firewall nat
# Forwarding
chain=dstnat action=dst-nat to-addresses=184.108.40.206 dst-address=220.127.116.11 dst-port=80,443
chain=srcnat action=src-nat to-addresses=126.96.36.199 src-address=192.168.1.128 src-port=80,443

# Masquerading
hain=srcnat action=masquerade src-address=192.168.1.0/24 dst-address=192.168.1.0/24

This rule should already exist:
chain=srcnat action=masquerade out-interface-list=WAN

Comment: but what if my external IP address if dhcp controlled by provider and different from time to time? are there any tricks to avoid explicitly declaring dst-address ?
Comment: @xorza maybe by using destination-address-list and updating that with a script. Honestly, you'll need to use a Static IP for this reason.


Vector space of matrices of rank $\le r$

Question:
Let $F$ be a field, and $M_{n\times n}(F)$ be the set of $n\times n$ matrices with entries in $F$. Let $V$ be a subspace of $M_{n\times n}(F)$ where every matrix in $V$ has rank at most $r$. Prove that $\dim V\le nr$.

This is a puzzle I found on the internet which I am having trouble solving. I suppose I am not even sure if the result is correct, but it seems so. It is easy to come up with subspaces of dimension $nr$, like the set of matrices where all but $r$ columns are zero, but these examples are all tight.
I have been able to find literature on subspaces of matrices of rank $\ge r$, but not of rank $\le r$. I would appreciate any hints, references, or even solutions which require $F=\mathbb R$ or $\mathbb C$.
Here is a failed attempt that might serve for inspiration:
Let $t=\dim V$, and assume $t=nr+1$. By using Gaussian elimination, we can find a basis $A^1,\dots,A^t$ for $V$ such that for each $1\le k\le t$, there exists a position $(i(k),j(k))$ where $A^k_{i(t),j(t)}=1$, while $A^\ell_{i(t),j(t)}=0$ for all $\ell\neq k$. These positions are the "leading ones" found by Gaussian elimination, and when choosing a matrix in $V$, the entries in these positions can be chosen independently of each other.
Since there are $nr+1$ leading ones, there exists $r+1$ leading ones which are in pairwise different rows and columns (this follows from a pigeonhole argument). I was hoping to leverage this to show how to that the $(r+1)\times(r+1)$ sub-matrix where these rows and columns intersect could be chosen to have rank $r+1$ by an appropriate choice of the leading ones. This fails, because there is no control over the other entries in the sub-matrix, and they can get in the way.
Many thanks!
Answer: According to H. Flanders, On Spaces of Linear Transformations with Bounded Rank, Journal of the London Mathematical Society, 1962

Theorem: Let $r\leq n\leq m$ be positive integers, let $\Bbb F$ be a field with at least $r+1$ elements, and let $V$ be a subspace of $\mathcal{M}_{m\times n}(\Bbb F)$ where each element has rank at most $r$.
  Then $$\dim V\leq nr.$$

The extra condition "with at least $r+1$ elements" can actually be omitted, according to R. Meshulam, On the maximal rank in a subspace of matrices, The Quarterly Journal of Mathematics, 1985.
Comment: Perfect answer, thank you!


File sync between two server behind load balancer

Question: I have a best practice question. We have an app running on two servers behind a load balancer. Most data is in a common DB, user uploaded files are in object-storage. So not much to keep in sync, except some YAML config files that are generated by the user via the app backend.
What is the best practice to keep these files in sync? One solution I thought of is to mount a shared volume to host the code and config files. Is there a better solution?
Comment: It's very hard to answer this without knowing what those yaml files for and what other engineering practices are there in your org.

Everyone's best practice is different. I'd say package those yamls in container using CI/CD and do gradual rollouts. I have no idea if it's applicable in your case though.
Comment: Questions seeking installation, configuration or diagnostic help must include the desired end state, the specific problem or error, sufficient information about the configuration and environment to reproduce it, and attempted solutions. Questions without a clear problem statement are not useful to other readers and are unlikely to get good answers
Answer: Assuming only one "best practice" is a trap. There always is more than one solution.
Storing the contents of the config files in the database is one option. Blobs managed by some application, possibly written out to disk if that is what some other thing is reading. Or alter the application to use discrete data fields in the DB rather than YAML documents.  Takes advantage of the existing central database, but requires that DB to be available first.
Store the config files in the software package or image containing the application. Deploy new ones by upgrading the app. Only makes sense if those files are changed by the same people or process updating the application.
Copy the files from the authoritative copy to each instance on a schedule, or on change. Take your pick of file copy software, rsync, sftp. Would need some extra scripting if the install should be transactional, in that all of the files are installed, or none of them are.
Mount a network file share. Beware that if NFS or SMB shares are disconnected in an unplanned manner, that can cause performance issues.


Como remover um mapeamento no visual studio no tfs

Question: Como eu faço para remover um mapeamento feito pelo VS 2010 Ultimate no tfs? Preciso fazer isso, para mapear corretamente, pois está errado.
Comment: Eu fiz assim. Peguei o servidor do tfs e cliquei com o direito e me apareceu no popup menu dele a opção Remove Map. Fiz isso e funcionou.
Comment: Posta isso como resposta :)
Comment: Existem formas de fazer isso pelo Visual Studio. porém eu só conheço a forma bruta, que é abrir o arquivo *.sln* da solução no bloco de notas e tirar a seção do TFS manualmente.
Answer: Eu fiz assim. Peguei o servidor do tfs e cliquei com o direito e me apareceu no popup menu dele a opção Remove Map. Fiz isso e funcionou.
Answer: Para fazer isto, existem algumas opções:

No Source Control Explorer, acesse o Dropdown de Workspaces;
Nele, selecione "Workspaces...". Você verá uma jenala para gestão dos seus workspaces e mapeamentos;
Selecione o Workspace que deseja editar (que contenha o mapeamento da sua pasta) e clique em "Edit..."
Aqui, nesta janela, você consegue tanto remover o mapeamento quanto ajustado. Isto é importante porque vi que você quer mapear corretamente, não é?

Abraços,


permutation arrange boys and girls in a circle

Question: got the following question:

how many ways there are to arrange 4 girls and 4 boys in a circle,
with no limitations.
all the boys are on one side and all the girls (4 girls on one side and 4 boys on the other side)
  are on one side.
every boy between two girls.

As I understand the answer to the first one is : $7!$
About the second and the third conditions I am not sure:
my strategy was:

arrange all the girls in a circle: $$3!$$
insert and rearrange the boys in the remaining spaces: $$4!$$
so the final answer should be: $$3!\cdot 4!$$

Is it correct?
Thanks A lot to the kind helper.
Comment: Your answer looks correct. There are 3! ways to arrange the girls in a circle. There are also 3! ways to arrange the boys in a circle and there are 4 possible places for Roman between 2 girls, so the answer is $3!\cdot 3!\cdot 4$
Comment: For the second coundition, using clockwise motion, there are 4! ways to arrange the girls in a row and 4! ways to arrange the boys in a row, so the answer is $4!\cdot 4!$.
Comment: Does only the boy-girl order matter or does each individual count in the order too
Comment: every individual is unique so if Roman sits between Anna and Lena in one circle and sits between Jane and Lori in the other circle those circles are **not** the same
Comment: and what about the second condition?
Answer: I think your second answer is not correct.
For the first it's just  $$\frac{8!}{8}=7!$$
because there are $8!$ permutations of $8$ children and since all this happens  in the circle we need to divide by $8$.
The second problem: $$4!4!$$
Because let $a$ be all four girls and $b$ be all four boys.
Thus, we need to place $a$ and $b$ on the circle, which gives $\frac{2!}{2}=1$ cases.
Now, we can remember that they are $4$ (boys and girls), which gives $(4!)^2$.
The third problem: $$3!4!$$
For the new second problem.
If you mean that we need $4$ boys placed together or $4$ girls placed together then the answer is
$$2\cdot\frac{5!4!}{5}$$
Comment: yes, I mean its again a circle so shouldn't it be the same as the third condition?
Comment: Does clockwise or counterclockwise matter? Would 132 and 123 be different?
Comment: That's exactly what I don't understand... why is this happening?
Comment: @misha312 About second? Let all girls are $a$ and all boys are $b$. We need to place $a$ and $b$ on the circle. It gives $\frac{2!}{2}=1$. Now, we can remember that they are $4$ girls and $4$ boys.
Comment: @misha312 You miss for example the following case. Place in the circle continuously $2$ boys, $4$ girls and $2$ boys again. It's one of cases, which you want in the second problem. Your reasoning misses this case.
Comment: @MichaelRozenberg I think I didnt explained my self correctly the second condition dictates that on each side of the circle we have 4 girls or 4 boys
Comment: @misha312 Your new second condition is possible if it's just the third condition. Maybe you mean $4$ boys are together or $4$ girls are together?
Comment: Each possible arrangement can be reversed
Comment: @MichaelRozenberg I dont quet understand what you mean
Comment: @misha312 I said many things. What do you mean? Do you mean my last words or my adding to the post?
Comment: @MichaelRozenberg never mind I understand now thanks!
Comment: @misha312 You are welcome!


How to save video from a url to disk, also how to begin playback after some buffering?

Question: First question is, given a url to an mp4 video, how can I save that file to disk?  The followup to that is while its saving, can I begin playback after its buffered some of the video to disk or do I have to wait for the entire file to be written and then:
MPMoviePlayerController* theMovie=[[MPMoviePlayerController alloc] initWithContentURL:theURL];

using the path to the local file.
Thanks,
Sam
Answer: The MPMoviePlayerController will start downloading the movie to it's own cache and will start playing the video as soon as enough data has been downloaded.
AFAIK there is no way to control the download and to for example save it to a known file that you specify.
Comment: This is indeed the case, I have to choose one or the other (save it to disk and then play, or play w/out saving it to disk).
Answer: 1.Using NSURLDownload or NSURLConnection can implement your request.
2.play downloaded file or localfile, just like play url link
[NSURL fileURLWithPath:yourlocalpath];
Answer: There is no simple way to do this, but you could use NSURLConnection to download the file and re-serve it from a specialized HTTP server of your making running locally on the device (your server would save the file to disk and reserve up the partial download for MPMoviePlayerController to access)


Laravel 5.2 throws HTTP ERROR 500

Question: I am using laravel 5.2 setup of pre-built project. I am looking to show errors on browser window for any issue happens. I know a simple step to  do that which is to modify the APP_DEBUG to true in .env file which is pointed by app.php config file with parameter debug. I did check that.
Additionally,

I added ini_set property in index file to display_errors as true.
Along with this, I commented all the $dontReport exceptions from app/Exceptions/Handler.php file-
AuthorizationException::class,
HttpException::class,
ModelNotFoundException::class,
ValidationException::class,

Given 777 permission to my project directory.

At the end, all these crazy methods didn't workout. I tried all I was aware of. Looking for help from you guys.
Comment: Setting `APP_DEBUG=true` in your `.env` file should suffice. If you changed it make sure to run `php artisan config:cache` to read in and cache the new settings
Comment: @NicoHaase it successfully writes the expected logs to laravel.log file located in storage. Only don't show on browser.
Comment: Is there anything written to your server's error log?
Comment: Silly question but is PHP code actually running?
Comment: @kerbholz, I tried with php artisan config:cache but no luck with that.
Answer: Step 1/2/3 is not necessary for Laravel and you should revert those changes.
Only APP_DEBUG=true in your .env file is required. If you are working on a local machine you should also set APP_ENV=local. To locate the 500 error without the browser you can always go look in the log file directly which is located at storage/logs.
Comment: I already have `APP_ENV` set to `local`, and `APP_DEBUG` to `true` and the `laravel.log` file always logs the errors correctly, but I am looking to show them on browser.
Comment: @DIGVJSS if you did that it should show in the browser. But obviously only on the endpoint where the error occurs. Commenting-out the $dontReport error does not solve anything since none of those are 500 errors anyway.

Laravel 5.2 throws HTTP ERROR 500


Function when multiple elements have been clicked

Question: I want a to have an animation only when seven elements have been click. Here is the code but it doesn't work:
var animp5 = function () {
    var i = 0;
    $("#ans1_p5").on('click', function () {
        i = i + 1;
        $("#ans1_p5").fadeOut(800);
        $("#correct1_p5").fadeIn(1000);
    });

    $("#ans2_p5").on('click', function () {
        i = i + 1;
        $("#ans2_p5").fadeOut(800);
        $("#correct2_p5").fadeIn(1000);
    });

    $("#ans3_p5").on('click', function () {
        i = i + 1;
        $("#ans3_p5").fadeOut(800);
        $("#correct3_p5").fadeIn(1000);
    });

    $("#ans5_p5").on('click', function () {
        i = i + 1;
        $("#ans5_p5").fadeOut(800);
        $("#correct4_p5").fadeIn(1000);
    });

    $("#ans7_p5").on('click', function () {
        i = i + 1;
        $("#ans7_p5").fadeOut(800);
        $("#correct5_p5").fadeIn(1000);
    });

    $("#ans9_p5").on('click', function () {
        i = i + 1;
        $("#ans9_p5").fadeOut(800);
        $("#correct6_p5").fadeIn(1000);
    });

    $("#ans10_p5").on('click', function () {
        i = i + 1;
        $("#ans10_p5").fadeOut(800);
        $("#correct7_p5").fadeIn(1000);
    });

    if (i === 7) {
        $("#ans4").fadeOut(800);
        $("#ans6").fadeOut(800);
        $("#ans8").fadeOut(800);
        $("#wrong1_p5").fadeIn(1000);
        $("#wrong2_p5").fadeIn(1000);
        $("#wrong3_p5").fadeIn(1000);
        $("#cor_p5").fadeIn(1000);
    }
};

I have tried other solutions (like .data('clicked') or .attr('clicked') but they didn't work either.
Comment: instead of trying to put a listener on a ton of elements based on id... it would be better to use a single listener based on a class name... then if something is clicked you could toggle class "clicked" or something like that on that element... then count `$(".clicked").length`
Comment: if you share your dom it might be easier to tell what is going on
Answer: Thanks for your answers.
As I have not much experience working with jquery I was unable to code your solution but I found a new one that works perfect. I put the "if" inside every click function so each time I click, code checks if the condition has been fulfilled and once this happens run the appropriate code.
Thanks again
Answer: You can use observer design pattern in javascript to achieve this the right way.
First create handlers, subscribe and execute functions and then you can subscribe waht ever you like in your case its comparison i===7. execute fade.execute after every click to validate.
Also it's advisable to use class selectors than id selectors in your case. As id selectors will be unmanageable and you will end up with a lot of duplicate code.
But for the sake of your question observer is your way to go.
jsFiddle
function Fade() { // Create Fade handlers
  this.handlers = [];  // observers
}

Fade.prototype = { // define subscribe and execute
   subscribe: function(fn) {
     this.handlers.push(fn);
   },
   execute: function(o, thisObj) {
      var scope = thisObj || window;
      this.handlers.forEach(function(item) {
        item.call(scope, o);
      });
   }
};

var fade = new Fade();
fade.subscribe(function(){ // pass function you want to subscribe
   console.log(i);
   if(i===7){
          $("#ans4").fadeOut(800);
          $("#ans6").fadeOut(800);
          $("#ans8").fadeOut(800);
          $("#wrong1_p5").fadeIn(1000);
          $("#wrong2_p5").fadeIn(1000);
          $("#wrong3_p5").fadeIn(1000);
          $("#cor_p5").fadeIn(1000);
      }
});

var animp5 = (function(){
    var i = 0;
    $("#ans1_p5").on('click',function(){
        i=i+1;
        $("#ans1_p5").fadeOut(800);
        $("#correct1_p5").fadeIn(1000);
        fade.execute(); // execute to check if condition met
    });

    $("#ans2_p5").on('click',function(){
        i=i+1;
        $("#ans2_p5").fadeOut(800);
        $("#correct2_p5").fadeIn(1000);
        fade.execute();
    });

    $("#ans3_p5").on('click', function(){
        i=i+1;
        $("#ans3_p5").fadeOut(800);
        $("#correct3_p5").fadeIn(1000);
        fade.execute();
    });

    $("#ans5_p5").on('click', function(){
        i=i+1;
        $("#ans5_p5").fadeOut(800);
        $("#correct4_p5").fadeIn(1000);
        fade.execute();
    });

    $("#ans7_p5").on('click', function(){
        i=i+1;
        $("#ans7_p5").fadeOut(800);
        $("#correct5_p5").fadeIn(1000);
        fade.execute();
    });

    $("#ans9_p5").on('click', function(){
        i=i+1;
        $("#ans9_p5").fadeOut(800);
        $("#correct6_p5").fadeIn(1000);
        fade.execute();
    });

    $("#ans10_p5").on('click', function(){
        i=i+1;
        $("#ans10_p5").fadeOut(800);
        $("#correct7_p5").fadeIn(1000);
        fade.execute();
    });

})();


Prove the following set relations.

Question: Prove the following set relations.
<code>(A∩B)⊆(A∪B)
</code>
My teacher show me the answer that:
<code>first,   assume x ∈ A∩B.
second,  x ∈ A and x ∈ B.
third,   x ∈ A or x ∈ B.
fourth,  x ∈ A∪B.
</code>
so my question is how can we get third step from the second step?
Comment: $x\in A$ and $x\in B$ means $x$ belongs to both $A$ and $B$, which implies that "$x$ is in at least one of $A$ and $B$." Does that make sense?
Comment: In case this is the cause of your confusion, note the inclusive "or" is being used here instead of the exclusive "or".
Answer: If $C$ and $D$ are both true, then $C$ must be true and $D$ must be true. Hence $C$ or $D$ is true.

Prove the following set relations.


General practice to organize a new End-to-end test in Cypress

Question: Just starting a new UI testing project, and wonder if there is any best practice to organize the Cypress end-to-end test structure?   For example - 1) embedded inside the source (under integration/...) or 2) separate file folder for this project?
Looking for some general guidelines and best practice.  Thanks.
Answer: It is up to you where you want to keep your test files there is no one single rule (Read this). In case you're writing the tests under integration folder, you don't have to do add any additional configurations as cypress by default searches for the test suite files from inside the integration folder. Also, in case if you decide to write your tests inside some other folder, you can add the required configurations in your cypress.json file and you are good to go.
This is how my folder structure inside integration folder looks like:

Locators contain all locators, so that they can be managed from a single place. Inside that I have a file called selectors.js
Module 1 and Module 2 contains the test suites asper the modules.

Example of the selectors.js file:
export default {

  toDoBtn: 'button[type="submit"]',
  input: 'form > input',
  listItems: 'ul > li'
};

Example of the test suite:
import selectors from '../../integration/Locators/selectors.js';

describe('Add Items in todo list and Validate', () => {

    before(function () {
        cy.pageIsLoaded(selectors.toDoBtn) //This is a custom command
    })

    beforeEach(function () {
        cy.fixture('testdata.json').then(function (testdata) {
            this.testdata = testdata
        })
    })

    it('Add Items', function () {
        cy.addItems(selectors, this.testdata) //This is a custom command
    })

    it('Validate Added Items', function () {
        cy.validateItems(selectors, this.testdata) //This is a custom command
    })
})

Answer: It's obviously a matter of opinion, but here's what guides me

end-to-end tests are not as tightly coupled to source files as unit tests, so it makes sense to place them in a separate folder structure

you tend to work on a bunch of source files to build a feature, then write an e2e to test that feature, which points to a feature hierarchy

Cypress allows for non-standard test location, but be wary as third party plugins (which you may add late in the project) may not

Cypress commands are quite expressive, so it does not make sense to write custom commands for everything (simple is better than complex)

named selectors are expressive, but keep them local (inside the spec file) as they will differ subtly from one page to another. Better still, ditch selectors and use a search tool like cypress-get-it


Manhattan Distance between (P, Q) and (R,)

Question: I am working on Manhattan distance. It works well with the simple for loop. But I am trying to avoid this for loop.
import numpy as np
import random
A = np.random.randint(5, size=(10, 5))
B = [1, 3, 5, 2, 4]
for i in range(10):
    dist = sum(abs(A[i]-B))
    print("Distances: ", dist)

Is there any optimal way than this? such as using advanced indexing..
Thank you for the guidance.
Comment: It's interesting that I tried to use the `scipy.spatial.distance.cityblock` to calculate the Manhattan distance and it turns out slower than your loop not to mention the better solution by @sacul.
Comment: @sacul Agreed 100%. Nice solution there! The `cdist` is slower than `numpy`, and with extra import. Take home message for me here is a pre-written library may not be necessarily faster than the code you build on your own.
Comment: @XiaoyuLu, I was just updating my answer to include a `scipy` method. It works well too, but I prefer using `numpy`, since the algorithm is pretty simple in this case, and it avoids an extra import
Answer: Pure numpy
You can do this within numpy:
>>> np.sum(np.abs(A-B), axis=1)
array([10,  6,  9,  9,  7,  7,  9,  8, 14,  8])

Compare this to the output from your loop:
Distances:  10
Distances:  6
Distances:  9
Distances:  9
Distances:  7
Distances:  7
Distances:  9
Distances:  8
Distances:  14
Distances:  8

Alternative: scipy
You could also use scipy if you wanted (personally I prefer the numpy method though):
from scipy.spatial.distance import cdist

>>> cdist(A,np.array(B).reshape(1,-1), metric='cityblock')
array([[10.],
       [ 6.],
       [ 9.],
       [ 9.],
       [ 7.],
       [ 7.],
       [ 9.],
       [ 8.],
       [14.],
       [ 8.]])

Answer: Wouldn't you use radians, or degrees, and calculate the result?  This should work for you.
from math import sin, cos, sqrt, atan2, radians

# approximate radius of earth in km
R = 6373.0

lat1 = radians(40.7619087)
lon1 = radians(-73.9690218)
lat2 = radians(40.760178)
lon2 = radians(-74.0037083)

dlon = lon2 - lon1
dlat = lat2 - lat1

a = sin(dlat / 2)**2 + cos(lat1) * cos(lat2) * sin(dlon / 2)**2
c = 2 * atan2(sqrt(a), sqrt(1 - a))

distance = R * c

print("Result:", distance)
print("Should be:", distance, "mi")


curl GET list of files restricted to 1000

Question: There are more than 1000 files in a storage server account and when I use curl to display the list of files, output is limited to only first 1000.
Just to test, I had deleted a file showing up in the GET list and then did a GET again, this time curl did display 1000 files with an additional file from full list.
Is there any way to tell curl to display full list instead of limiting to 1000?
Edit:
curl -X GET -u <user>:<passwd> <url-full-path-of-container>

curl version:
curl 7.29.0 (x86_64-redhat-linux-gnu)
I am not sure whether problem is on server side because I dont really have full privileges to check that.. Can it be on server side too?
Comment: I think this has to be on the server side. There is no reason I can think of for curl to do this.
Comment: Can you show the exact command you are using? I used `curl v7.19.7` and did not get this behaviour. Possibly a limit of the web server rather than curl? That's pure specuation of course.
Comment: Are you sure the problem is with curl, and not on the        server?
Answer: You should mention the protocol you're been using with curl.
The -X command restrict the list to: HTTP, FTP, POP3, IMAP. Which one?
Why are you using -X?
Anyway, it's possible that the remote server is limiting the list: curl has no intrinsic internal limit on listing AFAIK.
I'd suggest you to try an interactive session (especially if it's FTP) by using another command line tool or by elevating the debugging level with --verbose option.
Answer: It's a common and recommended practice for web services to paginate their responses.
That is, to limit the number of results returned in a response,
and let clients pass a parameter to get the next page.
Some services may allow changing the limit (= page size),
up to some hardcoded upper limit.
curl by itself doesn't impose limits on responses.
The limit that you have found is certainly at the server side.
Whether the server supports the additional parameters to customize the page size or to specify the page (other than the first),
depends entire upon the implementation of the service.
I would look for that information either in the API documentation,
or else in the response headers.


Suppose $\dim V=n$, $\dim W =m$, and $T\in L(V,W$)...

Question: Let $T\in L(V, W)$, and set $n = \dim V$ and $m= \dim W$.
(a.) Suppose $n < m$. Show that there exists a basis $w_1, \dots, w_m$ of $W$ such that the last $m-n$ rows of $M(T)$ consist only of $0$s for every choice of basis of $V$.
(b.) Suppose $n > m$. Show that there exists a basis $v_1, \dots, v_n$ of $V$ such that the last $n-m$ columns of $M(T)$ consist only of $0$s for every choice of basis of $W$.
Please help!
Comment: (a.) makes a lot of sense.
Comment: Hope this makes more sense now!
Comment: @anomaly You can actually just use $\dim$, instead of putting it into text mode.
Comment: @T.Bongers: Thanks, that's much easier. (I have a long file of DeclareMathOperator settings for my own tex documents, and I forget which are in the default.)
Answer: For (a), choose a basis corresponding the decomposition $W = (\text{im } T) \oplus (\text{im  }T)^\perp$, noting that $\dim (\text{im }T)^\perp = m - \dim (\text{im }T) \geq m - n$. For (b), choose a basis corresponding to the decomposition $V = (\ker T)^\perp \oplus (\ker T)$, noting that $\dim (\ker T) \geq n - m$.
Comment: Is there another way to solve this problem? I am not familiar with decomposition and just this general method of this solution. Thanks!
Comment: What are you familiar with, and what have you tried so far?
Answer: Hints: (a) Any $T(v)$ can be represented by a linear combination of a basis of $\operatorname{Im}(T)$.
(b) Each vector in $\operatorname{ker}(T)$ will be mapped to zero. What do the columns of $M(T)$ stand for?


What is the difference between GLM and splines?

Question: Suppose we want to predict $Y$ given the following $X$ observations:
x = c(abs(rnorm(2500, 0.1, 0.25)), abs(rnorm(2500, 0, 0.05)))
y = (x^0.35) + rnorm(length(x), 0, 0.25)
x = c(x, -x)
y = c(y, -y)

Clearly we have an exponential relationship between the predictor $X$ and $Y$. It's more obvious looking at a local regression plot:
regrplot = function(x, y, main.par="", regr.par=T, lowess.par=T, xlab.par=NULL, ylab.par=NULL)
{
  plot(x, y, cex=0.5, col="red", main=main.par, xlab=xlab.par, ylab=ylab.par, pch=".")
  if( regr.par )
    abline(lm(y ~ x), col="blue", lwd=1)
  if( lowess.par )
    lines(lowess(x, y), lwd=1, col="darkgreen")
}

This is a replica of an empirical distribution I have to model and predict.
What are the difference in using splines vs. GLM? Which GLM regression better predicts this kind of distributions?
From what I understand splines are better suited to study empirical distributions, because of the flexibility of the polynomials based on a guided number of knots. GLMs seems to be better to study theoretical distributions. Of course, the drawback with splines is overfitting, especially for prediction.
Answer: You are confusing a few issues.  A spline function is typically used to relax the linearity assumption of one or more predictors, whether in the context of a GLM or a non-GLM.  Loess is a local weighted linear regression, not a spline.
When discussing empirical distributions you really need to talk about the conditional distribution of $Y|X$ which may have little to do with the right hand side of the equation I discussed above.  Most models assume a parametric distribution for $Y|X$.  The empirical alternative is semi-parametric models such as cumulative probability ordinal response models (e.g., proportional odds and prop. hazards models).  These do not assume any model for $Y|X$, effectively using the empirical CDF.
Comment: There is no such thing as a "4-knot OLS". There is a "4-knot spline" in any regression model, and there is "OLS regression" with any form of predictors.
Comment: ok, so splines can be part of a GLM. Wouldn't a 4 knot splines OLS be a good choice for my example?
Comment: @Aniko I mean using a 4-knot spline *and* OLS.


Can I do model-level filtering in Entity Framework?

Question: In the latest version of Lightswitch, they have added a query pipleline method that allows you to catch all query requests to the database, and add a filter. This allows you to add (for example) a filter that restricts the data to ones whose "active" flag is true, without having to worry about doing this on every query you write.
Now, given that the database level stuff in Lightswitch is all built on Entity Framework, I was wondering if there is something similar there. I am working on a very large project, with loads of queries in around 50 or 60 separate repositories, and don't really want to have to ask every developer to go through every query in every repository and add code to check the active flag. Apart from the time involved, the chances of missing a query are high, as are the chances of someone forgetting to include it in a future query.
Anyone know if this can be done at a low level in Entity Framework? Thanks
Answer: You have to be able to intercept and modify your predicates.
One.  If you've abstracted your repository then you could do something like this:
All your Entities could inherit from an Abstract class or Interface with and Active property and your code would be:
    interface IActivatable {
        bool IsActive {get;set;}
    }

    class Repository<EntityType>
        where EntityType : class, IActivatable {

        private StackOverflowEntities context;

        public IQueryable<EntityType> GetAll() {

                return context.Set<EntityType>().Where(e => e.IsActive == false);

        }
    }

That way the GetAll returns the IQueryable with an initial predicate, the rest will be added with an AND.  Like so:
            Repository<Person> persons;
            var results = persons.GetAll().Where(p => p.IsMarried == false);

Which will result in a predicate equal to p.IsMarried == false && p.IsActive == false
Two.  If it's not practical to change your repository code or code at all you could create a view for every table.  The view can just include the IsActive in the where clause to exclude the records and then reload your EDMX based on those views - at least this is the way we used to do in back in the day.
Edit:
Three.  If you have a generated DbContext exposed to client code you could do this:
    public partial class StackOverflowEntities : DbContext
    {
        public StackOverflowEntities()
            : base("name=StackOverflowEntities")
        {
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            throw new UnintentionalCodeFirstException();
        }

        public DbSet<Blog> Blogs {
            return this.Set<Blog>().Where(b => b.IsActive == false);
        }
    }

Just means that you must turn off auto-code gen or modify the T4 template.  Easier to just take the generated code, turn of the gen and modify.
Comment: We have a GenericRepository, but unfortunately, that has a method that exposes the EF context to inherited classes, allowing them to query the context directly. This means that we can't intercept calls the way you showed, as repositories are using the context directly. Changing now would mean rewriting too much code. I was hoping there was some built-in pipeline in EF that we could tap, but thinking about it now, it's more likely that the Lightswitch team just did what you suggested. This would have been a great solution if we had done it originally, but it's too late to go back now. Thanks
Comment: Well... if you are exposing the class type of the generated (or code first) derived class of DbContext you could still modify the generated code to do the same i.e. include a predicate on the returned DbSet.  See my edit.
Comment: Hmm, that's an interesting idea. I'll have to go and see how that would work in practice. I'm not sure about turning off the auto-gen, but modifying the T4 template isn't a problem. Thanks again.
Comment: Just a caveat - they can still access the DbSet<> properties directly from the detived DbContext instance - completely bypassing your code... so that's a definite consideration
Comment: Actually, having looked at it again, changing the T4 template to make all entities implement an interface wouldn't have such disastrous consequences as I thought, so we could modify the generic repository so that it only sent out active entities. The generic repository would expose the context via a method that used the interface/filter, so the only danger would be if anyone tried to create their own instance of the context, rather than accessing it via the base generic repository. As they aren't supposed to do that, we should be able to check and modify the (hopefully) few places that do! Thx


Not able to move button in tcl/tk

Question: GUI snapshot
In this code i want to move new_button to right most side.But After changing row, column,columnspan also,it stays there only. What are the changes required in code.
ttk::frame .c
.c configure -borderwidth 7 -relief groove -padding "200 25"
button .c.cancle -text cancel -command {destroy .}
ttk::label .c.l -text "yash"
ttk::checkbutton .c.one -text One -variable oe -onvalue 1
ttk::button .c.ok -text Okay -command sp12
button .c.lop -text New_button

grid .c -column 0 -row 4
grid .c.l -column 0 -row 1 -columnspan 2
grid .c.one -column 0 -row 3 -columnspan 2
grid .c.ok -column 3 -row 3 -columnspan 2
grid .c.cancle -column 9 -row 3 -columnspan 2
grid .c.lop -column 30 -row 10 -rowspan 10 -columnspan 15 -sticky w

Comment: What layout are you trying to create? I've run your code and I'm not quite sure what it should look like…
Comment: Remove the padding on the frame `.c`.
Comment: yes @Jerry ,but it reduces window size ...how can i get bigger frame (window) ...i.e if i give column 30 button ,it shuld be far from column 9 button.
Comment: @Yash Can you upload a picture of what you want to get as result? Draw it in paint or something, but it's difficult to understand what you are looking for without more information.
Comment: @Jerry uploaded ..let me know if u r not able to access
Answer: grid can be tricky. If there are no widgets in one of the rows or columns, that row and/or column will be considered to have 0 width and/or 0 height. Thus increasing the row number and/or column number will not change anything.
In your current script, the padding to the frame prevents the widgets inside the .c grid to be near the .c border (padding adds a 'layer' of space between the border and the widgets inside it). So this is the first thing to remove. Once done, the widget will lose its size though, because the size of the widget depend on the size of the widgets inside it after all.
So a workaround here would be to define the minimum sizes:
ttk::frame .c
.c configure -borderwidth 7 -relief groove
wm minsize . 656 135  # Set a minimum size here
button .c.cancle -text cancel -command {destroy .}
ttk::label .c.l -text "yash"
ttk::checkbutton .c.one -text One -variable oe -onvalue 1
ttk::button .c.ok -text Okay -command sp12
button .c.lop -text New_button

# I cleaned up the columns
grid .c -row 0 -column 0 -sticky nsew # make it anchor all positions
grid .c.l -column 1 -row 1
grid .c.one -column 1 -row 2
grid .c.ok -column 2 -row 2
grid .c.cancle -column 3 -row 2
grid .c.lop -column 4 -row 3 -sticky se # make it anchor at south east position

# make the .c grid fit to the . window
grid columnconfigure . all -minsize 635 -weight 1
grid rowconfigure . all -weight 1
# force column before column 1 and row before row 1 to have some specific size
grid columnconfigure .c 0 -minsize 200
grid rowconfigure .c 0 -minsize 30
# make the last cell fill any spaces after it, if available
grid columnconfigure .c 4 -weight 1
grid rowconfigure .c 4 -weight 1

Result:

Not able to move button in tcl/tk


How to disable http basic auth in nginx for a specific ip range?

Question: I'm developing an application with facebook login. So far it's not public and is protected by http basic auth in nginx. Is it possible to disable http auth for facebook's ip range so that we can have our tester test the facebook capabilities as well? Please, include an example configuration snippet, if possible.
Answer: Use satisfy directive to allow access. 32934 is facebook autonomous system, look facebook ip.
<code>satisfy  any;
allow 18.104.22.168/20;
allow 18.104.22.168/21;
allow ...
deny   all;

auth_basic            "closed site";
auth_basic_user_file  conf/htpasswd;
</code>
Comment: You may also need to set the real ip if you are behind a proxy, at the server direct i.e. `set_real_ip_from   0.0.0.0/0; real_ip_header     X-Forwarded-For;`
Comment: There's an up to date list of IP ranges here: https://developers.facebook.com/docs/ApplicationSecurity/#facebook_scraper


How to plot VWAP in pine script for specific timeframe period?

Question: I'm using the built-in VWAP function in Tradingview and I'd like to plot only the VWAP line from the start of the selected timeframe period to the current bar. Nothing should be plotted before the selected timeframe period.
In the example below I'm plotting the VWAP with a monthly anchor, so it resets every month. And I'd like to plot from the start of the current month only and nothing before that. When a new month starts it should reset and anchor to the new month.
The plot()function have the show_last argument which I first thought could be a way to write some conditions, but I failed. It seems like the show_last argument isn't very flexible and only allows input integers.
Any ideas and suggestions how to achieve what I*m looking for would be much appreciated!
//@version=5
indicator("My script", overlay=true)
vwap = ta.vwap(close, timeframe.change("1M"))
plot(vwap, show_last=30)

Illustration of the end result
Thanks!
Answer: There is no good way to do this, unfortunately. Plotting only the last month would require your script to know when the last month begins at the very start of the calculation, which is info that it cannot access yet. Additionally, when a script has plotted something and the bar closed, the script can no longer change or remove these values.
But... there is a possible way I can think of. You can use timenow to check the time when the script was last updated, and then subtract 1M from that time and add this to the condition that you use to restart the VWAP anchor. The script below seems to work on my end:
//@version=5
indicator("My script", overlay=true)
tf = "1M"
// I added an extra day there (1440 * 60 * 1000) to make sure we go far enough into the past
// 1M is 30.4 days so otherwise there could have been issues with 31 day months
isLastMonth = time >= timenow - timeframe.in_seconds(tf) * 1000 + 1440 * 60 * 1000
vwap = ta.vwap(close, timeframe.change(tf) and isLastMonth)
plot(vwap)

Note that, if this script will be left on the chart without refreshing it and the month changes, the older data will still be on the chart. Refreshing the chart should clear it.
Comment: Right. I see. My suspicion was that a work around was needed. And the solution you presented works great.

BTW I stumbled upon this closed source indicator that seems to be doing what I wanted to achieve: https://www.tradingview.com/support/solutions/43000652199-vwap-auto-anchored/

Anyway thanks for your help!
Comment: This indicator is closed source because it's a built-in not written in Pine, and it's not written in Pine specifically because the functionality you seek cannot be implemented in Pine at the moment :)
Answer: I ended up doing this instead to be able to 'roll' the timeframe period and avoid the period reset from timeframe.change:
q = timenow - 30.4*3*86400000

f(x, y, z)=>
    ini = time>=x and time[1]<x
    src = hlc3 * volume
    vol = volume
    dev = hlc3*hlc3*volume
    src := ini?src:src+src[1]
    vol := ini?vol:vol+vol[1]
    dev := ini?dev:dev+dev[1]
    vwap = src/vol
    dev1 = math.sqrt(dev/vol-vwap*vwap)*y
    dev2 = math.sqrt(dev/vol-vwap*vwap)*z
    [vwap, dev1, dev2]

[vwap, dev1, dev2] = f(q, 1.0, 2.0)
plot(vwap)
plot(vwap+dev1)
plot(vwap-dev1)
plot(vwap+dev2)
plot(vwap-dev2)


Predicting the winner of a contest, given history

Question: In one of the online games I play, there's a daily contest where users can make bets. I'm hoping I can place more profitable bets by analyzing the contest's history :) (Though really I just wanna crack this problem; it's been bugging me for a while xP)
Here's what we know about the contest:

4 NPC players (that is, automated, not real people) enter the contest each day.
There are 4 features associated with each player, made public at the start of the day.
Let $F(p, f)$ be the value of feature $f$ for player $p$.

For example, $F(1, 1)$ might be how hungry player 1 is, and $F(2, 1)$ is how hungry player 2 is.

At the end of the day, betting is closed and one of the 4 players is announced as the winner. No other information regarding the contest's outcome is available.
(There's more to say about odds and how bets work, but, for now, I'm just interested in the subproblem of computing each player's probability of winning.)

Now, here's what I hypothesize happens behind the scenes:

There is some secret function $S(p)$ that computes the "score" of each player.
$S(p)$ is a linear function of player $p$'s features.

That is, $S(p) = c_1 F(1, 1) + c_2 F(1, 2) + c_3 F(1, 3) + c_4 F(1, 4)$.

These scores are normalized into probability of winning.

That is, $P(\text{player 1 wins}) = \dfrac{S(1)}{S(1)+S(2)+S(3)+S(4)}$.

Given a large set of historical contests, how can I infer the coefficients of $S(p)$?
If each player's scores were revealed at the end of the day, I could do a pretty straightforward linear regression. But they're not; could I maybe infer the scores somehow? My gut says you could kinda get there from looking at a particular feature vector's historical win/lose ratio, but I'm not sure how to take the normalization into account.
I'm also not sure whether inferring scores would even be effective. Most feature vectors only occur a handful of times, so I wouldn't be confident in the inferred score, and therefore would be hesitant to trust the coefficients we derive. (Note that the rarity of some feature vectors is why I even care about deriving the coefficients. Never-before-seen feature vectors arise often, and I want to be able to evaluate a vector the very first time I see it, rather than relying on its individual history.)
Comment: Hmm, I *do* like that :) I think our problem can probably be solved more directly, though, since the players in the contests are NPCs, and the features really are just 4 numerical stats that describe each player rather than some features that I've inferred. Still, I wonder how well something like TrueSkill would do... if we didn't have the feature vectors and just the NPC identities, probably pretty darn well, eh?
Comment: May be of interest: https://en.wikipedia.org/wiki/TrueSkill
Comment: There are some more in depth lecture slides on it at: http://mlg.eng.cam.ac.uk/teaching/4f13/1415/
Comment: It sounds like you first need to estimate $S(p)$ based on the linear function you've provided and then go on to calculate $P(win_{p_1})$. This feels like a generalized additive model.  See the Element of Statistical Learning by Hastie, Tibshirani, and Friedman, Chapter 9.
Answer: Let's accept your hypotheses that the score function is linear in the features and that the coefficients do not change. You'd like to find the most likely tuple of coefficients $c$ given the records at hand.
If we consider that the daily contests are independent, we can do something similar to a maximum likelihood estimation.
The likelihood of observing all the records in history if we consider that we are given $c$ is:
$$\mathcal{L}(c;records) = P(records | c) = \prod_{r \in records} P(r|c)\\
\mathcal{L}(c;records) = \prod_{r \in records} S_{normalized}(winner(r), r)$$
Where $winner(r)$ is the player who won in the record $r$.
The maximum likelihood estimator for $c$ would then be:
$$c = (c_1, c_2, c_3, c_4) = \underset{c}{argmax}(\mathcal{L}(c; records)) = \underset{c}{argmax} (\prod_{r \in records} S_{normalized}(winner(r), r))$$
Where $S_{normalized} (p) = \frac{S(p)}{\underset{q \in players}{\sum S(q)}}$ which is $P(player\ p\ wins)$ in your post.
You could compute this estimator by doing a gradient descent or another optimization technique on the likelihood function. Though the function is not differentiable everywhere, I'd say everything could still be fine with a gradient descent ;).
If you don't mind linking to part of your data we could try and look further into it.
Let me know if something does not make sense to you.
Comment: Sweet, thanks! I'll read over this when I get the chance—I'm realizing that I'm not sure I actually have time to really pursue this project *right* now, but I'll ping you when I get back to it :)
Comment: Ok. This may look sophisticated if you are not familiar with the notations but it is actually fairly simple to implement.
Comment: Yeah, I remember enough from stats class to recognize it, but not enough to analyze it on the fly to confirm that it matches my mental model of the problem. Once I parse it all I'll let you know xP Thanks!
Comment: Actually, I think $P(r|c)$ might be more nuanced than that. The player with the highest score doesn't automatically win; instead, the scores are weights that normalize into probability of winning. For example, if the 4 players' scores are 2, 4, 6, and 8, then their respective chances of winning are 10%, 20%, 30%, and 40%. I don't think that changes the fundamentals of your answer, though: just plug in that definition instead, and we can do whatever local search strategy we want. Cool :D
Comment: Woops you're right. I used S(p) instead of the normalized score.


Show that the sample Mean is not complete

Question: Suppose that $X_1, ..., X_n$ is a sample from a $\mathcal{N}(-\frac12 \sigma^2, \sigma^2)$ density. Show that the statistic $\bar{X}$ = $n^{-1} \sum_{i=1}^n X_i$ is NOT complete.
I am struggling to find a function of $\bar{X}$.
I was thinking let $g(Q) = \bar{X} + \frac n2{S^2}$ $\Rightarrow E(g(Q)) = -\frac 12 \sigma^2 + \frac{n}{2n} \sigma^2 = 0$,
but $S^2$ is not a function of only $\bar{X}$, since it is also a function of $X_i$.
Any hints/suggestions on what other function I can use?
Comment: Where does this exercise come from?
Comment: This is a past qualifying exam question from 2009.
Comment: This is very closely related to https://stats.stackexchange.com/questions/631935. One might generally consider the same question for any positive-codimensional submanifold of a multiparameter exponential family.
Answer: $n\bar{X} \sim \mathcal{N}(-n\sigma^2/2, n\sigma^2)$, so its mgf is
$$
M_{n\bar{X}}(t)
= \mathbb{E}[e^{tn\bar{X}}]
= \exp\left[-nt\sigma^2/2  + n\sigma^2 t^2/2\right].
$$
At $1$ we have $\mathbb{E}[\exp(n\bar{X})] = 1$. So $g(\bar{X}) := \exp(n\bar{X}) -1$ has expectation $0$ for all $\sigma^2 > 0$ yet it isn't $0$ wp1.
Comment: Awesome! I didn't think to use MGF. Very elegant solution!
Comment: Just to check your work, at t = 1, $E[exp(n \bar{X})] = e^0 = 1$, and so it should be $g(\bar{X}) = exp(n \bar{X}) - 1$. Which has expectation 0 for all $\sigma^2 > 0$ and isn't 0 wp1?


SignalR Invoke() method "Unauthorized" error

Question: I have added SignalR to our existing asp.net web application and everything is working fine.  I've published this web application to Azure and now I'm getting Unauthorized error on the invoke method.
I've enabled web sockets and ARR affinity on Azure.
I'm not using Authorize attribute.
Do I need to add something else to my application to authenticate the web app or the user?
StatusCode: 401, ReasonPhrase: 'Unauthorized', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
  Date:
  Set-Cookie: ARRAffinity=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx;Path=/;HttpOnly;Domain=MyAppx.azurewebsites.net
  WWW-Authenticate: Bearer realm="MyAppx.azurewebsites.net" authorization_uri="https://login.windows.net/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/oauth2/authorize" resource_id="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
  X-Powered-By: ASP.NET
  Content-Length: 58
  Content-Type: text/html
}
Comment: I've added this to my Startup method GlobalHost.HubPipeline.RequireAuthentication() and this to my hub connection connection.Credentials = CredentialCache.DefaultCredentials.  Still getting same error.
Answer: Because support for SignalR in asp.net is limited you must use some of the .net core libraries.Instead of using the invoke() method on the hub connection, you can take advantage of var context = GlobalHost.ConnectionManager.GetHubContext() which will eliminate a lot of pluming code. Using GlobalHost.ConnectionManager.GetHubContext solved the authorization issue as well.


how-do-i-validate-phone-number & dob-in-Openedge /Progress 4gl-programming

Question: define var num as integer label "S.No".
define var name as char label "NAME ".
define var dob as date label "DOB" format "99/99/9999".
define var mobnum as int label "Mobile No:" format "9999999999" .

assign num = 1.

repeat num = 1 to 3:

  display num with frame a.

  update dob with frame a.

  if dob >= today then do:

    display " enter correctly".

    update dob with frame a.

  end.
  else if dob < today then do:

    update name with frame a.

  end.

  update name with frame a.
  update mobnum with frame a.

  if mobnum >= 1000000000 and mobnum < 10000000000 then
    do:

      display mobnum with frame a.

      display num column-label "S.NO" with frame b.

      display name  column-label "NAME"
        dob column-label "DOB"
        mobnum column-label "mobile number"
       with frame b down.

      down with frame b.

    end.
   else
    do:

      display "enter exactly 10 digits please".

      update mobnum with frame a.

    end.

end.

In this Code I want to validate dob to > Todays date and mobilenum not less than 9 digits
and i want to display the output and in step by step process it moves to S.no, Dob,Name ,Mobile num..
But in my code when i enter mobile num it doesn't display anything in frame b.
and i want to add 3 records.. but it doen't allow me to update..
please help to solve this issue
Comment: This is a partial duplicate of https://stackoverflow.com/questions/73477553/how-do-i-validate-phone-number-in-openedge-progress-4gl-programming , which has a few answers already.
Answer: Date-based validation (comparison) is reasonably simple in ABL: use the =, >, < , <>, >=, <= operators.
define var dob as date label "DOB" format "99/99/9999".

IF dob <= TODAY THEN
    MESSAGE "Date is not in the future".

Answer: You can verify dob conditions using the following expression:
DEF VAR dob AS DATE NO-UNDO FORMAT "99/99/9999".

ASSIGN dob = TODAY.

/*
ASSIGN dob = TODAY.
ASSIGN dob = TODAY + 30. - always days
ASSIGN dob = TODAY - 30. - always days
*/

IF dob = TODAY THEN
    MESSAGE "dob is today.".
ELSE IF dob < TODAY THEN
    MESSAGE "dob is smaller than today.".
ELSE IF dob > TODAY THEN
    MESSAGE "dob is in the future.".
ELSE
    MESSAGE "dob is not assigned.".

And for the MobileNum:
You can use LENGTH(mobnum) to get the quantity of digits into the number... like:
This make possible to create separate message for each of the lengths of mobnum.
DEF VAR mobnum AS INT NO-UNDO FORMAT "9999999999" INITIAL "99999999".
DEF VAR ii     AS INT NO-UNDO.

ii = LENGTH(mobnum).

CASE ii:
//You can create a when for each of the sizes
    WHEN 9 THEN DO:
        DISPLAY "Number OK".
    END.
    OTHERWISE DO:
        DISPLAY "Number is not 9-digit long".
    END.
END CASE.

But if you want to make it simple, just use:
DEF VAR mobnum AS INT NO-UNDO FORMAT "9999999999" INITIAL "99999999".
DEF VAR ii     AS INT NO-UNDO.

ii = LENGTH(mobnum).

IF ii = 9 THEN DO:
    DISPLAY "Number correct".
END. ELSE DO:
    DISPLAY "Number incorrect".
END.


Poisson distribution with large mean

Question: The hits in a website can be modeled as a Poisson process with a rate of 5000 hits per day. Let X be the number of hits in 6 days. Give the distribution of X.
So, is the percentile x = 6 and the mean λ = 5000 * 6 = 30000? If so, should I use another distribution (as the normal distribution) to approximate it?
Comment: The poisson has the interesting property that the sum of poisson random variables is also poisson.  That should help
Comment: Maybe you need the self-study tag.
Answer: Changing the Poisson Rate to Match the Domain of a Model
One Day: It seems reasonable to model the number $X_1$ of events (hits) in one day
as $X_1 \sim \mathsf{Pois}(\lambda_1 = 5000),$ so that $E(X) = Var(X) = 5000.$
It is not clear what additional numerical problems about this distribution you want to solve. In R, the 25th, 50th (median), and 75th percentiles of this distribution are $4952, 5000,$ and $5048,$ as follows:
 qpois(c(.25, .5, .75), 5000)
[1] 4952 5000 5048

[If possible, expand the following image in your browser to resolve individual, evenly-spaced
bars.]

For example, if I have data for 300 individual days I might have summary
statistics as below:
set.seed(1017)
x1 = rpois(300, 5000)
summary(x1)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
   4809    4946    4999    5000    5051    5185

Thus, in this one sample of hits for each of 300 days, we see that
about 75% of the days (that's 225 days) had 5051 or fewer hits.
Specifically in this example, if we sort the 300 days from smallest to largest numbers of hits, days 224 through 226 in the list had 5050, 5050, and 5053 hits, respectively. (Of course, $5051$ in the sample of 300 can't be expected to match exactly $5048$ of the population, but the numbers are very close.)
sort(x)[224:226]
[1] 5050 5050 5053

Six days: If you want to know about the distribution of hits in six days, you need to
adjust the parameter $\lambda_1$ per day to $\lambda_6 = 6(5000) = 30\,000$ per six days (assuming that the rate remains the same over six days).
This is called changing the Poisson rate to match the domain of the model.
Here we have changed the domain from one day to six days.
Thus, $E(X_6) = Var(X_6) = 30\,000.$ And the first, second, and third quantiles are as shown below:
qpois(c(.25, .5, .75), 30000)
[1] 29883 30000 30117

You also say that the probability of no more than $20\,000$ hits in six days (less than or equal to $29\,500$ is very small---about $0.00192.$
ppois(29500, 30000)
[1] 0.001920345

If you want to use a normal distribution to approximate this probability,
then you can standardize and use printed tables of the standard normal CDF (or somewhat more accurately, with software):
$$P(X_6 \le 29\,500) =
P\left(\frac{X - \lambda_6}{\sqrt{\lambda_6}} < \frac{29\,500 - 30\,000}{\sqrt{30\,000}}\right)\\
\approx P(Z < -2.886751) = 0.00195,$$
where $Z$ is standard normal.
pnorm((29500-30000)/sqrt(30000))
[1] 0.001946209

Poisson distribution with large mean


Subclipse with Eclipse x64

Question: I've just bought a new computer x64 and intalled windows 7 and Eclipse Helios x64. When I tried to install subclipse it didn't work... after a few times trying to install it and getting stuck when eclipse was trying to check the dependences, I did get to install it but it simply didn't work.
When I chenged the perspective to SVN Repository I got an error. Anyway, I downloaded Eclipse Helios x86 and also got stuck on the dependeces checking part. But after a while trying it was installed and now it works.
But the thing is that I want to install eclipse helios x64 since I have a x64 computer.
Did anybody have the same or a similar problem? How did you solve it?
Thanks.
Answer: I'm using Eclipse64 with a working SVN plugin.
But I changed the SVN Client interface from "Java HAL" to "SVNKit" which works much better. I installed this module via Yoxos and then switched in the preferences Team > SVN > SVN interface to SVNKit.
Comment: using SVNKit works because this way you use a pure Java implementation of SVN, which usually is OK, but not quite as up to date as the native SVN version.
It is also a bit slower than the native SVN implementation with big merges.
Both version worked fine for me, but I have the feeling the native version was a bit more robust when operating with many files.
Answer: If you want to stick to JavaHL way of accessing the repository, you can also install the 64 bits version of JavaHL.
Referenced here  - look at the paragraph saying Windows 64-bit.  It will redirect you to slik subversion client
You can install the whole client (I could not install only javahl with the custom install)
To make sure it is taken into account, edit your eclipse.ini file and, after the -vmargs line, add -Djava.library.path=C:\programs\slik (or if you already have an item for the jni path, add your own path).

Subclipse with Eclipse x64


How to overlay Navigator.NavBar?

Question: How can I do overlay of Navigation.NavBar
Here what I have

But I want Red one should overlay green one NavBar ?
Answer: I made it using http://facebook.github.io/react-native/docs/modal.html#content
So I add there Navigator and it works as expected

How to overlay Navigator.NavBar?


Como usar uma função para varias divs em vanilla JavaScript?

Question: Preciso implementar uma regra apra a badge mudar de cor conforme o "Value" porem a regra só esta pegando a 1 badge as outras não esta pegando como deveria utilziar no meu JavaScript?

        <input id="ValBdg" type="hidden" value="1" />
         666

        <input id="ValBdg" type="hidden" value="2" />
         666

        <input id="ValBdg" type="hidden" value="0" />
         666

var ValBdg = document.getElementById('ValBdg').value;

function Msg(){
    var nodes = document.getElementsByClassName('bdg');

    for (let x=0, s=nodes.length; x<s; x++){
        nodes[x].classList.add("btn-danger");
    }
}

function NoMsg(){
    var nodes = document.getElementsByClassName('bdg');

    for (let x=0, s=nodes.length; x<s; x++){
        nodes[x].classList.remove("btn-danger");
        nodes[x].classList.add("btn-primary");
    }
}

if(ValBdg > 0 ){
    Msg();
}else{
    NoMsg();
}

Answer: De acordo com a especificação HTML, o atributo id deve ser único num documento. getElementById parte do princípio que isto é verdade e por isso apenas devolve um elemento - o primeiro que encontra do documento com um determinado id.
Contudo o atributo id não tem necessariamente que ser único (apesar de ser desaconselhado e uma má prática).
Para resolver o seu problema, sugiro as seguintes alterações:

usar class em vez de id no input;
utilizar getElementByClassName para obter os inputs;
iterar sobre os inputs e aplicar a lógica que pretende.

Exemplo:

function setBadges() {
  const badgeValues = document.getElementsByClassName('ValBdg');

  for (let i = 0; i < badgeValues.length; i++) {
    const badge = badgeValues[i].nextElementSibling;
    const badgeClass = badgeValues[i].value > 0 ? 'badge-danger' : 'badge-primary';

    badge.classList.remove('badge-danger', 'badge-primary');
    badge.classList.add(badgeClass);
  }
}

document.getElementById('setBadgesButton').addEventListener('click', setBadges);
.badge {
  font-size: 10px;
  padding: 2px;
  border-radius: 10px;
}

.badge.badge-primary {
  background-color: lightblue;
}

.badge.badge-danger {
  color: white;
  background-color: red;
}

  <input class="ValBdg" type="text" value="1" />
  AAA

  <input class="ValBdg" type="text" value="2" />
  BBB

  <input class="ValBdg" type="text" value="0" />
  CCC

<button id="setBadgesButton">Set Badges</button>
Comment: Editei a resposta e adicionei um exemplo. Por favor verifique,
Comment: Ótimo. Se resolveu o problema, por favor assinale esta resposta correta. Eu também prefiro js vanilla mas como o seu código inicial estava em jQuery, respondi em jQuery.
Comment: então eu fiz aqui uma classe chamada "ValBdg", dai fiz

document.getElementsByClassName('ValBdg');

porem ainda dentro disso preciso pegar o "value", sabe me dizer como faria isso para aplicar a function ?
Comment: Perfeito cara era justamente isso que eu precisava(editando ele não precisei nem usar o CSS) muito obrigado, eu preferia em JavaScript que tenho mais familiaridade mas vou me familiarizar no JQuery tb. Só mais uma pergunta nos casos em que o Value veio "0" eu gostaria de fazer com que a imagem fique em grayscale , eu achei alguma coisa aqui apenas com CSS não teria como fazer apenas em JS né.


Output behaviour of relational operators when used in printf - C Language

Question: This is the code that i was trying :
#include <stdio.h>
main(){
    int k = 35;
    int x = (k==35);
    printf("%d %d %d %d", (k==35), k=50, (k>40), x); // gives output => 0 50 0 1
    printf("\n%s",k==35); // gives output => (null)
    return 0;
}

I was wondering that a relational check returns Boolean true or false. Even when converted to integer type it should become 0 for false and 1 for true. What am i missing?
Comment: You're not missing anything. Why do you think you are?
Answer: Actually your k=50 with a single = is an assignment operator; since it appears in a list of arguments, the order of evaluation of arguments is undefined, and you get stuck by undefined behavior.
The compiler is free to pass (k>40) before or after doing k=50
BTW, with GCC version 4.9 on Debian/Sid, when compiling your code with
gcc -Wall danglingcruze.c -o danglingcruze

I am warned by the compiler:
danglingcruze.c:2:1: warning: return type defaults to 'int' [-Wreturn-type]
 main(){
 ^
danglingcruze.c: In function 'main':
danglingcruze.c:5:37: warning: operation on 'k' may be undefined [-Wsequence-point]
     printf("%d %d %d %d", (k==35), k=50, (k>40), x); // gives output => 0 50 0 1
                                     ^
danglingcruze.c:5:37: warning: operation on 'k' may be undefined [-Wsequence-point]
danglingcruze.c:6:5: warning: format '%s' expects argument of type 'char *',
        but argument 2 has type 'int' [-Wformat=]
     printf("\n%s",k==35); // gives output => (null)
     ^

Comment: Yes that outputs 50 and that is okay for me. The problem is when i compare even if it is true it returns 0.
Comment: Okay, I think i got it now. Thanks.
Answer: Order of evaluation of parameters in a function is not guaranteed. You are modifying k in one of the parameter and using its value in other parameters. That's why it invokes undefined behavior. An example of similar case
int i = 1;
printf("%d %d\n", i++, ++i); // Undefined behavior.

Answer: #include <stdio.h>
main(){
    int k = 35;
    int x = (k==35); // x =1
    printf("%d %d %d %d", (k==35), k=50, (k>40), x); // gives output => 0 50 0 1
    // k=50 changed your value
    printf("\n%s",k==35); // gives output => (null)
    // => printf %s + 0 => null
    return 0;
}

Comment: @sutirtha The %d format expects an integer as an argument, not an address.
Comment: I don't know but for me `printf("\n%d",k==35);` it is giving 0 as output.
Comment: Yes, why 0? why not 1?
Comment: Isn't it an undefined behavior then? I am not able to understand what it is you're trying to convey?
Comment: k==35 it will return 1 but `printf` takes address of an variable as an argument.
And 1 is not a valid address.
Comment: @DanglingCruze `k == 35` returns 0 because you did `k = 50`.
Comment: @Barmar I understand that i'm assigning the value inside function parameter which is causing the undefined behavior. Thank you :)


Finding $f(x)$ from the functional equation $f(x)=x f\left(\frac{2x+3}{x-2}\right)+3$

Question:
Find $f(x)$ if
$$f(x)=\begin{cases}
x\cdot f\left(\frac{2x+3}{x-2}\right)+3 \ , &\text{if } x\ne 2\\
0 \ , &\text{if }x=2
\end{cases} $$

No idea how to begin. I just noticed that $f(0)=3.$
Comment: That linear fractional transformation, applied twice, is the identity.
Answer: Prove that $$f(y)=yf(x)+3,$$where $y=\frac{2x+3}{x-2}$ and solve the system


How to find the average given that you have the mean, standard deviation and amount?

Question: I have an assignment where I'm asked to find the the average shoe number for men and women from given data:
Sum of men and women: 312
Amount of men: 239
Standard deviation of men: 1.63
Mean of shoe number for men: 43.5
Amount of women: 239
Standard deviation of women: 1.4
Mean of shoe number for women: 38.2
Variance squared: 2321
Sum of all shoe numbers: 13183
But I have no idea how to find that using this data. Please help. Thanks in advance!
Comment: @AlanRostem average and mean are the same thing.
Comment: ?! Mean of men: 43.5, Mean of women: 38.2 ?!
Comment: It is the mean of the shoe number for men and women
Comment: Isn't that what you want, the average shoe number?
Comment: Yes, I want the average shoe number specifically for men and specifically for women.
Comment: There is something strange about this question and those numbers need more context. What does sum of men and women mean? Certainly it is not the amount of men plus the amount of women ($239+239 \neq 312$).
Comment: Your numbers make more sense when you consider 73 women. In that case also the sum of all shoe numbers adds up correctly $73 \times 38.2 + 239 \times 43.5 \approx 13183$
Answer: When you want to know the mean and variance of a population given you have these values for different groups of this population, you need to compute what is called pooled mean and variance.
Given that you already have mean and variance for both groups, I have to assume your question is really for these pooled values, for which the formulas are:

pooled mean: $\frac{\sum_i^n N_i \mu_i}{\sum_i^n N_i}$
pooled variance: $\frac{\sum_i^n (N_i-1) \sigma_i^2}{\sum_i^n (N_i-1)}$

$N_i$, $\sigma^2_i$  and $\mu_i$ stand for the number of observations, variance and mean of group $i$, respectively.
Comment: Sorry for the inconvenience. Due to a language barrier I had misunderstood the question which made it much harder for myself than it should have. Thanks for trying to help though I learned a lot today!
Comment: @AlanRostem it is OK, did my answer help you?
Comment: Yes. I used that formula to find the variance then the standard deviation. Thanks!


Debugging missing capability in systemd services

Question: My OpenVPN server is unable to execute a python script configured as --learn-address when the daemon is launched as a systemd service. It works fine when launched manually as root. I found that it also work as a systemd service if I comment the following line in /etc/systemd/system/openvpn@.service:
CapabilityBoundingSet=CAP_IPC_LOCK CAP_NET_ADMIN CAP_NET_BIND_SERVICE CAP_NET_RAW CAP_SETGID CAP_SETUID CAP_SYS_CHROOT CAP_DAC_READ_SEARCH CAP_AUDIT_WRITE

So, I guess my problem is related to a missing Capability. How can I debug that to find out what's missing? OpenVPN log just say WARNING: Failed running command (--learn-address): external program exited with error status: 1. I find nothing related to this in the syslog either.
The learn-address script is used to apply custom firewall rules based on who is connecting. The script does group membership lookups (using /usr/bin/id command) and add rules/chain with the iptable command (with sudo). After further debugging, I think it may fails when trying to call iptables. The command exits with code 3.
It already worked for a while, I wonder if it doesn't stopped to work after a system update.
Comment: What is this learn-address script, and can you share a copy?
Comment: @JohnMahowald Added more information.
Comment: You might want to output stdout/stderr of that `iptables` command to some `/tmp/file`  to inspect a potential error message that iptables would emit.
Answer: Probably not a simple solution, but it can help:
Replace your command to start with an strace starting your command, and then examine the log to find out what system call is failing.
Then, reading the docs for that system call, guess what capability is missing.
Example command: strace -f -o /your/logfile your-command your-parameters
Maybe even try option -e status=failed.


Two properties of surface integrals.

Question: Let $\Omega$ be a bounded open set in $\mathbb{R}^n$ with $C^1$ boundary. I know the following (possible) definition for $$\int_{\partial\Omega}u\,d\sigma.$$
For each $x_0\in\partial\Omega$, there exist an open subset $U$ in $\mathbb{R}^n$ containing $x_0$, an open subset $A$ in $\mathbb{R}^{n-1}$ and a $C^1$ function $g:A\rightarrow\mathbb{R}$ such that its graph is $G_g=\partial\Omega\cap U$. By compactness of $\partial\Omega$, we can write $\partial\Omega=\cup_{j=1}^N U_j$, where each $U_j$ is open in $\mathbb{R}^n$, and $\partial\Omega\cap U_j=G_{g_j}$, where $g_j:A_j\rightarrow\mathbb{R}$ is $C^1$. Take a partition of unity $\{\eta_j\}_{j=1}^N$ corresponding to $\{U_j\}_{j=1}^N$: $\eta_j\in C_c^{\infty}(U_j)$, $0\leq\eta_j\leq 1$ and $\sum_{j=1}^N\eta_j=1$ on $\partial \Omega$.
Let $u:\partial\Omega\rightarrow\mathbb{R}$ measurable. Define $u_j=u\,\eta_j$, which has support in $U_j$. Then:
$$\int_{\partial\Omega}u\,d\sigma=\sum_{j=1}^N\int_{A_j}u_j(x',g_j(x'))\sqrt{1+|\nabla g_j(x')|^2}\,dx'$$(whenever the right-hand side exists).
My two doubts are the following:

Given a subset $\Gamma$ of $\partial\Omega$, in what sense it is understood $\int_\Gamma u\,d\sigma$? Is it true that $$\int_{\partial\Omega}u\,1_\Gamma\,d\sigma=\int_\Gamma u\,d\sigma\,?$$
($1_\Gamma$ is the characteristic function on $\Gamma$).
If $u_m\rightarrow u$ in $L^p(\partial\Omega)$, is it true that there exists a subsequence $u_{m_k}$ that converges pointwise almost everywhere on $\partial\Omega$?
Comment: You mean "By compactness of $\bar\Omega$" or "By compactness of $\partial\Omega$" since $\Omega$ itself isn't compact.
Comment: We must at least have $\Gamma$ measurable.
Comment: You haven't defined $\int_\Gamma$ when $\Gamma$ is not the boundary of a bounded open set. Therefore the first question is meaningless. But we can use the equation to defined $\int_\Gamma u \, d\sigma$, and then the equation will of course be true.
Answer: The answer to your questions is yes. Using the area formula for Lipschitz functions (you can find it in the book of Evans and Gariepy Evans and Gariepy ) you can show that
$$\int_{\partial\Omega}u\,d\sigma=\int_{\partial\Omega}u\,d\mathcal{H^{n-1}},$$ where $\mathcal{H^{n-1}}$ is the $n-1$ dimensional Hausdorff measure. Since $\mathcal{H^{n-1}}$ is a measure, all standard properties of integration and $L^p$ spaces hold for the surface integral.

Two properties of surface integrals.