How to center an element related to it's above sibling

Question: I have a simple form as below picture

I want to center "Send" button related to the textarea below "Message" label. If I do this with position absolute, relative and custom margins, it looks different and not centered on different resolutions. I'm also using Bootstrap.
My form is inside a parent div;

              <form className="contact-form">

                ...other elements

Message

                <textarea className="textarea" name="message" />
                <input className="sendbutton" type="submit" value="Send" />
              </form>

So what I'm trying to accomplish is, I want to put "sendbutton" element below-middle of "textarea" element. So far all of my tries were not succesful. How can I center an element to it's sibling responsively?
Comment: Ok add with 'contact form' classes "d-flex" to display flex and justify-content-center" to center all form content
Comment: do you use bootstrap ?
Comment: Yes @AhmedElbessfy I do, but I don't know why it doesn't center the button element
Comment: well @AhmedElbessfy this actually worked, the below answer also has worked tho. But I liked your answer better, but something weird happened. I've changed the button's classname to "btn btn-primary", when I do this it doesn't place well, but when I overwrite the style by "width: 50%" it actually centers the button very well. Why does it needs "width: 50%" ?
Comment: because "btn btn-primary" has "display: block" style rule so it will take as much space as available AKA the full width or 100% width but with "width:50%" the button won't take the full width so there is space to move the button. A little tip: inspect the element and take a look at the "Styles" tab in the Developer tools, you will see a checkbox for each style rule, try uncheck it and see what is happening and don't worry all of the changes are temporary and will go away on reloading
Comment: @AhmedElbessfy thanks a lot for the information. Really appreciated!
Answer:

   .contact-form{
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    }

              <form class="contact-form">

                ...other elements

Message

                <textarea class="textarea" name="message" ></textarea>
                <input class="sendbutton" type="submit" value="Send" />
              </form>

There are other methods too like you can give display: inline-block to form children and set their width: 100% and use text-align: center on the parent. But this is the safest.
Comment: I've already tried this, this doesn't work at all. Also please mention which classes I should apply this template.
Comment: @GLHF check it now. Is this what you need?
Comment: Yes this one has solved the issue, but I wonder why it didn't center the elements (the button and the textarea) since I'm using Bootstrap already.
Comment: I haven't used bootstrap classes much, only the grid system, but maybe there is a conflict? You are using react as I saw className, but even in react you can't use a single tag for textarea, and you need a closing tag. Maybe that was the issue?


Help in figuring an optimum spider speed

Question:
When a spider threw its web at a fly then one end of the spider's web sticks to the fly and the other one to the table's surface. The fly immediately tries to pull away from the spider's web and flies away with a constant speed while the web's thread began to stretch evenly and indefinitely.
  The spider scratched its head for a while then managed to assess the speed with which the fly flies away and decided to jump onto this stretching web's thread to crawl all the way to the fly.

Here is the question

What shall be the speed of the spider if it wants to catch up with the fly while crawling along this stretching evenly and indefinitely spider's web thread?
Comment: Not exactly a realistic scenario, but nevertheless a cute application of the fact that $\int_1^\infty \dfrac{dt}{t} = \infty$.
Comment: Is there actually optimization in the question, as the title implies?
Answer: Let $L$ be the starting length of the thread.  Let $R(t)$ and $S(t)$ denote the positions of the fly and spider, respectively, at time $t$.  Then $R(0) = l$ and $S(0) = 0$.
Then let $r$ and $s$ denote the speeds of the fly and spider, respectively.
Since $R'(t) = r$, we have that $R(t) = L + rt$.  The differential equation for $S$ is a bit tricker, but it comes out to
$$
S'(t) = s + \frac{S(t)}{R(t)} R'(t) \tag{1}
$$
or
$$
\frac{d}{dt} \left( \frac{S(t)}{R(t)} \right) = \frac{s}{R(t)} \tag{2}
$$
You can see either of these formulas directly.
For (1), note that there are two contributions to the spider's speed: his own movement $s$, and the movement gained by the string stretching behind him.
$\frac{S(t)}{R(t)} R'(t)$ is simply the rate of change in the length of the portion of string behind the spider.  For (2), note that if we pretend
the string has fixed length $1$, the spider's speed as a percentage of the length of the string is given by his speed divided by the length of the string.
At any rate, (2) gives
\begin{align*}
\frac{S(t_1)}{R(t_1)}
&= \int_0^{t_1} \frac{s}{R(t)} \; dt \\
&= \int_0^{t_1} \frac{s}{L + rt} \; dt \\
&= \frac{s}{r} \ln (L + rt_1) - \frac{s}{r} \ln L \\
&= \frac{s}{r} \ln \left(1 + \frac{rt_1}{L}\right) \\
\end{align*}
As long as $s, r, L > 0$,
since $\ln$ is unbounded,
there will be some time $t_1$ such that
$\frac{s}{r} \ln(1 + rt_1 / L) = 1$.
Then for this time $t_1$, $S(t_1) = R(t_1)$.
Thus the spider will eventually catch the fly no matter its speed.
Specifically, the spider will catch the fly at time
$$
t_1 = \frac{L}{r} \left( e^{r/s} - 1 \right).
$$


Remover espaços em branco ao contar Javascript

Question: Tenho esse código:

function contar() {
  var num_caracteres;
  num_caracteres = document.form1.txtTexto.value.length;
  document.getElementById("contador").innerHTML = num_caracteres;
  setTimeout("contar()", 100);
}

  <form id="form2" name="form1" method="post" action="">

      <input type="text" name="txtTexto" id="txtTexto" onkeypress="contar()"/>

  </form>

Como fazer para ele não contar os espaços em branco digitados?
Answer: Basta usar .replace(/\s/g,'') do Regex no value do seu Input, sendo assim ele removera os espaços em branco.
Regex tirado dessa pergunta.

function contar(e) {
    var num_caracteres;
    num_caracteres = document.form1.txtTexto.value.replace(/\s/g,'').length;
    document.getElementById("contador").innerHTML = num_caracteres;
    document.getElementById("contadorInput").value = num_caracteres;
    setTimeout("contar()", 100);

}

  <form id="form2" name="form1" method="post" action="">

  <input type="text" name="txtTexto" id="txtTexto" onkeypress="contar(event)"/>

Label:

Input <input type="text"  id="contadorInput" />

  </form>

Comment: e para exibir em um input ao inves da label?
Comment: @BetinhoSilva pronto ! exemplo com label e com input
Answer: Antes de contar a quantidade, você pode remover os caracteres em branco com expressão regular:
num_caracteres = document.form1.txtTexto.value.replace(/ /g, '').length;
Comment: e para exibir em um input ao inves da label?
Comment: basta selecionar um elemento do tipo input e atribuir um value para ele: document.getElementById("elemento-input").value = num_caracteres;
Answer: Use o replace para remover os espaços:
function contar() {
   var textoSemEspacos = document.form1.txtTexto.value.replace(' ', '');
   var num_caracteres = textoSemEspacos.length;
   document.getElementById("contador").innerHTML = num_caracteres;
   setTimeout("contar()", 100);
}


Como calcular taxa custodia tesouro direto

Question: Considere o seguinte investimento:
Capital inicial (C)   = 1000,00 reais
Juros (J)             = 12% ao ano
Período (n)           = 8 anos
Taxa de Custódia (TC) = 3% ao ano

A taxa de custódia (TC) é uma taxa cobrada anualmente sobre o montante acumulado até então. Ela é cobrada à parte e não influencia no montante.
Por exemplo: no 3º ano o montante será M3 = C*(1+J)^n = 1404,93 e o valor de custódia será VC3 = M3*TC = 42,15.
Segue abaixo uma tabela com os valores de custódia calculados para cada ano:

Consigo calcular o total que pagarei de custódia somando as 8 linhas da tabela acima.
Ou seja:
Soma Custódias (SC) = VC1 + VC2 + VC3 ...
SC = M1*TC + M2*TC + M3*TC ...
SC = TC*(M1+M2+M3...)

Assim, chegamos à seguinte fórmula:

Minha pergunta é:
É possível obter uma fórmula de Excel que calcule a soma dos valores de custódia?
Gostaria de uma fórmula que fosse possível colocar em uma célula do Excel e que fizesse referência somente às variáveis C, J, n e TC, sem ser necessário criar uma tabela com os cálculos parciais.
Para ser mais claro:
Só quero preencher as quatro variáveis citadas no começo da pergunta (C, J, n e TC), cada qual em uma célula, e quero ter outra célula que calcule o resultado. Sem necessidade de tabelas.
Comment: Um somatório é representado no Excel pela função SOMA (SUM, se o seu Office estiver em inglês). Você tem que ter todas os elementos a serem somados em sequência, i.e.: em uma mesma linha ou coluna. Daí você pode fazer algo do tipo =SOMA(A1:F1), por exemplo, que somaria o valor de todas as células no intervalo.
Comment: Mas para ter os elementos somados em sequencia eu teria que criar uma tabela, certo? Teria uma forma sem criar uma tabela? Uma fórmula que utilizasse somente as variáveis C, J e n (que estariam cada uma em sua célula)?
Comment: O complicado é que não sei se as fórmulas do Excel têm alguma estrutura de laço. Mas acho que há uma resposta correta para a sua pergunta e espero que você a consiga.
Comment: @RodrigoBorth pelo que entendi ele só quer preencher as quatro variáveis citadas no começo da pergunta e ter o resultado, sem ter que preencher uma planilha. É útil porque se você for variar a quantidade de anos envolvida você não tem que mexer nas informações da planilha. Isso seria algo trivial com um pequeno codigo em Javascript ou VBA, mas creio que o OP tem como requisito fazer isso em Excel puro.
Comment: @RodrigoBorth Sei que criar uma tabela em Excel é fácil. Porém, gostaria de saber se existe uma função no Excel que equivaleria à função de somatória da Matemática. Neste caso, não precisaria de tabela e não seria mágica, seria simplesmente uma implementação de um recurso matemático pelo Excel.
Comment: @Viniciusmss já tentou adaptar sua formula usando PGTO?
Comment: @Renan Exatamente isto Renan. Só quero preencher as quatro variáveis citadas no começo da pergunta. Obrigado.
Comment: agora sim, adicione esse detalhe a pergunta, to tentando uma bruxaria aqui no excel pra ver se da certo
Comment: @Viniciusmss calculei de varias formas diferentes, mas pelo que me parece é impossível... não encontrei uma forma de repetição de função escalonada dentro da função soma(ao meu ver seria a única possibilidade). Conclusão que cheguei pra resolver seria: Calcular o VC1, no VC1 você aplica o J e terá o VC2, no VC2 aplica o J e terá o VC3 e assim por diante, agora só precisaria de uma forma de fazer isso automaticamente N vezes e somar todos esse resultados. não encontrei uma forma de fazer isso, se você encontrar poste aí
Comment: Eu ainda acho que é possível, se o Excel tiver alguma fórmula para trabalhar com [Integrais](http://pt.wikipedia.org/wiki/Equa%C3%A7%C3%A3o_integral).
Comment: @Renan o vinicius achou a formula
Answer: Fórmula para resolver o exemplo inicial:
=B4*SOMARPRODUTO(B1*(1+B2)^LIN(INDIRETO("1:"&B3)))

Considerando que os valores das variáveis estejam nas seguintes colunas:
C   => B1
J   => B2
n   => B3
TC  => B4

Fórmula para calcular a taxa de custódia no TESOURO DIRETO:
A taxa de custódia cobrada pelo tesouro direto é provisionada diariamente. Logo, a fórmula acima não se aplica, pois provisiona anualmente. Segue abaixo o desenvolvimento de uma fórmula mais adequada para calcular a taxa de custódia para títulos prefixados do Tesouro Direto (LTN).
Como a taxa é provisionada diariamente, temos que converter as variáveis iniciais para valores diários:
J   =>  (J+1)^(1/365)-1
n   =>  n*365
TC  =>  (TC+1)^(1/365)-1

Substituindo, a fórmula fica da seguinte maneira:
=((B4+1)^(1/365)-1)*SOMARPRODUTO(B1*(1+(B2+1)^(1/365)-1)^LIN(INDIRETO("1:"&B3*365)))

Anulando operações opostas, fica assim:
=((B4+1)^(1/365)-1)*SOMARPRODUTO(B1*((B2+1)^(1/365))^LIN(INDIRETO("1:"&B3*365)))

Há ainda mais um detalhe: a taxa de custódia começa a ser cobrada em D+2. Por isto, alteramos a parte INDIRETO("1:"&B3*365) para INDIRETO("3:"&B3*365)
Finalmente, chegamos à fórmula definitiva:
=((B4+1)^(1/365)-1)*SOMARPRODUTO(B1*((B2+1)^(1/365))^LIN(INDIRETO("3:"&B3*365)))

Observações Importantes:

O resultado da fórmula é apenas uma estimativa, pois considera que o valor do título irá evoluir uniformemente de acordo com os juros informados. Porém, na realidade, a evolução do valor do título é influenciada também pela expectativa do mercado em relação ao futuro da taxa SELIC. De qualquer maneira, acredito que seja a melhor forma de estimar o total de taxa de custódia que será cobrado ao longo da aplicação. É um valor bem próximo do real, sobretudo se o vencimento do título não for de muito longo prazo e a SELIC não variar muito. Esta fórmula é muito útil para se poder estimar a rentabilidade real de um investimento em título prefixado do Tesouro Direto.
A taxa de custódia cobrada pela BM&FBOVESPA na verdade é 0,3% ao ano.
Além da taxa de custódia há também uma taxa cobrada pela instituição financeira intermediária. Geralmente é algo em torno de 0% a 0,3%. Há um ranking de taxas no seguinte link: http://www.tesouro.fazenda.gov.br/ranking-das-taxas
Você pode adaptar a fórmula para calcular também (ou juntamente) a taxa total da instituição financeira, pois geralmente é calculada da mesma maneira.
Comment: E se solucionou mesmo, marque sua própria resposta como aceita.
Comment: Boa :D Vou testar aqui depois pra ver se vai funcionar direitinho
Answer:
Depois de várias tentativas e muita pesquisa, cheguei a uma conclusão: É impossível reduzir isso a uma unica fórmula no excel.

O que fazer então?
Para facilitar sua vida, sugiro que deixe as 3 primeiras colunas separadas para validação.
A primeira coluna irá representar o ano(preencha quantos anos achar necessário), a segunda coluna o montante e a terceira a taxa de custódia paga nesse ano.

Na segunda coluna, use a função SE para verificar se o ano correspondente da linha é menor ou igual ao periodo. Ex: =SE(A1<=H2;F2*(1+G2)^A1;0) nesse caso, caso verdadeiro ele irá calcular o montante, caso falso deixará como 0.

Pronto, agora é só usar a fórmula que você já tem para calcular a Taxa paga na terceira coluna =B1*I2 como você já verificou na segunda coluna o periodo não precisa verificar novamente, pois o resultado sempre será 0;
Por ultimo use uma célula para calcular o somatória da terceira coluna tendo o resultado final: =SOMA(C:C)

Não é uma formulá para fazer todo o calculo, mas é uma forma de ter o resultado que você quer podendo alterar somente as 4 variáveis que você citou.

Ficará assim:

Correção

É possivel com a fórmula da resposta do @Viniciusmss
Answer: vamos lembrar da somatória de uma progressão geométrica ?
se você tem a série: a^1 + a^2 + a^3 + ... + a^n
a Soma seria: a(a^n -a)/(a - 1)
Se substituir a = 1 + j, no final você terá => (1+j)([1+j]^8 -1)/(j)
O resultado multiplica por R$1000,000 e depois por 3%.
Exemplo: (1+12%)([1+12%]^8 -1)/(12%) = 13,7756563120849
13,7756563120849 * R$ 1000,00 * 3% = 413,269689362547 (Que é o resultado final)
Espero que tenha facilitado a vida de vocês!
abcs.
Comment: Excelente Diogo! Muito obrigado!


Binary strings (words) proof

Question: I was trying to improve myself in proofs before the exams and came across a problem, that no matter what I try, I have no idea how to solve:
Rules for a valid binary word:
1) There are no words of length 1
2) Words of length 2 are "10" and "00" only
3) If the word is longer than 2, it is valid only if it is composed of a shorter valid word, in a way that 1s are kept on the same place and ALL 0s are each replaced with any valid word (even the same)
Prove, that the total count of valid words for the given word length = n equals to:
$$
\dfrac{2^{n}+2(-1)^n}3
$$
I've come up with a few examples:
Word length = 2:
Valid words: 10, 00 (by definition); count = 2
Word length = 3:
Valid words: 110, 100; count = 2
Word length = 4:
Valid words: 1010, 1000, 0010, 1110, 0000, 1100; count = 6
I've tried to prove it using induction, but all I achieved was worthless cycles.
I've even written a simple program to calculate all the possible words for the given length, but that also didn't help at all.
Comment: Thanks. I guessed as much, but still, what about word $0001$? How do you get that?
Comment: I saw this question a few weeks ago.
Comment: Could you please post a link? I was trying to find the same exercise for about two hours
Comment: @Somos sorry, I've edited the description, hope it's more clear now. The point is, that all 0s have to be replaced - you cannot leave any 0 the same
Comment: My apologies, I've made a mistake - it should be correct now. I really should have double checked. 0001 was originally 0010 in my notebook...
Comment: I agree with the strings for $n=4$ after the correction.
Comment: @DonThousand  https://math.stackexchange.com/questions/3445516/complex-mathematical-proof#comment7082980_3445516 -- we didn't answer the question,but we did try to understand it.  The link to OEIS probably has a reference to a proof....
Comment: Hardest part is the number of usable strings into the next step.
Comment: @RoddyMacPhee yeah, I thought about focusing on finding the number of 0s in each step first (which I thought could be used to calculate the number of possible strings), but it really didn't got me anywhere
Answer: I'll give you some help:
1) A previous valid word, is only easily usable to produce part of the next step, if there are exactly the difference in word length number of 0's
2) It immediately follows that only words of length greater or equal to $\lceil {n\over 2}\rceil$ are easily usable.
3) Each 0, can be replaced with a word starting with a 1, or a 0 of length 2.
4) Therefore smaller usable words, produce most of the next step ( in the case $n=5$ word length 3 gives 4 of the supposed 10 without resorting to the next trick.
5) The trick is, any words whose lengths add to the next step, can replace the 0's in 00 ( you can actually generalize this to any doubled zero in a word), This allows word length 3, to produce  8 more words using  this! But some are repeats. (100,10,00)==(00,110,00)  where the first argument is a string getting its 0's replaced, ordering the rest by 0 its replacing.
Comment: Was $\lceil n\rceil$ meant to be $\lceil n/2\rceil$?
Comment: oh and by rule 3 in the OP, the set of all valid binary words is a group under 0 replacement. okay, exception can't get the start ones.

Binary strings (words) proof


SPARQL Construct. How to assign the value of an RDF attribute to an actual RDF variable

Question: My query (excerpt) is roughly this.
CONSTRUCT {
?publication fb:type ?type;
fb:publicationType ?publicationType;
}
WHERE
{
?publication a bibo:Document .
?publication vitro:mostSpecificType ?publicationType .
}

And it returns output similar to...
<rdf:Description rdf:about="https://abcd.fgh/individual/publication12345">
    <fb:publication>Example pub title</fb:publication>
    <fb:publicationType rdf:resource="http://purl.org/ontology/bibo/AcademicArticle"/>
</rdf:Description>

Perhaps a beginner-esque question, but how do I tweak the query such that the output is:
<rdf:Description rdf:about="https://abcd.fgh/individual/publication12345">
    <fb:publication>Example pub title</fb:publication>
    <fb:publicationType>Academic Article</fb:publicationType>
</rdf:Description>

Thanks
Answer: On the assumption that the bibo ontology is in the store you're querying, you can use its rdfs:label property in a property path:
CONSTRUCT {
  ?publication fb:type ?type;
    fb:publicationType ?publicationType;
} WHERE {
  ?publication a bibo:Document ;
    vitro:mostSpecificType/rdfs:label ?publicationType .
  FILTER (LANG(?publicationType) = "en")
}

The ?a vitro:mostSpecificType/rdfs:label ?b is shorthand for ?a vitro:mostSpecificType ?something. ?something rdfs:label ?b, without binding the intermediate term.


What would be the cardinality of $S$?

Question: Let $S$ be the set of polynomials $f(x)$ with integer coefficients satisfying $$f(x)\equiv 1\mod (x-1)$$ and $$f(x)\equiv 0\mod (x-3)$$
What would be the cardinality of $S$?
Second equation means $x=3$ is a root of $f(x)$. That means $f(3)\equiv 1\mod2 $
 and that means $0\equiv 1\mod 2$ which is a contradiction. So $S$ is empty.
