How to run tomcat7 web app through https over port 8443?

Question: I have a vaadin 7 app running on tomcat 7 on an EC2 server. The app runs through port 8080, so I redirect my domain from 80 to 8080 using:
/sbin/iptables -t nat -I PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 8080

Now, I need to use an SSL certificate that should run on ports 8443 or 443, but checking my port using sudo netstat -nlp, I get this:
    Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address               Foreign Address             State       PID/Program name
tcp        0      0 0.0.0.0:22                  0.0.0.0:*                   LISTEN      2332/sshd
tcp        0      0 127.0.0.1:25                0.0.0.0:*                   LISTEN      2371/sendmail
tcp        0      0 0.0.0.0:3306                0.0.0.0:*                   LISTEN      2987/mysqld
tcp        0      0 :::8080                     :::*                        LISTEN      3204/java
tcp        0      0 :::80                       :::*                        LISTEN      3151/httpd
tcp        0      0 :::22                       :::*                        LISTEN      2332/sshd
tcp        0      0 ::ffff:127.0.0.1:8005       :::*                        LISTEN      3204/java
tcp        0      0 :::8009                     :::*                        LISTEN      3204/java
udp        0      0 0.0.0.0:68                  0.0.0.0:*                               2063/dhclient
udp        0      0 172.30.0.27:123             0.0.0.0:*                               2356/ntpd
udp        0      0 127.0.0.1:123               0.0.0.0:*                               2356/ntpd
udp        0      0 0.0.0.0:123                 0.0.0.0:*                               2356/ntpd
Active UNIX domain sockets (only servers)
Proto RefCnt Flags       Type       State         I-Node PID/Program name    Path
unix  2      [ ACC ]     STREAM     LISTENING     1742   2987/mysqld         /var/lib/mysql/mysql.sock
unix  2      [ ACC ]     STREAM     LISTENING     10316  2151/dbus-daemon    /var/run/dbus/system_bus_socket
unix  2      [ ACC ]     STREAM     LISTENING     9565   1/init              @/com/ubuntu/upstart
unix  2      [ ACC ]     SEQPACKET  LISTENING     9820   1578/udevd          @/org/kernel/udev/udevd

So, as I understand, those ports aren't even there...How can I "activate" them and then use them for my https connection?
Answer: You are supposed to configure your certificate in your tomcat as shown here .
Then you should open those ports in the EC2 console as shown here.
Comment: Thanks!! Already did that.....my server.xml contains: `` and `` as the first link you sent says, any ideas?
Comment: Have you checked your catalina.out for errors? Do your HTTPS local request work? What Linux distro are you using? Are you using a firewall? (If Ubuntu/Debian) Have you checked your Iptables?


Server 2012 with DAC setup

Question: I am trying to setup DAC in Server 2012 Standard. However, it gets a little confusing on how the client has groups. 8 total groups (including Administrators and All Users). However, 1 user might be a member of 3 different groups, another member might be a member of 2 of those 3 & member of 2 more. Only a few users out of 28 are in the same groups. So, setting up by primary groups doesn't seem to be a best practice.
So, looking for suggestions on setting up DAC for user access when the groups are not the best. Anyone have any ideas, links, examples, or etc. that can be shared to assist?
Thanks in advance,
Gene
Answer: DAC uses claims to create access policies.  Groups are only 1 of the claimtypes you could use.  See https://technet.microsoft.com/en-us/library/hh846167.aspx for an example using department.
Comment: Thanks Jim. Understood. I was hoping for some guidance when it comes to setting up DAC when groups isn't possible. If another user has had experience with a different claim. I have seen that example with departments, and read it many times. However, it does not fit into my scenario, and that is where I am stuck.
Comment: what claims would you like to use?  Why are the groups not possible?
Comment: Because users are members of different groups, and not all users are in the same groups to be consistent. Unless I am misunderstanding. User 1 might be in HR, IT, and All, User 2 is in HR, All, Manager, and Internal. User 3 is in HR, IT, Internal, and Remote.
Comment: what users are in what groups is just a claim.  whatever claimset you use is what has to be in common, you don't need to create or have a group- just a claim value, groups are just really convenient since they are easily created and populated.  if you want completely arbitray groupings then you must use a group (even without DAC)

Server 2012 with DAC setup


Combinatorics - Hexadecimals, how many possible numbers.... with ascending order?

Question:
How many different numbers with 4 figures can you make out of the sixteen hexadecimal 'figures' $\{0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F\}$

$16^4$ possible solutions

(i) How many numbers are 'real' 4-figure numbers, meaning the first figure $ \neq 0$?

$16^4 - 16^3 = 61440$ numbers, because $0,16,16,16 $are the undesirable outcome

(ii) How many numbers from (i) have four different figures?

$15 \cdot 14 \cdot 13 \cdot 12 = 32760$ out of the $61440$ possible numbers

(iii) How many numbers from (ii) end with figure 0?

$15 \cdot 14 \cdot 13 \cdot 11$?

(iv) How many numbers from (ii) have figures in increasing order?

This is where I am confused the most. I think it would be $1/4! \times 4$ since there are $4!$ ways to order $4$ numbers initiating with $1$ number, but there are $4$ numbers.
Comment: For i, it should be the  first figure is not equal to zero.  Your answer is correct.
Comment: Please read this [tutorial](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) on how to typeset mathematics on this site.
Comment: Thanks will do!
Answer:
How many $4$-character strings can be formed using the sixteen hexadecimal digits?

Your answer $16^4$ is correct?

How many $4$-digit numbers can be formed using the sixteen hexadecimal digits?

Your answer $16^4 - 16^3$ is correct.

How many $4$-digit hexadecimal numbers have distinct digits?

We have $15$ choices for the leading digit since we cannot use $0$, $15$ choices for the next digit since we can now use $0$ but cannot use the leading digit, $14$ choices for the third digit since we cannot use the first two digits, and $13$ choices for the fourth digit since we cannot use the first three digits.
$$15 \cdot 15 \cdot 14 \cdot 13$$

How many $4$-digit hexadecimal numbers with distinct digits end with $0$?

We have $1$ choice for the last digit, $15$ choices for the leading digit, $14$ choices for the second digit, and $13$ choices for the third digit.
$$15 \cdot 14 \cdot 13 \cdot 1$$

How many $4$-digit hexadecimal numbers with distinct digits have digits written in increasing order?

Observe that since the leading digit cannot be $0$ and the digits are increasing, the four digits of such a number must be selected from the set
$$\{1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F\}$$
A $4$-digit hexadecimal number with strictly increasing digits is completely determined by which $4$ of these $15$ digits are selected since once the four digits are chosen, there is only one way to arrange them in increasing order.  Hence, there are
$$\binom{15}{4}$$
such numbers.
Comment: Now I see, they all make sense now.
Answer: Edit: Thanks to commenters.
Presumably what's being asked here is how many four digit hexadecimal numbers are there whose digits are all in increasing order. We also have the restriction that $0$ can't be chosen, because, given digits of increasing order, this would imply $0$ as the first digit, which isn't allowed for a number in the proper format. So, we must have $4$ increasing digits chosen from $1$ to $15$. Increasing implies the digits are distinct. Since any choice of $4$ digits gives rise to exactly one such number and vice versa, we just need to count the number of sets of $4$ distinct digits chosen from the set of $15$. This is simply $$15 \choose 4$$
Comment: But it has to be a subset of ii, which prohibits zero in the first place.  As the digits have to be increasing, we can't use zero at all.  This leaves $15 \choose 4$
Comment: The problem actually says that you can't use 0 for the FIRST digit
Answer: i) is fine.
ii) There are $15$ possible values for the first digit, $15$ for the second digit, $14$ for the third and $13$ for the last digit. Giving $ 15 \times 15 \times 14 \times 13$.
iii) There are $15$ possible values for the first digit, $14$ for the second digit, $13$ for the third and $1$ for the last digit. Giving $ 15 \times 14 \times 13 \times 1$.
iv) The first digit cannot be zero so there are $ \binom {15}{4} $ ways to choose $4$ digits , now put them in ascending order.
Comment: iii is not correct because we can't have $0$ in the second or third place.  iv is not correct because we are not permitted zero in the first place, and zero cannot be in any other place either.  That leaves $15 \choose 4$


PutHBaseJSon Processor in Apache-Nifi

Question: I am using PutHBaseJSon processor  that will fetch data from hdfs location and to put it into hbase.The data present in hdfs location is like below format and this is in a single file.
<code>{"EMPID": "17", "EMPNAME": "b17", "DEPTID": "DNA"}
{"EMPID": "18", "EMPNAME": "b18", "DEPTID": "DNA"}
{"EMPID": "19", "EMPNAME": "b19", "DEPTID": "DNA"}
</code>
when I execute the PutHBaseJSon processor, it's only fetching the first row and put it into the hbase table which I have created. Can't we  able to fetch all the rows present in that file using this processor? or How to fetch all the records from the single file to hbase?
Answer: PutHBaseJSON takes a single JSON document as input. After fetching from HDFS, you should be able to use the SplitText processor with a line count of 1 to get each of your JSON documents into a single flow file.
If you have millions of JSON records in a single HDFS file, then you should perform a two phase split, the first SplitText should split with a line count of say 10,000 then then a second SplitText should split those down to 1 line each.
Answer: You can make use of SplitJson processor to split them as individual records serially they will be sent to puthbasejson

PutHBaseJSon Processor in Apache-Nifi


Problema ao inserir rodadas em jogo de pedra , papel e tesoura

Question: Bom dia , não estou conseguindo implementar um sistema de rodadas nesse jogo , as rodadas devem trocar quando a Mao do jogador se esvaziar. , oque aconteçe agora é que quando a lista jogador e jogador2 se esvaziam o jogo continua a execução com ela vazia , mas oque deveria acontecer era ele sortear novamente as cartas para começar a outra rodada.
import random
print("-"*32)
print("jogo de pedra, papel e tesoura")
print("-"*32)
jogador = []
jogador2 = []
escolha1 = ''
escolha2 = ''
aposta = 0
aposta2 = 0
rodada = 0
dinheiro = 0
dinheiro2 = 0
res = 0
res2 = 0
saldo = 0
saldo2 = 0
dinheiro = 1000
dinheiro2 = 1000
rodada = 1
jogo_roda = True
def sorteio_Cartas(jogador,jogador2,rodada):
  for i in range (3):
    a = len(jogador)
    b = len(jogador2)
    p1 = random.randint(1,3)
    p2 = random.randint(1,3)
    rodada += 1
    i += 1
    if p2 == 3:
        jogador.append("Pedra")
    elif p2 == 2:
        jogador.append("Papel")
    else:
        jogador.append("Tesoura")
    if p1 == 3:
        jogador2.append("Pedra")
    elif p1 == 2:
        jogador2.append("Papel")
    else:
        jogador2.append("Tesoura")
return jogador, jogador2 , rodada
def escolha_Cartas(escolha1,jogador):
    if escolha1 in jogador[0]:
        print("A Carta escolhida foi ",escolha1)
        escolha1 = jogador[0]
        jogador.pop(0)
    elif escolha1 in jogador[1]:
        print("A Carta escolhida foi ",escolha1)
        escolha1 = jogador[1]
        jogador.pop(1)
    else:
        print("A Carta escolhida foi ",escolha1)
        escolha1 = jogador[2]
        jogador.pop(2)
return escolha1 , jogador,rodada

fUNÇÃO PARA O JOGADOR 2 ESCOLHER UMA CARTA
def escolha_Cartas2(escolha2,jogador2):
    if escolha2 in jogador2[0]:
        print("A Carta escolhida foi ",escolha2)
        escolha2 = jogador2[0]
        jogador2.pop(0)
    elif escolha2 in jogador2[1]:
        print("A Carta escolhida foi ",escolha2)
        escolha2 = jogador2[1]
        jogador2.pop(1)
    else:
        print("A Carta escolhida foi ",escolha2)
        escolha2 = jogador2[2]
        jogador2.pop(2)
