QtQuick.Controls 2.12 does not show focus on buttons

Question: I am using QtQuick.Controls 2.12 and i am trying to display window with 3 buttons where one of the buttons will have focus. With QtQuick.Controls 1.4 everything is fine and Button1 has focus(blue border):

But with QtQuick.Controls 2.12 this is the result:

If i press Tab focus is passed on Button2, Button3, Button1...

I have also tried with force focus but no result.
This is main.qml
import QtQuick 2.12
import QtQuick.Window 2.12
import QtQuick.Layouts 1.3
import QtQuick.Controls 2.12

Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    RowLayout{
        anchors.fill: parent

        Button{
            id: button1
            text: "Button1"
            focus: true
        }
        Button{
            text: "Button2"
            onClicked: {
                button1.forceActiveFocus()
            }
        }
        Button{
            text: "Button3"
        }
    }
}

I am trying to get this when window is started:
Answer: The property that allows highlighting is visualFocus, and if the docs is reviewed:

visualFocus: bool [read-only]
This property holds whether the control has visual focus. This
  property is true when the control has active focus and the focus
  reason is either Qt.TabFocusReason, Qt.BacktabFocusReason, or
  Qt.ShortcutFocusReason.
In general, for visualizing key focus, this property is preferred over
  Item::activeFocus. This ensures that key focus is only visualized when
  interacting with keys - not when interacting via touch or mouse.
See also focusReason and Item::activeFocus.

(emphasis mine)
So you must use forceActiveFocus() but passing one of the reason indicated because if you do not pass arguments the reason is Qt::OtherFocusReason as the docs points out:

forceActiveFocus(reason)
This is an overloaded function.
Forces active focus on the item with the given reason.
This method sets focus on the item and ensures that all ancestor
  FocusScope objects in the object hierarchy are also given focus.
This method was introduced in Qt 5.1.
See also activeFocus and Qt::FocusReason.

forceActiveFocus()
Forces active focus on the item.
This method sets focus on the item and ensures that all ancestor
  FocusScope objects in the object hierarchy are also given focus.
The reason for the focus change will be Qt::OtherFocusReason. Use the
  overloaded method to specify the focus reason to enable better
  handling of the focus change.
See also activeFocus.