Please have a look at the work. Am I right?
Thanks.
Comment: I think you got confused writing your argument. You probably want to say that, since $3\equiv 1 \pmod 2$, then $0=f(3)\equiv f(1)=1 \pmod 2$, which is a contradiction.
Comment: It's rather obvious from context that the congruences of polynomials are intended to take place in the ring $\mathbb{Z}[x]$ (or perhaps some larger ring of polynomials like $\mathbb{Q}[x]$, but it doesn't make a difference since $x-1$ and $x-3$ are monic).
Comment: I'm not sure of the use you give to "congruent to", but imo $\;f(x)\cong 1\mod{(x-1)}\;$ means $\;f(1)=1\;$, whereas I agree with the other one that $\;f(3)=0\;$ . Thus, for example, $\;f(x)=-\frac12(x-3)\in S\;$ ...Am I missing something? I honestly didn't understand what you did with $\;\mod 2\;$ and all that...
Comment: @DonAntonio: I think OP means, for example, that $f(5) \equiv 1 \pmod 4$ and $f(5) \equiv 0 \pmod 2$.
Comment: OP: No, your reasoning is not correct.  $f(3) \equiv 0 \pmod 0$ is kind of meaningless.  You haven't explained what domains these modular equations are supposed to hold over.
Comment: @BrianTung Perhaps, yet why would he use polynomials then? $\;f(x)]\cong 1\mod{(x-1)}\;$ shouild mean, imo, that $\;f(x)=q(x)(x-1)+1\;$ ...I'm not sure, though.
Comment: @DonAntonio I have edited
Comment: @DonAntonio: Although...I just realized that there is no value for $f(5)$ which can be equivalent to $1$ modulo $4$ and to $0$ modulo $2$.
Comment: @BrianTung Please see the edited post. I hope it clears the notation
Comment: @BrianTung And I still can't understand why you care about $\;f(5)\;$ **precisely...
Comment: @StammeringMathematician How in the world $3$ being a root of $\;f\;$ would imply $\;f(3)=1\pmod 2\;$ ?! It would imply $\;f(3)=0=0\pmod 2\;$ ...! I think you better write down **the definition** of your "congruency" .
Comment: @DonAntonio: It's just an example, but it's an example which leads me to suspect that either (a) there aren't any solutions, or (b) I've misunderstood the problem.
Comment: Well, everything is useless and hopeless as long as the OP doesn't clarify completely what that $\;\cong\;$ relation means applied to polynomials...
Comment: @EricWofsey Thank you! That's my point from the beginning...but **no** : it is not that "obvious" as the explanation the OP gave, and still gives, in his post doesn't fit into that...
Comment: @DonAntonio This was asked in a competitive exam(CSIR NET June 2018). I copied the statement of problem as it is. I put $x=3$ in $f(x)\equiv 1\mod (x-1)$. That is how I get $f(3)\equiv 1 \mod 2$. Is it wrong. Thanks for taking time to go through the problem.
Comment: @StammeringMathematician I think I finanlly got it. I think your argument is correct. You can see my proposed answer below.
Answer: Ok, after the very last comment below the question by the OP I think the following can be what was intended: it is given $\;f(x)\in\Bbb Z[x]\;$ s.t. both the following are true:
$$\begin{cases}I\;\;\;f(x)\cong1\mod{(x-1)}\iff f(x)=1+(x-1)p(x)\;,\;\;p(x)\in\Bbb Z[x]\\{}\\
II\;\;f(x)\cong0\mod{(x-3)}\iff f(x)=(x-3)q(x)\;,\;\;q(x)\in\Bbb Z[x]\end{cases}$$
but then we get:
$$\begin{cases}I\;\implies\; f(1)=1=1\pmod 2\\{}\\
II\implies f(1)=-2q(1)=0\pmod2\end{cases}\;\;\;\implies\text{ contradiction}$$
and what the OP did is thus correct: we get that in fact $\;S=\emptyset\;$ .
Comment: This was an interesting question:...and I think it was clear from the very beginning! It is just the proposed solution by the OP succeeded in confusing me...and apparently some others as well.
Answer: Your argument is correct, but mixing the meaning of $\equiv$ between the ring of intergers and the ring of integer polynomials is a dangerous thing to do, because it is not obvious if one equation interpreted as over one ring will hold over the other, or even what interpretation you are using at any given moment.
For a polynomial $p$ I'll use the notion $p(x)$ when I'm talking about the element of the polynomial ring and $p[y]$ when I'm talking about the result of 'applying' $p(x)$ to the integer $y$.
But at least one direction is easy: If $a(x),b(x)$ and $q(x)$ are integer plynomials, and
$$a(x) \equiv b(x) \pmod {q(x)}$$
is true, it is also true that
$$\forall x\in \mathbb Z:a[x] \equiv b[x] \pmod {q[x]}$$
That's because in the ring of integer polynomials we know there exists a polynomial $k(x)$ with
$$a(x)-b(x) = k(x)q(x).$$
Now addition and multiplication of polynomials have been designed such that they 'mimic' the functional evaluation, so we can derive from this that
$$\forall x\in \mathbb Z: a[x]-b[x] = k[x]q[x]$$
which then implies what we wanted to proof.
You applied the polynomial ring interpretation to your equation
$$f(x)\equiv 0\mod (x-3)$$
to arrive at (in my notation)
$$f[3]=0$$
and used the integer ring interpretation of
$$f(x)\equiv 1\mod (x-1)$$
for $x=3$ to get (in my notation)
$$f[3] \equiv 1 \mod 2,$$
which is a contradiction, as you noted. My above proof shows that you can go from the polynomial ring interpretation to the integer ring interpretation. But as I said in the beginning, to prevent errors, one should distinguish between working in one ring and the other, if possible.
Comment: It should perhaps also be mentioned that for the implication you mention to be correct, the statement $a(x) \equiv b(x) \pmod {q(x)}$ must take place in the ring $\mathbb{Z}[x]$ rather than a larger ring like $\mathbb{Q}[x]$ or $\mathbb{R}[x]$, so that $k(x)$ has integer coefficients.  For this particular problem it doesn't make a difference though ($k(x)$ will always have integer coefficients since it can be found by long division by $q(x)=x-1$ which involves no division of coefficients since $q(x)$ is monic).
Answer: If $f$ is a polynomial with integer coefficients, then $f(x)$ is an integer whenever $x$ is an integer. Moreover, if $a$ and $b$ are distinct integers, then $a-b$ divides $f(a) - f(b)$.
In this case, $f$ would need to satisfy $f(1) = 1$ and $f(3) = 0$, meaning that $3-1$ would have to divide $f(3) - f(1) = -1$.
Hence there are no polynomials with those properties.
Answer: $f(x)\equiv  1\bmod (x-1)$ is a congruent condition as polynomials, i.e. $f(x)=1+p(x)(x-1)$ for some polynomial $p(x)\in\mathbb{R}[x]$. In particular, $f(3)=1+p(3)(2)$. Note that $p(3)$ (a priori) does not need to be integer, so saying $f(3)\equiv 1\bmod 2$ is not justified unless you can prove that $p(3)\in\mathbb{Z}$ (which would be true if you can prove $p(x)\in\mathbb{Z}[x]$)
Comment: @DonAntonio I didn't see that $f\in\mathbb{Z}[x]$, and I think with that you can prove that $p(x)\in \mathbb{Z}[x]$.
Comment: Use `\bmod` for the binary operator, that has equal spacing on both sides; for the parenthetical operator, use `\pmod`. Compare `a\equiv b\mod x`, `a\equiv b\bmod x` and `a\equiv b\pmod{x}`:  $a\equiv b\mod x$, $a\equiv b\bmod x$, $a\equiv b \pmod{x}$.
Comment: I agree with the first part, yet about the second one: it is given the polynomial is an *integer* one, and thus we definitely have $\;p(3)\in\Bbb Z\;$ .
Comment: @DonAntonio: Well, the polynomial that is known to be integer is $f(\cdot)$, not $p(\cdot)$.  But I don't agree with a definition of modular equivalence which permits $p(\cdot)$ to hold non-integer values.  Otherwise, any value $x$ could be equivalent to $1$ modulo $2$, simply by using the appropriate multiplier on $2$.
Comment: @BrianTung What $\;p\;$ are you talking about, anyway?
Comment: @DonAntonio: He says that $f \equiv 1 \pmod u$ implies that there is some $p$ such that $f = 1 + p \cdot u$.  We normally require $p$ to be an integer, because otherwise, it's meaningless to say that $f \equiv 1 \pmod u$.  We could say that, for instance, $\pi$ is odd because $\pi = 1 + 2p$, where $p = \frac{\pi-1}{2}$.
Comment: @BrianTung Sorry but I can't understand where you see that anywhere in the original post...
Comment: @BrianTung, it makes sense to talk about modularity seen as polynomials, when you divide two polynomials you can express $f(x)=q(x)(x-3)+r(x)$ where $deg(r)<1$, i.e. $r$ is some constant. In this case they are telling you that $r$ is in fact 1.
Comment: @JulianMejia Again, I can't see where in the Original post, either the edited one of the first one, is there **any** $\;p\;$ at all...!@
Comment: @DonAntonio What does it mean $17\equiv 2\mod 5$? It means that there is some $p=3$ such that $17=2+5p$. But in this case we are looking at polynomials, so $f(x)\equiv 1\mod(x-3)$ means $f(x)=1+(x-3)p(x)$.
Comment: @JulianMejia That I already wrote many comments ago...perhaps with different names. You though seemed to be talking of a very specific, unnamed polynomial.
Comment: @DonAntonio this comment section is from my answer, not from the post. In my answer I explained what was $p(x)$.

What would be the cardinality of $S$?


how to get simple android client and pc server get working

Question: I have a simple server running on my pc and a simple client on my htc desire running android 2.2.
The server and client both use the same port. I hard code the servers ip into the clients code. When I try to connect to the running server via the client on android the client throws this exception:
<code>IOException ...: java.net.SocketException: The operation timed out.
</code>
Here are parts of the client and server codes:
client code
<code>  InetAddress addr;
  Socket socket = null;

  byte [] ipAddress = new byte[] {(byte)82,(byte)168,(byte)175,(byte)141};

  try{

   addr = InetAddress.getByAddress(ipAddress);

   socket = new Socket(addr, 1234);
   System.out.println("socket = "+socket);

   BufferedReader in = new BufferedReader(
            new InputStreamReader(
             socket.getInputStream()));

   PrintWriter out = new PrintWriter(
            new BufferedWriter(
             new OutputStreamWriter(socket.getOutputStream())),true);

        out.println("hello");
        socket.close();
  } catch (UnknownHostException e) {
   System.out.println("UnknownHostException ...: "+e);
  } catch (IOException e) {
   System.out.println("IOException ...: "+e);
  }
</code>
,
server code
<code>    ServerSocket ss = new ServerSocket(PORT);
  System.out.println("Started:"+ss);

  try{
   //block until a connection occures
   Socket socket = ss.accept();

   try{
    System.out.println("Conncetion accepted:"+socket);
    InputStream IS = socket.getInputStream();
    InputStreamReader ISR = new InputStreamReader(IS);
    BufferedReader in = new BufferedReader(ISR);

    OutputStream OS = socket.getOutputStream();
    OutputStreamWriter OSR= new OutputStreamWriter(OS);
    BufferedWriter BW = new BufferedWriter(OSR);
    //output automatically flushed by PrintWriter
    PrintWriter out = new PrintWriter(BW,true);

    while(true){
     String str = in.readLine();
     System.out.println("Client: "+str);
     out.println("hi");
    }
   }finally{
    System.out.println("Closing...");
    socket.close();
   }
  }finally{
   ss.close();
  }
</code>
This code is working using wifi but not through 3g.
Any help is welcome...and thank you in advance.
Answer: You probably use a router/wifi-access-point to connect to internet?
If your router uses NAT protocol, then any devices on the Internet can not open connectio to your PC. NAT only allows PC to open connection to the internet and not vice-versa.
So when your phone is on wifi it can connect to PC because they are both on the same network and NAT is not used. When your phone is on 3g, and hence of the internet, than there is NAT in-between your phone and your PC.
Solution:
Enable port forwarding on your router, than connect with your app to router's IP which will forward this connection to your PC.
Comment: Kengo, thank you for your reply. So this means that if there is NAT there is no tcp connection? Or is there a solution to this?
Comment: NAT does not allow inbound (inet-to-PC) connections. Solution to this is port forwarding.


What is the motivation for semidirect products?

Question: I haven't the slightest idea why (inner or outer) semi-direct group products are an interesting construction. I understand inner direct products, because you're just giving conditions for which a group can be considered the direct product of two of its subgroups, and I "get" direct products. They're a very simple construction, and showing that a group decomposes into that structure is a very strong statement.
But the outer semi-direct product construction seems totally arbitrary and bizarre. What's the intuition, here?
Answer: A very important question in group theory is the extension problem: given groups $H,N$, can you classify the groups $G$ that have $N$ as a normal subgroup with quotient $H$? In other words, groups that fit in a exact sequence $1 \to N \to G \to H \to 1$. Motivation from that comes from the classification of finite simple groups and the existence of composition series: if we could do all of that, and given these two other tools, we could classify all finite groups. That's very interesting!
As it turns out, the extension problem is very hard in general. The direct product $H \times N$ gives a "trivial" example of an extension of $H$ by $N$, but there's not a lot that can be said -- that's only one possible structure, there are many others.
There is one simplification though: split extensions. These are extensions such that there exists a section of the projection $p : G \to H$ (that is, a morphism $s : H \to G$ such that $ps = id$). This class of extension is exactly the class of semidirect products $N \rtimes H$. So semidirect products give a partial answer to the question of classifying group extensions.