return escolha2 , jogador,rodada

COMPARAÇÃO DE QUEM GANHOU A RODADA E QUEM PERDEU!
defcomparacao(escolha1,escolha2,aposta,aposta2,dinheiro,dinheiro2,saldo,saldo2,res,res2):
# Comparações de Vitoria jogador 2
 if escolha1 == "Pedra" and escolha2 == "Tesoura":
     print("O Jogador 1 Ganha!!")
     print("O Jogador 1 escolheu:", str(escolha1))
     print("O Jogador2 escolheu:", str(escolha2))
     dinheiro -= aposta
     res = aposta + aposta2
     saldo = dinheiro + res
     saldo2 = dinheiro2 - aposta2
     print("O Saldo do jogador 1 é: ",str(saldo))
     print("O Saldo do jogador 2 é: ",str(saldo2))
 elif escolha1 == "Tesoura" and escolha2 == "Papel":
     print("O Jogador 1 Ganha!!")
     print("O Jogador 1 escolheu:", str(escolha1))
     print("O Jogador 2 escolheu:", str(escolha2))
     dinheiro -= aposta
     res = aposta + aposta2
     saldo = dinheiro + res
     saldo2 = dinheiro2 - aposta2
     print("O Saldo do jogador 1 é: ",str(saldo))
     print("O Saldo do jogador 2 é: ",str(saldo2))
 elif  escolha1 == "Papel" and escolha2 == "Pedra":
     print("O Jogador 1 Ganha!!")
     print("O Jogador 1 escolheu:", str(escolha1))
     print("O Jogador 2 escolheu:", str(escolha2))
     dinheiro -= aposta
     res = aposta + aposta2
     saldo = dinheiro + res
     saldo2 = dinheiro2 - aposta2
     print("O Saldo do jogador 1 é: ",str(saldo))
     print("O Saldo do jogador 2 é: ",str(saldo2))
# Comparações de Vitória jogador 2
 elif escolha2 == "Pedra" and escolha1 == "Tesoura":
     print("O Jogador 2 Ganha!!")
     print("O Jogador 1 escolheu:", str(escolha1))
     print("O Jogador 2 escolheu:", str(escolha2))
     dinheiro2 -= aposta2
     res2 = aposta + aposta2
     saldo2 = dinheiro2 + res2
     saldo = dinheiro - aposta
     print("O Saldo do jogador 2 é: ",str(saldo2))
     print("O Saldo do jogador 1 é: ",str(saldo))
 elif escolha2 == "Tesoura" and escolha1 == "Papel":
     print("O Jogador 2 Ganha!!")
     print("O Jogador 1 escolheu:", str(escolha1))
     print("O Jogador 2 escolheu:", str(escolha2))
     dinheiro2 -= aposta2
     res2 = aposta + aposta2
     saldo2 = dinheiro2 + res2
     saldo = dinheiro - aposta
     print("O Saldo do jogador 2 é: ",str(saldo2))
     print("O Saldo do jogador 1 é: ",str(saldo))
 elif escolha2 == "Papel" and escolha1 == "Pedra":
     print("O Jogador 2 Ganha!!")
     print("O Jogador 1 escolheu:", str(escolha1))
     print("O Jogador 2 escolheu:", str(escolha2))
     dinheiro2 -= aposta2
     res2 = aposta + aposta2
     saldo2 = dinheiro2 + res2
     saldo = dinheiro - aposta
     print("O Saldo do jogador 2 é: ",str(saldo2))
     print("O Saldo do jogador 1 é: ",str(saldo))
 else:
     print("EMPATE!!!")
     print("O Jogador1 escolheu:", str(escolha1))
     print("O Jogador2 escolheu:", str(escolha2))
return saldo , saldo2

função para rodar o jogo
def jogoroda(jogo_roda,rodada):
##declaracao de saldo de dinheiro
   while jogo_roda == True:
       while rodada != 3:
          if rodada == 1:
              sorteio_Cartas(jogador,jogador2,rodada)
              jogoroda(jogo_roda,rodada)
          elif rodada == 2:
              sorteio_Cartas(jogador,jogador2,rodada)
              jogoroda(jogo_roda,rodada)
          elif rodada == 3:
              sorteio_Cartas(jogador,jogador2,rodada)
              jogoroda(jogo_roda,rodada)
          else:
              jogo_roda = False
      else:
          print("Fim de jogo")
      print("Esta é a primeira {} Rodada!!".format(rodada))
      print("O jogador 1 {} reais!!!!, Boa sorte! ".format(saldo))
      print("As Cartas do jogador1 são: "+str(jogador))
      print("-"*32)
      aposta = float(input("Porfavor Faca uma Aposta: "))
      escolha1 = input("Jogador 1 escolha uma carta: ")
      print("O jogador 2 {} reais!!!!, Boa sorte! ".format(saldo2))
      print("As Cartas do Jogador 2 são: ",str(jogador2))
      print("-"*32)
      aposta2 = float(input("Porfavor Faca uma Aposta: "))
      escolha2 = input("Jogador 2 escolha uma carta: ")
      escolha_Cartas(escolha1,jogador)
      print(escolha1)
      escolha_Cartas2(escolha2,jogador2)
      print(escolha2)
      comparacao(escolha1,escolha2,aposta,aposta2,dinheiro,dinheiro2,saldo,saldo2,res,res2)

     # chama a Execução
     jogoroda(jogo_roda,rodada)

Comment: O que seriam as "cartas" em um jogo de pedra, papel e tesoura?
Comment: no caso as "cartas" nesse jogo seriam o conteudo da lista dos jogadores , por exemplo na lista jogador2 tem três strings , essas seriam as "cartas"
Answer: A variavel 'rodada' está sendo declarada duas vezes sem ser utilizada no início do programa. Primeiro 'rodada = 0' depois 'rodada = 1' sem que nada tenha acontecido.
A funcionalidade da variavel 'jogo_roda' compete com a função da variavel 'rodada', e ambas não são necessárias antes da função jogoroda(), então não precisam ser declaradas antes, muito menos precisam ser passadas dentro de todas as outras funções.
Dentro de jogoroda() tudo abaixo da linha 'print("Fim de jogo")' será alcançado APENAS quando rodada>3, porém a única função que atualiza o valor de rodada é sorteio_Cartas() e você não está capturando esta informação ( quando você altera 'rodada' dentro de um função, você está alterando uma cópia de 'rodada'). Fora da função o valor não será atualizado.

Então o jogo roda diversas vezes sempre achando que é a primeira rodada. Além disso, sua função jogoroda() chama a sí mesma, mas não está preparada para isso. Vários outros problemas com variaveis vão aparecer.
Considere reescrever o programa fazendo um dicionário com os jogadores sendo as chaves e o saldo de cada jogador sendo o valor armazenado. O sorteio das cartas dos jogadores deve acontecer imediatamente antes do momento em que os jogadores farão a escolha da carta. Na mesma função você sorteará as cartas, os jogadores escolherão a cartas usada, e você escolherá o vencedor e atualizará o saldo. Acima dessa função você faz um contador de rodadas para finalizar o jogo. Lembre que alterações de variaveis dentro de uma função não são carregadas pra fora. Você tem que capturar as alterações você mesmo.


What space is this Homeomorphic to?

Question: Let $X$ be a topological space and let $A ⊂ X$.  Let $\sim$ be an equivalence relation on $X$ such that the equivalence classes are:

$A$ itself and
Singletons $\{x\}$ such that $x ∉ A$.