(emphasis mine)
So the solution is:
Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    RowLayout{
        anchors.fill: parent

        Button{
            id: button1
            text: "Button1"
        }
        Button{
            text: "Button2"
        }
        Button{
            text: "Button3"
        }
    }

    Component.onCompleted: button1.forceActiveFocus(Qt.TabFocusReason)
}
Answer: it looks like this only works with QML.
(https://doc.qt.io/qt-5/qstyle.html#developing-style-aware-custom-widgets)
Comment: Is this a question?
Comment: I recommend against rhetoric questions in answers. They risk being misunderstood as not an answer at all. You are trying to answer the question at the top of this page, aren't you? Otherwise please delete this post.


Microtonal theorists who go beyond describing temperament and scale construction

Question: I know of a couple of composers and theorists who have written why they prefer a given tuning or number of notes.  But what I am looking for is someone who addresses typical analytical and compositional questions about melody and harmony, but generalized to non-12-tone scales.  For instance, how would one determine whether a given chord progression represents an increase or decrease of tension?  What would be considered smooth voice leading?  Could one establish "functional" harmonic categories like tonic/dominant/subdominant?  Has anyone addressed these questions?
(I hope this isn't closed as an "asking for resources" question - please let me know if I should rephrase).
Comment: Elaine Walker touched on some of these things for the Bohlen-Pierce system in [her talk at the BP symposium in 2010](https://www.youtube.com/watch?v=noBPeHMorVI).
Answer: There are a number of microtonal theorists who can and will answer questions about musical issues and problems concerning the actual use of microtonal materials.
Joe Monzo maintains a website that you would probably find helpful. http://tonalsoft.com/enc/encyclopedia.aspx
You should check out the Xenharmonic Wiki at https://en.xen.wiki/w/Main_Page
Lots of information there, of all kinds.
There is a group on Facebook called the Xenharmonic Alliance that is full of helpful people.  Among them find Paul Erlich, who is one of the primary architects of Regular Temperament Theory, and who has written extensively about the musical uses of 22 tone equal temperament, about the use of harmonic lattices to show harmonic structures in 7-limit tunings, and about regular temperaments. Paul is always very helpful to everyone interested in microtonal theory, from the rawest beginner to other very advanced thinkers in this realm.
Here are his three primary papers.  Start with tFot, the Forms of Tonality paper, then read the decatonic paper, about 22 tET, then read Middle Path.  Go to the Facebook groups and ask him questions.  He can clarify questions which the paper will raise.
http://lumma.org/tuning/erlich/erlich-decatonic.pdf
http://lumma.org/tuning/erlich/erlich-tFoT.pdf
http://dkeenan.com/Music/MiddlePath.pdf
Another person who can be very interesting and enlightening to talk to, especially about medieval music, and neo-medieval music, is Margo Schulter.  She also spends a lot of time on the Xenharmonic Alliance facebook groups.
Hope this is helpful.
Answer: Robert Hasegawa writes on microtonality. A couple of examples:

Clashing Harmonic Systems in Haas's Blumenstück and in vain (Music Theory Spectrum 37/2 [Fall 2015], pp. 204-223)
Gegenstrebige Harmonik in the Music of Hans Zender (Perspectives of New Music
49/1 [Winter 2011], pp. 207-234)

Julia Werntz has written on the use of "functional" microtonality.

Adding Pitches: Some New Thoughts, Ten Years after Perspectives of New Music's "Forum: Microtonality Today" (Perspectives of New Music 39/2 [Summer 2001], pp. 159-210)

The "Forum: Microtonality today" referred to in Julia Werntz's title is a two-part collection of articles that can be found here:

Part 1: Perspectives of New Music 29/1 (Winter 1991), pp. 173-257.
Part 2: Perspectives of New Music 29/2 (Summer 1991), pp. 72-211.

Ben Johnston writes about the function of just-tuned triadic intervals in

"On Sonata for Microtonal Piano", Maximum Clarity and Other Writings on Music (2006, University of Illinois Press).

The open access book Experimental Affinities in Music, includes a discussion of how "microtonality" was handled before "microtonality" existed.

"Chapter Three 'Vieltönigkeit' instead of Microtonality: The Theory and Practice of Sixteenth- and Seventeenth-Century 'Microtonal' Music", by Martin Kirnbauer.

And a few other articles dealing with specific pieces:

"Microtonal Storm and Stress: Georgy Rimsky-Korsakov and Quarter-Tone Music in 1920s Soviet Russia", by Lidia Ader, Tempo 63/250 (Oct. 2009), pp. 27-44.
"Flamenco, Fractals, and the Refigured Past: Three Creative Paths for Implementing Microtones in Contemporary Spanish String Quartets", by José L. Besada, Perspectives of New Music 55/1 (Winter 2017), pp. 5-39.
"Composing a Sound: Giacinto Scelsi's L'âme ailée / L'âme ouverte for violin solo", by Thomas DeLio, College Music Symposium 57 (2017)


como faço uma matriz NxN, sendo N uma variavel(adquirida no input), em python. Pois o exemplo abaixo nao consigo mudar os valores nos indices?

Question: e1 = input().split()
e2 = input().split()
matri, numj = e1
nome, idj = e2
matriz = [[0,0,0],[0,0,0],[0,0,0]] # nao consigo fazer a matriz que seja de escolha do usuario, ou seja uma variavel..
for l in range(0,3):
for c in range (0,3):
    matriz[l][c] = 0

for l in range(0,3):
for c in range(0,3):
    print(f'[{matriz[l][c]:^5}]',end='')
print()

jg1 = input('Jogada 1:').split()
jgl, jgc = jg1
matriz[jgl][jgc]
print(matriz)
jg2 = input('Jogada 2:').split()
jgl2, jgc2 = jg2
print(jgl2)
nesse caso eu não estou conseguindo mudar um determinado indice. Por exemplo, quero mudar o inidice 2x1 de 0 para 2, eu nao consigo... ?
Answer: Se queres mesmo usar listas, pode criar dois laçoes aninhados para adicionar sublistas dentros de outra lista e zeros dentro das sublistas.
N = input("Digite o valor de N: ")
N = int(N)

mat = []
for i in range(N):
    mat.append([])
    for j in range(N):
        mat[i].append(0)

print(mat)

Pra acessar e/ou modificar os índices, use matriz[linha][coluna] normalmente:
entrada = input("Digite os indices: ").split()
linha, coluna = entrada
linha = int(linha)
coluna = int(coluna)
print(f"Linha: {linha}")
print(f"Coluna: {coluna}")

entrada = float(input("Digite o novo valor: "))
mat[linha][coluna] = entrada

print(mat)

Espero ter ajudado. Se não, tente explicar melhor sua dúvida ;)
Comment: Muito Obrigado R.Pinho, deu certo, e era realmente o que eu precisava!!


Asymptotes and Polynomials

Question: Problem:

Let
  $$f(x) = 3\frac{x^4+x^3+x^2+1}{x^2+x-2}.$$Give a polynomial $g(x)$ so that $f(x) + g(x)$ has a horizontal asymptote of $0$ as $x$ approaches positive infinity.

How would I start this? I found the partial fractions expansion of this, but what do I do next?
Comment: Long division of numerator by denominator to write $f(x)$ in the form
$q(x) + \frac{r(x)}{x^2+x-2}$, where $r(x)$ has degree $< 2$.  Then as $x \to \infty$, $r(x)/(x^2+x-2) \to 0$, so the polynomial you want is $-q(x)$.
Answer: Let $a(x)=3x^4+3x^3+3x^2+3$ and $b(x)=x^2+x-2$ so that $f(x)=\frac{a(x)}{b(x)}$.
Since we are dealing with a division of polynomials, there exist two other polynomials $q$ and $r$, such that the degree of $r$ is less than the degree of $b$ and $a=qb+r$, or equivalently
$$
\frac{a}{b}=q+\frac{r}{b}.
$$
Now, since $\deg r<\deg b$, when $x\to+\infty$ we have that $\frac{r}{b}\to 0$, therefore $f$ is asymptotically like $q$ at infinity.
You should be able to find what needs to be added in order to obtain what you want, now.

Asymptotes and Polynomials


Why parenthesis() are not used for some functions like @@IDENTITY

Question: I have seen many functions, on every function I see they have parenthesis() on its end like,
SELECT SCOPE_IDENTITY();

SELECT IDENT_CURRENT('TableName');

But why some function's do not use with parenthesis() like function
SELECT @@IDENTITY;

Answer: @@xxxxx are system functions without parameters which should be treated as read-only variables
Comment: but without parameters fuction uses the () sysmbol
Comment: yes, there are many functions with parenthesis and without parameters, like sys.fn_cdc_get_max_lsn().  They just decided to do it in different ways for many functions.
Answer: I believe that these used to be referred to as "server variables" and so had a "variable-like" syntax rather than a function syntax. They have since been re-defined as functions, but maintain the older syntax for backwards-compatibility.
Unfortunately, I cannot find any online resources presently to back-up this claim, and I think the "server variables" definition had been retired by the 2000 release of the product.

If we take the example of @@ROWCOUNT. In SQL Server 2000 BOL, it's described as:

Returns the number of rows affected by the last statement.
...
This variable is set...

(My emphasis).
Compare that with the current documentation, which refers to it having its value set but now avoids referring to it as a variable (or a function). And, of course, it's modern, enhanced, doesn't have to support backwards compatibility sibling ROWCOUNT_BIG which has normal function syntax. And is explicitly referred to as a function.

I do not believe that Microsoft have introduced any new functions using the @@ variable syntax since before 2000 was released.


Sum of "positive" numbers

Question: Given this definition of a positive real number: $$\forall x\in\mathbb{R},x\geq 0:\Leftrightarrow\exists y\in\mathbb{R},x=y^2$$
how to prove that the sum of two positive numbers is a positive number? It is fairly easy for the product, but not so for the sum.
EDIT: To add a context to this, let's say we define real numbers as the completion of rationals (but I'm not sure whether it needs an order to be defined on the rationals). Then, I'd like to define positivity on real numbers in order to create a total order with $x\geq y$ iff $x-y\geq 0$.
Comment: Assume $a>b>0$. Then there are $x,y$ such that $a=x^2$ and $b=y^2$. Then $(a+b)^{1/2}=x(1+y^2/x^2)^{1/2}=x\sum_{k=0}^{\infty}\binom{1/2}{k}(y/x)^k$.  The completeness (or which ever axiom you have replacing it) tells you that $x\sum_{k=0}^{\infty}\binom{1/2}{k}(y/x)^k$ is a real number. Its square is $a+b$.
Comment: What axioms do you have to work with? (This context would be especially helpful because common definitions of the real numbers often have the conclusion you want included as an axiom)
Comment: Do you mean "... the sum of two positive numbers is a *positive* number"?
Comment: What kind of completion is involved in your construction of $\mathbb{R}$? This is very crucial because we must lift the ordering of $\mathbb{Q}$ to $\mathbb{R}$ along with the construction and then show that this coincide with your definition. Without ordering, we have counter-examples such as $p$-adic fields $\mathbb{Q}_p$, which are Cauchy-completions of $\mathbb{Q}$ under different types of "absolute values". There, it turns out that the positivity, defined as in OP, needs not be preserved under addition. For instance, in $\mathbb{Q}_3$, $1=1^2$ is "positive" but $2=1+1$ is not positive.
Comment: Normally o prove that the sum of positive numbers is positive one doesn't need to do this. For example, if the real numbers were defined as Dedekind cuts of the rationals, then you only need to take two rationals in them that are larger than zero and add them. Since the sum is larger than zero, the sum of the Dedekind cuts is also larger than zero. The argument above is assuming that you wanted to pass through the implication that the sum is a square.
Comment: @MartinR Thanks, I edited my question
Comment: @MoonLightSyzygy Actually, this partially answers my question, because I haven't defined $a>b$ (yet I could say $a-b>0$ and $x>0$ iff $x\geq0$ and $x\neq0$) and the convergence of this power series is yet to prove. Also, I don't want to use Dedekind cuts as they need to define first an order on the rationals.
Comment: @MiloBrandt Please look at my edit (currenty in progress) for details concerning the context.
Comment: @Maxence1402 Those missing details you can complete.
Comment: @SangchulLee I consider the real numbers as equivalence classes of rational Cauchy sequences, but it needs an order to be defined first. My conclusion is that real numbers can't exist without an order defined first on the rationals.
Answer: Perhaps I don't have the whole answer of the edit, but here's how you could show the first part.
If we define the field $\Bbb R$ so that it is totally ordered : see here, then this means, among other things, that
$$ \forall x,y,z \in \Bbb R, \; x \le y \implies x+z \le y+z  \qquad (1) $$
$$ \forall a,b,c \in \Bbb R, \; a \le b \; and \; b \le c\implies a \le c \qquad (2) $$
In this case, if we let $ x=0 $ and $ y, z $ be positive real numbers, we get by $(1)$ :
$$ 0 \le y \implies 0+z \le y+z $$
But $0+z=z \; and \; 0 \le z $, therefore we get by $(2)$ :
$$0 \le y+z $$
Therefore the sum of two positive numbers is a positive number.
EDIT :
Alright, so here is a more "geometrical" way I'm trying to give to prove that the sum of two positive real numbers is a positive real number.
First, we'll assume that the product of two real numbers with the same sign is a positive real number.
Let $a,b \in \Bbb R$ so that $x=a^2$ and $y=b^2$ are positive real numbers (by  definition).
Let's now consider a right triangle $ABC$ where $AC$ is the length of the hypothenus and so that $AB=x, BC=y$.
By the Pythagorean Theorem, we have : $AC^2=AB^2+BC^2=x^2+y^2$.
The fact that $x,y \ge0 $ is not a problem, because $(-w)^2=w^2 \quad \forall \ w \in \Bbb R $.
From now on, if we let $X=x^2, Y=y^2$ and $Z=AC^2$, we get that :
$ \forall \ X,Y \ge 0, \exists \ Z \ge  0 $ so that $X+Y=Z$.
Therefore the sum of two positive real numbers is a positive real number.
Comment: Actually no, and you're using the result in your proof. The point is that I haven't defined yet an order on real numbers. Also, being a total order does not imply that it is compatible with operations. I can define a total lexicographical order on complex numbers but it won't be compatible with operations.

Sum of "positive" numbers


How do I see the text when the text box is really small?

Question: I have a gameObject that I added a Canvas. In this Canvas I have a Text UI element.
The text is not visible, or it may be too blurry to see. (it may be really small)
How do I fix this?
I have best fit selected.
Here is an image:
Answer: A solution to the blurriness is doing the following:
Set the X, Y scale from the inspector to a lower number like 0.2 or even 0.02
Set the font size to larger number like [100, 200] depending on the scale you previously selected.
Expand the text area from the game view so the text is visible or change the overflow property of the text.


Fingering indication for double glissando (Ravel, Alborada del Gracioso)

Question: In this piece, fourth of the five Images Miroirs by Maurice Ravel, there are three "double glissandi", ascending then descending, over white keys of the piano. One of them uses a fourth interval, the next one uses a third interval.
What fingers would you use to perform those glissandi?
Comment: Are you sure it isn't from Miroirs?  That's the suite name according to IMSLP.
Comment: @Babu: Sorry, you're right, it is from the *Miroirs* indeed. I wonder what led me to misremember the title.
Answer: An edition hosted on IMSLP here (PDF page 40) indicates that you should use 4-2 for the ascending glissandi, and 3-1 for the descending ones.
I'm personally not a fan of the 3-1 fingering, because it's harder to rotate the hand so your nails impact the next key (Doing that makes glissandi hurt MUCH LESS on pianos with a stiff action).  On the other hand, it does prevent you from having to pop your elbow up to play the descending glissandi, like you would have to if you were to use 4-2 on the descent.  I'm 100% a fan of the 4-2 ascending fingering.


TO_DATE(SYSDATE, 'YYYY-MM-DD') funciona as vezes

Question: Estou com o seguinte problema:
Utilizo o JDBC para se conectar com o Oracle. E chamo rs.getTimestamp(index) para pegar um campo data.
Quando executo a função TO_DATE(SYSDATE, 'YYYY-MM-DD') o getTimestamp as vezes retorna um valor negativo, as vezes retorna o valor correto.
Sei que o TO_DATE não está sendo usado corretamente, pois ele deve receber uma string. Mas, mesmo assim, eu gostaria de saber o motivo de o resultado variar.
Obs: essa variação só ocorre no getTimestamp do Java. Se eu rodar o TO_DATE diretamente no banco, o resultado é sempre o mesmo.
Obs²: Quando o resultado vem negativo, a data formatada retornada pela função é 0014-03-17 00:00:00.0 e quando vem o resultado correto vem como 2017-03-14 00:00:00.0.
Comment: Talvez isso ajude http://www.guj.com.br/t/formatar-data-no-padrao-dd-mm-yyyy-hh-mm-ss/42479
Comment: `TRUNC(SYSDATE)`? Assim, retira-se a hora.
Answer: Como você disse, o TO_DATE() espera uma string como parâmetro.
Quando você executa  TO_DATE(SYSDATE, 'YYYY-MM-DD') implicitamente o Oracle converte sua query para TO_DATE(TO_CHAR(sysdate), 'DD MONTH YYYY') e como não foi passado o segundo parâmetro para o TO_CHAR(sysdate) ele vai pegar a máscara padrão do seu NLS_SESSION_PARAMETERS.
Dessa forma pode acontecer que algumas datas funcionem com a máscara padrão e outras não.
Comment: Tenho conhecimento disso. Mas a máscara de conversão NLS do oracle é uma só. Eu quero saber o motivo de funcionar AS VEZES. Qual é o padrão pra isso ocorrer? É problema do banco, do driver ou do java?


How do i run node save in background process

Question: I have created drupal website for ecommerce store.
Issue:
After node save i will redirect to thankyou (destination) page for tracking but it takes long time to complete.
Customer may skip if it takes long time to complete the process.
How do i run node save in background process and display thankyou page immediately after placed order.
I want to track order conversions and node save.
Please help me to resolve this issue.
Thanks,
Yadavan
Comment: You might be able to do this by altering the Drupal node save form `hook_form_alter` and redirecting it to the Drupal queue API. It is however not the Drupal way, and would require quite a lot of custom code to achieve. And what if the process fails? The user will be under the impression all was fine.
Comment: You could save in background but as Neograph734 says, you have to be careful about what could happen if there  an error during node save in background.
Could you tell us how much time takes to save the node?
Answer: You can instead of saving the node directly, modify the node object with attributes from the form and then add it to a queue so you can use the Drupal queue system to do the actual node_save() operation on it.


Uniform continuity and sequentially compact space

Question: Let $(X,d)$ be a sequentially compact metric space and let $(Y,d')$ be a metric space. Let $f: X \to Y$ be a continuous function. Then,$f$ is uniformly continuous.
Just to be sure, by sequentially compact I mean: From any sequence in $X$, there is a convergent subsequence.
I feel this is so simple, but still I'm missing something. We let $f$ be indeed continuous, and we assume $f$ is not uniformly continous. By the proof, it just looks like we are showing "continuity implies uniform continuity".
$f$ is not uniformly continuous:
$\exists \epsilon \gt 0$ : $\forall n \gt 0, \exists x_{n}, y_{n} \in X, d(x_{n},y_{n}) \lt \frac{1}{n}, d'(f(x_{n}),f(y_{n})) \gt \epsilon$.
Then, we've built in the mean time two sequences $(x_{n})_{n}$ and $(y_{n})_{n}$
, converging both to say $l$.
Yet, $d'(f(x_{n}),f(y_{n})) \gt \epsilon, \forall n \in \mathbb N $, which contradicts the continuity of $f$.
How is it important to know $(X,d)$ is sequentially compact ? It seems to me we are not using this assumption at all. We just take the "discrete" definition of uniform continuity to get two convergent sequences leading us to the contradiction. So this would show continuity is anytime equivalent to uniform continuity (of course not).
Any help appreciated.
Comment: Something is wrong with your negation of uniformly continuous.
Comment: When you wrote $d'(f(x_n,f(y_n))<\epsilon$, my guess is that you meant to write $d'(f(x_n),f(y_n))>\epsilon$.
Comment: Yes ! Thank you.
Answer: You made an unjustified jump when you asserted that the sequences $(x_n)_{n\in\mathbb N}$ and $(y_n)_{n\in\mathbb N}$ converge. Why?
Take a subsequence of $(x_n)_{n\in\mathbb N}$ which converges to some $l$. Then the similar subsequence of $yx_n)_{n\in\mathbb N}$ will converge to $l$ too. What I mean by "similar" here is this: if your sebsequence of $(x_n)_{n\in\mathbb N}$ is $(x_{n_k})_{k\in\mathbb N}$, take the sequence $(y_{n_k})_{k\in\mathbb N}$.
The rest is more or less right. You should justify why there is a contradiction with the continuity of $f$. And when you deny that $f$ is uniformly continuous, you should have written $\geqslant\epsilon$ instead of $>\epsilon$.
Comment: That is, we have $(x_{n})$ and $(y_{n})$ two random sequences. Since X is sequentially compact, they both have two subsequences $(x_{ni})$ and $(y_{ni})$ converging both to say $l$. Since we know: $\forall n,\exists \delta_{n}$, st $d(x_{n},y_{n}) < \delta_{n}$, we know that $(x_{n})$ and $(y_{n})$ are Cauchy. Therefore, $(x_{n})$ and $(y_{n})$ converge both to $l$. Is this right ?
Comment: It might be useful to add that $(\delta_{n})$ is a bounded decreasing sequence ?
Comment: @AudreyI No, it is not right. You have no reason to suppose that $(x_n)_{n\in\mathbb N}$ and $(y_n)_{n\in\mathbb N}$ are Cauchy sequences.
Comment: How can I show that $(x_{n})$ and $(y_{n})$ are convergent then ? All I know is that the two sequences are linked by $\delta_{n}$ and they each have a convergent subsequence. Maybe by using the continuity of $f$ ? Do I know if the limit of $f(x_{ni})$ is unique ?
Comment: @AudreyI What makes you think that they converge? They don't have to converge.
Comment: Because by the proof I'm looking at, it's written: Without loss of generality, $(x_{n})_{n} \to x$ and $(y_{n})_{n} \to y$. I just assumed it was somehow necessary. Isn't it ?If we don't need $(x_{n})_{n}$ and $(y_{n})_{n}$ to converge, we don't need to know X is sequentially compact. I'm confused here.
Comment: @AudreyI "Without loss of generality" *doesn't* mean that it happens all the time. It means that you are adding no extra hypothesis if you assume that it happens.
Comment: So where is it useful to assume X is sequentially compact ? It just seems that $\forall f$ continuous, $f$ is uniformly continuous, which is not true.
Comment: @AudreyI It is useful because it implies that the sequences $(x_n)_{n\in\mathbb N}$ and $(y_n)_{n\in\mathbb N}$ have convergent subsequences; more precisely, there is a strictly increasing sequence $(n_k)_{k\in\mathbb N}$ of natural numbers such that both sequences $(x_{n_k})_{k\in\mathbb N}$ and $(y_{n_k})_{k\in\mathbb N}$ converge. And then we can assume *without loss of generality* that the sequences $(x_n)_{n\in\mathbb N}$ and $(y_n)_{n\in\mathbb N}$ themselves are convergent.
Comment: I got it now ! Thank you very much.
Comment: @AudreyI I'm glad I could help.
Answer: You need the sequential compactness. The fact that $d(x_n, y_n) < \frac1n$ doesn't say anything about covergence of the sequences. It just means they are "equiconvergent" – if one converges to $l$, than the other converges to $l$ as well. You have to use sequential compactness to move to a convergent sumsequences $x_{n_k}$, $y_{n_k}$.
Comment: So it just show that they have the same nature. How can I show then that since X is sequentially compact, these two sequences converge ? This neither tell us if these sequences are bounded or ... ?
Comment: As I say, these sequences may not converge, but they have convergent subsequences by the sequential compactness. Sequential compactness means exactly this – every sequence have convergent subsequence – there is no boundedness assumption.
Answer: When you build these two sequences $x_n$ and $y_n$ you will need the compactness of $X$. Otherwise they do not have to converge. Think for example of $x_n=n$ and $y_n=n+\frac{1}{n}$


Are node data stored in the render array $page?

Question: Are node data (e.g. title, body, comments) stored somewhere in the renderable array $page, and converted into HTML during rendering? Or does a renderable array just contain properties that indirectly cause to load particular templates files?
Where are variables that store these values printed?

Comment: how i do that ?
Answer: Yes, it's probably in there somewhere. However, it much easier to get the current node object (if there is any) with the menu_get_object() function:
if ($node = menu_get_object()) {
  // Do stuff with $node.
}

Comment: You shouldn't ask two questions. That's not how the site works. Yes is the response to the answer in the question title. For the second one, install devel.module and use dpm($node), that will tell you what's in there.
Comment: i asked two situation, yes to what ?
Comment: sir, i am drupal newbie can you please elaborate  this answer in simple words. please help me, rendering concept confuse me too much
Answer: I can advice three places where you can alter node render array:

hook_node_load . Called when node is just have been loaded from DB.
hook_node_view . This hook is called after node load. (As for me this is the best place to alter node render array). You can find render array in $node->content.
After this two hooks node render array goes to themming. You can alter node in your node template file(node.tpl.php). In node tpl file variables are printed using php print. E.g.
print render($content);
Comment: milkovsky,you explain how i alter the node data before it go for theming. but my question is what happen when line executed in page.tpl.php that make node.tpl.php comes into play? In above picture you see node title(defui et populus)come first,then body(commodo exerci..)who define serial order of these two field? Is in render array variable that store node title, stored just above node body variable, that why it comes first or it depend upon node.tpl.php file coding structure.milkovsky if you know rendering array and template concept please help me
Comment: Of course page title and page body are separated. The order of them you can define in the page.tpl.php file. Find title string "print $title;" and "print render($page['content']);" in your_theme_folder/page.tpl.php or in modules/system/page.ptl.php. You can see that title and content are printed in different places. Change order here OR as alternative you can use "Delta blocks" module to use page title as block.
Comment: is it means node title is not part of render array $page['content']?
Comment: yes title is rendered by 'print $title' usually in  tag
Answer: yes,  A render array is an associative array which conforms to the standards and data structures used in Drupal's theme rendering system.
for more info check out: Render Arrays in Drupal 7


Send Javascript Push Notification - AFTER Form POST and URL redirection

Question: Use case (Django Project):
I want to log in on my login page -> Therefore I use this form in html (login.html):
<form class="loginform" action="" method="POST">
    {% csrf_token %}

        {{form.as_p}}

        <input type="submit" class="btn btn-success loginbtn" value="Login">
</form>

In case of successful log in I will redirect with DJANGO to this URL (localhost/welcome/)-> welcome.html:
LOGIN_REDIRECT_URL = "welcome"

I am able to send javascript notifications with alertify, but only when using simple things such as
click on it or mouseover:
function notification(text) {
console.log(text)
alertify.success(text);
}

I tried it with onsubmit="javascript:notification("")" in the html form tag, however this will
be displayed only BEFORE the URL redirection.
So my question is:

How is it possible to activate /send the push notification AFTER the URL redirection and in
case of successfull POST/ Log in?

I really appreciate your help! Thank you a lot!!
Answer: Javascript is client-side. That means your alertify.success(text); will be executed client-side, once server already did his render process.
The authentication process is server-side. So you have to make your server make your alertify a part of the rendered content.
Knowing that, you just have to change your LOGIN_REDIRECT_URL content page to include in it a call to notification:

Be remembered that the notification will then display each time the person visits this page. You may want either to redirect him again, or to introduce a variable in Django to avoid displaying it again.
Comment: Thanks for your quick response! I think I try to implement it in this way with a separated html file or similar


debugging JBoss 100% CPU usage

Question: We are using JBoss to run two of our WARs. One is our web app, the other is our web service. The web app accesses a database on another machine and makes requests to the web service. The web service makes JMS requests to other machines, aggregates the data, and returns it.
At our biggest client, about once a month the JBoss Java process takes 100% of all CPUs. The machine running JBoss has 8 CPUs. Our web app is still accessible during this time, however pages take about 3 minutes to load. Restarting JBoss restores everything to normal.
The database machine and all the other machines are fine, only the machine running JBoss is affected. Memory usage is normal. Network utilization is normal. There are no suspect error messages in the JBoss logs.
I have set up a test environment as close as possible to the client's production environment and I've done load testing with as much as 2x the number of concurrent users. I have not gotten my test environment to replicate the problem.
Where do we go from here? How can we narrow down the problem?
Currently the only plan we have is to wait until the problem occurs in production on its own, then do some debugging to determine the cause. So far people have just restarted JBoss when the problem occurred to minimize down time. Next time it happens they will get a developer to take a look. The question is, next time it happens, what can be done to determine the cause?
We could setup a separate JBoss instance on the same box and install the web app separately from the web service. This way when the problem next occurs we will know which WAR has the problem (assuming it is our code). This doesn't narrow it down much though.
Should I enable JMX remote? This way the next time the problem occurs I can connect with VisualVM and see which threads are taking the CPU and what the hell they are doing. However, is there a significant down side to enabling JMX remote in a production environment?
Is there another way to see what threads are eating the CPU and to get a stacktrace to see what they are doing?
Any other ideas?
Thanks!
Comment: I think that this question will probably get more attention at http://stackoverflow.com than here.
Answer: You can send a SIGQUIT signal to the running JVM to get each thread's stacktraces printed to stdout.  This doesn't kill the process, though I think it does put all threads to sleep while the stack traces are being printed.
Then, correlate the thread IDs listed with your preferred method of seeing thread-wise CPU utilization.  prstat -L for Solaris, top -H for Linux.  Note that the tid's in the java stack traces are printed in hexadecimal; you'll probably have to convert to decimal when comparing to top or prstat output.
Comment: I have the tools ready to debug the problem next time it happens in production. This client uses Windows (don't ask). I ended up using CDB, a Windows tool, for getting all time thread CPU usage and native IDs. I have a script to run this twice with 10 seconds between runs, the threads that change the most are the culprits. Then I run jstack from the JDK to get the thread stacktraces, including native IDs. Now we just need production to chowder again! :)
Answer: I do a thread dump. However, on my Production systems this cannot be done unless the JVM is started with certain parameters that we would never enable in Production. In this case, I use the JMX console's jboss.system:type=ServerInfo mbean to do the thread dump (listThreadDump()).
The thread dump output is mostly meaningless to me when I haven't written the code. But the person who wrote the code may be able to make sense of it. In these cases where thread dumps don't help, I prefer using "strace -fp <PID of JBoss' java process> -o outfile.txt" to have another view into what is happening on a system-call level. It's a bit like drinking from a firehose, but sometimes it helps.
Comment: Java is multithreading and strace will not connect to all threads if the process is already started. However it is possible to find the thread that uses 100% CPU by using `top -Hp ` and then after finding the PIO of thread run `strace -fp  -o outfile.txt`
Comment: @curious_george, what's the command you type on the Jboss/Wildfly CLI tool that gives you the thread dump?  I tried "listThreadDump()" as you list, but got the error, "'listThreadDump()' is not a valid operation name."
Comment: @Dave: Sorry, I can't remember. I made the comment over 8 years ago.

debugging JBoss 100% CPU usage


Is there an HTML Canvas Video Context Buffer

Question: The HTML audio context has a freely accessible source buffer that can be used to write bytes data directly to be played by the speakers.
https://developer.mozilla.org/en-US/docs/Web/API/BaseAudioContext/createBufferSource
Is there an equivalent 'image buffer source' that we can access and directly write/copy RGB data bytes?
What I've tried:
I implemented this pixel-by-pixel in the end using:
context.fillStyle = "rgb(" + source[pointer].toString() + "," + source[pointer+1].toString() + "," + source[pointer+2].toString() + ")";

and then doing a:
context.fillRect (x, y, 1, 1);

to draw this pixel by pixel to the canvas, which works out fine though I suspect that's not the most efficient way to go about doing it.
I am still open to other suggestions.
Comment: @VC.One thank you, i implemented this pixel-by-pixel in the end using: context.fillStyle = "rgb(" + source[pointer].toString() + "," + source[pointer+1].toString() + "," + source[pointer+2].toString() + ")"; and then context.fillRect (x, y, 1, 1); to draw this pixel by pixel to the canvas, which works out fine though i suspect that's not the most efficient way to go about doing it... :)
Comment: [`getImageData`](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/getImageData) and [`putImageData`](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/putImageData) allow you to get/write an [`ImageData`](https://developer.mozilla.org/en-US/docs/Web/API/ImageData) object, which contains a `Uint8ClampedArray` of the RGBA values
Comment: My source image happens to be in a PPM format already which, after chopping off the header, is already a linearly stated R,G,B byte values for the entire image... is there a way to "feed" this directly somewhere into a buffer, without converting byte-by-byte into ImageData and then feeding the ImageData to the canvas? Thanks
Comment: You ask about image buffer source in the body of the question, but your title says "video". While video is certainly made up of images, the way they are generated and streamed are quite different, AFAIK.
Comment: the ImageData constructor accepts an Uint8ClampedArray as input, no need to feed each pixel one by one, but you need to specify the width and height of the image
Comment: Thanks Kaiido! Getting close now... I checked the ImageData constructor which accepts r,g,b,a (4 values) for each pixel... Are there any options for it to accept a plain rgb array (3 values) without the 'a' component? Thanks
Comment: @HereticMonkey Video is a bit of an ambiguous term. It can just mean a static image (as in video RAM, Video Graphic Array (VGA), video card, etc. ) or it can mean a series of frames to represent movement. I think the OP means the former.
Comment: @LeeTaylor The terms are quite well defined in HTML; there's the `img` element (and `Image` interface) for  displaying the former (and possibly animated versions of GIF and PNG in a pinch), and the `video` tag (and the `HTMLMediaElement` interface) for the latter. [MDN has an article on working with video (in the HTML meaning) on canvas](https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Manipulating_video_using_canvas).
Comment: @HereticMonkey I'm talking in the larger context of computing. Hence the terms sometimes get confused.
Comment: @James You cannot have RGB, only RGBA as imageData in HTML5. Just use a **FOR** loop to read the input pixels into your imageData object. For every 3 pixels that you read, you also write a 4th `alpha` value into imageData. If you update your question with what you've tried then we might advise or fix the code
Answer: Yes, html5 canvas's image data allows you to edit each pixel's rgb value directly.

var can = document.getElementById('can');
var ctx = can.getContext('2d');
var imgData = ctx.createImageData(100, 100);

for(var i = 0; i < 100*100*4; i+=4) {
  imgData.data[i+0] = 0; // red
  imgData.data[i+1] = ((i/4)%100)/100*255; // green
  imgData.data[i+2] = Math.floor((i/4)/100)/100*255; // blue
  imgData.data[i+3] = 255; // alpha
}
ctx.putImageData(imgData, 0, 0);
<canvas width="100" height="100" id="can"></canvas>
Comment: Thanks! Getting close now... I checked the ImageData constructor which accepts r,g,b,a (4 values) for each pixel... Are there any options for it to accept a plain rgb array (3 values) without the 'a' component? Thanks


O que são processamentos assíncronos e processamentos síncronos?

Question: Eu estou tendo esta dúvida enquanto estou estudando sobre a classe Handler.
No livro diz que quando uma Thread estiver sendo utilizada para realizar algum processamento assíncrono e precisar atualizar a interface gráfica da tela, é obrigado a usar um Handler.
Answer: Processamento assíncrona refere-se a processamentos que não dependem do resultado de outros, e podem, portanto, ocorrer simultaneamente/separadamente. Eles correm em Threads diferentes.
Em oposição, o processamentos síncronos são executados um a seguir ao outro, o próximo só inicia quando o anterior terminar. Eles correm na mesma Thread.
O Handler permite colocar Messages e Runnables na MessageQueue da Thread onde foi criado, permitindo que código de uma Thread seja executado em outra.
O Android, bem como a maioria dos sistemas, obriga que código que utiliza "objectos da UI" tenha de correr na UIThread(MainThread).
Quando o código que corre num Thread diferente necessita de actualizar a UI, recorre a um Handler associado a UIThred para o colocar na sua MessageQueue para ser executado.
Nota: O assunto foi aqui abordado de forma simplista, numa tentativa de facilitar a sua compreensão, se quiser aprofundar siga os links.
Answer: Processamento assíncrono no contexto da sua pergunta é um processamento que leva um certo tempo para executar e (tipicamente) ao fim desse processamento a interface gráfica precisa ser atualizada.
Você poderia simplesmente encapsular esse processamento e a atualização da tela em um método, chamar esse método (a partir da thread principal, caso contrário a atualização da tela não funciona) e esperá-lo executar. Isso seria o processamento síncrono. Mas devido ao fato do processamento ser demorado o método irá demorar para executar e a tela perderá a responsividade (não responderá a comandos de toque nem atualizará a interface gráfica) pois a thread principal ficará ocupada executando-o. Idealmente a thread principal deveria ficar restrita a atualizar a tela e tratar input (no caso os ditos comandos de toque).
Por esse motivo você faz o processamento de forma assíncrona: solicita a uma thread separada (seja criando uma diretamente, ou então indiretamente através de uma AsyncTask ou outro meio) para executar esse processamento e continua seu caminho normalmente, executando outros comandos.
Quando o processamento terminar a thread secundária colocará na fila de mensagens da thread principal o comando que atualiza a interface gráfica (seja via Handler, ou runOnUiThread(), ou um método callback de AsyncTask como o onPostExecute(), por exemplo).
Answer: Não é necessário implementar um handler, mas é sim necessário criar um thread separada do processamento assíncrono para atualizar a interface gráfica. Você pode fazer isso de forma bem simplificada usando o runOnUiThread. Por exemplo, se você tiver uma progressDialog que precisa ser exibida e escondida no início e fim de um processamento, você faria algo como:
//Mostrar dialog de progresso:
runOnUiThread(new Runnable() {
        @Override
        public void run() {
            progressDialog.show();
        }
});
//Esconder dialog de progesso:
runOnUiThread(new Runnable() {
        @Override
        public void run() {
            progressDialog.dismiss();
        }
});

O runOnUiThread deve ser chamado por uma activity.


post hoc test for 3 way anova

Question: I am doing ANOVA using three fixed independent factors of which one is sex (two levels 'male' and 'female'), temperature (three levels: 1,2,3) and quality (two levels: good and bad) and I want to see the effect of these factors on dependent variable factors like life-span, weight and development.
Now alongwith significant main effects I have significant interactions too.
For eg. for weight I have significant three-way interaction of the above factors, and for development I have significant two way interaction of quality and temperature.
the groups have unequal sample sizes.
So what post-hoc tests can I use keeping in mind the unequal sample size and the three way interaction?
I am interested in comparing between the good and bad quality effects for the three way interaction (as shown in the image below)
Could anyone please guide me ? thanks .
Answer: Easiest may be to perform regression where you can choose whichever interactions you want:
lm(y ~ temperature + quality + gender, mydata)

or:
lm(y ~ temperature*quality + gender, mydata)

or:
lm(y ~ temperature*quality*gender, mydata)

or:
lm(y ~ temperature*quality*gender - quality*gender, mydata)

Comment: The interactions will be much clearer with regression. You can perform both if needed. Anova and regression are actually very similar. In anova also you can use terms as mentioned above.
Comment: But I have done anova, and want to do post-hoc test to see which levels/combinations are significant?

post hoc test for 3 way anova


If $f(x) = (x^2+2\alpha x + \alpha^2-1)^{\frac{1}{4}}$ has its domain and range so that union is $\mathbb{R}$, what does $\alpha$ satisfy?

Question: My question asks:
If $f(x) = (x^2+2\alpha x + \alpha^2-1)^{\frac{1}{4}}$ has its domain and range such that their union is set of real numbers, what does $\alpha$ satisfy? (Answer is stated to be $\alpha \leq -1 $)
My approach was as follows, I can clearly see that the range has to be positive so that the domain must comprise of all negative real numbers, so that the union of range and domain consists of the full set of real numbers. For domain, the part under the radical sign must be $\geq 0$
$$x^2+2\alpha x + \alpha^2-1 \geq 0$$
$$\implies (x+\alpha-1)(x+\alpha +1)\geq 0$$
But now I'm stuck, how do I get the range for $\alpha$, and what condition do I apply such that the domain is negative? How do I proceed from here?
Comment: Note that since both conditions need to be satisfied, we can just focus on the second one (why?). Then $x \le -1 - \alpha$. We want the $x \le 0$. What should $\alpha$ be then?
Comment: Hint: What conditions pop out when both terms in parenthesis are negative?
Comment: You're using the inequality in the wrong direction. Our alpha should include $x \le 0$, you should see that $\alpha \ge -1$ will not allow this (try $\alpha = 0$!). We need $-1 - \alpha \ge 0$ to ensure that $x \le 0$ is satisfied.
Comment: It doesn't make $x$ negative, it just includes $x \le 0$. You may need to try looking at it graphically to convince yourself. If $\alpha = -1$ you should see that $x \le 0$. What about $\alpha = -2$, then you see that $x \le 1$. This domain includes $x \le 0$ as a subset.
Comment: What is "+ve"??
Comment: @Gary I meant positive, sorry if that wasn't clear, I'll edit it out
Comment: @Gregory $x<1-\alpha$ and $x<-1-\alpha$ but I dont know how that would let me get the range of $\alpha$? COuld you please elaborate further?
Comment: @Gregory I think we can only focus on the 2nd one as it is more negative and thus will be the only required boundary and the 1st one will be already satisfied. (Correct me if I'm wrong here...) But now, even if I set $-1-\alpha \leq 0$, I get $\alpha \geq -1$ which isn't the answer.... where am I going wrong here?
Comment: @Gregory Why is $-1-\alpha > 0 $ here? Could you tell me how that makes x negative? I got confused by that part
Answer: Opting for a different route than the one suggested by @Gregory in the comments.
Going from what you have
$$g(x) = (x-(-\alpha +1))(x-(-\alpha-1)) \geq 0$$
So, if you plot $1-\alpha$ and $-1-\alpha$ on a number line; notice that the function $g$ is positive everywhere to the right of $(1-\alpha)$ and also positive to the left of $(-1-\alpha)$ and thus satisfies the inequality when
$$x \in D = (-\infty, -1-\alpha] \cup [1-\alpha, \infty)$$
Moreover, notice that the vertex coordinates of the upward open parabola representing $g$ is simply $(-\alpha, -1)$ (thereby making its range $[-1,\infty)$). Therefore, the range of $f$, regardless of the value of $\alpha$ is $R = [0,\infty)$ (because of the fourth root on the outside).
Now, we know $$D \cup R = \mathbb{R} \implies (-\infty, -1-\alpha] \cup [1-\alpha, \infty) \cup [0,\infty) = \mathbb{R}$$
Notice that when $\alpha \leq -1$, we have the first interval in the above equality becomes $(-\infty, c]$ where $c$ is non-negative, the second interval becomes redundant because of the third interval. Therefore, the inequality is held true.  So $\alpha \leq -1$.
Edit: If the last bit of the above argument is a little messy, here's neater a way by contradiction. If $\alpha > 1$, then $-\alpha$ can never be in $D \cup R$, can you see why?
Hint: $-1-\alpha + 1 = -\alpha$, and $-1-\alpha + 2 = 1- \alpha$.


Linux slow command response despite no apparent load

Question: Once in a while some of my Linux boxes enter some kind of strange state that results in having to reboot them.
All commands take about 5 seconds to execute. But if you run the same command twice in a row, the first will take 5 seconds, but the second will be instant. Even the time command doesn't see the 5 seconds:
[root@node48 ~]# time echo 1
1

real    0m0.000s
user    0m0.000s
sys     0m0.000s
[root@node48 ~]# time echo 1
1

real    0m0.000s
user    0m0.000s
sys     0m0.000s
[root@node48 ~]# time echo 2
2

real    0m0.000s
user    0m0.000s
sys     0m0.000s
[root@node48 ~]# time echo 2
2

real    0m0.000s
user    0m0.000s
sys     0m0.000s

In the above example, the 1st echo took 5 seconds, the 2nd was instant, the 3rd took 5 seconds, the 4th was instant. Yet all 'time' results are 0.
I'm confused as to what might cause this. Load was non-existent on this node, and the problem persisted even after I stopped all running services on it.
[root@node48 ~]# top
top - 16:17:22 up 42 days, 11:02,  1 user,  load average: 0.17, 0.83, 1.20
Tasks: 292 total,   1 running, 291 sleeping,   0 stopped,   0 zombie
Cpu(s):  0.4%us,  0.2%sy,  0.0%ni, 99.3%id,  0.0%wa,  0.0%hi,  0.0%si,  0.0%st
Mem:  32934476k total, 21642992k used, 11291484k free,    11296k buffers
Swap:  4095996k total,        0k used,  4095996k free,   343152k cached

There's no swap usage, no zombies, plenty of cpu idle time.
What would you look at if you would have such an issue?
Thank you,
Comment: does it happen with all commands? how about memory usage and io activity? Do you see any difference before and after dropping cache (`echo 3 > /proc/sys/vm/drop_caches`)?
Comment: 1.check `ps -ef` for strange process
2.disk io activity
Comment: Potentially your connection to the (over ssh) is very slow or has some issue (eg failing interface). Also, are you doing this in a VM ? If so, are other guests on the same VM competing for resources? Check also dmesg. Does the problem go away if cron is stopped? Are there heavy jobs running (assuming this may be a compute node)
Comment: @Tux_DEV_NULL Yes, this happens on all commands. I showed example with echo as it's a very simple command that should execute right away. I will try drop cache that next time.
Comment: @Corleone No io activity, all services stopped
Comment: @CameronKerr It's a physical node. SSH connection is good, local network. no packet loss. Problem still happens after stopping all services. Will check dmesg next time
Comment: Use strace to see what takes so long.
Comment: Something bad/unavailable in your PATH? What if you use time /bin/echo instead? (Assuming that echo is not a shell built-in). I would second the suggestion to also try strace, with timing info. Do you have things like sssd (network auth) or nfs/samba in play also? Does this problem ever occur when there is disk IO happening?
Answer: tldr; systemctl | grep "abandoned" | cut -f3 -d ' ' | xargs systemtctl stop fixed it for me.
I noticed for me, not all commands were slow, specifically things having to do with logins were slow (ssh, w, top, etc) but other things like iostat, ls, etc were speedy.
When doing an strace -v w for instance, I noticed it got hung up waiting on D-bus. Of course D-bus is tied intrinsically to systemd, you can not just restart D-bus without rebooting. So I did some poking and searching and noticed:
systemctl | grep "abandoned" | wc -l returned 711 for this machine. (you can also see this information ls -l /run/systemd/sessions/ | wc -l).
That's a lot of abandoned login sessions that never got cleaned up.  I cleaned them up: systemctl | grep "abandoned" | cut -f3 -d ' ' | xargs systemctl stop and everything got instantly better.
I'm not saying this will fix your machine, but it fixed mine, and it might help the poor lost souls who end up here like me without a great place to start.


How not to repeat code using Bower and Gulp?

Question: I use Bower to manage front end packages on my project and Gulp to minify and create a single file with all CSS and JS from the packages. It saves that file on the assets folder, which is from where I get the files on html.
Right now, this is my bower list
├── cssfx#0.9.6
├── font-awesome#4.3.0
├── jquery#2.1.3
├─┬ jquery.cookie#1.4.1
│ └── jquery#2.1.3
├── jquery.ellipsis#0.7.1
├── normalize.css#3.0.3
└─┬ semantic-ui#1.12.0
  └── jquery#2.1.3

As you can see, I have Semantic UI and normalize.css installed. The problem is that Semantic UI uses normalize.css as reset, so the normalize.css is included in the Semantic UI code. On the css file generated by Gulp, the normalize.css is included twice, which is a problem because:

The code is repeating, making the file bigger
Semantic UI uses normalize.css v3.0.1, and the normalize.css installed with Bower is v3.0.3

This is the first time this happens to me, but let's say I use a package with includes another package that I already have installed, and the situation would be the same as above. So I believe the solution would have to be something that is valid to all packages.
Is there a way I could remove automatically the repeated code? In my case above, remove the normalize.css from Semantic UI and use the installed normalize.css package?
If this can't be done, the only way I could remove the repeated code is manually or there's another package manager like Bower or something like Gulp that has that feature?
Answer: There is a gulp task named gulp-minify-css that acts as a wrapper for clean-css:  https://github.com/jonathanepollack/gulp-minify-css
For grunt, the clean-css wrapper is named grunt-contrib-cssmin:  https://github.com/gruntjs/grunt-contrib-cssmin
The underlying module (clean-css) is different from simple minification in that there are options to combine property declarations and eliminate declarations which are ultimately overridden by later ones.  I haven't tested myself, but I would imagine it would eliminate any redundancies in css which would be caused by the double inclusion of (almost) the same file.
However, this doesn't really address the problem.
In this case, you should just remove the standalone normalize.css.  If it included before Semantic UI, it will largely, if not entirely, be overridden by Semantic UI and its own copy of normalize.css. If it's included afterwards, then it is probably resetting things defined by Semantic UI, and you don't want that either.
Generally, if a framework includes normalize.css, it is intended to be used by itself with no other frameworks.  (i.e. You wouldn't use Foundation 5 and Semantic UI at the same time.)
When you concatenate your css, include any global frameworks first (Semantic UI) then add other things like icon packs, sliders (such as Slick.js), mobile navigation patterns (Slidebars.js), etc.
If you are using Semantic UI and you decide that Foundation (or some other framework) has a really nice feature that you want to use, you will often find that frameworks have CSS and JS broken down for individual components too.  Simply include the CSS file specific to the feature you are interested in.  In this case, there should be no duplicate code, although namespace conflicts are possible.
Also, if you're concerned about missing out on v3.0.3 of normalize.css because Semantic only has v3.0.1 included, I imagine there's hardly a difference.


Calculate the limit $\lim_{x\rightarrow 0}\frac{x^2 \cos\left(\frac{1}{x}\right)}{\sin(x)}$.

Question: We could use L'Hospital here, because both numerator as well as denominator tend towards 0, I guess. The derivative of the numerator is $$x^2\cdot \left(-\sin\left(\frac{1}{x}\right)\right) \cdot \left( -\frac{1}{x^2}\right) + 2x \cos\left(\frac{1}{x}\right)=\sin\left(\frac{1}{x}\right) + 2x \cos\left(\frac{1}{x}\right) $$  The derivative of the denominator is $\cos(x)$. So,  $$\lim\limits_{x\rightarrow 0}\frac{x^2 \cos\left(\frac{1}{x}\right)}{\sin(x)} = \lim\limits_{x\rightarrow 0}\displaystyle\frac{\sin\left(\frac{1}{x}\right) + 2x \cos\left(\frac{1}{x}\right)}{\cos(x)}$$
Is that right so far?
Thanks for the help in advance.
Best Regards,
Ahmed Hossam
Comment: For all practical purposes this is a duplicate of [1](https://math.stackexchange.com/q/2166886/11619), [2](https://math.stackexchange.com/q/2072914/11619) and [3](https://math.stackexchange.com/q/726976/11619) proving once again that calculus answering machines think that the site rules don't apply to them.
Comment: The numerator is essentially $\pm x^2$ and the numerator $x$.
Comment: Well, $\lim\limits_{x\to0}{\frac{x^2\cdot\sin\frac{1}{x}}{\sin x}}$ ist not the same as $\lim\limits_{x\to0}{\frac{x^2\cdot\cos\frac{1}{x}}{\sin x}}$
Comment: See also https://math.stackexchange.com/questions/2608201/compute-the-limit-without-lhospitals-rule, for completeness.
Answer: We don't need l'Hopital, indeed by standard limits
$$\frac{x^2 \cos\left(\frac{1}{x}\right)}{\sin(x)}=\frac{x \cos\left(\frac{1}{x}\right)}{\frac{\sin(x)}x}\to \frac01=0$$
indeed by squeeze theorem
$$\left|x \cos\left(\frac{1}{x}\right)\right|\le |x|\to0$$
Comment: Thanks for your answer.
Answer: Hint: Without using L'Hôpital's Rule, note that
$$\frac{x^2\cos\big(\frac{1}{x}\big)}{\sin x} = \frac{x}{\sin x}\cdot x\cos\bigg(\frac{1}{x}\bigg)$$
and recall $\lim_\limits{x \to 0}\frac{\sin x}{x} = 1$.
Comment: order of zero is higher in Numerator then in denominator hemce 0
Comment: Thanks for your answer.
Answer: As we know that $$\lim_{x\to 0}{x\over \sin x}=1$$therefore $$\lim_{x\to 0}{x^2\cos {1\over x}\over \sin x}=\lim_{x\to 0}x\cos{1\over x}=\lim_{u\to \infty}{\cos u\over u}=0$$
Answer: With the Taylor power series, $\sin x= x+o(x)$
$$\lim_{x\rightarrow 0}\frac{x^2 \cos\left(\frac{1}{x}\right)}{\sin(x)}=\lim_{x\to0}{x \cos\left(\frac{1}{x}\right)}=0$$
Because $x\to0$ and $\cos(1/x)$ is bounded from $-1$ to $1$ as $x\to0$
Comment: Thanks for your answer.


Configuring django with LDAP

Question: I have configured LDAP successfully with a python application using little more than these statements in db/model.py:
from gluon.contrib.login_methods.ldap_auth import ldap_auth
auth.settings.login_methods = [ldap_auth(mode='ad', server='ldap.example.com', base_dn='dc=example,dc=com')]

I am trying the same with Django, but all the instructions that I have seen online are fairly complicated.
What would be the Django equivalent to my web2py LDAP setup?
Is there a simple way to debug the LDAP connection process to the django server console?
Here is what I have attempted:
import ldap
from django_auth_ldap.config import LDAPSearch, GroupOfNamesType

# LDAP Configuration
AUTH_LDAP_SERVER_URI = "ldap://ldap.example.com"
AUTH_LDAP_BIND_DN = ""
AUTH_LDAP_BIND_PASSWORD = ""
AUTH_LDAP_USER_DN_TEMPLATE = "uid=%(user)s,ou=users,dc=example,dc=com"

# group names:
#AUTH_LDAP_GROUP_SEARCH = LDAPSearch("ou=groups,dc=example,dc=com",
#         ldap.SCOPE_SUBTREE, "(objectClass=groupOfNames)"
#         )
#AUTH_LDAP_GROUP_TYPE = GroupOfNamesType()
#AUTH_LDAP_FIND_GROUP_PERMS = True
#AUTH_LDAP_CACHE_GROUPS = True
#AUTH_LDAP_GROUP_CACHE_TIMEOUT = 300

AUTH_LDAP_USER_ATTR_MAP = {"first_name": "givenName", "last_name": "sn", "email": "mail"}
AUTH_LDAP_PROFILE_ATTR_MAP = {"home_directory": "homeDirectory"}

AUTH_LDAP_USER_FLAGS_BY_GROUP = {
    "is_active": "cn=active,ou=groups,dc=example,dc=com",
    "is_staff": "cn=staff,ou=groups,dc=example,dc=com",
    "is_superuser": "cn=superuser,ou=groups,dc=example,dc=com",
}

AUTHENTICATION_BACKENDS = (
    'django_auth_ldap.backend.LDAPBackend',
    'django.contrib.auth.backends.ModelBackend',
)

This is what I am currently seeing when I try to authenticate:
Comment: Increase log level on the LDAP side, so you know why this error is happening. For OpenLDAP: http://www.zytrax.com/books/ldap/ch6/#loglevel
Comment: Looks like you got a typo in that AUTH_LDAP_USER_DN_TEMPLATE line - the letter "s" after the "uid=%(user)" is making it expect EVERY user ID to end with "s".
Comment: That 's' is actually python string formatting operation. https://docs.python.org/2.4/lib/typesseq-strings.html
Answer: a while ago while debugging a graphite ldap installation
ldap.set_option(ldap.OPT_DEBUG_LEVEL, 65535)
which I got from the graphite docs (http://graphite.readthedocs.io/en/latest/config-local-settings.html).
It might tell you more about what is going on in your app.
Comment: Thanks. This is very helpful. It explains how to use the logging that @kamilhack mentioned.
Comment: not exactly, @kamilhack suggests to increase logging on the ldap server side, my suggestion is for the ldap client side ;-), but both are valid ways to look at the problem.

Configuring django with LDAP


getopt not changing value C

Question: This code is supposed to filter a list of students using getopt. It filter's CS, Math and Physics students based on their points.
Everything in this switch case works using getopt accept case v which is just supposed to set the value to 1 and filter the list of students so only CS and Math students will be in the list. I don't know why it wouldn't work. I've found multiple examples in books doing it the same way.
I'm sorry I know the code is ugly I tried to make it better for the post.
#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
#include "zulassung.h"

int main(int argc, char *argv[]){

int percentageNeededToPassCS = 50;
int percentageNeededToPassSecondSubject = 50;
int passingMinCS = 0;
int passingMinSecongSubject = 0;
int maxPoints = atoi(argv[1]);
int points;

int studentID;

int CheckV = 0;

char subject[20];
char option;

while((option = getopt(argc, argv,"i:m:v")) != EOF){
    switch(option){
        case 'i':
        percentageNeededToPassCS = atoi(optarg);
        break;
        case 'm':
        percentageNeededToPassSecondSubject = atoi(optarg);
        break;
        case 'v':
        checkV = 1;
        break;
        default: //The default dosen't work yet it's not needed
        printf("Unknown Option: '%s'\n", optarg);
        break;
    }
    argc -= optind;
    argv += optind;
}

passingMinCS = calculate_pointsneededtopass(maxPoints,percentageNeededToPassCS);
passingMinSecongSubject=calculate_pointsneededtopass(maxPoints,percentageNeededToPassSecondSubject);

printf("\t %d\n", CheckV);
while(scanf("%d %s %d", &studentID, subject, &points) == 3){
    if(checkV == 1){
        if(subject_is_cs_or_math(subject) == 1){
        if(filter_student(passingMinCS,passingMinSecongSubject,checkV,studentID,subject,points) == 1){
        printf("%d\n", studentID);
            }
        }
    }else{
    if(filter_student(passingMinCS,passingMinSecongSubject,checkV,studentID,subject,points) == 1){
        printf("%d\n", studentID);
    }
    }
}

return 0;
}

Comment: @ikegami It compiles if you add the missing #includes, `main()` function, etc, yes. :) It doesn't work as intended, though.
Comment: @Erwin, I meant as intended for `-v`, contrary to what the OP claimed.
Answer: Setting aside that it's an incomplete piece of program, the thing that is tripping you up is that you've put this inside the while loop.
    argc -= optind;
    argv += optind;

Move it after the while loop and I think you'll find it works as intended. The printf() in the default: case is unnecessary.

getopt not changing value C


calculation of area and perimeter of cleared areas (without using integral calculation)

Question: How can I find the area and perimeter of [these cases], can you help me?

Thanks
Comment: for area, see [this](https://math.stackexchange.com/q/977998) and [that](https://math.stackexchange.com/q/2184713). In particular, if you answer the figure in this [answer](https://math.stackexchange.com/a/2184746), you will know how to calculate the perimeter.
Comment: What have you tried so far?
Comment: The perimeter of an ellipse is given by a complete elliptic integral of the second kind, so I guess there is no way to avoid integrals. On the other hand good algebraic approximations are known, for instance Ramanujan's.
Comment: oops, I mean 'understand' the figure..
Answer: Call the area in the first picture A, the one in the second picture 4B, the one on the third picture 4C.
Then using equivalence of areas we get that: \
$A+4B+4C=L^{2} \\
A+3B+2C=\frac{\pi L^{2}}{4} \\
A+2B=\frac{(\pi - 2)L^{2}}{2}$ \
Solve the equations for A, B, C.
Comment: Degenerate equations
Comment: I guess we need another equation then, but I can't quite spot it. Considering geometrical shapes seems a good path though.
Answer: BIG HINT
An area of $A+2B+C$ is formed by the union of two sectors of angle $60^o$ of a circle of radius $L$. These sectors overlap in an equilateral triangle of side $L$. This gives us the extra equation we need
$$A+2B+C=\frac{1}{3} \pi L^2-\frac{\sqrt(3)}{4}L^2.$$
Answer:
Let [.] denote areas of various shapes below.
Case 1.
One of the little grey areas is
$$I_1 = [ABCD] - [CDS] - 2[DAS]$$
where the areas of the triangle CDS and the circle sector DAS are given by
$$[CDS] = \frac{\sqrt 3}{4}L^2, \>\>\> [DAS] = \frac{\pi}{12}L^2$$
Thus,
$$ I_1 = \left(1- \frac{\sqrt 3}{4} - \frac{\pi}{6}\right)L^2 $$
and its perimeter is $\left( 1+\frac{\pi}{3}\right)L$.
Case 2.
One of the four areas in the second case is
$$ I_2 = [ABCD] - [ADB] - 2I_1 = \left(\frac{\sqrt 3}{2}-1 + \frac{\pi}{12}\right)L^2 $$
and its perimeter is $\frac{\pi}{2}L$.
Case 3.
The area in the case of the middle area,
$$ I_3 = (1-4I_1-4I_2)L^2=\left(1-\sqrt 3 + \frac{\pi}{3}\right)L^2$$
with perimeter $\frac{2\pi}{3}L$.


How to prevent duplicate URL patterns and not have "-#" appended to the URL alias?

Question: We have a situation where we need to prevent the same URL from being generated within the same language.
Current situation (all for en):

Create nodeA with a URL alias of "page/node-title"
Create nodeB with a URL alias of "page/node-title"
Create nodeC with a URL alias of "page/node-title"

Results of current situation

nodeA generates "page/node-title"
nodeB generates "page/node-title-0"
nodeC generates "page/node-title-1"

Expected results:

get created as expected
user is prompted to modify the url since for the en language, that alias already exists
user is prompted to modify the url since for the en language, that alias already exists

That is not the expected results however. When nodeB and nodeC are generated, then the user should be prompted to let them know that the URL alias is a duplicate and thus it must be changed so it is unique. We have reviewed a lot of the documents for URL generation in Drupal but cannot find the correct configuration to prevent duplicate node alias from being generated.
Comment: Drupal core (+ Pathauto as far as I know) doesn't have such a configuration option. Probably wouldn't be too hard to implement with a form alter and a validation function though
Answer: As Clive mentions, Pathauto does not have a configuration to disable uniquification (suffixing "-#").
If you look through the main function that builds paths, pathauto_create_alias() you can see that the only way to prevent pathauto_alias_uniquify($alias, $source, $language) from running would be to trigger one of the scenarios in which pathauto gives up on alias creation (e.g. empty pattern, updating an existing alias, etc.) which wouldn't help where you need it still generated in some cases.
Your best bet to cover this scenario is to have a custom node validation function execute pathauto_create_alias()'s logic with $op = 'return' to see what the generated alias would be  before generation, and throw back errors upon duplicate uniquified paths.


Query para coletar dados de várias colunas da mesma linha, por Primary Key do registro

Question: tudo tranquilo?!
Vejam se conseguem me ajudar!
Da query abaixo (uso phpMyAdmin), estou precisando apenas trazer os resultados de "LETRAA", "LETRAT", "LETRAG" e "LETRAF" para a tela do browser (via PHP), porém não sei qual parte do código da query deve ser alterada para chegar ao resultado que preciso.
SELECT
    tr_id,
    LENGTH(TAB.RESPOSTAS)-LENGTH(REPLACE(TAB.RESPOSTAS,'A','')) LETRAA,
    LENGTH(TAB.RESPOSTAS)-LENGTH(REPLACE(TAB.RESPOSTAS,'T','')) LETRAT,
    LENGTH(TAB.RESPOSTAS)-LENGTH(REPLACE(TAB.RESPOSTAS,'G','')) LETRAG,
    LENGTH(TAB.RESPOSTAS)-LENGTH(REPLACE(TAB.RESPOSTAS,'F','')) LETRAF
FROM (
    SELECT
        tr_id,
        concat(
        tr_1 ,tr_2 ,tr_3 ,tr_4 ,tr_5 ,tr_6 ,tr_7 ,tr_8 ,tr_9 ,tr_10,
        tr_11,tr_12,tr_13,tr_14,tr_15,tr_16,tr_17,tr_18,tr_19,tr_20,
        tr_21,tr_22,tr_23,tr_24,tr_25,tr_26,tr_27,tr_28,tr_29,tr_30,
        tr_31,tr_32,tr_33,tr_34,tr_35,tr_36,tr_37,tr_38,tr_39,tr_40,
        tr_41,tr_42,tr_43,tr_44,tr_45,tr_46,tr_47,tr_48,tr_49,tr_50,
        tr_51,tr_52,tr_53,tr_54,tr_55,tr_56,tr_57,tr_58,tr_59,tr_60,
        tr_61,tr_52,tr_63,tr_64,tr_65,tr_66,tr_67,tr_68,tr_69,tr_70,
        tr_71,tr_52,tr_73,tr_74,tr_75,tr_76,tr_77,tr_78,tr_79,tr_80,
        tr_81
        ) RESPOSTAS
    FROM
        tetra_respostas
    WHERE
        tr_id = 11
) TAB

Para melhor entender, segue abaixo uma imagem do resultado esperado:

Abaixo, o código da página a ser exibida, mas mesmo assim os dados não estão vindo da consulta. Por isso acho que é alguma coisa no código da query.

      <?php echo $row_Tetragrama['tr_id']; ?>
      <?php echo $row_Tetragrama['RESPOSTAS']; ?>
      <?php echo $row_Tetragrama['LETRAA']; ?>
      <?php echo $row_Tetragrama['LETRAT']; ?>
      <?php echo $row_Tetragrama['LETRAG']; ?>
      <?php echo $row_Tetragrama['LETRAF']; ?>

Comment: Como você diz que o resultado no phpMyAdmin está correto então tudo leva a crer que o problema não está com a expressão SQL, mas talvez eu não tenha entendido sua dúvida.
Answer: Se a consulta no MyPhpAdmin está trazendo o resultado desejado, só está faltando imprimir o valor das variáveis em cada  da sua tabela.
Dá pra ver que você conseguiu imprimir o código 11 na coluna tr_id;
vc só precisa imprimir as demais em cada
vc deve ter feito algo assim:

  <?php print $resultado['tr_id'];?>

É só completar:

  <?php print $resultado['tr_id'];?>

  <?php print $resultado['LETRAA'];?>
  <?php print $resultado['LETRAT'];?>
  <?php print $resultado['LETRAG'];?>
  <?php print $resultado['LETRAF'];?>

Comment: Se você usar aliases no nome da coluna o erro persiste? Exemplo.: SELECT
    tr_id,
    LENGTH(TAB.RESPOSTAS)-LENGTH(REPLACE(TAB.RESPOSTAS,'A','')) as LETRAA,
Answer: Finalmente achei o erro!!!
Eles estão nas linhas 17 e 18 da query, em: "tr_52" e "tr_52", onde o correto é: "tr_62" e "tr_72", respectivamente... por isso os resultados não estavam sendo exibidos como esperado.
SELECT
tr_id,
LENGTH(TAB.RESPOSTAS)-LENGTH(REPLACE(TAB.RESPOSTAS,'A','')) LETRAA,
LENGTH(TAB.RESPOSTAS)-LENGTH(REPLACE(TAB.RESPOSTAS,'T','')) LETRAT,
LENGTH(TAB.RESPOSTAS)-LENGTH(REPLACE(TAB.RESPOSTAS,'G','')) LETRAG,
LENGTH(TAB.RESPOSTAS)-LENGTH(REPLACE(TAB.RESPOSTAS,'F','')) LETRAF
  FROM (
   SELECT
    tr_id,
    concat(
    tr_1, tr_2 ,tr_3 ,tr_4 ,tr_5 ,tr_6 ,tr_7 ,tr_8 ,tr_9 ,tr_10,
    tr_11,tr_12,tr_13,tr_14,tr_15,tr_16,tr_17,tr_18,tr_19,tr_20,
    tr_21,tr_22,tr_23,tr_24,tr_25,tr_26,tr_27,tr_28,tr_29,tr_30,
    tr_31,tr_32,tr_33,tr_34,tr_35,tr_36,tr_37,tr_38,tr_39,tr_40,
    tr_41,tr_42,tr_43,tr_44,tr_45,tr_46,tr_47,tr_48,tr_49,tr_50,
    tr_51,tr_52,tr_53,tr_54,tr_55,tr_56,tr_57,tr_58,tr_59,tr_60,
    tr_61,tr_62,tr_63,tr_64,tr_65,tr_66,tr_67,tr_68,tr_69,tr_70,
    tr_71,tr_72,tr_73,tr_74,tr_75,tr_76,tr_77,tr_78,tr_79,tr_80,
    tr_81
    ) RESPOSTAS
   FROM
    tetra_respostas
   WHERE
    tr_id = idResp
) TAB

Sempre suspeitei de algum erro no SQL... ufa!!! Segue o jogo...


Problem-solving

Question: I just finished my second year as a mathematics student at university. At university, we learn about advanced mathematics and problems. However, I'm also interested in some problems that doesn't acquire deep results from mathematics or a certain theory to solve them.
Now I'm looking for a good guide to learn more about this type of problem-solving. I want some pdf or a book that gives some brief introduction to a problem solving technique and after that a large bunch of problems. I don't want these problems to be too easy but I also don't want them to be too hard so that I have to know much modern results in mathematics to understand them.
Does anyone of you knows such a guide at my level (university student)?
Comment: The [Putnam exams](http://amc.maa.org/a-activities/a7-problems/putnamindex.shtml) might interest you.
Comment: I forget if Polya's "How to Solve It" has problems, but it was the go-to recommendation for this sort of thing when I was young.
Comment: Maybe try - ''Mathematical circles''. Just take a look at problems from chapters like - invariants . I think it might be too easy for you?
Answer: I like "The Art and Craft of Problem Solving" by Paul Zeitz
Answer: Problem-Solving Strategies
Arthur Engel
http://www.amazon.com/Problem-Solving-Strategies-Problem-Books-Mathematics/dp/0387982191
Comment: I was going to recommend the same book.
Answer: I have just the thing for you: "The Top-Down Approach to Problem Solving", by Eduardo Corpeño (yours truly), ISBN 979-8464073296. You can find it on amazon as paperback and ebook.
I hope it helps.

Problem-solving


Expression for 1-forms in 1-dimensional manifold

Question: Let $M$ be an $1$-dimensional manifold. Consider a 1-form $w\in\Omega^1(M)$.
I saw that we can write it $$w(t)=g(t)\,dt$$ but I have a question about this:
$w(t)\in \bigwedge^1(T^*M)$, so we can write it in a basis of $\bigwedge^1(T^*M)$. $dt\in \Omega^1(M)$ spans $\Omega^1(M)$, not $\bigwedge^1(T^*M)$, while $dt(t)$ does span $\bigwedge^1(T^*M)$. So, shouldn't we write $w(t)=g(t)\,dt(t)$ instead? This may be nitpicking, but I want to make sure I am understanding this correctly.
Answer: Let $\omega\in \Omega^{1}(M)$. For $t\in M$, we have $\omega(t)\in \Lambda^1 T_t^\ast M$. Now take a chart $\varphi\colon U\cong V$ with $t\in U$. Then $\frac{\partial}{\partial{t}} \in T_tM=\operatorname{Der}(\mathscr{C}^\infty_t, \mathbb{R})$ defined by $\frac{\partial{}}{\partial{t}}([f])=\frac{\partial{f \circ \varphi^{-1}}}{\partial{x}}(\varphi(t))$ ($\partial{}/\partial{x}$ denotes the usual (partial) derivative) gives you a basis of $T_tM$. Thus, the dual element $dt$ will give you a basis of $T^\ast_t M$. Hence, you may uniquely write $\omega(t)=g(t)dt$, where $g(t)\in \mathbb{R}$.
Since this works for every element $t\in U$, you may $\textit{locally}$ write $\omega$ as $\omega(t)=g(t)dt$. To be precise, $\omega\vert_U = g(t)dt$, where $g\colon U\to \mathbb{R}$ is the function assigning each point $t$ the unique coefficient $g(t)$ satisfying $\omega(t)=g(t)dt$.
And strictly speaking, yes, $dt$ depends on the chosen point $t$ as you can tell from the definition of $\frac{\partial{}}{\partial{t}}$; so it would be perfectly correct to write $\omega(p)=g(p)dt(p)$ for $p\in U$.


Imagem transparente e cor de fundo

Question: Tenho o seguinte código:
FileStream fs = new FileStream(@"\path\imagem1.png", FileMode.Open, FileAccess.Read);
Image image = Image.FromStream(fs);
fs.Close();

Bitmap b = new Bitmap(image);
Graphics graphics = Graphics.FromImage(b);

graphics.DrawString("Meu texto", new Font("Arial", 50), Brushes.White, 0, 0);
b.Save(@"\path\resultado.png", image.RawFormat);

image.Dispose();
b.Dispose();

Imagem1:

Sim, tem imagem aí! Mas ela além de não ter cor de fundo, também tem um grande nível de transparência.
O problema é que eu gostaria de colocar um background nela, assim o resultado seria:

Tentei desenhar um retângulo vermelho, mas ele sobrepõe a imagem.
Answer: Bem, o código a seguir resolveu o problema:
FileStream fs = new FileStream(@"\path\imagem1.png", FileMode.Open, FileAccess.Read);
Image image = Image.FromStream(fs);
fs.Close();

var imageHeight = image.Height;
var imageWidth = image.Width;

Bitmap b = new Bitmap(image);
Graphics graphics = Graphics.FromImage(b);
graphics.Clear(Color.FromArgb(255, Color.Red));

graphics.DrawImage(image, 0, 0, imageWidth, imageHeight);

graphics.DrawString("Meu texto", new Font("Arial", 50), Brushes.White, 0, 0);
b.Save(@"\path\resultado.png", image.RawFormat);

image.Dispose();
b.Dispose();

Imagem transparente e cor de fundo


Showing $\prod_{n\geq 1} (1+q^{2n}) = 1 + \sum_{n\geq 1} \frac{q^{n(n+1)}}{\prod_{i=1}^n (1-q^{2i})}$

Question: I want to show
\begin{align}
\prod_{n\geq 1} (1+q^{2n}) = 1 + \sum_{n\geq 1} \frac{q^{n(n+1)}}{\prod_{i=1}^n (1-q^{2i})}
\end{align}
I know one proof via self-conjugation of partition functions with Young Tableaux.  But it seems not natural for me. [In the process of the proof it appears Durfee square, etc]
Is there any other (simple?) proof for this equality?
Comment: I really don't think you can hope for anything better than a bijective proof...
Answer: Substituting $\sqrt{q}$ for $q$, we get
$$
\prod_{n=1}^{\infty}(1+q^n)=\sum_{k=0}^{\infty}{\frac{q^{\binom{k+1}{2}}}{\prod_{i=1}^{k}{(1-q^i)}}}.
$$
The left-hand side is the generating function for partitions with distinct parts (a part of each size $n$ occurs $0$ or $1$ times).
On the other hand, if a partition with distinct parts has $k$ parts, then the $i$th smallest part is of size at least $i$. Given a partition $0<\lambda_1<\lambda_2<\dots<\lambda_k$, subtract $i$ from the size of the $i$th smallest part to get a partition with parts $0\le\lambda_1-1\le\lambda_2-2\le\dots\le\lambda_k-k$ with $\le k$ parts (after exluding the $0$s), whose conjugate is a partition with the largest part $\le k$. The "staircase" we subtracted has $1+2+\dots+k=\binom{k+1}{2}$ cells. That yields the summand on the right-hand side:
$$
q^{\binom{k+1}{2}}\prod_{i=1}^{k}{\frac{1}{1-q^i}}.
$$
I think this is about as simple as it gets. The Durfee square need not be involved, as you can see.


Identifying Vocal Harmonies

Question: I have been trying to improve my songwriting, and have hit a block when it comes to vocal harmonies.  To train myself in this regard I have been listening to a lot of Beatles tunes and other rock songs that involve harmonies, and I am having a really hard time picking them out. I can usually sing along with the main vocals, but if I try to sing the harmony parts I get stuck pretty quickly.
I am sure voice lessons would be the best path to take, but that's not an option for me right now, but I hope to take some eventually.  For the time being, I have done some research on constructing vocal harmonies and learned about using thirds and sixths, contrary motion, certain intervals to avoid etc., but I want to figure out how to begin to hear the different voices in a given song and eventually be able to pick out a part and sing along with it.  I would assume more work on recognizing intervals would help, but is there anything more specific to vocal harmonies I can do to follow along?
Answer: Beatles harmonies are a little difficult to figure out because Paul and John used a lot of diminished 7ths and 5ths and were quite unconventional.  Not to mention that they would usually harmonize down scale (using lower notes than the main voice) instead of up scale (using higher notes than the main voice) as is most common.
I would suggest starting with something a bit easier.  Something with simple up scale 3rds and 6ths to complete a harmony.  These are called tight harmonies.  For example, The Eagles, STYX, and practically every other pop song you hear out there.  Try these kind of harmonies first until your ear is trained to recognize the notes automatically.  Then you can take on chord harmonizers like The Beatles; Simon and Garfunkel; Crosby, Stills and Nash, and The Indigo Girls.
Here's a link for you
Answer: A good start point will be thirds. A lot of the more simple harmony is sung this way. Think Everly Brothers, or Beatles All My Lovin'. The basic tune is sung, and the harmony is a third on top. Consider the scale - we'll stick to C maj. Going up the scale, if a C note is sung, a third above it will sound good, thus, E. Next, D, and a third above is F. Then E, and the harmony note is G. Some of the intervals are major, some minor thirds, but as long as the two notes are from the particular key, it works. On a keyboard, it's easy to see. When in C, the 'main tune' note will have a harmony the next-but-one white note above.
Obviously, this will work for any key, using the appropriate scale note - minor as well.The harmony that sounds a bit bare is the 5th. It fits in with the underlying chord (that's the main point), but because there's no third involved, it sounds hard. Use it as the third note in harmony. As in, going back to the first para., if a C and an E are sung, the third harmony is usually the G, which gives 1,3 and 5. That can be under or over. Ears are pretty good at deciding.
This is only a start point. The harmonies will follow the chord structure, otherwise they will not fit. Look at barber shop stuff. The harmonies go where least expected, but still fit with the underpinning chords. Some of the old 'theory and rules of harmony' don't seem to be adhered to these days, as music and tastes change, but it's the old adage 'if it sounds good...
Answer: There may be some good ideas to be found in the answers to this related question:
How do I learn to detect chord voicing by ear?
Answer: Recognizing intervals is the vertical method. That's when you hear a chord and pick out the root, 3rd, 5th, 7th, etc. It's useful, but you should also do ear training with the horizontal method. Often this is easier. You pick any note that's being sung or is part of the chord, and you "follow" it across several measures, going up or down only a step or two. So if you have a chord progression C -> F -> G, you might start with the note C, and if you followed it, you would either go C -> C -> D, or C -> C -> B. Then you would go back listen to E, and you would hear E -> F -> G, or E -> D -> D, etc. This is helpful for determining chords, but can help with harmonies, especially when the harmony is the same note several times in a row.

Identifying Vocal Harmonies


Como adicionar campos adicionais no formulário de cadastro WordPress (Woocommerce)

Question: Tenho um site em Wordpress, e uso um plugin de loja virtual (woocommerce) gostaria de adicionar um campo CPF/CNPJ no cadastro de cliente da loja, como poderia fazer isso?
Answer: Você vai usar o plugin WooCommerce Extra Checkout Fields for Brazil que foi desenvolvido por um brasileiro porque nossas lojas aqui sempre precisam ter o CPF no checkout, segue o link: https://br.wordpress.org/plugins/woocommerce-extra-checkout-fields-for-brazil/
Comment: Muito obrigado <3


Passar um array de objetos para um component no angular 8

Question: Boa tarde,
Gostaria de uma ajuda para passar um array de objetos para um component no angular 8.
No caso tenho um formulário que utilizo em duas partes no meu código em um deles preciso desse formulário em branco e no outro preciso que ele venha preenchido com informações do banco.
O em branco é para cadastrar novos serviços e o preenchido é para editar um serviço.
Então quando faço a chamada no arquivo HTML para carregar essas informações não consigo passar esses dados para o component.
Já tentei com o @Input, mas sem sucesso.
Aqui faço a chamada do component app-form-service:

<ion-content>
  <app-form-service></app-form-service>
</ion-content>

Aqui é o component onde preciso carregar as informações do DB:
<ion-content>
  <form action="">

    <ion-item>
      <ion-label>Categorias</ion-label>
      <ion-select>
        <ion-select-option value="01">Cabelo</ion-select-option>
        <ion-select-option value="02">Pedicure</ion-select-option>
        <ion-select-option value="03">Manicure</ion-select-option>
        <ion-select-option value="04">Pele</ion-select-option>
        <ion-select-option value="05">Sobrancelha</ion-select-option>
        <ion-select-option value="06">Maquiagem</ion-select-option>
        <ion-select-option value="07">Bronzeamento</ion-select-option>
      </ion-select>
    </ion-item>
    <ion-item>
      <ion-label position="floating">Título do serviço</ion-label>
      <ion-input></ion-input>
    </ion-item>
    <ion-item>
      <ion-label position="floating">Descrição</ion-label>
      <ion-input></ion-input>
    </ion-item>
    <ion-item>
      <ion-label position="floating">Preço</ion-label>
      <ion-input></ion-input>
    </ion-item>
    <ion-item>
      <ion-label position="floating">Tempo do serviço (em minutos)</ion-label>
      <ion-input></ion-input>
    </ion-item>

    <ion-button type="submit" expand="block">Cadastrar</ion-button>
  </form>
</ion-content>

Comment: Mas vc não utiliza um **model** pra isso?
Comment: @LeAndrade poderia mostrar um exemplo de como utilizar o model?
Comment: Basicamente um model é uma classe Javascript (Typescript) que serve de modelo(espelho) para os dados retornados pelo Banco (Api), vc instancia a classe e pode usá-la em formulários, espelhando os dados e enviando o model para o banco. Da uma pesquisada na diretiva do Angular chamada **ngModel**.
Comment: Você poderia compartilhar o código TypeScript? Nos seletores dos seus componentes (markups 'xml') não ví os atributos para enviar informações do componente pai (parent) para o component filho(child) via anotação @Input.
Answer: Suponha que você tenha um componente "Pai" (parent component)
**componente-pai.ts**
----------

@Component({
    selector: 'componente-pai',
    templateUrl: './componente-pai.html',
})
export class ComponentePai implements OnInit {
    public valorEnviado: string;

Abaixo o template (markup) do componente pai:
**componente-pai.html**
----------

<componente-filho [valorRecebido]="valorEnviado"></componente-filho>

E um componente "Filho" (child component)
**componente-filho.ts**
----------

@Component({
    selector: 'componente-filho',
    templateUrl: './componente-filho.html',
})
export class ComponenteFilho implements OnInit {
    @Input() public valorRecebido: string;

Abaixo o template (markup) do componente filho:
**componente-filho.html**
----------

Mostrando valor recebido: {{ valorRecebido }}

Comment: Para passar um Array de objetos a lógica é exatamente a mesma, ao invés de passar uma `string` você irá passar um `Array`