I would also argue that the construction is not that far-fetched. I feel like the dihedral group is a great example. It's the set of isometries of a regular $n$-polygon. You've got rotations ($\mathbb{Z/nZ}$) and a symmetry with respect to a given line. Any element can be written as a product of a rotation and either the identity or the symmetry. But when you multiply two such elements, there's an interaction between the rotation and the symmetry and the rotation (it gets changed to the opposite rotation). If you think about it, it means that the dihedral group can be represented as a semidirect product $\mathbb{Z/nZ} \rtimes \mathbb{Z/2Z}$. So another possible answer is that the semidirect product is useful to construct interesting groups, for example the dihedral group.
Comment: So a split extension is one in which the quotient group $H$ has a set of "representatives" ($s(H)$ in your notation) which form a subgroup isomorphic to it?
Comment: Yes, that's pretty much it. If you follow the steps of the proof you'll see that then, $G$ is the (inner) semidirect product $i(N) \rtimes s(H)$ (where $i : N \to G$ is the injection).
Comment: Does it follow that every element of $G$ can be uniquely represented as a product of one of those representatives and an element of $N$?
Answer: Direct products for matrix groups are pretty easy to understand:
$$G\times H = \left\{ \begin{bmatrix} g & 0 \\ 0 & h \end{bmatrix} : g \in G, h \in H \right\}$$
They are just diagonal matrices. Multiplying elements of $G\times H$ can be done by looking at the $G$ and the $H$ parts separately. They have basically nothing to do with each other.
Sometimes though a group acts on something. For matrix groups, they tend to act on vector spaces. If $G$ is a matrix group and $V$ is a vector space for it (so that $V$ is a vector space of column vectors, and $gv \in V$ whenever $v \in V$) then we can form something similar to the direct product with upper triangular matrices:
$$G\ltimes V = \left\{ \begin{bmatrix} g & v \\ 0 & 1 \end{bmatrix} : g \in G, v \in V \right\}$$
In this group the $G$ part can be done ignoring the $V$ part: $$\begin{bmatrix} g & v \\ 0 & 1 \end{bmatrix} \begin{bmatrix} h & w \\ 0 & 1 \end{bmatrix} = \begin{bmatrix} gh & gw+v \\ 0 & 1\end{bmatrix}$$
but the $V$ part (the $w$) is altered by the way the $G$ part (the $g$) acts on $V$.
This sort of factorization happens automatically in some nice cases. For instance if $X$ is a finite group whose Sylow 2-subgroup $G$ is cyclic, or isomorphic to $C_4 \times C_2$, or many other common things, then $X$ automatically has such a $V$ (though it need not be a vector space, but the formulas for multiplication still work).
Also if a finite group has exactly one Sylow $p$-subgroup $V$, then $X$ has a $G$. Again $V$ need not be a vector space so $G$ need not be a matrix group, but the formulas still hold.
Comment: There is a inconsistency. It says "V  is a vector space of column vectors" and later you put a v in V as element of a matrix. Can you clarify me that please? I believe both need to be groups. Is the vector space a group, with addition as operator?
Comment: @Santropedro yes, a vector space is an additive group.
Answer: One important idea of a semidirect product $H \ltimes N$ is the group action of $H$ on $N$. The outer semidirect product just shows that any group action of $H$ on $N$ (from another point of view, any homomorphism $H \rightarrow \operatorname{Aut}(N)$) determines a group, in the "obvious way".
So if you want to study groups $G = HN$, where $N$ is normal in $G$ and $H \cap N = 1$, the construction of external semidirect products gives you all possible such groups (and you might want to study these, since there are many important examples of semidirect products, and they are common).
The definition of the operation in external semidirect product is very natural, in $G$ above we have
$$(h'n')(hn) = (h'h)((h^{-1}n'h)n)$$
and now here $n \mapsto h^{-1}nh$ is the group action. So given $H$, $N$ and a group action $\phi: H \rightarrow \operatorname{Aut}(N)$ (with $h \mapsto \phi_h$), to make the set of pairs $(h,n)$ into a semidirect product, we should define
$$(h',n') \cdot (h,n) = (h'h, \phi_h(n')n)$$
and this turns out to work.
Comment: What do you mean by "the obvious way" ?
Comment: Perhaps that is badly phrased. But if you read further, I'm trying to explain why the definition is a bit obvious, and not arbitrary and bizarre.
Answer: For outer semidirect products, there is the splitting lemma saying that the existence of a short exact sequence $1 \rightarrow N \rightarrow G \rightarrow H \rightarrow 1$ gives you that $G$ is isomorphic to a semidirect of $N$ and $H$.
An intuitive understanding of this is a generalisation of orthogonality, which is a property that requires a scalar product. In linear algebra, one probably have seen that an euclidean vector space can be decomposed into $W = V \oplus V^{\perp}$ with componentwise addition. The condition of exactness of this short exact sequence is $im({N \rightarrow G}) = ker({G \rightarrow H})$. Imaging embedding $V$ in $W$ and making a projection on $V^{\perp}$ will satisfy the exactness condition.
But we are looking at groups and their products! So there is no orthongonality available but we found a nice condition, namely the exactness of the short exact sequence, which captures the idea of decomposing the group into a product so that componentwise operations are still possible. The semidirect products look strange at first, but it is just as unusual as nonstandard scalar products at first. They still keep up the property of componentwise operation which is easy to handle.
Answer: When we encounter any group for the first time, a natural question is: how can I do computations in this group? How can I actually take $a$ and $b$ and determine the value of $ab$? This question really breaks down into two parts:

Come up with a suitable notation for elements of the group.
Determine how to, given the notation for $a$ and $b$, find the notation for $ab$.

For example, in kindergarten we all learn how to answer to these requirements using decimal notation for the group of integers. Note that having a good notation for the group is absolutely essential to what we really mean by "performing a calculation", since without specifying a notational scheme in which the answer is to be expressed, we could technically answer the question "what is $2+2$" by saying "it's the integer equal to $2+2$".
How we do this for a given group depends on how we define the group. Many times a group presents itself to us naturally via a generating set. We have in mind some set of elements of an existing group, and consider the subgroup generated by those elements. In that case, it's natural to look for notational schemes involving those generating elements.
A nice case is when the generating set is $A\cup B$, where $A$ and $B$ both generate subgroups $G$ and $H$ respectively, and every element of $A$ commutes with every element of $B$. Since an arbitrary element of $\langle A\cup B\rangle$ can be written as a product of $a_i$-s in $A$ and $b_i$-s in $B$, we can see that by commutativity we can shuffle all of the $b_i$-s over to the right hand side and end up with a product $a_1...a_nb_1...b_m=gh$ for $g\in G$, $h\in H$, so that we now have a nice simple notation for elements of our group: a product $gh$ with $g\in G$ and $h\in H$, or more abstractly just the pair $(g, h)$. Multiplication in this notation is simple: $(g_1h_1)(g_2h_2)=(g_1g_2)(h_1h_2)$ by commutativity, so what we basically have here is a direct product (modulo the caveat that the notation we have chosen may not be unique if $G$ and $H$ have a non-trivial intersection).
More often we don't have commutativity. However, sometimes although the identity $ab=ba$ fails, the weaker identity $ba=ab'$ holds: for $g\in G, h\in H$, there is always an $h'\in H$ such that $hg=gh'$.
Example. Consider the group of permutations on the set of all binary matrices of size $n\times n$. Let's consider all such transformations which can be obtained from the following moves:

Swap two rows.
Swap two columns.
Invert a row (turn $1$-s to $0$-s and vice versa)
Invert a column.

We can break this generating set apart into the set of "row and column swaps" $A$ and the set of "row and column inversions" $B$. Each generates some subgroup. You can check for yourself that if $a$ is a swap operation and $b$ is an inversion operation, then we have $ba=ab'$ for some other (potentially equal to $b$) inversion operation.
This means we can do something similar to what we did previously in our attempt to find a general notation for transformations obtained from our generators. In a general product of $a$-s and $b$-s, we can shuffle all the $b$-s over to right, but at the cost of transforming them into different $b$'s. Still, it remains true that a general element of $\langle A\cup B\rangle$ can be written as $gh$, for some $g\in G=\langle A\rangle$ and $h\in H=\langle B\rangle$. Now, how do we perform multiplications in that notation?
It turns out that this type of situation can always be modelled as a semi-direct product. Suppose that, as above, $ba=ab'$ for some $b'\in B$, for any $a\in A, b\in B$. We can write that $b'$ as $f_a(b)$, since its value certainly depends only on $a$ and $b$. Now what is this function $f_a$? Well, rearranging the equation:
$$f_a(b)=a^{-1}ba$$
So $f_a$ is always an automorphism on the ambient group! More than that, it's a conjugation, so that $a\to f_a$ is a homomorphism from $G=\langle A\rangle$ into the automorphism group.
Now return to the question posted above: how can we multiply together two elements written as $g_1h_1$ and $g_2h_2$? Well, starting from $g_1h_1g_2h_2$, what we want to do is move $h_1$ "through" $g_2$ to get an answer in the proper form. By writing down $h_1$ and $g_2$ as products of elements of $A$ and $B$ respectively, you can see that we have $h_1g_2=g_2f_{g_2}(h_1)$, and so, expressed in "pair notation":
$$(g_1, h_1)(g_2, h_2)=(g_1g_2, f_{g_2}(h_1)h_2)$$
Which is precisely the defining formula for a semi-direct product.
Comment: This is, in my opinion, the most layman-friendly answer.


192.168.1.x more exploitable?

Question: Our IT services firm is proposing a network reconfiguration to use the IP range 10.10.150.1 – 10.10.150.254 internally as they state the current IP scheme using manufacturer defaults of 192.168.1.x is "making it to easy to exploit".
Is this true? How does knowing / not knowing the internal IP scheme make a network more exploitable? All internal systems are behind a SonicWall NAT and firewall router.
Comment: If you don't have an NDA with the IT services company, can you name and shame them? Then everyone here can avoid them due to their lack of clue and a desire to create billable work that achieves nothing
Comment: Thought I would add this question: http://serverfault.com/questions/33810/odd-routing-issue-after-ip-change
 It seems this outlines some problems you may have if you were to go this route.