Then define $X/A$ to be the quotient space $X/{\sim}$.  (i.e. collapse $A$ to a point)
Let $D^2$ denote the unit disk in $R^2$ and let $S^1$ denote its boundary.
What's a fairly well-known space, then, that $D^2/S^1$ is homeomorphic to?
Is it $S^2$? And why?
Comment: Jimmy, do not do this. You just edited two of your questions, the other being [this question](http://math.stackexchange.com/questions/1036265/the-rotation-group-so3-may-be-mapped-to-a-2-sphere-by-sending-a-rotation-m), to ask a complete different question identical at both posts. You were totally invalidating the answers given on both counts.
Answer: Yes. $S^1$ (the boundary of $D^2$) is being contracted to a single point.  And the quotient map restricted to the interior of $D^2$ is a homeomorphism.
You may also want to note that the open disc is homeomorphic to the plane $\mathbb R ^2$, which is homeomorphic to the deleted sphere $S^2\setminus \{p\}$ via the stereographic projection.  We can identify the singleton $\{p\}$ with the contracted boundary of $D^2$.
Think of a gym bag with a drawstring lying flat on the floor.  Then you lift it, pulling the drawstring closed.
Comment: So it is homeomorphic to $S^2$ then?
Comment: @Jimmy Yes it is.
Comment: Ok thank you.  In a few sentences, how could I show that?  "$S^1$ (the boundary of $D^2$) is being contracted to a single point.  The quotient map restricted to the interior of $D^2$ is a homeomorphism."  Could you help me go into a little more detail?
Comment: (+1) Fantastic intuitive answer! And here I was, misreading the question! (I was searching for a familiar space homeomorphic to $\Bbb R^2/S^1$, instead.)
Comment: @Jimmy The quotient $D^2/S^1$ collapses $S^1$ to a single point by definition.  I updated my answer to show how the homeomorphism can be constructed.
Comment: Yes thank you very much for this explanation
Answer: Yes, $D^2 / S^1$ is homeomorphic to $S^2$ and in general, $D^n / \partial D^n$ is homeomorphic to $S^n$. To see this intuitively, take a disc and place a sphere tangent to its center. Pull the boundary of the disc up to the equator so that the disc covers a hemisphere, then move the boundary along the surface of the sphere to the uncovered pole; at the pole, the boundary will have to be glued together.
To actually show homeomorphism, we of course need to construct a map. As a starting point, I would send the center of the disc to one pole and the boundary to another.
If you know about stereographic projection, you might be able to modify that somewhat to apply here.
Comment: This is very helpful too
Answer: To add to the points already been made, one can think of $D^2$ as follows :
$$D^2=\{ (tx_1, tx_2) \mid 0\leq t \leq 1,  (x_1,x_2)\in S^{1}\}. $$
Now define a map $f:D^2\rightarrow S^2$ by $(tx_1, tx_2)\mapsto (ux_1, ux_2, 2t-1)$, where $u=(1-(2t-1)^2)^{1/2}$. Basically it sends the ray from $0$ to $(x_1, x_2)$ to the longitude that runs from the south pole $(0,0,−1)$ through the equatorial point $(x_1,x_2,0)$ to the north pole $(0, 0, 1)$.
Now the universal property of the quotient gives you a unique induced map $\widehat{f}:D^2/S^1\rightarrow S^2$ from compact to Hausdorff spaces.

What space is this Homeomorphic to?


How to have a node which displays & interacts differently with different type of users?

Question: Title might not be very clear. But to clarify my question, I'll take example of a Book Content Type.
I've 3 different types of users: Authors, Reviewers, Admin. Now this is what I want to achieve:
On the Book Page [a display which is shown to even unauthenticated user], Registered Reviewer submits a review for a book which should appear in Approve Reviews page of Admin, When the admin approves it should Appear in respective Author's Reviews for my books page and when finally the Author approves, it should be displayed on the Book Page.
And the reviewer must have a Submitted Reviews page which should list all the reviews he submitted each showing its present status like:
"Waiting for Admin's Approval", "Waiting for Author's Approval", "Approved"
I don't know how to achieve this.
Answer: There are many ways to accomplish this but here's one:

create content type Book
create content type Review
add a custom status field to Review (select list) and add the three states (admin approval, author approval, approved)
download and enable references module (also enable submodule node reference)
download and enable rules module (also enable rules ui submodule)
add a node reference field to Review (e.g. autocomplete widget)
create roles admin_reviews, author, reviewer
create view lists for reviews content and set permissions per role for admin_reviews, author and reviewer pages. Filter on field status of review for each role
use field permissions module to show / hide fields per role

create rules to set status of review (After saving new content -> set data value)
Comment: Wow! thanks a ton. I'll try this out and post the status but for learning purposes, if its not too much to ask, could you kindly point out other ways of accomplishing?
Answer: What you are talking is called a workflow. For Review content-type you need to setup a workflow. You can use workflow module for that. It needs a bit of training. Search Google/Youtube for "Workflow module drupal"


rxjs/angular how to convert http response to array-like object

Question: need to convert a json response body into a array-like object in an Angular 13 environment
the incoming response data looks like:
 [
    {
      "n": 1,
      "s": "s1"
    },
    {
      "n": 2,
      "s": "s2"
    },
    {
      "n": 3,
      "s": "s3"
    }
  ]

the resulting array-like object needs to look like
{
   numArray: [1,2,3],
  stringArray: ['s1','s2','s3']
}

have tried using map, flatmap, toArray + others from RxJS library seem to be unable to make the list. generally end up with:
{n: 1, s: 's1'}
{n: 2, s: 's2'}
{n: 3, s: 's3'}

how to do this translation?
Answer: A reduce is what you need, you need a starting accumulator that has the arrays for collecting strings and numbers and each iteration push the current items properties into the corresponding array on the accumulator

const result = [
  {
    "n": 1,
    "s": "s1"
  },
  {
    "n": 2,
    "s": "s2"
  },
  {
    "n": 3,
    "s": "s3"
  }
].reduce(
  (acc, current) => {
    acc.numArray.push(current.n);
    acc.stringArray.push(current.s);
    return acc;
  },
  { numArray: [], stringArray: [] } // your starting accumulator
);

console.log(result);

or you could use two maps but then you are iterating the array twice

const array = [
  {
    "n": 1,
    "s": "s1"
  },
  {
    "n": 2,
    "s": "s2"
  },
  {
    "n": 3,
    "s": "s3"
  }
];

const results = {
  numArray: array.map(item => item.n),
  stringArray: array.map(item => item.s)
};

console.log(results);

so in your Angular service you use the RxJs map operator and in the function you pass in you use the array's built in reduce or map function. When you have an RxJs stream and you want to transform the value emitted by the stream that is always a map, the function passed into the map then does the transformation and in this case of transforming an array we use the array's built in functions such as map, filter, find or reduce.
this.http('yourApiUrl').pipe(
  map(result => result.reduce(
    (acc, current) => {
      acc.numArray.push(current.n);
      acc.stringArray.push(current.s);
      return acc;
    },
    { numArray: [], stringArray: [] } // your starting accumulator
  ))
)

or
this.http('yourApiUrl').pipe(
  map(result => ({
    numArray: result.map(item => item.n),
    stringArray: result.map(item => item.s)
  }))
)


Teste de Variâncias no R

Question: Estou com dúvida no resultado obtido no teste de variâncias no R ao utilizar as amostras e o código abaixo:
x1 <- c(264.6, 253.9, 294.8, 225.2, 244.3, 253.7, 254.0)
x2 <- c(284.6, 283.9, 284.8, 285.2, 284.3, 283.7, 284.0)

var.test(x1,x2,alternative = "two.sided")

Resultado:
F test to compare two variances

data:  x1 and x2
F = 1541.8, num df = 6, denom df = 6,
p-value = 5.441e-09
alternative hypothesis: true ratio of variances is not equal to 1
95 percent confidence interval:
  264.9234 8972.8394
sample estimates:
ratio of variances
          1541.789

Ao observar resultado, o p-valor é 5.441e-09, ou seja, rejeita-se H0 para a igualdade de variâncias. No entanto, o intervalo de confiança contém o valor da razão das variâncias, discordando do p-valor?
Answer: Note que o teste aplicado aqui é o teste de razão entre as variâncias, que utiliza a estatística F de Snedecor. As hipóteses testadas aqui foram

Note que, se

então

Note que a razão estimada entre as variâncias é bastante alta, sendo igual a 1541.789. Assim, o p-valor do teste realizado acabou ficando bastante baixo, fazendo com que a tendência seja rejeitar a hipótese nula. Por exemplo, considerando um nível α = 0,05, a hipótese nula é rejeitada e, portanto, a razão entre as variâncias não é igual a 1 e, portanto, elas são diferentes.
Isso não entra em conflito com o intervalo de confiança. Perceba que o intervalo de confiança contém a razão entre as variâncias, mas a hipótese alternativa diz que true ratio of variances is not equal to 1. Mas, de fato, 1 não pertence ao intervalo de confiança, que é dado por (264.9234 8972.8394). Logo, o valor colocado como hipótese nula não pertence ao intervalo de confiança e a razão não é igual a 1. Logo, as variâncias são diferentes. Portanto, não há contradição alguma.

Teste de Variâncias no R


Pyspark Dataframe: Get previous row that meets a condition

Question: For every row in a PySpark DataFrame I am trying to get a value from the first preceding row that satisfied a certain condition:
That is if my dataframe looks like this:
X  | Flag
1  | 1
2  | 0
3  | 0
4  | 0
5  | 1
6  | 0
7  | 0
8  | 0
9  | 1
10 | 0

I want output that looks like this:
X  | Lag_X | Flag
1  | NULL  | 1
2  | 1     | 0
3  | 1     | 0
4  | 1     | 0
5  | 1     | 1
6  | 5     | 0
7  | 5     | 0
8  | 5     | 0
9  | 5     | 1
10 | 9     | 0

I thought I could do this with lag function and a WindowSpec, unfortunately WindowSpec doesnt support .filter or .when, so this does not work:
conditional_window = Window().orderBy(X).filter(df[Flag] == 1)
df = df.withColumn('lag_x', f.lag(df[x],1).over(conditional_window)

It seems like this should be simple, but I have been racking my brain trying to find a solution so any help with this would be greatly appreciated
Answer: Question is old, but I thought the answer might help others
Here is a working solution using window and lag functions
from pyspark.sql import functions as F
from pyspark.sql import Window
from pyspark.sql.functions import when
from pyspark.context import SparkContext

# Call SparkContext
sc = SparkContext.getOrCreate()
sc = sparkContext

# Create DataFrame
a = sc.createDataFrame([(1, 1),
                        (2, 0),
                        (3, 0),
                        (4, 0),
                        (5, 1),
                        (6, 0),
                        (7, 0),
                        (8, 0),
                        (9, 1),
                       (10, 0)]
                     , ['X', 'Flag'])

# Use a window function
win = Window.orderBy("X")
# Condition : if preceeding row in column "Flag" is not 0
condition = F.lag(F.col("Flag"), 1).over(win) != 0
# Add a new column : if condition is true, value is value of column "X" at the previous row
a = a.withColumn("Flag_X", F.when(condition, F.col("X") - 1))

Now, we obtain a DataFrame as shown below
+---+----+------+
|  X|Flag|Flag_X|
+---+----+------+
|  1|   1|  null|
|  2|   0|     1|
|  3|   0|  null|
|  4|   0|  null|
|  5|   1|  null|
|  6|   0|     5|
|  7|   0|  null|
|  8|   0|  null|
|  9|   1|  null|
| 10|   0|     9|
+---+----+------+

To fill null values :
a = a.withColumn("Flag_X",
                 F.last(F.col("Flag_X"), ignorenulls=True)\
     .over(win))

So the final DataFrame is as required :
+---+----+------+
|  X|Flag|Flag_X|
+---+----+------+
|  1|   1|  null|
|  2|   0|     1|
|  3|   0|     1|
|  4|   0|     1|
|  5|   1|     1|
|  6|   0|     5|
|  7|   0|     5|
|  8|   0|     5|
|  9|   1|     5|
| 10|   0|     9|
+---+----+------+


"Repassing" function arguments

Question: I'm doing this class assignment, using classic C, and am stuck with this problem about callback functions that take variable arguments count and type.
Basically, I'm working on a Hashed Tree (a tree where each of the nodes is a hash tree), and I have a certain traversal strategy that will be used multiple times for different purposes, so I implemented it as ht_walk(HashTree tree, (*callback)(Element e)), so that the function called as callback will process the Element whatever way necessary.
Problem being, in most situations in my problem the callback function will have to take different arguments. I know how to design a function with a variable argument list using 'variadic' functions (using stdarg, printf-way), but I don't know how to 'repass' these arguments to the callback function.
Let me provide a concrete example: suppose I have a callback function called addToList(Element e, List list), and that my ht_walk declaration is now ht_walk(HashTree tree, (*callback)(Element e), ...). Consider I want to use ht_walk like in the following snippet:
HashTree my_tree = ht_create();
/* run some algorithm that populates the tree somehow */
List my_list = list_create();
ht_walk(my_tree, addToList, my_list);

Is there a way to do this? Thanks in advance!
Answer: You can solve this using one of two methods.
The most common, understandable, and clean method is to use a 'user' structure:
void ht_walk(HashTree tree, void (*callback)(Element e, void *user), void *user);

void addToList(Element e, void *arg)
{
    STATIC_ASSERT(sizeof(void *) >= sizeof(List));

    List list = arg;

    /* ... */
}

HashTree my_tree = ht_create();
/* run some algorithm that populates the tree somehow */
List my_list = list_create();
ht_walk(my_tree, addToList, my_list);

Another method is to accept va_list:
#include <stdarg.h>

void ht_walk(HashTree tree, void (*callback)(Element e, va_list args), ...)
{
    for(..)
    {
        va_list args;
        va_start(args, callback);
        callback(element, args);
        va_end(args);
    }
}

void addToList(Element e, va_list args)
{
    List list = va_arg(args, List);

    /* ... */
}

HashTree my_tree = ht_create();
/* run some algorithm that populates the tree somehow */
List my_list = list_create();
ht_walk(my_tree, addToList, my_list);

Comment: I think the first ht_walk should be: void ht_walk(HashTree tree, void (*callback)(Element e, void *user), void *user); because the callback needs a return type and because you have to pass the user data to ht_walk so it can convey it onwards.  The call then needs adjusting too.
Comment: The second ht_walk also needs the return type on the callback.  I guess that your conception of List includes a pointer: typedef struct ListItem *List; or something similar.  If not, then I think the call to ht_walk may need to take the address of my_list.
Comment: @Leffler, Thanks for your comments.  Forgetting void *user was a typo.  Missing return types for the callbacks were copy-paste issues (OP didn't have them).  Yes, I do believe List is a pointer, seeing how HashTree is passed by value, too.
Answer: There is a series of functions and macros for dealing with variadic arguments (e.g., va_start)
GNU has a good guide here
That being said, you seem to be describing sort of a visitor pattern. I am not sure I like the use of variadic argument lists here. If you can't typically establish what parameters your callback would be getting consistently for all nodes, you are in trouble to begin with.
Answer: I don't think what you want to do is pass an arbitrary number of arguments.  I think what you have here is a case where you have multiple types of callback.  In your example, you're passing a List, but you also mention sometimes you'll pass an Element.  So it seems to me what you really want to do is declare your callback to take a void* and a flag to indicate what it is.  Something like:
void callback(void* arg, int type) {
    switch (type) {
    case ARG_TYPE_LIST:
        List* list = (List*)arg;
        ...
        break;
    case ARG_TYPE_ELEMENT:
        Element* ele = (Element*)arg;
        ...
        break;
    ...
}

If you're passing things as a list, the list should know the count, so you don't have to worry about passing that.
Alternatively, you could define multiple types of callback and always callback the right one based on what sort of processing you need to do.
If you're not restrained to straight C (i.e. you can use C++) you may investigate using boost::bind, as it is very useful for this sort of thing.
Answer: I believe you use the va_list macro. See the man page for stdarg.
It has been a while since I tried this though...
Answer: I would pass in a void *, as I don't think you can use variable number of arguments in a callback function. I could be wrong though.
typedef void (*tree_walk_callback)(Element e, void *data);

add_element(Element e, void *data)
{
    List *list = (List *)data;
    add_element_to_list(list, e);
}

...in your function...
List my_list;
ht_walk(my_tree, &add_element, (void *)&my_list);

If the user wants to pass multiple arguments, then they would pass a struct through containing whatever they need.

"Repassing" function arguments


How Do I Make My Site Full Size in Mobile?

Question: I have tried every variation I can think of to try and get my site to show up correctly on mobile. I've entered these codes into my head tags, but to  no avail:
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="viewport" id="viewport" content="width=device-width,minimum-scale=1.0,maximum-scale=10.0,initial-scale=1.0" />

And all other variations! Nothing makes me able to change the original look of the site on mobile, or allow me to zoom in or out! I have no idea what to do next. If there's ANY advice you guys can give, I'm desperate.
The site is www.justthestork.com
Comment: Those were tried separately, not together...
Answer: Sounds like you want your site to load as it does on a desktop browser but zoomed out? In that case you want to give your content a constant width that's larger than the screen size:
<meta name="viewport" content="width=1024">

This means that your page will layout into a window that's 1024 pixels wide (you can adjust the width to see what looks best). The browser will then zoom out until it fits on the screen.
If you don't specify a viewport <meta> at all, the browser will pick a default width (e.g. 980px).
Answer: Try this one here, it should force the correct screen size:
<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0;">

Comment: Unfortunately, that did not help :( - thanks for the suggestion though


Adjusting a double array - Matlab

Question: How can I adjust the boundary double array that looks like that:
102     8
101     9
100     9
99      9
…       …

To be a double array that looks like this:
102   8   101   9   100   9   99   9 … …

Code:
I = imread('coins.png');
BW = im2bw(I, graythresh(I));
[B,L] = bwboundaries(BW,'noholes');
boundary = B{1}

Comment: `boundary = reshape(boundary.',1,[])`
Comment: Possible duplicate https://stackoverflow.com/questions/21413164/is-matlab-row-specific-or-column-specific
Answer: % consider A is your matrix.
At=A.';
At(:)  % this matrix will give what you want.

Adjusting a double array - Matlab


Harddrive Compatibility Issues

Question: i recently bought a HP DL580 G7 from ebay. It didnt come with harddrives so i bought 2 x ST1200MM0118 harddrives.
I am seeing hell to try to get it working. I contacted HP support who told me to purchase HP harddrives ( not very helpful ), however they did assist me in updating the firmware of the p410i controller to 6.64 and all over drives using the SPP to the newest for that server.
I still get no response from both drives. Ive tried what i believe to be EVERYTHING. Ive tried booting with only 1 drive in, ive tried a random sata drive i have laying around ( which works perfectly in my external sata to usb dock ).
Im wondering if the backplane or the sas cable could be the problem, however im wondering if that might even be the problem.
When i log into the iLO, the 2 harddrive informations says "fault" which leads me to believe the problem may be with the drives and not the sas cables or the backplane.
Im looking for some suggestions on what would be the best way forward.
Comment: Whilst this won't be helpful with your problem but you're going to run into the same problem as I did where HP has, on purpose, crippled their RAID adapters so that if you use 3rd party (read: non HP branded drives) the fans will go into overdrive and blow at 100% so if you're going to  run this server in a non-server room environment, be prepared to be in a world of hurt.

Edit:
What did pop into my mind was, did you completely erase and RAID information that may have been left over from the previous owner from the option rom config for arrays? F8 on startup as I recall.
Comment: Ok so i defaulted the entire server erasing memory or all raid etc. The machine rebooted and even rechecked all the memory etc. so i believe the server is at its full default state. Same issue with the hard drives. I am even beginning to even wonder if my harddrives are even good, but i dont see 2 used drives both being bad at the same time. so leads me back to wonder if it might be the sas or backplane... im trying to avoid wasting money on purchasing another back plane and sas cables and cant confirm if they are the problem.
Comment: Could you please add to your question a picture of your server booting at a point when RAID adapter initialized, displayed the detected drives and waits for F8 to be clicked...
Comment: Im not sure how to upload am image yet, but i can tell you what it says.

Slot 0 HP Smart Array P410i Controller (1024MB, v6.64) 0 Logical Drives
1785-Slot 0 Drive Array Not Configured
         No Drives Detected

Press  to run the Option ROM Configuration for Arrays Utility
Press  to run the Option ROM Configuration Command Line Interface
Press  to Skip Configuration and Continue
Comment: I Uploaded a screenshot to the original quesiton
Answer: Ok, so solution was to purchase a LSI card. The HP server backplane and even the SAS cables worked, everything works perfectly now

Harddrive Compatibility Issues


Loop through a multi value entity reference field working only on the first selected item

Question: 1) I have an entity reference view articles_per_user listing all nodes of type article authored by the current logged in user.
2) On the Article Entity, there is a taxonomy reference field field_article_country referencing the taxonomy vocabulary: "Countries" (One value is allowed)
3) On the User Entity, there is a multi-value taxonomy reference field field_user_article_countries referencing the same taxonomy vocabulary: "Countries" (Unlimited value are allowed)
4) On a Webform, I have an entity reference field articles referencing the above entity reference view 'articles_per_user' with unlimited values where the users can select one or more article.
5) When Webform is submitted, I want to:

Load each selected Article.
Get value of the field_article_country
Load the current logged in user entity.
Set the retrieved value to field_user_article_countries
Save the User entity.

Quick Demonstration:
Say the Current User selected on the Webform 3 articles where:

Article 1 has field_article_country = United States
Article 2 has field_article_country = Egypt
Article 3 has field_article_country = Spain

After the Webform is submitted, the field_user_article_countries at the User Entity must have 3 values selected:

United States
Egypt
Spain

The error I am facing is at field_user_article_countries, I see only one value selected:

United States

Below is my code:
// Function to be fired while submitting the Webform.
public function submitForm(array &$form, FormStateInterface $form_state, WebformSubmissionInterface $webform_submission) {

    // Load the account of current logged in user.
    $CurrentUid = \Drupal::currentUser()->id();
    $CurrentUser = \Drupal\user\Entity\User::load($CurrentUid);

    // Get the selected 'Articles' Value.
    $ArticleIDs = $values['articles'];     // NIDs

    // Load all "Articles" according to their IDs.
    $Articles = \Drupal\node\Entity\Node::loadMultiple($ArticleIDs);

    // Loop through loaded articles entities.
    foreach ($Articles as $Article) {

    // Get the "Article Country" Value from the loaded article.
    $ArticleCountry = $Article->get('field_article_country')->target_id;

    // Set the 'User Country' value on the user account.
    $CurrentUser->set('field_user_article_countries', $ArticleCountry);
    }

    // Save the User account.
    $CurrentUser->save();

}

Comment: `$CurrentUser->field_user_article_countries[] = ['target_id' => $ArticleCountry];`
Comment: Cause your `set` is overidding it on each loop iteration rather than adding to it.
Comment: @NoSssweat can you please provide an example on how I can add the values rather than override them ?
Comment: Thank you so much for your help, can you please add your comment as an answer so I can accept it
Answer: foreach ($Articles as $Article) {

  // Get the "Article Country" Value from the loaded article.
  $ArticleCountry = $Article->field_article_country->target_id; // shorter way

  // Set the 'User Country' value on the user account.
  $CurrentUser->field_user_article_countries[] = ['target_id' => $ArticleCountry]; // use array

}


facebook v2.2 c# posts function oauthexception #100

Question: I need help to solve one of my Facebook problem. Below is the error I met:

I tried changing the limit from 5000 to 1000 to 25 to 10. But this error still exists. I've also checked that it is ";" and not ":". I tried changing whatever I could but to no avail. Can anyone help me with this???
Your help will be greatly appreciated!
Answer: I assume that the problem is with until parameter that you passing in
fb.Get method. as it states in the error message ensure that it has a correct representation (unixtime or date/time format)
Comment: How do I ensure that it has the correct representation (unixtime or date/time format? I only have `string datetime = string.Format("{0:yyyy-MM-dd_hh-mm-ss-tt}", DateTime.Now);` in my coding


Injecting multiple constructor parameters of the same type with Ninject 2.0

Question: I'm using Ninject 2.0 to handle DI in one of my apps and I've come across something that's confusing me.  Having zero documentation doesn't help too much either to be honest.
Say I have a constructor with the signature -
ctor(IServiceFactory factory1, IServiceFactory factory2)
{
    this.factory1 = factory1;
    this.factory2 = factory2;
}

Although these two services implement the same interface, they are quite different implementations and are used at different times so I don't want to inject an IEnumerable<IServiceFactory>.
My question is, when I'm binding the instances, how do I tell Ninject what to inject for each?
Thanks in advance.
Update
For the sake of anyone wanting to see the code would end up after reading Remo's links,...Here it is in brief. (I never realised C# had parameter attributes!)
//abstract factory
public interface IServiceFactory
{
    Service Create();
}

//concrete factories
public class Service1Factory : IServiceFactory
{
    public IService Create()
    {
        return new Service1();
    }
}

public class Service2Factory : IServiceFactory
{
    public IService Create()
    {
        return new Service2();
    }
}

//Binding Module (in composition root)
public class ServiceFactoryModule : NinjectModule
{
    public override void Load()
    {
        Bind<IServiceFactory>()
            .To<Service1Factory>()
            .Named("Service1");

        Bind<IServiceFactory>()
            .To<Service2Factory>()
            .Named("Service2");
    }
}

//consumer of bindings
public class Consumer(
    [Named("Service1")] service1Factory,
    [Named("Service2")] service2Factory)
{
}

Answer: First of all you have to ask yourself if using the same interface is correct if the implementations need to do a completely different thing. Normally, the interface is the contract between the consumer and the implementation. So if the consumer expects different things then you might consider to define different interfaces.
If you decide to stay with the same interface than you have to use conditional bindings. See the documentation about how this is done:
https://github.com/ninject/ninject/wiki/Contextual-Binding
https://github.com/ninject/ninject/wiki/Conventions-Based-Binding
Comment: I think you didn't understand correctly. From point of the consumer they do not the same thing. The interface should be defined from the perspective of the consumer. E.g. if you have a factory interface `Fruit CreateFruit()` and the consumer expects two implementations one for bananas and one for oranges then you should better define the interface as `Banana CreateBanana()` and `Orange CreateOrange()` even if you need them only as fruits.
Comment: Thanks Remo.  They're actually different implementations of an abstract factory which create Tabs in the UI so they do the same thing,...just for different reasons.
Comment: I see.  You're suggesting that I use factory methods rather than an abstract factory with concrete factory classes. It's an option but the factory classes themselves have dependencies (sub-screens in this case) which need to be injected.  Those dependencies are much easier to resolve with concrete factories and constructor injection rather than factory methods aren't they or does Ninject have some other magic I'm missing?


find the eigenvalues of a linear operator T

Question: Let $A$ be $m*m$ and B be $n*n$ complex matrices, and consider the linear operator $T$ on the space $C^{m*n}$ of all  $m*n$ complex matrices defined by $T(M) = AMB$.
-Show how to construct an eigenvector for $T$ out of a pair of column vectors $X, Y$, where $X$ is an eigenvector for $A$ and $Y$ is an eigenvector for $B^t$.
-Determine the eigenvalues of $T$ in terms of those of $A$ and $B$
-Determine the trace of this operator
Answer: Suppose $u_A$ is a right eigenvector of $A$ corresponding to an eigenvalue $\lambda_A$.
Similarly, let $u_B^T$ be a left eigenvector of $B$ corresponding to an eigenvalue $\lambda_B$. Then by a simple calculation, we have $T(u_A u_B^T) = \lambda_A \lambda_B u_A u_B^T$, hence $u_A u_B^T$ is an eigenvector of $T$ corresponding to the eigenvalue $\lambda_A \lambda_B$.
The trace can be calculated by summing the eigenvalues of $T$. This involves computing a formula assuming that $A,B$ are diagonalizable, and then using the fact that the diagonalizable matrices are dense coupled with continuity of $\mathbb{tr}$.
Alternatively, we can pick a basis for $\mathbb{C}^{m \times n}$ and compute the trace directly. A simple basis is given by $E_{ij} = e_i e_j^T$. If $X \in \mathbb{C}^{m \times n}$, let $[X]_{ij}$ denote the component of $X$ along  $E_{ij}$, ie, $X = \sum_{i,j} [X]_{ij} E_{ij}$. Then the trace of $T$ is given by $\mathbb{tr}(T) = \sum_{i,j} [T(E_{ij})]_{ij}$. A simple computation shows that $[T(E_{ij})]_{ij} = [A]_{ii}[B]_{jj}$, from which the following formula follows:
$$\mathbb{tr}(T) = \sum_{i,j} [A]_{ii}[B]_{jj} = \sum_i [A]_{ii} \sum_j [B]_{jj} =  \mathbb{tr}(A) \mathbb{tr}(B).  $$
Answer: Suppose $X$ is an e-vector for $A$ then $AX = \lambda_A X$ for some $\lambda_A \in \mathbb{C}$. Likewise, suppose $Y$ is an e-vector for $B^t$ then $B^tY = \lambda_B Y$ for $\lambda_B \in \mathbb{C}$. The linear operator $T: \mathbb{C}^{m \times n} \rightarrow \mathbb{C}^{m \times n}$ maps matrices to matrices. Given the data $X$ an $m \times 1$ vector and $Y$ a $n \times 1$ vector we need to construct an $m \times n$ object. The most natural guess is simply $XY^t$ which has the right size to be an "$M$" of the problem statement.
$$ T(XY^t) = AXY^tB = AX(B^tY)^t $$
using the socks-shoes property of the transpose. Continuing,
$$ T(XY^t) = \lambda_A X (\lambda_B Y)^t = \lambda_A\lambda_B XY^t.$$
this shows $T$ has e-vector $XY^t$ with e-value $\lambda_A\lambda_B$.
To calculate trace, you should think about what theorems are known connecting the trace and eigenvalues for an operator.
Comment: You have found some of the eigenvectors and eigenvalues of $T$, but have you found all of them?
Comment: maybe not... I certainly didn't derive them. This is the trouble with guessing :)
Answer: There is a standard way to do this kind of exercise.  Firstly assume that $ A$ and $ B$ are diagonal.  Then a short calculation shows that the eigenvalues are as given in previous solutions, i.e., the pairwise products of those of these matrices.  The result then holds for diagonalisable matrices by a suitable choice of bases.  The easiest way to get the final version is to use the fact that the diagonalisable matrices are dense in all matrices and employ a continuity argument involving the characteristic polynomials.


PHP - upload de uma imagem

Question: Tenho o seguinte codigo para fazer o upload de uma imagem:
<code>var_dump ( $_FILES );

$target_dir = "uploads/";
$target_file = $target_dir . basename ( $_FILES ["fileToUpload"] ["name"] );
$uploadOk = 1;
$imageFileType = pathinfo ( $target_file, PATHINFO_EXTENSION );

if (isset ( $_POST ["submit"] )) {
    $check = getimagesize ( $_FILES ["fileToUpload"] ["tmp_name"] );
    if ($check !== false) {
        echo "File is an image - " . $check ["mime"] . ".";
        $uploadOk = 1;
    } else {
        echo "File is not an image.";
        $uploadOk = 0;
    }
}
</code>
mas no entanto o seguinte erro aparece quando carrego fazer o upload da imagem:
array(1) { ["fileToUpload"]=> array(5) { ["name"]=> string(8) "css3.jpg" ["type"]=> string(10) "image/jpeg" ["tmp_name"]=> string(14) "/tmp/php8UjGak" ["error"]=> int(0) ["size"]=> int(21455) } } File is an image - image/jpeg.
Comment: Isso aí não é erro, é saída do `var_dump()`
Comment: rray o que devo fazer entao?
Comment: É só remover o `var_dump()`
Comment: rray removi e deu certo, mas eu clico "escolher ficheiro" escolho a foto e depois clico upload, so que eu quero apenas que o aparece o ficheiro como tendo sido uploaded, no entanto isso não acontece aparece uma pagina em branco com a informação do echo. tem como voce me ajudar pf?obrigado, pf veja a imagem, acabei de adicionar
Comment: Na hora de escrever a mensagem mande o html formatado, aí vc joga a mensagem dentro de uma div com as classes de formatação.
Answer: Pelo que parece seu código deu certo, ele checou que é uma imagem. O que apareceu para você foi a saida do var_dump ( $_FILES );
No lugar do echo: "File is an image - " . $check ["mime"] . ".";
Você deve escrever seu código que define o que fará com essa imagem (normalmente mover para um diretório permanente).
Comment: Marlon, isso eu ja tenho feito: $Image = $conn->real_escape_string ( file_get_contents ( $_FILES ["fileToUpload"] ["tmp_name"]));

PHP - upload de uma imagem


Apache connecting to SSL SNI reverse proxy

Question: I have reverse proxy set up in my DMZ, ApacheDMZ which is configured using SNI. I'm adding a new Apache server Outside that needs to use mod proxy to access certain resources through ApacheDMZ.
Both are CentOS 6.x.
I am getting a 403 forbidden when I visit the pages on Outside and No hostname was provided via SNI for a name based virtual host in the ApacheDMZ logs.
How can I correct this?
Answer: See this bug where this should be fixed; which version are you on, and do you have ProxyPreserveHost On enabled?


Problem in hiding empty staves

Question: Could anyone know a possible solution for sorting out this hiding empty stave problem?
(P.S) I'm using join multiple measure option, so does that make any problem for hiding?
Comment: Hi Sanjai S. Welcome to the site. It might help you get the best answer if you add to your post: 1) The version of Sibelius you're using, and 2) The steps you're currently taking to hide the staff.
Comment: @Sanjai S, you only want to hide the empty bar of the top stave right?
Answer: You can't use the Hide Empty Staves function, because the top stave isn't completely empty.
If you want a 'cut-away' stave, the trick is to select the portion you want hidden and apply an Instrument Change to 'No instrument (hidden)'
There are a few Sibelius experts here.  Rather more in the official forum www.sibelius.com/cgi-bin/helpcenter/chat/chat.pl?groupid=3 and the various Sibelius Facebook groups.

Problem in hiding empty staves


How to find derivative of improper integral with variable limit?

Question: I am working with the following, general improper integral and I need to compute it's derivative.
$$F(x)=\int_{x}^{\infty}f(s,t)^2ds$$
I want to say that derivative of integral is just the function, but the square is throwing me off. Is it just
$$\frac{d}{dx}(F(x))=\frac{d}{ds}F(s)=2f(s,t)f_x(s,t)?$$
Thanks!
Comment: Are you sure it is $t$ and not $x$ inside the integral ?
Comment: $dF(x)=\int_{x+dx}^\infty f(s,t)^2\,ds-\int_{x}^\infty f(s,t)^2\,ds=$ $-\int_{x}^{x+dx} f(s,t)^2\,ds=$ $-f(x,t)^2\,dx$, $dF/dx=-f(x,t)^2$.
Answer: Look up the Leibniz integal rule. In your case, it yields
$$ \frac{d}{dx}\left(\int_{x}^{\infty} f(s,t)^2 ds\right) = -f(x,t)^2.$$


Which criteria should I adopt when deciding to implement hook_xmlrpc() or supporting the Services module?

Question: If I should decide between implementing hook_xmlrpc() and supporting the Services module, what should I consider on taking this decision?
Answer: Consider carefully your

audience
goals
time
alternatives

Is your audience going to know how to make calls to your implementation in hook_xmlrpc? Many developers today are familiar with using RESTful services, but I would argue the number working with xml-rpc services is dwindling. Is your audience willing to install the services module to use your functionality, or would they more likely want a solution that is already available in core?
Is your goal to do something simple, such as interface with Drupal's blog system? If so, then hook_xmlrpc may be a better approach. Is your goal to create a fully featured web service for integration with external apps? Then, you may be better off using the services module.
Do you have the time to learn setup and learn the Services module? This could take more time than using a simple hook_xmlrpc, but it could also save you much time in the long run.
Have you considered the alternatives such as Rest Server?


Views exposed filter - Replace '-Any-' by Select All

Question: I have a view with an exposed filter of taxonomy terms. Because I'm using charts, when I select the option '-Any-', the chart gets messed up. I noticed that, if I select all terms available instead of '-Any-', the chart looks ok.
So my question is, it is possible to replace the '-Any-' with a select all or, in some way, force the any to select all?
Comment: Updated the link to charts module.
Answer: This question is already answered. Please find the answer in below link
https://stackoverflow.com/a/5975294/5093173
or use this code
<code>function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'views_exposed_form' && $form_state['view']->name == 'view name') {
      $form['filter_name']['#options']['All'] = t('select all');
}
</code>
}
Comment: Thanks Vamsi, but that solution is to change the label. What I need is to select all terms in the exposed filter when I select all - this can be done in any way, I just need that functionality.


What is the fastest way to copy a large file to S3 from Node.js?

Question: I imagine using child_process with the AWS CLI using aws s3 cp is faster than using the aws-sdk module, but I'm wondering if this has actually been tested before? Is there a faster way to copy files asynchronously from a Node.js environment, ideally using a separate thread?
Answer: To copy single file to S3 bucket:
aws s3 cp filename s3://bucket/ --recursive
To copy all files in a directory to S3 bucket:
aws s3 sync directory/ s3://bucket/ --recursive
Comment: I ran a test locally, though, and using the JS SDK is actually faster than the CLI...


Limit of an infinite sequence

Question: Let $$P_n=\frac{2^3-1}{2^3+1}\frac{3^3-1}{3^3+1}.....\frac{n^3-1}{n^3+1}$$ Prove that $\lim_{n \to \infty}=\frac{2}{3}$. I tried factorizing them but not much canceling or some other thing happened. What can I do?
Comment: Try proving $P_n$'s are bounded above/below and increasing/decreasing and then prove sup/inf is $2/3$
Comment: I would take a logarithm, turning the product into a sum.
Comment: http://math.stackexchange.com/questions/856965/infinite-product-prod-k-2n-frack3-1k31
Answer: We have
\begin{align}P_n = \prod_{j = 2}^n \frac{j^3 - 1}{j^3 + 1} &= \prod_{j = 2}^n \frac{j-1}{j+1} \frac{j^2 + j + 1}{j^2 - j + 1}\\
&= \frac{2(n-1)!}{(n+1)!}\prod_{j = 2}^n \frac{(j+1)^2 - (j+1) + 1}{j^2 - j + 1}\\
&= \frac{2}{(n+1)n}\frac{n^2 + n + 1}{2^2 - 2 + 1}\quad \text{by telescoping}\\
&= \frac{2}{3}\frac{n^2+n+1}{n^2+n}\\
&\to \frac{2}{3} \quad \text{as} \quad n\to \infty.
\end{align}
Comment: How did you get 2 out in the second step?
Comment: @Garvil it comes from computing the product $\prod_{j = 2}^n (j+1)$, which is $(n+1)!/2$.