Comment: Fire them they are "not smart"..
Answer: This will add at best a very thin layer of "security by obscurity", as 192.168.x.y is a way more commonly used network address for private networks, but in order to use the internal addresses, bad boys have to be already inside your network, and only the most stupid attack tools will be fooled by the "non standard" address scheme.
It  cost nearly nothing to implement this, and it offers nearly nothing in return.
Comment: Depending on the size of your network, I'd argue that the cost is much greater than nothing. If you really want to bake the consultants noodle, tell him that you believe that predictability is a foundation of information security, and implementing this change will make the network less secure because it will require you to alter many access control lists and other technical security controls.
Comment: +1 for "costs nothing offers nearly nothing".  I'd question whether or not such a change might not be more of a pain in the a$$ than its worth but if you're REALLY, REALLY concerned... go ahead and use a non-standard IP range.  Just be sure to change your default router passwords and ports... because otherwise its just embarrassing. *grin*
Comment: Another agreement. The change only "costs nothing" on a completely DHCP network that requires no static IP addresses (usually means no servers on the network). It costs headaches and lots of time otherwise.
Comment: +1 Agreed.  I would be wary of anyone who goes to lengths to implement something for the sole purpose of security by obscurity.
Comment: I agree with dr.pooter on this one.  This is a very large change to your infrastructure, with damn near no real benefit.  For a medium sized environment and higher, the logistics (and risks) of this are ulcer invoking.
Comment: I can think of 1 reason they're correct: someone brings in their own router/switch, and it starts handing out 192... IP addresses on its own DHCP. Can be a bitch to find sometimes. If everyone's on the 10 network, the damage will be minimal. Its not much of a security issue (unless they bring a wireless router in).
Answer: Sounds like billable busywork to me.
Aside from the fact that many consumer appliances use the 192.168.x.x address space (which can be exploited, like anything else), I don't feel that really changes the security landscape of a corporate network.  Things inside are locked down, or they aren't.
Keep your machines/devices on current software/firmware, follow best practices for network security, and you'll be in good shape.
Comment: +1 for the "billable busywork" observation. Someone needs to pay their lease up for the year and got creative with their client proposals. =)
Comment: +1 - Perhaps next the burglar alarm company will suggest that you try and paint the exterior of the building in camouflage colors to ward off burglars! Security through absurdity...
Answer: Sounds like your IT firm wants some billable work to me.
The only legit reason I can think of to stay away from the 192.168.0.x or 192.168.1.x subnets are due to the likely hood of having overlapping subnets with vpn clients.  This is not impossible to work around but does add some complication to setting vpn's up and diagnosing issues.
Comment: Yep, this is the only reason I usually choose strange networks like 10.117.1.0/24 for offices that may have users VPNing into them.
Comment: @kashani That is a sensible practice. So sensible in fact, that if you want to use private addresses in IPv6 it is even mandated in [RFC 4193](https://tools.ietf.org/html/rfc4193) to put 40 random bits into the prefix.
Answer: One big advantage to not using 192.168.x.x addressing is to avoid overlap with users' home networks. When setting up VPN it is a lot more predictable if your network is distinct from theirs.
Comment: +1: This is one of two good reasons to change (the other is needing more addresses in the subnet).
Answer: I do not think this is likely.
Any exploit worth its weight will be using all three private subnet ranges for scanning.
Here are some references for your IT,

Article reference: Hacking Intranets Through Web Interfaces, discusses covering even the possibilities of companies using networks like 22.214.171.124/8 and 188.8.131.52/8!
Old Sasser scanned 10/8 and 192.168/16
Answer: (sniff...sniff) I smell ... something.  It seems to be coming from the direction of your IT firm.  Smells like...baloney.
Switching subnets provides, at best, a figleaf of protection.  Nevermind the rest of you isn't covered...
The days of hard-coded viruses is long past, and you'll find that malicious code is "smart" enough to look at the infected machine's subnet, and start scanning from there.
Comment: I was originally going to say "codpiece", but somehow that sounded sturdier than need be...
Answer: I would say it is not more secure. If they break into your router, it is going to show them the internal range anyways.
Answer: As another person said, only good reason to change from 192.168.1.x is if you are using VPN from home routers on the client side.  It's the reason every network I administer has a different subnet because I and my client machines do VPN.
Answer: My guess would be that some drive-by router exploit scripts are hardcoded to go looking at the standard homerouter address.  So their response is "security through obscurity"... except it's not obscure because depending on how the script works, it probably has access to the gateway address.
Answer: Really, it is just an urban legend.
Anyway, their reasoning might be as follows: assume, that the 192.168.x.0/24 range is used more commonly. Then, perhaps, the next assumption will be, that, were there a piece of malicious software on one of the PCs it would scan the 192.168.x.0/24 range for active computers. Disregard the fact, that it would probably use some Windows built-in mechanism for network discovery.
Again - it sounds like cargo-cultism for me.
Answer: Manufacturer defaults are always more exploitable as they are the first options that will be attempted, but the 10 range is also a very well known private range, and - if 192.168 doesn't work - will be the next one tried.  I'd call "bull" on them.
Answer: Both ranges are "private" addresses and equally well known. Get someone else to look after your IT.
Knowing which address range you use internally is of absolutely no advantage. Once someone has access to your internal network they can see what addresses you use. Up to that point it's a level playing field.
Answer: I am not a network guy...but as a Linux person, I don't see how that would make any difference.  Swapping one internal Class C to another doesn't really do anything.  If you are on the network, you will still get the same access regardless of what the IP addresses are.
There may be a tiny difference from the perspective of people who don't know what they are doing bringing in their own wireless routers that would default to 192.168.0/32.  But it is really no more secure.
Answer: Many of today's threats come from inside through careless users executing malware. Although it may not offer much protection, I wouldn't completely dismiss it as urban legend.
It would be called security through obscurity if the protection relied on the obscurity alone (like putting secret document on a public web server with "random" folder name), this clearly is not the case.
Some scripts may be hardcoded to scan 192.168.1.x range and spread its own copy. Another practical reason is that home routers are typically configured with that range, so it may conflict when you set up vpn from the home machines, sometimes causing accidents.
Answer: If an attacker is in position to compromise your internal network, they're in position to know your IP range.
It's sort of like this: If the only protection you're using is your IP address range, I can plug an unconfigured machine into the switch and learn your network configuration in a couple of seconds, just by ARP requests. This is essentially busywork if the only reason behind it is "security".
All pain, no gain.
Answer: Using one addressing class over another offers no real security above and beyond what is already implemented.
There are three major types of privatized IP address classes:
Class A: 10.0.0.0 - 10.255.255.255
Class B: 172.16.0.0 - 172.31.255.255
Class C: 192.168.0.0 - 192.168.255.255
Comment: Sigh. Class based routing has been irrelevant for years. What you actually mean is that there are three private subnets for use.

192.168.1.x more exploitable?


Indexing MongoDB collection in Java

Question: I am creating a collection in MongoDB in the following way and I want to create a 2dsphere index on location field of this collection from Java code. But I am not able to do so.
collection.ensureIndex() method expects a DBObject as a parameter but I cannot pass location to it.
How do I create collection.ensureIndex({"location" : "2dsphere"}) in Java code?
MongoDB allows me to do so in command prompt. But, I want to index it through code written in Java.
BasicDBObject doc = new BasicDBObject("attr1", nextLine[0])
                              .append("attr2", nextLine[1])
                              .append("edge-metro-code", nextLine[6])
                              .append("location", new BasicDBObject("type", "Point")
                                                            .append("coordinates",latLong))
                              .append("attr3", nextLine[9])
                              .append("attr4", nextLine[10])

Answer: ensureIndex() has been deprecated now. You should use createIndex() instead:
MongoClient mongoClient = new MongoClient();
DBCollection test = mongoClient.getDB("testdb").getCollection("test");
test.createIndex(new BasicDBObject("location","2dsphere"));

Comment: can you please share the doc link saying __deprecated__?
Answer: You should construct a new DBObject that represents your index. See the code bellow:
DBObject index2d = BasicDBObjectBuilder.start("location", "2dsphere").get();
DBCollection collection = new Mongo().getDB("yourdb").getCollection("yourcollection");
collection.ensureIndex(index2d);

Comment: how do I use $near for the collection built with above structure of the document? I want to run a query from java which has $near in it. I tried QueryBuilder and BasicDbObject but could not find a right solution for it. Could you please help me on this?

Indexing MongoDB collection in Java


Rules scheduler and views- how to show normal users the schedule?

Question: I am using Rules Scheduler and Flag to handle troublesome users by issuing a one-week ban.  I flag the user with a temporary ban flag, and then the user sees a special block that says "You have been temporarily banned for being a jerk."  I have a rule that automatically schedules the user to be unflagged one week later.
However, I want to show users how much time they have remaining.  My first thought was to create a block/content pane in Views, so I made a view of type Rules scheduler, but when I went to add the UID as a Contextual Filter, I realized that Rules scheduler views only provide these options:

Null
Component name

Is there some other way I can show the user how much time they have until an arbitrary Rules Scheduler action will be evaluated?
What I tried
Based on this question, I added a filter for user-provided identifier, set the value to a garbage value (punishme), and added views_pre_view() as follows:
function MYMODULE_views_pre_view(&$view) {
  global $user;
  if ($view->name == 'punishment_show_details') {
    if ($user->uid) {
      $newvalue = 'punish/' . $user->uid;
      $view->display[$view->current_display]->handler->options['filters']['rules_scheduler']['value'] = 'punish/' . $user->uid;
    }
  }
}

However, this doesn't work; for some reason, when I dpm() the view, the value for filters is empty.
Answer: Why not add a user profile field that stores the ban removal date? Then you could use the "Time ago" formatter with the "Time hence" setting and then just set or unset it using the rule (and it's associated de-ban rule). You can show that field using Views and/or on the user's profile page. Or panels. Or custom code... etc.
Comment: I'll consider this, but my general question is about how to show users the date that a rule that applies to them has been scheduled for, which might be necessary in a variety of other situations where your suggested approach might not work.
Comment: Since all of the Scheduler data is stored inside the `data` column, you'd have to iterate through every Scheduled rule entity and find the matching rule and the grab the information from it. It'd be far easier, faster, and simpler, to just take the rules that creates the scheduled rule and write the metadata into a place like the user profile. Rules and the rules scheduler just isn't currently built for this. But if you wanted to make it more generic, you'd still need to capture the rule save, grab the info you want, and write it somewhere.
Answer: I solved this by creating a view with a filter of user-provided identifier, setting the default value to "changeme," and then adding the following code to a custom module to provide the correct identifier (to match the identifiers used to schedule my rules):
function MYMODULE_views_pre_view(&$view) {
  global $user;
  if ($view->name == 'punishment_show_details') {
    if ($user->uid) {
      $newvalue = 'punish/' . $user->uid;
      $view->display[$view->current_display]->handler->options['filters']['identifier']['value'] = 'punish/' . $user->uid;
    }
  }
}


2 Pagers showing for Views Block

Question: I created a Custom View block in  Drupal 7 which it is simply pulling random "Did you know Tips" for visitors. I created a mini pager for the block to allow visitors to toggle through them (Ajax enable as well for the asynchronous refresh of the block)
Everything is working accordingly except one tiny issue... I have 2 Pagers on my home page??? One is the mini pager under the block which is desired, but an additional Full pager is created at the bottom of my main page. Oddly, it's only found on the main page!!! No other nodes pages have this issue.
It seems that the behavior is along the lines that the additional pager is being "promoted to the front page" however, the content type has that excluded. Is there a way to hide this additional pager in template.php / views-view.tpl.php? Perhaps I missed something along the way?
Answer: In investigating this issue further, I resided to installing the Views Litepager module as it's an increase in performance and it resolved my issue as well with the 2 pagers.
Answer: This issue just happened to me there's a field on the pager detail screen that allows you to set an id for the pager. This is usually set to 0. I updated the id and the second full pager at the bottom of the page went away.
Wanted to post this in case anyone finds this page as I did.

2 Pagers showing for Views Block


Fitting distributions, goodness of fit, p-value. Is it possible to do this with Scipy (Python)?

Question: INTRODUCTION: I'm a bioinformatician. In my analysis which I perform on all human genes (about 20 000) I search for a particular short sequence motif to check how many times this motif occurs in each gene.
Genes are 'written' in a linear sequence in four letters (A,T,G,C). For example: CGTAGGGGGTTTAC... This is the four-letter alphabet of genetic code which is like the secret language of each cell, it's how DNA actually stores information.
I suspect that frequent repetations of a particular short motif sequence (AGTGGAC) in some genes are crucial in a specific biochemical process in the cell. Since the motif itself is very short it is difficult with computational tools to distinguish between true functional examples in genes and those that look similar by chance. To avoid this problem I get sequences of all genes and concatenated into a single string and shuffled. The length of each of the original genes was stored. Then for each of the original sequence lengths, a random sequence was constructed by repeatedly picking A or T or G or C at random from the concatenated sequence and transferring it to the random sequence. In this way, the resulting set of randomized sequences has the same length distribution, as well as the overall A,T,G,C composition. Then I search for the motif in these randomized sequences. I permormed this procedure 1000 times and averaged the results.

15000 genes that do not contain a given motif
5000 genes that contain 1 motif
3000 genes that contain 2 motifs
1000 genes that contain 3 motifs
...
1 gene that contain 6 motifs

So even after 1000 times randomization of true genetic code, there aren't any genes which have more than 6 motifs. But in the true genetic code, there are a few genes which contain more then 20 occurrences of the motif, which suggest that these repetition might be functional and it's unlikely to find them in such an abundance by pure chance.
PROBLEM: I would like to know the probability of finding a gene with let's say 20 occurences of the motif in my distribution. So I want to know the probability to find such a gene by chance. I would like to implement this in Python, but I don't know how.
Can I do such an analysis in Python?
Any help would be appreciated.
Comment: @Josh Sorry, I should have closed this earlier :-(
Comment: @mbq: Perhaps you can reconsider since four people (at the time I posted this) have up-voted it? It seems to be really a basic question of probability buried in a complex context (genetics), and being asked by someone who is an expert in a scientific field but not statistics perhaps.
Answer: I am confident that you can code this in Python and there are likely to be multiple packages that will make the coding easier. I don't  know that I understand the true computational issue you face though. Perhaps if you include a code snippet showing how you are doing the 1,000 iteration randomization it would make things more concrete for someone like me lacking the genetics background.
The first thing that comes to mind though is a Monte Carlo sampling of your distribution. For example, use the random_integers() function in numpy to randomly select a motif out of your list of motifs. Add 1 to a counter if its length is equal to 20 otherwise don't count it. Do this thousands of times and your estimate of Prob(motif_length = 20) is counter / simulation_length.


How to call a button using two variables, in C#?

Question: On the form there are several buttons all within a panel. What I'm trying to do is enable any of the 64 buttons using 2 predetermined variables. The button I enable is dependent on which button was selected previously. Each button has the name:
"button" + # between 1-9 + letter between A-H. I determine the letter using ASCII values.

Example: button3A, button 7H, etc.

The code I have crashes and gives me a null value:
<code>x = Convert.ToInt32(listBox1.SelectedItem.ToString().Substring(0, 1)); x = x + 1;
y = (int)listBox1.SelectedItem.ToString()[1]; y = y + 2;
DB4.Items.Add("" + x + (char)y);
if ((x == 1 || x == 2 || x == 3 || x == 4 || x == 5 || x == 5 || x == 6 || x == 7 || x == 8 || x == 9) && (y == 65 || y == 66 || y == 67 || y == 68 || y == 69 || y == 70 || y == 71 || y == 72))
    (this.Controls["button" + x + (char)y] as Button).Enabled = true;
</code>
Comment: You said all buttons are placed on `panel` but you are searching `button` on **Form's controls**. You need to search **panel's controls**.
Comment: The full exception message as well as where it occurs would be helpful.
Comment: try replacing listBox1.SelectedItem.ToString() with listBox1.selecteditem.value
Comment: Crashes *and* gives you a null value? What does that mean?
Comment: I overlooked that, thank you Berkay!
Answer: (Posted solution on behalf of the OP).
The problem was that I used this.Controls instead of panel1.Controls. Props to Berklay for noticing such a small detail!


What does LS (least square) means refer to?

Question: I have been reading clinical papers and recently come across the term "LS-means", referring to what seems to me as an estimation of some population's mean measure. Obviously, I know what "mean" refers to and I know when one estimates a mean for a population from a sample, one has to put some measure of confidence to it, or a measure of standard error, otherwise it's just a number - this does not seem to be the case with LS-means measure (at least not in the papers I encountered, maybe they just did a sloppy job, I don't have enough knowledge to tell). I also know what "least square" refers to when it comes to regression models or optimization problems.
I have never encountered the combination "LS-mean". I admit that my background in statistics may be lacking since it is not my primary field of occupation. A quick search of online sources doesn't seem to yield a satisfactory explanation of what does this combination of words actually refers to (regression? estimation?) and how does least-squares method (of what I can only assume is optimization) fit with calculating an average measure of a population.
Example of something one may find in clinical literature (paraphrasing):
A clinical trial of a drug was conducted against a matched placebo control group. This trial lasted several weeks. Each week the subjects were tested for symptom severity. The results of the study were presented in a chart "improvement from baseline vs week of treatment". X axis - weeks, Y axis "LS-means change". Change in placebo group was significantly smaller than drug group - hurrah our drug great.
I know that this question is very broad, so to limit the discussion, these are the things I am looking to find out:
(1) Can anyone tell me what "LS-mean" may be referring to in the context of clinical trials (or any experimental work for that matter). It doesn't have to be long and/or exhaustive - a few bullet points with keywords would be great to start my self-education journey.
(2) A good online source or a book for getting up to speed on the topic of "LS-means", whatever it may be referring to.
Thanks.
Comment: " Some of us feel that type III sum of squares and so-called ls-means are
statistical nonsense which should have been left in SAS. "
   -- Brian D. Ripley
      s-news (May 1999)
Answer: Consider the model:
$$
y = \beta_0 + \beta_1 \text{treatment} + \beta_2 \text{block} + \beta_3 \text{year}
$$
Where $y$ is some outcome of interest, treatment is a treatment factor,
block is a blocking factor and year is the year (a factor) where the experiment is repeated over several years.
We would like to recover $E(Y|\text{treatment})$, but it cannot done from this model. Instead we find $E(Y|\text{treatment}, \text{block}, \text{year})$.
However we could average the fitted value from $E(Y|\text{treatment}, \text{block}, \text{year})$, over block and year, and then think of it as
$E(Y|\text{treatment})$. If the model is estimated by least squares (OLS in the linear case), this is the LS-mean (of treatment, in this case).
For a reference on implementation (in R) see this pdf it also covers LS-means from the common models.
Comment: I think it would be fair to mention that your explanation comes from the PDF. Simply referencing the PDF while explaining should be sufficient.
Answer: "In an analysis of covariance model, [LS Means] are the group means after having controlled for a covariate."
The blog On Biostatistics and Clinical Trials has a post with what seems to be a good layman's explanation. References therein are also helpful.


Is this cadence correctly written?

Question: Sorry for the vague question title, I'm not sure how to phrase it more descriptively.

In the following image, I've written in an imperfect I-V cadence for a melody in D major.  I've tried to follow these rules as much as possible:

The melodic note should be at the top of the chord.
The note which is common to both chords should remain the same pitch.
Other notes should transition as smoothly as possible.

I believe I have followed these rules as closely as possible, except the transition doesn't feel smooth, as (assuming I'm using piano), the right hand must completely lift every finger and assign new keys to each.

Question: Is there a better way to complete this exercise?
Comment: We're not typically in the business of checking homework. However, if you re-title your question to be specific to voice-leading for authentic cadences, then this question would be useful to further readers. // Put the tenor line in the top voice of LH to give  yourself more options. Also, there's a 2 octave gap between Bass and Tenor in final voice; max spacing should be a 10th. This would be much smoother if you used a vi chord, voicing: B, B, F#, D moves to A, C#, E, E. Not ideal but better.
Comment: Thanks for the extra information about the 10th!  I didn't know that was an additional rule to keep in mind.  I also wasn't sure if this question was appropriate in its current form (but was concerned about it), and asked this question: https://music.meta.stackexchange.com/questions/2855/are-questions-of-the-form-is-this-correct-acceptable-here/2856#2856 on meta at roughly the same time.
Answer: That's fine for piano writing.  Many of the 'rules' of harmony are about 4-part SATB writing. In that context we could complain about the voice leading I suppose!
Here's a version for SATB. Note that I've tried to give each voice some melodic interest.   And that, as long as it ends on V, there are many ways of approaching an imperfect cadence, not just I, V.
Comment: The alto G quaver rising to an A makes a parallel fifth with the soprano line rising D to E
Comment: Does the "b" mean first inversion? Also, the 10th between alto and tenor in the IV chord, depending on the rules in play, may be considered incorrect spacing.
Comment: Brian and Richard, fair points. I favoured melodic interest over 'correctness'.   Tim, this is for SATB, not piano.
Comment: @Richard on spacing, Absolutely - entirely depends on the school of thought; either an octave or tenth. In school I always used the octave limit to be safe. Never seen a "b" after Roman numeral; meaning there is unclear.
Comment: a,b,c etc. indicate inversions.  A useful system.
Comment: Those tenths are quite stretchy for some players.
Comment: @LaurencePayne Is that system used broadly? I have never encountered it. People typically write: 6/5, 4/3, 4/2 for inversions after Roman Numerals
Comment: It's the system I was taught here in the UK.  We also used figured bass, but as a performance notation, not with Roman numerals for analysis,   Anyway, it's easy to understand and, should you come across it again, you'll now know what it means!
Answer: The A in treble clef gets played in both,(it's the only common note), so your penultimate paragraph isn't accurate. Yes, it's fine, you've gone from a D F# A triad (I) to A C# E (V) making an imperfect cadence.
Comment: Thanks for this; but can you clarify what part of which paragraph exactly isn't correct?  I'm not sure where to look.
Answer: On guitar, the best transition would be to use G (classical music admits 7th chords on V) as the bass note of the chord; which would make it the 3rd inversion but that would move the melodic note which is not what you want.
On piano, well, maybe the first inversion, seeing as C sharp is a half-step from D. I'd say C sharp in bass clef, A stays where it is in treble clef and D moves up to E.
Answer: I think your answer is fine.
Another possibility is to go to an open position for the V-chord:
The A keeps its place as a common note, and the F# goes down to the C# just above middle C.
The chord then has following notes from low to high: A C# A E
Comment: Sorry for the slow response; it's exam season, and I procrastinated digesting these answers.  Thanks for the suggestion about the alternative!  I've never encountered the phrase "open position", but I think I can guess by context what you mean.  I have actually since realized that the fingering 124 to 135 in my existing answer, while holding the 4th finger to make the transition legato, results in a *fairly* smooth transition between the V and the I after all.
Comment: Ahh, the definition of an open position chord is quite straightforward I see:  https://www.ars-nova.com/Theory%20Q&A/Q21.html.

Is this cadence correctly written?


Prove that R and R* are numerically equivalent

Question: I need to prove that $\mathbb{R}$ and $\mathbb{R}^*$ are numerically equivalent (with $\mathbb{R}^*$ being the set without $0$).
I made the exercise, and added the solution within. The bold text is the part i didn't understand.
We define the function $f:\mathbb{R}^* \to \mathbb{R}$ by $f(x)=x$. Because $f$ is one-to-one it follows that $\vert \mathbb{R}^* \vert\leq \vert \mathbb{R}\vert$. By Corollary 15 (of my book) the sets $(0,1)$ and $\mathbb{R}$ are numerically equivalent and so there exists a bijective function $g:\mathbb{R} \to (0,1)$.
This function can be used to define a one-to-one function $h:\mathbb{R} \to \mathbb{R}^*$ where $h(x)=g(x)$ for each $x\in\mathbb{R}$. Thus $\vert \mathbb{R}^* \vert\leq \vert \mathbb{R}\vert$ and by "Schroder Bernstein theorem" follows $\vert \mathbb{R}^* \vert= \vert \mathbb{R}\vert$.
It's obvious i'm missing something here. In what manner do we use the function $g$ to "give" us this function $h$. Thanks!
Comment: The language may be a little clumsy but the concept is clear.  $h=g$ is a bijection, and therefore a $1-1$ function, with range $(0, 1) \subseteq \Bbb R^*$.
Comment: I think i get it. So what it basically says is that we now define a one-to-one function $h$ where for all $x\in\mathbb{R}$ the values of the range of $h$ are equal to the range of $g$ , so within $(0,1)$. Thank you!
Comment: If $f:A\to B$ is a bijection.  And $B\subsetneq C$ and $h:A\to C\supset B =f(A)$ via $h(x) = f(x)$ then $h$ is one to one but is not onto. So we have $g:\mathbb R\to (0,1)$ and $(0,1)\subsetneq \mathbb R^*$ ad $h:\mathbb R\to \mathbb R^*\supset (0,1) = g(\mathbb R)$ is onto to one but not onto ($h(x): h(x)\ge 1$ or $f(x) \le 0$ never occurs.)
Comment: By numerically equivalent, do you mean of the same cardinality? If so, other adjectives you could use are equinumerous or equipollent. (I prefer that last one because of the related term, infrapollent, for when one set can be injected into the other.)
Comment: @J.G. yes i meant same cardinality. They use "numerically equivalent" in my book. I already noticed that the word was less popular/used. Thanks!
Comment: @Wouter Fair enough. I'll add that phrase to my list of synonyms.
Answer: Your proof using the Schroeder-Bernstein theorem is correct.
A simpler proof is as follows: The map $f\!:\>{\mathbb R}^*\to{\mathbb R}$ defined by $f(x):=x-1$ when $x\in{\mathbb N}_{\geq1}$, and $f(x):=x$ otherwise, is bijective.
Comment: That is indeed more simple and easy to understand. Thank you!!


Como apagar um repositório existente com Git?

Question:
Preciso de ajuda para apagar este repositório e para criar um novo, pois toda vez que tento criar aparece essa mensagem. E não consigo enviar o meu projeto para o github. Detalhe: Já exclui ele no github.
Comment: Você pode criar um outro repositório em outra pasta também. Qual a encrenca para não fazer isso?
Answer: Só apagar a pasta .git que está dentro de /site e usar o comando git init novamente. Lembrando que dependendo do seu ambiente a pasta pode não aparecer pois ela é oculta.
Comment: Muito Obrigado broder, já consegui!!!


Exposing a type of field operation (flag lists) for search index view

Question: I installed the flag list operations module which gives me the ability to do operations on my views results. But this flag list operations doesn't show up on my search index view as seen below.
I'm sure there is some parameter or variable that is set in the flag list module that is preventing this operation to show up on the search index view.
What should I be looking for in the flag list module code to enable this operation to show up in the search index view?
Answer: Those flag list operations come from a Views handler; they're applied only to the node entity type in flag_lists_views_data_alter.
The Indexed node isn't a node entity, it's something specific to the search API module (added in search_api_views_views_data). It only contains fields that are indexed, plus any extra stuff search API or contrib modules add on.
I haven't tried it, but you may be able to include the nid in the index, and add a relationship in the View to Content. That would, in theory, give you access to everything that Views knows about for a node.
Failing that, you'll probably have to implement your own Views handler, implement hook_views_data_alter, and find the table whose field handler you need to override (it'll be search_api_index_MACHINE_NAME). The class in includes/flag_lists_handler_field_ops.inc would probably be a good template to start from.
Comment: thanks clive, im totally stuck for the past 2 days. see: http://prntscr.com/i5nmoi  i added a new array to the existing $data array and pointed it to a new handler --- but it still doesn't show up on the "search index" view. I tried to look at the views_bulk_operations.views.inc and see how they did it as that "operation" shows up on the search index view. I'm totally lost on where you find this "table" you speak of. The **extended class** that is used in flag_lists is views_handler_field but views_bulk_operations uses the class **views_handler_field_entity** ...
Answer: Took me a good 20-30+ hours to figure this one out as this involved knowing how Views Handlers work and reverse engineering the flag list module code.
In the case of the flag_list module not working with the search api index, it had to do with creating a new handler. The flag list operations handler was extending the class views_handler_field but you needed views_handler_field_entity for the search api view to see it. I'm not sure why, but I followed the views_bulk_operations module as an example.
From there I copied all the code from the original flag list operations handler code into my new handler that uses the views_handler_field_entity with some modifications in the code that had to do with targeting the nid as the $data array was different from the $data array in the views_handler_field.
Then, to get the flag list operations form to show up, I had to find the form_alter in the flag_lists.module file and have it recognize the new handler I had.
In total I had to modify:

flag_lists.module
flag_lists.views.module
flag_lists_handler_field_ops_xxx.inc (this is my new handler file called xxx)


ISC DHCP/DDNS setup: Static entries for non-dhcp clients

Question: I have set up a local network with ISC BIND9 and DHCP service. New leases trigger the DHCP to add an A and PTR record which works perfectly.
I also added lots of static host entries in the dhcpd.conf. Now I noticed that the DDNS update only works for clients that actually request a lease from the DHCP server. I have a few devices in the network that do not support DHCP. I still added static entries in the dhcp.conf. For those, no lease is requested and now no DNS-records are created. What options do I have to add those static entries in a way that DNS-records get created?
I would prefer to only use the dhcpd.conf if possible.
Greatly appreciate any suggestions!
Answer: I stumbled across this post when looking for info on another issue I have with ISC-DHCP and BIND9.
If your devices aren't requesting DHCP leases then adding static entries to dhcpd.conf won't matter. If you've set a static IP on the devices itself, you'll need to add a DNS A record for those devices.
You'd do it like this:
sudo rndc freeze yourzone
sudo nano /etc/bind/db.yourzone

add your entry at the bottom like so
hostname         A          192.168.X.X

save and exit (but don't forget to increment the serial number at the top by one)
sudo rndc thaw yourzone

Maybe you've already fixed this yourself, but it might be helpful to someone else!
Do the same to the reverse lookup zone if you have one configured.
EDIT: Also make sure the static IP you set is not in the DHCP range, to avoid IP conflicts.
Answer: Add ddns-hostname to the static dhcp definition like so ...
host sark {
    hardware ethernet ....;
    fixed-address ....;
    ddns-hostname "sark";
}


How is this played?

Question: This debate didn't solve this at all.

https://www.reddit.com/r/pianolearning/comments/16n0rtx/how_is_this_played/?utm_source=share&utm_medium=web2x&context=3
How is this played? Do you play the F and then the F, A, D together, or do you not play the first F, and then play the F, A, D together. And if you don't play the F at all, then why do you play the other quarter notes with the exact same notation, or do you not play any of the quarter notes?
Comment: There are **many** very similar questions, the best match seems to be [this](https://music.stackexchange.com/questions/23158/how-to-play-a-note-while-the-same-note-is-being-held) and there is also a related [meta question](https://music.meta.stackexchange.com/a/3504/2600).
Answer: You play the F, A and D at the same time. There is only one F to be played. All other quarter notes are played as they are, and are unimpacted by the "extra" F.
The reason the extra F is there is to communicate to the reader that the F in the D + A + F chord serves as part of the melody.
Comment: Adding to this answer: this is a common feature of keyboard notation (not specific only to the piano but also on the organ and the harpsichord), where the same instrumentist effectively plays multiple separate musical parts (called "voices") and a distinction needs to be made between them so as to make the structure of the music more easily understood.
Comment: What? Why? Why is the F at the start of the measure not played?
Comment: @javabart Think of it as if, instead of a piano, you had an orchestra or a choir. Sometimes, some instruments or singers, each with their own separate part, will end up on the same note (maybe for the same duration, maybe, as in your example, not). The way this is written in the example is how one can make clear for the pianist which part is which - i.e. melody and accompaniment.
Comment: @javabart I think Andy Bonner's answer below raises a good point. The F quarter note slightly to the left of the F half note; it's not at a different time. Both those Fs occur right at the onset of the beat. That answers your question: "why is the F ...?" Just remember that sheet music a tool used to communicate music. Often it's communicating what to play and when. But sometimes it communicates song structure. That's what this "extra" F is; the writer saying "by the way, in case you hadn't noticed, this F at start of the measure works as both part of the D + F + A chord, and also the melody".
Answer: I see one potential point of confusion that other answers haven't covered. You ask about timing, and which notes you play first or play together. You might be asking because the F quarter note appears to the left of the other notes. This doesn't actually mean anything about timing; both the quarter and half note Fs count as "beat one"; it's just that one has to be shifted a bit to avoid overlapping.
This is about the idea of having multiple "voices" at once. This might seem odd since you're not a choir, just one pianist. But the idea is that your one instrument can "suggest" multiple ones at once, or that "if this music were being sung by a choir, here are the notes that one voice would sing."
Let's make up a simple example. Say this is the melody:

Now let's add a few notes:

The way we've notated this, with noteheads sharing a single stem, we're implying that this is not two voices, just a single instrument that can play double stops. But what if this were actually for two singers? On beat one, what happens? Do they both sing F, or does one of them rest? Both could be options:

For singers, those two versions are very different. But for piano, the two examples above will be performed almost exactly the same. You'll press the F key, then the F and A together, etc. So why bother notating it this way? Well, for one thing, even if both examples wind up sounding exactly the same, it shows an idea about the music. Notated music is more than instructions about what to press when. And secondly, you might try to show the different ideas by making some notes louder or more connected than others.
Now, say you want this:

You want to press the F key on beat one, and keep it down while adding A in beat two. This is one way to show it. But so is this:

These two notations say the same thing about timing. The only difference is that the second one shows "two voices." And honestly it might be even clearer than the previous one, in which the tie could be confused for a slur between the F and the A. In the second notation, you still only press the F key once. The quarter notehead is shifted to the left since it can't just overlap the half note, but they happen at the same time. And, as a pianist, you only have the one key to press, but if this were sung, two people would both be singing Fs at that moment.
Comment: But then if you don't play the F quarter note 1) how is that denoted here, and 2) why are we playing all the other quarter notes in the measure?
Comment: I am having a mental block. The two links you used make no sense to me. This all sounds like gibberish to me. "Let's look at what going in the bass clef. You are playing a B for beats 1 and 2 and then playing another B on beat 3, but you also play a D for beats 2 and 3 in the bass. Because you play the D on beats 2 and 3 and the B is also being played on beats 1 and 2, the rest is used to show you what beat to start playing the D." Well no duh, the D doesn't get played with the B, it isn't positioned there. This all sounds like people are saying random things.
Comment: @javabart I'll see if I can edit with clearer examples.
Comment: Solved. It seems insane to me to put notes on the page I am not intended to play, but I get it.
Comment: @javabart Or you could say that you *do* play "both" Fs "at once" in a single key press! That's the thing—on a piano, these "voices" are to some degree "imaginary." But they're still a real idea.
Answer: This notates multiple voices where two voices fall together in one voice. This means you play the a and the f and keep them pressed over the next beat where you add the c. It then requires some differentiated touch to phrase this in such a way that the individual voices are audible.
Alternatively one might increase differentiation by playing certain notes early or late, but this is not specified in the score! If notated you'd expect to find tied grace notes to denote this. If it is not notated you can of course still do so as personal choice, but I see no real advantage from doing so in this particular case.
Comment: The other person above said to NOT play the F quarter note at all though...
Comment: @javabart You do play it, it is just that you can only press down a key once. But you will need to play the note by means of phrasing and articulation.
Answer: To all intents and purposes the very first F crotchet is there to 'make up the numbers'. It is the melody, and also part of the accompaniment, but the melody lasts for 1 beat, while the accompaniment lasts for two. So play F,(at the same time as the A beneath) and hold it down.
As in, this is a piano transcription, with multiple parts. The tails up could have been played by one instrument, tails down by a different one. Writing it out for piano, the sums need to add up, so the F is shown with the top line (stems up), and also middle line (of music), (tails down). So there's no need to play the F twice, just keep it pressed while you play the C after. It's a bit of a stretch, so might benefit from use of the damper pedal.
Comment: @user1079505 - edited: better? I meant ignore as in not play twice, which I gathered OP was confused about.
Comment: Not playing twice doesn't equal ignoring. The voices are notated for a reason.
Comment: I still don't understand. There are some people saying play the quarter note and hold it into the half not, and others saying don't play the quarter note at all. I do not understand why we would write a note that isn't played at all.

How is this played?


Is that possible to find an $N_{\epsilon }$ such that for every $x,n\geq N $, $\sum\limits_{k=n}^\infty \frac{x^k}{k!}>\epsilon$

Question: Is that possible to find an $N_{\epsilon }$ such that for every $x$ and for every $n\geq N_{\epsilon}$, $\sum\limits_{k=n}^\infty \frac{x^k}{k!}>\epsilon$. If yes, what will be the function of $N$ in terms of $\epsilon$?
I'm trying to prove that the Taylor expansion of $e^x$ doesn't converge uniformly to $e^x$. I know how to prove it using sup-difference-test but still trying to prove it directly using definition.
Comment: @AnirbanMandal Only on bounded intervals, not on $\mathbb{R}$.
Comment: The infinite series expansion of $e^x$ does converge uniformly to $e^x$. Please check this [answer](http://math.stackexchange.com/questions/594724/uniform-convergence-involving-ex)
Comment: @JuliánAguirre Thanks for the correction.
Comment: @monotonic: do you want $\sum_{k=n}^\infty x^k/k! > \epsilon$ or $\sum_{k=n}^\infty x^k/k! < \epsilon$??
Comment: $>\epsilon $ to obtain a contradiction of uniform convergence
Comment: Have you tried to evaluate your series at $x=0$? (Hint: you get $0$ if $n\geq1$).
Comment: At x=0, the series equals 1? But now we want the statement hold for all x.
Comment: Please observe that your statement is not logically equivalent to "does not converge uniformly". For proving the negation it is sufficient to find a specific $\epsilon_0>0$, a specific $N_\epsilon$ and a specific $x_0\in\mathbb{R}$ such that $\| e^{x_0} - \sum_{k=n}^{\infty} \frac{x_{0}^{k}}{k!}\|>\epsilon_0$ for all $n>N_\epsilon$.
Comment: Please observe that your statement is not logically equivalent to "does not converge uniformly" (to $e^x$). For proving the negation it is necessary and sufficient to find a specific $\epsilon_0>0$ and a specific $x_0\in\mathbb{R}$ such that for all $N>0$ there is a $n_0 > N$ such that $\| e^{x_0} - \sum_{k=0}^{n_0} \frac{x_{0}^{k}}{k!}\|>\epsilon_0$ . Please ignore my wrong comment above, I was too slow in editing it.
Answer: The series does not converge uniformy on $\mathbb{R}$. If $\sum_{k\ge n}x^k/k!<\epsilon$ for all $x$, then $x^n/n!<\epsilon$ for all $x>0$, which abviously false for $x$ large enough.
However, the answer to your question is no, since for all $x$
$$
\lim_{n\to\infty}\sum_{k\ge n}\frac{x^k}{k!}=0.
$$
What is true is that $\sum_{k\ge n}x^k/k!>\epsilon$ for some (but not all) $x$. Given $n$ let $x_n=(n!)^{1/n}$. Then
$$
\sum_{k\ge n}\frac{x_n^k}{k!}>\frac{x_n^n}{n!}=1.
$$
Comment: I think we should be able to find it since the series doesn't converge to e^x uniformly? Then we can use this to obtain a contradiction?
Comment: I am sorry. I read $<\epsilon$ instead of $>\epsilon$. I will edit acordingly.
Comment: But can we actually find such $x$ in terms of $\epsilon $ though? Just an alternative proof by directly negating the statement.
Comment: Yes, I have added it to the answer.
Answer: Even more demonstrative is to take $x=n$ and to observe that for the degree $n$ term one has
$$
\frac{n^n}{n!}\sim e^n
$$
which gets arbitrarily large as $n$ grows. In total contradiction to the behavior you need to apply the Weierstraß theorem on uniform convergence.


Dynamically Add Customized HTML Form File Input with jQuery

Question: I have some jQuery, JavaScript, and CSS that allows me to customize the appearance of HTML form file inputs. I also have a bit of jQuery that allows users to dynamically add as many files as they need to attach.
The problem I'm having is that after a user selects their first file, presses add, and adds the second file, the behavior of the customized input type doesn't apply.
I have a JSFiddle that you can view here:
JSFiddle - Dynamically Add Customized HTML File Inputs
HTML

  <input type="file" name="files[]">Choose File

JavaScript / jQuery
var CUSTOMUPLOAD = CUSTOMUPLOAD || {};

CUSTOMUPLOAD.fileInputs = function() {
  var $this = $(this),
      $val = $this.val(),
      valArray = $val.split('\\'),
      newVal = valArray[valArray.length-1],
      $button = $this.siblings('.file-button'),
      $fakeFile = $this.siblings('.file-holder');
  if(newVal !== '') {
    $button.text('File Chosen');
    if($fakeFile.length === 0) {
      $button.after('                ' + newVal + '');
    } else {
      $fakeFile.text(newVal);
    }
  }
};

$(document).ready(function() {
    $('.file-wrapper input[type=file]').bind('change click', CUSTOMUPLOAD.fileInputs);
    var counter = 2;
    $('#del_file').hide();
        $('img#add_file').click(function(){
            $('#file_tools').before('
<input type="file" name="files[]"/>Choose File
');
            $('#del_file').fadeIn(0);
        counter++;
        });

        $('img#del_file').click(function(){
            if(counter==3){
                $('#del_file').hide();
            }
        counter--;

        $('#f'+counter).remove();
    });
});

CSS
.file-wrapper{font-size:11px;cursor:pointer;display:inline-block;overflow:hidden;position:relative;}
.file-wrapper .file-button{width:auto;display:inline-block;font-size:14px;font-weight:bold;background:#1468b3;color:#fff;cursor:pointer;padding:8px 20px;text-transform:uppercase;border:1px solid #fff;-webkit-border-radius:5px;-moz-border-radius:5px;border-radius:5px;}
.file-wrapper input{font-size:100px;cursor:pointer;height:100%;position:absolute;right:0;top:0;filter:alpha(opacity=1);-moz-opacity:0.01;opacity:0.01;}

Comment: possible duplicate of [Event binding on dynamically created elements?](http://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements)
Answer: That's because they're dynamically appended, you'd need to use event delegation, e.g
$('#file_container').on('click', 'img#add_file', function(){
        $('#file_tools').before('
<input type="file" name="files[]"/>Choose File
');
        $('#del_file').fadeIn(0);
        counter++;
 });

Full jsFiddle here.
Comment: Thanks man! Works like a champ. I knew I was missing something simple.  I'm more of a back-end PHP developer than UI/UX so I'm trying to learn as I go.
Answer: Since you have dynamic element use event delegation
$('#file_container').on('change click', '.file-wrapper input[type=file]', CUSTOMUPLOAD.fileInputs);

Answer: You might need this check my Fiddle
    var CUSTOMUPLOAD = CUSTOMUPLOAD || {};

    CUSTOMUPLOAD.fileInputs = function() {
    var $this = $(this),
      $val = $this.val(),
      valArray = $val.split('\\'),
      newVal = valArray[valArray.length-1],
      $button = $this.siblings('.file-button'),
      $fakeFile = $this.siblings('.file-holder');
      if(newVal !== '') {
     $button.text('File Chosen');
    if($fakeFile.length === 0) {
               $button.after('                ' + newVal + '');
    } else {
      $fakeFile.text(newVal);
    }
  }
};

$(document).ready(function() {
    $('#file_container').on('change click', '.file-wrapper input[type=file]', CUSTOMUPLOAD.fileInputs);
    var counter = 2;
    $('#del_file').hide();
        $('#file_container').on('click', 'img#add_file', function(){
            $('#file_tools').before('
<input type="file" name="files[]"/>Choose File
');
            $('#del_file').fadeIn(0);
        counter++;
        });

        $('#file_container').on('click', 'img#del_file', function(){
            if(counter==3){
                $('#del_file').hide();
            }
        counter--;

        $('#f'+counter).remove();
    });
});


How to take the integral $\int_0^a x^2\sqrt{a^2-x^2}dx$?

Question: I am not sure if $a$ is a constant or is a parameter. if I take it as a constant therefore I get the following steps:
$$\int_0^a x^2\sqrt{a^2-x^2}dx$$
so usual steps like $t = \sqrt{a^2-x^2}, t^2 = a^2-x^2$ and so on, do not match with the answer.
Comment: @M.Mass here $a$ is a constant and $x$ is the one which varies from $0$ to $a$ . We can be more helpful if you show all the steps after you made the substitution.
Answer: Hint. By the change of variable
$$
x=a\cos t,\quad dx=-a\sin t\:dt,
$$ one gets
$$
\int_0^a x^2\sqrt{a^2-x^2}dx=a^4\int_0^{\pi/2} \cos^2t\cdot\sin^2t\:dt=\frac{a^4}4\int_0^{\pi/2} \sin^2(2t)\:dt
$$ the latter integral is then evaluated classically.
Answer: It can be also done by using the concept of differentiation under integral sign.  Let $$F(a)=\int_0^a x^2 \sqrt{a^2-x^2} dx$$ Then $$F'(a)=\int_0^a x^2 \frac{2a}{2 \sqrt{a^2-x^2}}dx$$ Now write $x^2$ as$-(a^2-x^2-a^2)$ So that $$F'(a)=-a \int_0^a \sqrt{a^2-x^2} dx + a^3 \int_0^a  \frac{dx}{\sqrt{a^2-x^2}}$$ which can be evaluated using classical formulas.