Limit of an infinite sequence


DRAC with External IP?

Question: We have a Dell 1950 with a DRAC. The DRAC is assigned an external IP and we don't have access to the firewall to create any rules to secure it.
Assuming the password is secure enough to avoid brute force attacks, can the DRAC have an external IP like this?
My gut says no, but I've always worked with the OS, never with the hardware.
Thanks!
Comment: I personally wouldn't trust this to just a "sufficiently secure" password. Can the party that manages the firewall create the appropriate rules for you?
Comment: Agreed with @joeqwerty. This should be behind a restrictive firewall, accessible via VPN.
Answer: DRAC firmware changelogs have security fixes just like anything else, you will want to keep up with those very closely if this is exposed. I'd trust it more if just TCP/443 were exposed. DRACs don't have much in the way of brute-force attack prevention, though.

DRAC with External IP?


Ignorar acentuação ao usar busca no menu (input)

Question: Eu criei um input search e uma lista (menu lateral) abaixo, quando faço a pesquisa está ok, mas estou com problema quando alguma
 tem palavra com acentuação.
Como eu poderia implementar uma expressão regular pra me ajudar?
$(function() {
    $("#buscar-menu").keyup(
        function() {
            var menuBuscado = $(this).val().toUpperCase();
                $(".menu-busca li").css("display", "block");
                $(".menu-busca li").each(function() {
                            if ($(this).text().toUpperCase().indexOf(
                                    menuBuscado.toUpperCase()) < 0) {
                                $(this).css("display", "none");
                            }
                });
        });
});

Answer: É possível criar uma função para esse determinado caso, que seria a remoção dos acentos apenas na consulta, no exemplo abaixo introduzi uma função chamada removeAcento que irá receber um parâmetro(string) e retornar a mesma string sem os acentos, basta fazer isso no input digitado e no texto recuperado dentro da função each do jquery.
Ficando parecido com isso:
function removeAcento(text){
    text = text.toLowerCase();
    text = text.replace(new RegExp('[ÁÀÂÃ]','gi'), 'a');
    text = text.replace(new RegExp('[ÉÈÊ]','gi'), 'e');
    text = text.replace(new RegExp('[ÍÌÎ]','gi'), 'i');
    text = text.replace(new RegExp('[ÓÒÔÕ]','gi'), 'o');
    text = text.replace(new RegExp('[ÚÙÛ]','gi'), 'u');
    return text;
}

$(function() {
  $("#buscar-menu").keyup(
    function() {
      var menuBuscado = removeAcento($(this).val().toUpperCase());
      $(".menu-busca li").css("display", "block");
      $(".menu-busca li").each(function() {
      if (removeAcento($(this).text()).toUpperCase().indexOf(
        menuBuscado.toUpperCase()) < 0) {
        $(this).css("display", "none");
      }
    });
  });
});

Referência:
Remove accents/diacritics in a string in JavaScript
glmxndr
Comment: Feito, adicionado como referência ao código
Comment: Eu não ia negativar, mas me perdoe, eu tive, porque eu acho muito incorreto a atitude de alguns usuários de pegar algo pronto e colar na resposta e nem no mínimo creditar os autores ou a postagem original que lhe ajudou em parte do código. Peço que sempre o faça, porque as pessoas merecem algum reconhecimento, assim como se você formular um código e outra pessoa usar ela também deve lhe citar, não é regra, mas é uma questão de cordialidade. Prometo até lhe positivar se o fizer e por favor não leve pro lado pessoal, é apenas uma critica construtiva.
Comment: Outra sugestão, esse código não é bom, recomendo tentar outros mais completos, que incluem `ç` ou usando o proprio `NFD` (veja sobreo  NFD e outros em https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/String/normalize)
Comment: @GuilhermeNascimento, pode ter sido descuidado e ignorante com o "criador" dessa função de minha parte, mas não faço a mínima ideia de quem seja o autor, uso essa função em meu código a anos para corrigir esse mesmo problema da pergunta à cima, para as próximas perguntas antes de usa uma função que não criei irei pesquisar se acho o autor, muitas vezes pode ser até difícil pela quantidade de função duplicadas que deve existir, mas obrigado pelo conselho de citação do autor, irei prestar mais atenção isso, criticas construtivas sempre são bem vindas!
Comment: Em codecs nada é perfeito de se controlar, a não ser que tudo seja muito bem feito por parte do autor da pergunta, é claro, mas de qualquer forma uma sugestão que possa resolver melhor, maiusculos, minusculos, utf vs iso-8859-1/latin e outros seria o uso disto https://stackoverflow.com/a/37511463/1518921, se editar a resposta eu posso remover o downvote, pq depois de 40 min não é mais possivel remover a não ser q vc edite, é um bloqueio do sistema. Fico no aguardo


Git clone/push/pull - where's that username comes from?

Question: I've set up gitosis and able to pull/push through ssh. Gitosis is installed on Debian Lenny server, I'm using git from windows machine (msysgit). The strange thing, if I enable loglevel = DEBUG in gitosis.conf, I see something like this when doing any actions with gitosis server:
D:\Kaze\source\test-project>git pull origin master
DEBUG:gitosis.serve.main:Got command "git-upload-pack 'test_project.git'"
DEBUG:gitosis.access.haveAccess:Access check for 'email@example.com' as 'writable' on 'test_project.git'...
DEBUG:gitosis.access.haveAccess:Stripping .git suffix from 'test_project.git', new value 'test_project'
DEBUG:gitosis.group.getMembership:found 'email@example.com' in 'test'
DEBUG:gitosis.access.haveAccess:Access ok for 'email@example.com' as 'writable' on 'test_project'
DEBUG:gitosis.access.haveAccess:Using prefix 'repositories' for 'test_project'
DEBUG:gitosis.serve.main:Serving git-upload-pack 'repositories/test_project.git'

From 192.168.175.128:test_project
 * branch            master     -> FETCH_HEAD
Already up-to-date.

Question is: why am I firstname.lastname@example.com? This email is in global user.email config variable, too.
Yesterday, when the gitosis was installed, it seen me as kaze@KAZE, this is the name under which I was added to gitosis-admin group (and it worked). But today git (or gitosis) started to see me as firstname.lastname@example.com. This is true for all repositories I push or clone. I had to add this address to gitosis.conf directly on server to be able to edit configs again (it worked). There are 2 public keys in keydir: email@example.com and email@example.com, their content is identical and they have kaze@KAZE at end. Origin URL looks like git@lennyserver:test_project.
Now, the question is - why Git (or gitosis) suddenly decided to call me by email instead of name@machinename? I've changed a couple things trying to set up Gitosis (updated git on server to 1.6.0 for example), but maybe I broke something in my local git installation?
Comment: Did you by any chance push to the repo then afterwards in msysgit enter your username and email address?
Comment: Nope, AFAIR. It works this way even if I clone repo to a new folder.
Answer: From Gitosis' point of view, your name is just the name, in keydir, of the public key that you authenticated with.  No configuration on your local machine matters, except as it affects what public key you use, and the string at the end of the key doesn't matter -- just the filename.
You've given your public key two names, so when you authenticate with that key it is undefined which one of them it finds when it looks for a name for that key.  When you changed some other things in Gitosis, presumably it happened to change the arbitrary choice of which name it found.
(Specifically, I believe Gitosis generates its own authorized_keys to contain all the keys in keydir, one per line, with options to tell sshd to only let the user run Gitosis, only in a controlled manner, and telling Gitosis the name of the key.  If multiple lines have the same key, I'm not sure which one sshd ends up using -- maybe the first, maybe the last, maybe it's arbitrary.  The order in which Gitosis writes them may also be arbitrary.  But really the details of how the arbitrary choice happens are beside the point, because nobody guarantees they won't change in the next update to sshd or gitosis.)
You should pick which name you want to use to refer to yourself in the Gitosis config, and keep in keydir only the copy of your key under that name.


Is there a mathematical symbol for "For every element"?

Question: Is there a mathematical symbol that means "For every element"? I want the meaning to have similar function as an iteration, say for loop.
Comment: In writing, you'll probably be better off being clear and using words, not symbols.
Comment: What about the "for all" quantifier, i.e. $\forall$?
Comment: Your question would be much clearer if you gave an example of an actual use. Maybe you are looking for induction? E.g. *"By induction over $i\ge 2$, define $a_i=a_{i-1}+a_{i-2}$."* This applies to any well-ordered set.
Comment: @drum: If I understand your last comment, no; unless you happen to have some enumeration indexed by $\mathbb{N}$, in which case the usual way of writing it is "for $i=1,2,3,\ldots$"
Comment: I don't think that counts since it takes all elements at once and is not iterable.
Comment: @ArturoMagidin: Yes that's what I meant. If you say so, I guess I have no choice but keep writing that over and over again...sigh...time to invent a new symbol!
Comment: You can write for i in range (a,b) by specifying the two ends.
Answer: This should work.
$\forall x\in A\cdots$
Comment: For all x in A. You have it backwards.
Comment: These conditions should be separate. It would be too easy to think that this means "for all elements in A" it should read: ∀x; x ∈ A. Which separately says "for all x" and then "x is an element of A".
Comment: Just to make sure I follow, this means something along the lines of "for all x containing member A", right?
Comment: @ashley That's not always right. *Some* systems of logic admit unrestricted comprehension: "for all $x$ (in the universe)". But in many logics (esp. type and set theories) admitting that kind of construction leads to contradictions. E.g. Russell's paradox can use unrestricted comprehension to construct the set of sets that do not contain themselves.
Comment: Unrestricted comprehension puts you in Russell Paradox territory.  All discussions demand a context.
Answer: I still think the universal quantifier is the answer you are looking for.
From the wording you use e.g. "loop" and "iteration", I infer that your confusion might be coming form the fact that in mathematics there are no variables only constants (here I using the meaning from computer science). For example when you define $x = 2$, even if mathematician would say it is a variable, in fact (in computer science sense) it is a constant: you set $x$ only once, and afterwards it does not change. If it would, then we would have a contradiction i.e. $x = 2 \land x \neq 2$ (please note, that if there are other $x$-es in the text, it just means that those are different constants, but with the same name).
So, when computer scientist wrote
for i from 2 to n do
    a[i] := a[i-1] + a[i-2]

then mathematician would write $\forall i \in \{2,\ldots,n\}.\ a_i = a_{i-1} + a_{i-2}$. The order does not matter, $a_i$-s are constants that are defined by such recursive formula and that's it. You might not know how many solutions there are (none, single, many?), but usually you do if the formula is simple enough. You don't care how to compute it, how much time would it take or worry if you have enough memory to calculate it--those problems are just uninteresting :-)
Welcome to mathematics!
P.S. Naturally, there are domains of mathematics (notably theoretical computer science :D) in which you do care about such things, I am just teasing you ;-)
Comment: How might you extend this notation to higher dimensions.  This would be useful for nested loops. For example $\forall i\in \{1,\dots,I\}, \ \forall j\in \{1,\dots,J\}, \ \forall k\in \{1,\dots,K\}\ \  a_{ijk}=\cdots$.  However this notation seems a bit cumbersome at higher dimensions.
Comment: @AaronHendrickson Note, that even the identifier with indices $a_{i, j, k, l, m, n, \ldots}$ is cumbersome at higher dimensions. On the other hand, observe that $\forall i \in I.\ \forall j \in J.\ a_{i,j} = \ldots$ is equivalent to $\forall (i,j) \in I \times J.\ a_{i,j}$. So, in higher dimensions, instead multiple indices one would use tuples, and then quantify over product of relevant sets. For example, if we wanted $i_1 \in I_1$ and so on up to $i_k \in I_k$, then we could set $\mathcal{I} = \prod_{j=1}^{k}I_j$ and write $\forall \bar\imath \in \mathcal{I}.\ a_{\bar\imath}=\ldots$.
Comment: You say that there variables can't vary in maths, but when you do `∀i` isn't the `i` a different value each time ?
Comment: @Pacerier There is no "each time" (because there is no time). If you want to use time, then they would be there all at the same time. The exact meaning of the quantifier is a bit more involved, but a rough simplification would be that you get a bunch of formulas $a_{34}=a_{33}+a_{32}$, $a_{5426}=a_{5425}+a_{5424}$, and so on with every possible/allowed values, and the $i$ is not even there. As I said, that's not technically correct (study logic if you want to know more), but this is a good intuition for quantification over finite sets.
Comment: @dtldarek, So is it that when you do `∀i` for the range 10 to 15, we end up having i1, i2, i3, i4, i5, i6? Thus, it's like an array?
Comment: @Pacerier I'm not sure I understand you. $\forall i \in \{10,11,12,13,14,15\}.\ a_i = a_{i-1} + a_{i-2}$ is roughly $a_{10}=a_{9}+a_{8} \land a_{11}=a_{10}+a_{9}\land a_{12}=a_{11}+a_{10}\land a_{13}=a_{12}+a_{11}\land a_{14}=a_{13}+a_{12}\land a_{15}=a_{14}+a_{13}$. Does that agree with your understanding?
Answer: The very concept of "doing something in some order" doesn't really make sense in mathematics. Things are defined once and for all, the whole set exists "all the time". This has the great advantage that there is no ambiguity: "do you mean, the variable at position $n$ before or after we looped past it?"
If you come from imperative programming, you may be surprised that it's possible to do any useful stuff when you're not allowed to modify something after its definition. But it's quite possible – also in programming! What you could write in C as
int v[14];
v[0] = first_value;
for(int i=1; i<14; ++i)
  v[i] = function_for_next(v[i-1]);

can also be written, without explicit mention of an "order" in which the set is traversed, as recursive buildup of e.g. a linked list. In Haskell,
v = vBuild 0 firstValue
     where vBuild 14 _ = []
           vBuild i lastValue
               = lastValue : vBuild (i+1) (functionForNext lastValue)

or simply
v = take 14 $ iterate functionForNext firstValue

This also works for arbitrarily more complicated examples, in fact you only need a very simple notational system to calculate anything that can be calculated at all. And in mathematics, you're usually not so much interested in how to calculate results (so it's not a problem if some calculations are a bit less efficient without explicit state, mutable variables, iterations etc.), but it's always very important that expressions aren't ambiguous so you can prove various properties.
Comment: Do you mind elaborating the last paragraph with an example? It's hard to wrap around my head the "Why would maths not be concerned with how results are worked out"?
Comment: @Pacerier mathematical theorems are often formulated like "there exists $X$ such that $P$", without any direct elaboration as to how $X$ can actually be obtained. In fact, for some examples like [Banach-Tarski](https://en.wikipedia.org/wiki/Banach%E2%80%93Tarski_paradox) it's not really possible to [construct](https://en.wikipedia.org/wiki/Constructivism_(mathematics)) the concrete solution, instead its existance is inferred from an [axiom](https://en.wikipedia.org/wiki/Axiom_of_choice).
Comment: What are good examples of "there exists `X` such that  `P`"?
Comment: @Pacerier [Picard-Lindelöf](https://en.wikipedia.org/wiki/Picard%E2%80%93Lindel%C3%B6f_theorem): there exists a unique solution to any Lipschitz-continuous ODE. [Nash existance theorem](https://en.wikipedia.org/wiki/Nash_equilibrium#Nash.27s_Existence_Theorem): in a game with a finite number of players who can choose from finitely many pure strategies, there exists a Nash equilibrium. [Borsuk-Ulam theorem](https://en.wikipedia.org/wiki/Borsuk%E2%80%93Ulam_theorem): for any continuous mapping from the $n$-sphere, there exists a pair of antipodal points with identical function values.
Answer: From your comments, it seems that you want to take the elements of your index set in a specific order, as in an iteration.
There is no single symbol for that; the general shorthand only works when the index set has order type $\omega$, that is, it is indexed by $\mathbb{N}$, in which case the standard way of signaling this would be "for $i=1,2,3,\ldots$".
Answer: Looking for a formal notation for the same, I think that $\{\dots\}$ should be the right answer, either $\{1,2,3,4,5\}$ or $\{x$ $|$ some condition here$\}$
Then a 'loop' that, say, gives the double for every element of a set $A=\{x$ $|$ some condition here$\}$, can be written as $\{y$ $|$ $\forall x\in A,$ $y=2x\}$
As per programming, depending on the application it makes sense to loop a set. For example in python there is the set() function that ensures that a collection of values (i.e. a list or a tuple) is a set (with no duplicates,) and is definitely iterable.
Answer: Representing for what is shown this as incident cofinal retreats will work.
$\forall \in_n:\in_n \in A$
$A$ would be cofinaly filtered if $\langle \in_n,\geq \rangle$ is prime in element number.


How to make ImageButton look pressed in libgdx?

Question: I am using ImageButton in my game and I want to show it touched or pressed. How can I accomplish this, I am new to libgdx framework.
TextureRegion btLeft = new TextureRegion(new Texture("NUMBEROFF.png"));
        Drawable drawableLeft = new TextureRegionDrawable(new TextureRegion(btLeft));
        buttonLeft = new ImageButton(drawableLeft);

Answer: There are different constructors for ImageButton that allows you to add multiple Drawables for when the button is in different states (up, down, and checked). But I prefer to use the ImageButtonStyle to do this.
https://libgdx.badlogicgames.com/ci/nightlies/docs/api/com/badlogic/gdx/scenes/scene2d/ui/ImageButton.ImageButtonStyle.html
ImageButtonStyle style = new ImageButtonStyle();
style.imageUp = ...your drawable for up (normal) state
style.imageChecked = ...your drawable for checked state
style.imageDown = ...your drawable for down (pressed) state

ImageButton button = new ImageButton(style);


Template error no rspec-rails

Question: Estou usando o rspec-rails para testar minha aplicação, entretanto ao testar uma view que usa o Ransak para filtros tenho o seguinte erro de retorno:
1) admin/cities/index renders a list of admin_cities
   Failure/Error: render
   ActionView::Template::Error:
   No Ransack::Search object was provided to search_form_for!

Meu controller
def index
  @q = City.search(params[:q])
  @cities = @q.result(distinct: true).page params[:page]
end

Minha view
= search_form_for [:admin, @q] do |f|
  = f.text_field :nome_cont
  table
    tr
      th Nome
    - @cities.each do |city|
      tr
        td = city.nome

Meu teste
require 'rails_helper'
RSpec.describe "admin/cities/index", type: :view do
  city_params1 = {codigo_municipio: 1, nome: 'Maringá', uf: 'PR', municipio: 1}
  city_params2 = {codigo_municipio: 2, nome: 'Maringá2', uf: 'PR', municipio: 1}
  before(:each) do
    assign(:admin_cities, [
      City.create!(city_params1),
      City.create!(city_params2)
    ])
  end
  it "renders a list of admin_cities" do
    render
  end
end

O que poderia resolver isto?
Answer: Adicionar o código seguinte no começo do teste:
before(:each) do
  assign :q, City.ransack
end

Template error no rspec-rails


I'm trying to implement the Lapis JSF Exporter use PrimeFaces 5.3

Question: In 2.1.20 version jsf error occurs and the Project NOT rises

Abr 26, 2016 5:29:21 PM org.apache.catalina.loader.WebappClassLoaderBase checkThreadLocalMapForLeaks GRAVE: The web application [] created a ThreadLocal with key of type [javax.faces.context.FacesContext$1] (value [javax.faces.context.FacesContext$1@1e0429c3]) and a value of type [org.apache.myfaces.context.servlet.StartupFacesContextImpl] (value [org.apache.myfaces.context.servlet.StartupFacesContextImpl@2351d09a]) but failed to remove it when the web application was stopped. Threads are going to be renewed over time to try and avoid a probable memory leak

In the 2.1.28 version jsf the project up and Using the JSF Lapis Exporter occurs Error:

java.lang.UnsupportedOperationException

Fonte: https://github.com/rdicroce/jsfexporter
Answer: After verification , I identified that in my pom.xml file was using the premises " api and impl " MyFaces with the " api and impl " JSF is conflict , after removing the jsf dependencies work.
MY pom.xml...
<dependency>
        <groupId>org.apache.myfaces.core</groupId>
        <artifactId>myfaces-api</artifactId>
        <version>${myfaces.version}</version>
</dependency>

<dependency>
    <groupId>org.apache.myfaces.core</groupId>
    <artifactId>myfaces-impl</artifactId>
    <version>${myfaces.version}</version>
</dependency>

comment or remove...
<dependency>
    <groupId>com.sun.faces</groupId>
    <artifactId>jsf-api</artifactId>
    <version>2.1.28</version>
</dependency>

<dependency>
    <groupId>com.sun.faces</groupId>
    <artifactId>jsf-impl</artifactId>
    <version>2.1.28</version>
</dependency>


How to show the intersection of two compact subsets is compact

Question: Let (X,d) be a metric space and A,B $\subset$ X be two compact subsets.
Show $A\cap B$ is also compact.
I attempted this question by showing the intersection is bounded and closed.
But I stated that Bounded and Closed $\Rightarrow$ Compact (Heine-Borel) but I didn't realise this only holds for $\mathbb R^n$.
Most of the other similar problems on here were dealing with $\mathbb R^n$, so how would you go about showing this for a general space X?
Any help would be greatly appreciated!
Comment: Refer to "Topology of Metric Spaces" by S Kumaresan.
Answer: In metric space, any compact subset is closed. In particular, this means $X \setminus B$ is open.
For any open cover $\mathscr{O}$ of $A \cap B$, $\mathscr{O} \cup \{ X \setminus B \}$ will be an open cover of $A$. Since $A$ is a compact, $\mathscr{O} \cup \{ X \setminus B \}$ has a finite sub-cover $\mathscr{F}$. It is easy to see $\mathscr{F} \setminus \{ X \setminus B \}$ is a finite sub-cover of $\mathscr{O}$ for $A \cap B$. Since the open cover $\mathscr{O}$ is arbitrary, $A \cap B$ is compact.
Comment: This makes a lot of sense, thanks! So just to clarify the definition of compactness, in $R^n$ you can say $A\ Compact \Leftrightarrow A\ bounded \wedge A\ closed$ but for a general metric space X $\ A \ Compact \Rightarrow A\ bounded \wedge A\ closed$
Comment: @user113867 Compactness is a pure topological concept (compactness = every open cover has finite sub-cover). What you say is not the definition of compactness but they are true.
Answer: This is true for arbitrary Hausdorff spaces, not only for metric spaces.
Try to prove the following slight generalisation: any closed set in a compact space is compact. This should be easy with the usual definition of compactness (any cover admits a finite subcover). If you insist on working with metric spaces, it's even easier, using the definition that a set in a metric space is compact iff every sequence has a convergent subsequence.
Comment: Actually, this is not necessarily true for non-Hausdorff spaces. Take the line with two origins, and the two "intervals" corresponding to $[-1,1]$.
Comment: @ronno: Touche. I thought about a different formulation: intersection of a closed set and a compact set is compact, which is true in general. But of course in non-Hausdorff spaces a compact set need not be closed...
Answer: $A$ is closed in $X$, so $A \cap B$ is closed in $B$. Now, a closed subset of a compact space is compact.


How to do chain rule in matrix calculus?

Question:
$$f(x,y) = \begin{bmatrix} x^2 + y^2 \\ xy \end{bmatrix}$$ and $$g(u,v)=\begin{bmatrix} g_1 \\ g_2 \end{bmatrix}= \begin{bmatrix} 2u -v \\ v-u \end{bmatrix}$$, find $ [f \circ g]'$

I got the derivative matric of $f$:
$$ Df= \begin{bmatrix} 2x & 2y \\ y & x \end{bmatrix}$$
And, I can not figure out the correct derivative matrix of g: should it be $ \begin{bmatrix} \frac{\partial g_1}{\partial u} & \frac{\partial g_2}{\partial u} \\ \frac{\partial g_2}{\partial v} & \frac{\partial g_1}{\partial v}\end{bmatrix}$ or  $ \begin{bmatrix} \frac{\partial g_1}{\partial v} & \frac{\partial g_2}{\partial v} \\ \frac{\partial g_1}{\partial u} & \frac{\partial g_2}{\partial u}\end{bmatrix}$ for taking  chain rule correctly? Which one is correct and why?
Thanks in advance.
Comment: Hmm, I think the key phrase in the first sentence of that article is "especially over spaces of matrices". If we're dealing with functions that take a matrix as input, then we're doing matrix calculus. But if we're dealing with functions that take a point in $\mathbb R^n$ as input, then we're just doing vector calculus. At least, that's what I think is the difference between vector calculus and matrix calculus. Someone correct me if I'm wrong.
Comment: This is most definitely standard vector calculus... $f,g: \mathbb{R}^2\to \mathbb{R}^2$.
Comment: Tangential comment, but this isn't "matrix Calculus", it's just vector calculus, right? The Jacobian and the multivariable chain rule are standard topics in vector calculus.
Comment: Going by the first paragraph in this [wiki page](https://en.wikipedia.org/wiki/Matrix_calculus#:~:text=In%20mathematics%2C%20matrix%20calculus%20is,especially%20over%20spaces%20of%20matrices.&text=Both%20of%20these%20conventions%20are,(rather%20than%20row%20vectors).) it seems pretty accurate
Comment: You need the [multivariable chain rule](https://en.wikipedia.org/wiki/Chain_rule#General_rule) $\frac{\partial f_i}{\partial x_k}=\sum_j\frac{\partial f_i}{\partial g_j}\frac{\partial g_j}{\partial x_k}$.
Comment: Oh, I think I got what to do from your comment @J.G. Let me add an answer
Answer: Instead of telling you which is the correct formula for the Jacobian of $g$, let me just tell you that
$$
(f\circ g)(u,v)= f(g(u,v))=\begin{bmatrix}
(2u-v)^2+(v-u)^2\\(2u-v)(v-u)
\end{bmatrix}
$$
So, you can compute the derivatives of $f$ with respect to $u,v$ and compare to what you would get by using each of the versions of the Jacobian of $g$ that you mention.
Answer: Expanding on J.G.s comment, call $(u,v) = (\nu_1,\nu_2)$ then we have in tensor notation:
$$ \frac{\partial f_i \circ g}{\partial \nu^j} = \sum \frac{ \partial f_i}{\partial g^k} \frac{\partial g^k}{ \partial \nu^j}$$
Setting $ \frac{\partial f_i}{\partial g^k} = a_k^i $ and $ \frac{\partial g^k}{\partial \nu^j} = b_j^k$ it becomes clear that the matrix of partial derivatives i.e: $Df \circ g$ takes the following form:
$$ D f  \circ g = \begin{bmatrix} \frac{\partial f_1}{\partial g^1} &  \frac{\partial f_1}{\partial g^2} \\ \frac{\partial f_2}{\partial g^1} &  \frac{\partial f_2}{\partial g^2} \end{bmatrix} \begin{bmatrix} \frac{\partial g^1}{\partial \nu^1}  &  \frac{\partial g^1}
{\partial \nu^1}
\\ \frac{\partial g^2}{\partial \nu^1}  & \frac{\partial g^2}{\partial \nu^2} \end{bmatrix} $$
Answer: Here is a somewhat detailed derivation of the chain rule using matrix calculus. We have
\begin{align*}
&f:\mathbb{R}^2\to\mathbb{R}^2\\
&f(x,y)=\begin{bmatrix}f_1(x,y)\\f_2(x,y)\end{bmatrix}
=\begin{bmatrix}x^2+y^2\\xy\end{bmatrix}\\
\\
&g:\mathbb{R}^2\to\mathbb{R}^2\qquad\qquad\qquad\qquad\ \\
&g(u,v)=\begin{bmatrix}g_1(u,v)\\g_2(u,v)\end{bmatrix}
=\begin{bmatrix}2u-v\\v-u\end{bmatrix}
\end{align*}

We obtain
\begin{align*}
\color{blue}{\frac{\partial (f\circ g)}{\partial(u,v)}}
&=\frac{\partial f}{\partial\left(g_1,g_2\right)}\,\frac{\partial g}{\partial(u,v)}\\
&=\begin{bmatrix}
\frac{\partial f_1}{\partial g_1}&\frac{\partial f_1}{\partial g_2}\\
\frac{\partial f_2}{\partial g_1}&\frac{\partial f_2}{\partial g_2}
\end{bmatrix}
\begin{bmatrix}
\frac{\partial g_1}{\partial u}&\frac{\partial g_1}{\partial v}\\
\frac{\partial g_2}{\partial u}&\frac{\partial g_2}{\partial v}
\end{bmatrix}\\
&=\begin{bmatrix}
\frac{\partial }{\partial g_1}\left(g_1^2+g_2^2\right)&\frac{\partial }{\partial g_2}\left(g_1^2+g_2^2\right)\\
\frac{\partial}{\partial g_1}\left(g_1g_2\right)&\frac{\partial }{\partial g_2}\left(g_1g_2\right)
\end{bmatrix}
\begin{bmatrix}
\frac{\partial g_1}{\partial u}&\frac{\partial g_1}{\partial v}\\
\frac{\partial g_2}{\partial u}&\frac{\partial g_2}{\partial v}
\end{bmatrix}\\
&=\begin{bmatrix}
2g_1&2g_2\\g_2&g_1
\end{bmatrix}
\begin{bmatrix}
2&-1\\-1&1
\end{bmatrix}\\
&=\begin{bmatrix}
2(2u-v)&2(v-u)\\v-u&2u-v
\end{bmatrix}
\begin{bmatrix}
2&-1\\-1&1
\end{bmatrix}\\
&\,\,\color{blue}{=\begin{bmatrix}
10u-6v&-6u+4v\\
-4u+3v&3u-2v
\end{bmatrix}}
\end{align*}

A crosscheck by using @PierreCarres result. We have
\begin{align*}
(f\circ g)(u,v)=\begin{bmatrix}
(2u-v)^2+(v-u)^2\\
(2u-v)(v-u)
\end{bmatrix}
=\begin{bmatrix}
5u^2-6uv+2v^2\\
-2u^2+3uv-v^2
\end{bmatrix}
\end{align*}

It follows
\begin{align*}
\color{blue}{\frac{\partial (f\circ g)}{\partial (u,v)}}
&=\frac{\partial}{\partial (u,v)}\begin{bmatrix}
5u^2-6uv+2v^2\\
-2u^2+3uv-v^2
\end{bmatrix}\\
&\,\,\color{blue}{=\begin{bmatrix}
10u-6v&-6u+4v\\
-4u+3v&3u-2v
\end{bmatrix}}
\end{align*}
in accordance with the result above.
Comment: @Buraian: Most often we are used to write a single letter boldface $\mathbb{x}=(x_1,\ldots,x_n)$ when writing $\frac{\partial f}{\partial \mathbb{x}}$ for economical reasons. Here I just wanted to keep your coordinate notation. There is no substantial difference.
Comment: Where did you get the notation $\partial(u_1,u_2)$ I think I've seen something similar for jacobian determinant but not sure


Modify DataFrame in parallel

Question: I have a DataFrame which is fairly big (1 million rows). To keep things simple let's look at a simple DataFrame df1 with only 5 rows:
df1 = pd.DataFrame({'id':      ['1', '2', '3', '4', '10'],
                    'date':    ['4', '5', '6', '7', '8'],
                    'str':     ['a', 'b', 'c', 'd', 'e']})

I want to modify the str-column. For the sake of this example let's say that I want to apply the following function to each row of df1:
def alter_array(i):
    return (df1.str[i] + " a").upper()

for i in range(len(df1)):
    df1.str[i] = alter_array(i)

Is there a way to apply this function in parallel? As the individual rows are independent of each other, this would (I guess) greatly speed up the process.

EDIT: Here is an attempt at it, but this just hangs when I run the script in the terminal:
import multiprocessing as mp
import pandas as pd

def alter_array(df1):
    for i in range(len(df1)):
        df1.str[i] = (df1.str[i] + " a").upper()
    return df1

df1 = pd.DataFrame({'id':      ['1', '2', '3', '4', '10'],
                    'date':    ['4', '5', '6', '7', '8'],
                    'str':     ['a', 'b', 'c', 'd', 'e']})

if __name__ == '__main__':
    pool = mp.Pool(processes = (mp.cpu_count() - 1))
    with mp.Pool() as pool:
        results = pool.map(alter_array, df1)

Answer: You can greatly speed your computation by avoiding the for loops. Could you try this first?
df1['str'] = df1['str'].add('a').str.upper()

If it is still slow you could try:
from dask import delayed

@delayed
def alter_array(df1):
    df1['str'] = df1['str'].add('a').str.upper()
    return df1

df1 = alter_array(df1).compute()

Modify DataFrame in parallel


Usages of private static object in java?

Question: Could someone let me know the places where we need to use private static object in java?
the places i mean is about the reasons behind in using them or the use cases where we need to use them.
Thanks,
Kathir
Answer: Another common use is for the Singleton Pattern:
http://en.wikipedia.org/wiki/Singleton_pattern
public class Singleton {
    private static final Singleton instance = new Singleton();

    private Singleton() {}

    public static Singleton getInstance() {
        return instance;
    }
}

Answer: One common example is for logger.
private final static Logger LOGGER = Logger.getLogger(Something.class);

Or even for constants local to the class.
Answer: example from JDK:
public class HashSet<E>
    extends AbstractSet<E>
    implements Set<E>, Cloneable, java.io.Serializable
{
    static final long serialVersionUID = -5024744406713321676L;

    private transient HashMap<E,Object> map;

    // Dummy value to associate with an Object in the backing Map
    private static final Object PRESENT = new Object();
...


What is the conditional probability if we condition with the empty set?

Question: It's an interesting question I think (or what is most likely I'm missing some subtle details). On one hand, we know that the empty set is independent of any other event so for any $A \in \mathcal{F}:$ $P( A \, | \, \emptyset) = P(A)$, on the other hand, if we write this conditional probability using the definition, we might get that something is divided by zero. So what is $P( A \, | \, \emptyset) :
 \\
P(A)\,, \, 0 \, \,\text{or something undefined ?}$
p.s.: I added zero because intuitively if we know that everything is wrong (our condition) then A must be wrong (like never to happen).
Comment: The probability is not defined in such case.
Comment: Well, by definition, the conditional probability of A given B would be the probability of their intersection / conjunction divided by the probability of B. If B is the empty set you get null probability (the empty set has no measure) and thus would yield division by 0. Thus, undefined.
Comment: How can you elaborate that?
Comment: You can't really ever condition on the empty set. You can condition on a set of probability zero sort of, in the case of continuous random variables, but that isn't proper conditional probability and is really a different construction.
Comment: You can condition on an event of probability 0 by taking a limit, but the result can depend on how you "approach" the null event. This is [Borel's paradox](https://en.wikipedia.org/wiki/Borel%E2%80%93Kolmogorov_paradox).
Comment: $0/0.$.........
Answer: I know it is way too late, but just for other people checking this post: The conditional probability is only defined when the event that has already occurred (B) has a probability greater than zero.
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).