Please help me compute this$ \sum_m\binom{n}{m}\sum_k\frac{\binom{a+bk}{m}\binom{k-n-1}{k}}{a+bk+1}$

Question: Compute following:
$$
\sum_m\binom{n}{m}\sum_k\frac{\binom{a+bk}{m}\binom{k-n-1}{k}}{a+bk+1}
$$
Only consider real numbers a, b such that the denominators are never 0.
Now I simplify it into
$$
-\frac{1}{n}\sum_k\binom{n}{k}\binom{-n}{a+bk+1}(-1)^{a+bk+k}
$$
I have problem with this question in which I can't eliminate coefficient b.
But I can't find any formula to get answer.Please help me!
Answer: Here is a slightly different variation of the theme. It is convenient to use the coefficient of operator $[z^n]$ to denote the coefficient of $z^n$ of a series. This way we can write e.g.
\begin{align*}
[z^k](1+z)^n=\binom{n}{k}
\end{align*}

We obtain
  \begin{align*}
\sum_{m=0}^{n}&\binom{n}{m}\sum_{k=0}^{n}\frac{1}{a+bk+1}\binom{a+bk}{m}\binom{k-n-1}{k}\tag{1}\\
&=\sum_{k=0}^{n}\frac{(-1)^k}{a+bk+1}\binom{n}{k}\sum_{m=0}^{n}\binom{n}{m}\binom{a+bk}{m}\tag{2}\\
&=\sum_{k=0}^{n}\frac{(-1)^k}{a+bk+1}\binom{n}{k}\binom{a+bk+n}{n}\tag{3}\\
&=\frac{1}{n}\sum_{k=0}^{\infty}(-1)^k\binom{n}{k}\binom{a+bk+n}{n-1}\tag{4}\\
&=\frac{1}{n}\sum_{k=0}^{\infty}(-1)^k[z^{k}](1+z)^{n}[u^{n-1}](1+u)^{a+bk+n}\tag{5}\\
&=\frac{1}{n}[u^{n-1}](1+u)^{a+n}\sum_{k=0}^\infty(-1)^k(1+u)^{bk}[z^k](1+z)^n\tag{6}\\
&=\frac{1}{n}[u^{n-1}](1+u)^{a+n}(1-(1+u)^b)^n\tag{7}\\
&=\frac{(-1)^n}{n}[u^{n-1}](1+u)^{a+n}\left(\sum_{j=1}^\infty\binom{b}{j}u^j\right)^n\tag{8}\\
&=0
\end{align*}
Comment:

In (1) we write lower and upper limits of the sum.
In (2) we exchange the sums, do small rearrangements and use the identity
\begin{align*}
  \binom{k-n-1}{k}=(-1)^k\binom{n}{k}
  \end{align*}
In (3) we apply Vandermonde's identity. With $q:= a+bk$ we get
\begin{align*}
  \sum_{m=0}^{n}\binom{n}{m}\binom{q}{m}=\sum_{m=0}^{n}\binom{q}{m}\binom{n}{n-m}=\binom{q+n}{n}
  \end{align*}
In (4) we use the identity
\begin{align*}
\frac{q}{p-q+1}\binom{p}{q}=\binom{p}{q-1}\\
  \end{align*}
and we also change the uppper limit of the series to $\infty$ without changing anything since we add only zeros.
In (5) we apply the coefficient of operator twice
In (6) we use the linearity of the coefficient of operator and do some rearrangements
In (7) we apply the substitution rule of the coefficient of operator
\begin{align*}
  A(u)=\sum_{k=0}^\infty a_ku^k=\sum_{k=0}^\infty u^k[z^k]A(z)
  \end{align*}
In (8) we use the binomial series expansion and observe the smallest power of $u$ is $n$ so that the coefficient $[u^{n-1}]$ is zero.
Comment: @MarkoRiedel: Thanks for this nice comment. But retirement? Surely you're joking Mr. Riedel! :-)  Awaiting many inspiring answers from you ....
Comment: (+1). Good work, better than what I have. I see I can retire soon.
Comment: The detour through $[z^k] (1 + z)^n$ is not needed, you go back to binomial coefficients anyway.
Comment: @vonbrand:  Many thanks for the hint and also for the upvotes, professor! In fact I do not fully agree, since the motivation is to also present this technique in a methodologically coherent way for those who are not familiar with it. So, I do  not necessarily focussing on the shortest possible road. This technique is based upon P.G. Egorychev's *[classic](https://www.amazon.com/Representation-Computation-Combinatorial-Translations-Mathematical/dp/0821845128)*.
Answer: Suppose we seek to evaluate
$$\sum_{m=0}^n {n\choose m}
\sum_{k=0}^{n+1} \frac{1}{a+bk+1}
{a+bk\choose m} {k-n-1\choose k}.$$
Now we have
$${a+bk\choose m} =
\sum_{q=0}^m (-1)^{m-q} {a+bk+1\choose q}
\\ = (-1)^m + \sum_{q=1}^m (-1)^{m-q} {a+bk+1\choose q}$$
and hence
$$\frac{1}{a+bk+1} {a+bk\choose m}
= \frac{(-1)^m}{a+bk+1}
+ \sum_{q=1}^m \frac{1}{q} (-1)^{m-q} {a+bk\choose q-1}.$$
Now from the first component we get in the main sum
$$\sum_{m=0}^n {n\choose m}
\sum_{k=0}^{n+1} \frac{(-1)^m}{a+bk+1} {k-n-1\choose k}
\\ = \sum_{k=0}^{n+1} \frac{1}{a+bk+1} {k-n-1\choose k}
\sum_{m=0}^n {n\choose m} (-1)^m = 0.$$
We are thus left with the following sum:
$$\sum_{k=0}^{n+1} {k-n-1\choose k}
\sum_{m=0}^n {n\choose m}
\sum_{q=1}^m \frac{1}{q} (-1)^{m-q}  {a+bk\choose q-1}.$$
Working with the inner sum we obtain
$$\sum_{m=1}^n {n\choose m}
\sum_{q=1}^m \frac{1}{q} (-1)^{m-q}  {a+bk\choose q-1}
\\ = \sum_{q=1}^n \frac{(-1)^q}{q} {a+bk\choose q-1}
\sum_{m=q}^n {n\choose m} (-1)^m
\\ = \sum_{q=1}^n {n-1\choose q-1} \frac{1}{q} {a+bk\choose q-1}
\\ = \frac{1}{n}
\sum_{q=1}^n {n\choose q} {a+bk\choose q-1}.$$
Now put
$${a+bk\choose q-1} = {a+bk\choose a+bk-q+1}
= \frac{1}{2\pi i}
\int_{|z|=\epsilon} \frac{1}{z^{a+bk-q+2}} (1+z)^{a+bk} \; dz$$
to get
$$\frac{1}{n} \frac{1}{2\pi i}
\int_{|z|=\epsilon} \frac{1}{z^{a+bk+2}} (1+z)^{a+bk}
\sum_{q=1}^n {n\choose q} z^q \; dz
\\ = \frac{1}{n} \frac{1}{2\pi i}
\int_{|z|=\epsilon} \frac{1}{z^{a+bk+2}} (1+z)^{a+bk}
(-1 + (1+z)^n)\; dz $$
The inner constant term does not contribute and we are left with
$$\frac{1}{n} \frac{1}{2\pi i}
\int_{|z|=\epsilon} \frac{(1+z)^{a+bk+n}}{z^{a+bk+2}} \; dz
= \frac{1}{n}{a+bk+n\choose a+bk+1}
= \frac{1}{n}{a+bk+n\choose n-1}.$$
Returning to the main sum we thus have
$$\frac{1}{n} \sum_{k=0}^{n+1} {k-n-1\choose k}
{a+bk+n\choose n-1}
\\ = \frac{1}{n} \sum_{k=0}^{n+1} {-k\choose n+1-k}
{a+b(n+1)+n-bk\choose n-1}.$$
Note that $${-k\choose n+1-k}
= \frac{1}{(n+1-k)!} \prod_{q=0}^{n-k} (-k-q)
= \frac{(-1)^{n-k+1}}{(n+1-k)!} \prod_{q=0}^{n-k} (k+q)
\\ = \frac{(-1)^{n-k+1}}{(n+1-k)!} \frac{n!}{(k-1)!}
= (-1)^{n-k+1} {n\choose k-1}.$$
This means for the main sum
$$\frac{(-1)^{n+1}}{n} \sum_{k=1}^{n+1} {n\choose k-1}
(-1)^k {a+b(n+1)+n-bk\choose n-1}
\\ = \frac{(-1)^{n}}{n} \sum_{k=0}^{n} {n\choose k}
(-1)^k {a+bn+n-bk\choose n-1}.$$
Introduce
$${a+bn+n-bk\choose n-1}
= \frac{1}{2\pi i}
\int_{|z|=\epsilon} \frac{1}{z^n} (1+z)^{a+bn+n-bk} \; dz$$
We get for the sum
$$\frac{(-1)^{n}}{n} \frac{1}{2\pi i}
\int_{|z|=\epsilon} \frac{1}{z^n} (1+z)^{a+bn+n}
\sum_{k=0}^n {n\choose k} (-1)^k \frac{1}{(1+z)^{bk}}
\; dz
\\ = \frac{(-1)^{n}}{n} \frac{1}{2\pi i}
\int_{|z|=\epsilon} \frac{1}{z^n} (1+z)^{a+bn+n}
\left(1-\frac{1}{(1+z)^b}\right)^n
\; dz
\\ = \frac{(-1)^{n}}{n} \frac{1}{2\pi i}
\int_{|z|=\epsilon} \frac{1}{z^n} (1+z)^{a+bn+n}
\frac{((1+z)^b-1)^n}{(1+z)^{bn}}
\; dz
\\ = \frac{(-1)^{n}}{n} \frac{1}{2\pi i}
\int_{|z|=\epsilon} \frac{1}{z^n} (1+z)^{a+n}
((1+z)^b-1)^n\; dz.$$
This is
$$\frac{(-1)^{n}}{n} [z^{n-1}] (1+z)^{a+n} ((1+z)^b-1)^n.$$
Note however that
$$((1+z)^b-1)^n =
\left({b\choose 1}z + {b\choose 2}z^2 + \cdots\right)^n
= b^n z^n + \cdots$$
so there  is no  coefficient on $[z^{n-1}]$  because the  powered term
starts at $z^n.$ Therefore the end result of the whole calculation is
$$\Large\color{#0A0}{0}.$$
Remark. We have made several uses of
$${n\choose m} = \sum_{q=0}^m (-1)^{m-q} {n+1\choose q}.$$
If this is not considered obvious we can prove it with the integral
$${n+1\choose q} =
\frac{1}{2\pi i}
\int_{|z|=\epsilon}
\frac{1}{z^{q+1}} (1+z)^{n+1} \;dz$$
to get
$$\frac{1}{2\pi i}
\int_{|z|=\epsilon}
\frac{1}{z} (1+z)^{n+1}
\sum_{q=0}^m (-1)^{m-q} \frac{1}{z^q}\;dz
\\ = \frac{1}{2\pi i}
\int_{|z|=\epsilon}
\frac{(-1)^m}{z} (1+z)^{n+1}
\frac{1-(-1/z)^{m+1}}{1+1/z}
\\ = \frac{1}{2\pi i}
\int_{|z|=\epsilon}
(-1)^m (1+z)^{n+1}
\frac{1-(-1/z)^{m+1}}{1+z}
\; dz
\\ = \frac{1}{2\pi i}
\int_{|z|=\epsilon}
(-1)^m (1+z)^{n}
(1-(-1/z)^{m+1})
\; dz
\\ = - (-1)^m \times (-1)^{m+1} {n\choose m}
= {n\choose m}.$$


field_collection_item not updating / old data preserved

Question: I am using SalesForce suite to pull data from SalesForce to Drupal.
In the SalesForce object I have multiple date fields.  These fields needs to map to a field-collection in the node.  The field-collection can have multiple (unlimited) values.
So for example in the SalesForce object I have

sales_force_object -> start_date
sales_force_object -> event_date
sales_force_object -> end_date

which needs to map to

node -> the_dates [0] = sales_force_object -> start_date
node -> the_dates [1] = sales_force_object -> event_date
node -> the_dates [2] = sales_force_object -> end_date

The solution was to add 'temporary' fields on the node, let's call them:

node -> sync_start_date
node -> sync_event_date
node -> sync_end_date

When I get data from SalesForce (using pull; and yes the data comes through OK) - I map the values from the SalesForce object to the sync fields.  Then just before the node is saved (updated), I use hook_node_presave to take values from the sync fields and create the field-collection items.  This is the code:
  $fc = field_collection_item_load($key_dates_entity_id);
  $fc_wrapper = entity_metadata_wrapper('field_collection_item', $fc);
  $fc_wrapper->field_date->set((int) $date);
  $fc_wrapper->save();
  field_attach_update('node', $node);
  field_attach_presave('node', $node);
  entity_get_controller('node')->resetCache([$node->nid]);

You can safely assume that $key_dates_entity_id is the correct field-collection entity ID.
Inspecting the code I can see the entity is correctly updated (nothing wrong with the data), and when I check the MySQL general-log, I can see the data being saved to the database, however, when the set of instructions end, the old (cached) data is also saved.  In other words the DB is updated twice - once with the new value, and once with the old values: net result is field collection items are not updated.
I have tried all sorts of combinations - nothing works.  Any help please.
Answer: I would love to tell you why, but I have not been able to figure it out: I just know it works.
Initially I executed the code above in hook_node_presave($node), but obviously it did not work.  So I figured I should try hook_node_update($node) - but that did not work either.
Then I discovered drupal_register_shutdown_function and now my hook_node_update looks like this:
function mymodule_node_update($node) {
  if ($node->type === 'node_type') {
    drupal_register_shutdown_function('_update_from_sync_fields', $node);
  }
}

node_type is the type of node I am checking against.  Any case, once the node is actually saved - that is all processing is done, db transactions completed, etc - drupal will call my shutdown function.  Now when I update the field values, and in specific field-collection fields - they are saved.
Of-course saving these fields and calling:
  field_attach_update('node', $node);
  field_attach_presave('node', $node);
  entity_get_controller('node')->resetCache([$node->nid]);

at the end of my shut-down function triggers hook_node_update again, but fortunately I have a token that tells me - so I do not execute the code again.
This solution works - what I am not happy about is the fact that it executes when Drupal is shutting down.
I think the problem is related to the fact that node_save starts a DB transaction, and when I update related entity (field-collection) items in hook_node_save or hook_node_presave I am starting another (nested) transaction.  Clearly my transaction updating field-collection items completes, but when the outer (first) transaction then complete, it is writing old/dirty data.
The trick is going to be to clear the dirty data from cache.  I was hoping entity_get_controller('node')->resetCache([$node->nid]); would do that - but clearly it does not?
So next I changed the hook_node_update to :
function mymodule_node_update($node) {
  if ($node->type === 'node_type') {
    _update_from_sync_fields ($node);
  }
}

in other words - from hook_node_update I simply call the 'shut-downfunction, then I rebuilt the drupal registry (drush rr`) and voila - it worked.  Now I am even more confused.  It is possible that my original code worked all along, but there was something wrong with the registry (or caches).  All things being equal, all the examples I read was right.
From hook_node_update, load the field collection entity, update and save the entity.  The clear the caches and do a field_attached_presave and field_attached_update like so:
  entity_get_controller('node')->resetCache([$node->nid]);
  field_attach_presave('node', $node);
  field_attach_update('node', $node);


Passar variável PHP no onclick="history.go(-1)"

Question: Estou tentando criar um botão que retorna ao formulário para corrigi-lo, desta forma mantendo todo o conteúdo digitado no HTML para que o usuário corrija a informação errada, porém enviando uma variável PHP para que eu possa fazer o UPDATE no MySQL, sem inserir um novo cadastro.
Pensei em enviar um ID:
<!DOCTYPE html>

    <form>
        <input type="hidden" name="ID" value="<?php echo $ID; ?>"/>
        <input type="submit" formaction="cancela_cadastro.php"
               value="Cancelar pedido">
        <input type="submit" formaction="../index.php" value="novo pedido">
        <input type="button" value="Corrigir"
            onClick="(history.go(-1), '<?php echo $ID; ?>')"/>
    </form>

porém sem sucesso. O ID é inserido no "cancela_cadastro.php?ID=XX" e no "../index.php?ID=XX" - este último sem querer, mas não faz diferença.
Gostaria de saber se há como enviar essa variável no history.go(-1), ou se há como enviar essa variável no retorno ao formulário preenchido.
PS. O history.go(-1) parou de funcionar quando atribuí essa variável PHP.
Comment: se voce quer que ele volte porque não valida o formulário ?
Comment: Obrigada pela resposta, acho que tive uma idéia com ela . Ao invés de retornar à submissão, eu mostro os campos preenchidos e peço para o usuário corrigir ou realmente enviar o formulário... Claro! Valeu mesmo!
Comment: Só pra complementar, não é possível passar outros parâmetros no método `go()` do `window.history`. Ele só aceita um `int` ou uma `string` contendo uma URL.
Comment: Obrigada pelas respostas. Acho que ficarei com um formulário "intermediário", entre o de envio e o de confirmação.
Answer: Ao invés de:
<input type="button" value="Corrigir" onClick="(history.go(-1), '<?php echo $ID; ?>')">

Sugiro:
<input type="button" value="Corrigir" onClick="parent.location.href='pagina_destino.php?id=<?php echo $ID; ?>'">

Comment: Testei a sua sugestão, porém o formulário original voltou em branco. Gostaria de passar o "ID" mantendo o que foi digitado anteriormente, mas ou menos como o botão "voltar" do navegador.
Comment: Na tela anterior os arquivos não foram salvos no banco de dados?
Answer: Ao invés de fazer history.go(-1) crie uma função onde você passa o ID e redireciona ele para a pagina que precisa por exemplo:

Caso queira da para adicionar o parâmetro page no método, para que você reutilize em outros lugares se necessário.
Comment: Vou testar aqui. Obrigada pela resposta!
Comment: De nada, se for útil e puder votar e aceitar agradeço


Attractive pairwise interaction point process

Question: I'm doing some spatial pattern analysis. After looking over some work on Markov Point Processes, I'm finding that all of the pairwise interaction processes are 'repulsive'.
In "Statistical Inference and Simulation for Spatial Point Processes" by Moller, he states simply that 'the attractive case is not well defined'. I was wondering if there are special cases in which it is well defined? How can I model an attractive pairwise interaction?
I suppose the alternative would be to move away from pairwise interaction and try to infer the intensity function for an inhomogeneous process?
Answer: The issue with attractive pairwise interactions is that the integral of the intensity of the process is infinite as each new point always increases the intensity for others in the neighbourhood.
If your process is mildly attractive on medium distances and strongly repulsive on very short ones (like physical particles), you can consider a pairwise interaction like Lennard-Jones or similar. See Van Lieshout (2000) Markov point processes and their applications or in a more applied fashion using R: Baddeley (2010) Analysing spatial point patterns in 'R'.
Else, the best way out is to use higher-order interactions such as area-interaction process (e.g. Baddeley and van Lieshout, 1995) or one of the processes in Geyer (1999) Likelihood inference for spatial point processes. Higher order interactions allow for both attractive and repulsive behaviour, e.g. points could be pairwise attractive, but triplets of points could be repulsive.
Depending on your application, the inhomogeneity of space could play a very important role. However, whether the intensity depends on the properties of underlying space or on the presence of other points should be dictated by theory. Even if these effects potentially could be hard to tell apart empirically.
Comment: (+1) Welcome to the site, Sergiy!
Comment: I am trying to figure out how to calculate the expected value of the are interaction point process, do you have any advice about how should i proceed? since for me is confusing because the conditional intensity function uses a "predefined point pattern" $\int_{W} \lambda(x_j,\textbf{x})$


UITextView with white background showing as Color Blended Layer in instruments and simulator

Question: So, i have some UILabels and UITextViews in a Cell. My table was scrolling a little slow and i tried the "Color blending layers" utility available in iOS simulator and Instruments. It show in red the layers that are blending and are causing the slow scroll.
All of the elements were blending, so i put a white background to the UILabels (same as the cell) and now the UILabels are ok (they had clearColor as background before).
I did the same with the UITextViews, i selected white background, but they are still showing in screen as blending layers (colored in red).
Every UITextView configuration is done in interface builder, i tried with every option, but they still appear in red.
What do i have to do to the UITextViews so that their layers don't blend?
Thanks in advance!
PD: Sorry but i can't include captures
Answer: I was struggling with this problem as well. I have a UITableView that was scrolling fine on iPhone but just jittered like crazy on the iPad. I turned on Color blending layers in Instruments and, like you said, it appears opaque = YES; and backgroundColor = [UIColor whiteColor]; have no effect.
Bob is correct too, UILabels are more performant. However my implementation relies on exclusion paths, which are only available in UITextView because of the exposed TextKit stack. I couldn't just use UILabel so out of desperation I tried this and the red on my UITextViews disappeared:
for (UIView *subview in textView.subviews) {
    subview.backgroundColor = theme.post.backgroundColor;
}

I know this is an old question but I've spent the better part of the day debugging this. I hope other people find it useful.
Comment: This removed the blended-layer from my textview. I added this loop in my initializer.
Answer: Well, the UITextView is a more advanced view that's scrollable and supports custom text formatting, so you might not be able to get it to 'not blend'. With other views you should check the opaque checkbox, but I doubt if that will work in this case.
Your best bet would be to use a UILabel instead. You could replace it with a UITextView when the user needs to edit a field, but using UILabel while scrolling should improve the speed considerably.
Comment: That's what i did, i replaced each UITextView with a UILabel and now the scrolls works fine :)
Thanks!
Comment: But the UILabel do not support touch events of the url.


How do you find the minima of a function in python?

Question: Say we have a quadratic function in x, where the domain of input x is Real Numbers. How can we find the minimum value of the function (output y) in a programming language like python?
Immediately what strikes me is to use gradient descent but then again how do I calculate the derivatives for any given function? (say sin(x), log (x), etc.) I need a solution from scratch in any programming language.
Using loops is clearly not feasible because the input x can be any real number. It is not possible to check the output value (y) of the function for every possible value of input (x).
I encountered this question in an interview where he went on to say I am free to do it in SQL as well.
Any help would be greatly appreciated.
Answer: There are a bunch of numerical optimization libraries for most of the programming languages. In python you can use scipy.optimize.
Example:
<code>    import numpy as np
    from scipy.optimize import minimize

    fun = lambda x: np.sin(x)
    x0 = [1.]
    res = minimize(fun, x0)
    print(res.x, fun(res.x))
</code>
Comment: If you aren't interested in implementing the method yourself, then this is the answer. It's worth noting that you can also specify which algorithm you'd like to use within the options of minimize (and other similar functions).


How to study a javascript-based roulette's pattern?

Question: So recently I've been playing on an online roulette and after some time on this site I detected a pattern the roulette has, like I have the feeling when the green will come out for example. Is it possible to create a script based on the roulette's code and that way getting at least probabilities of what will come next? Should I know JavaScript?
Comment: Do you have access to the underlying source code? This doesn't quite make sense.
Comment: I think I do. The site has a section where it shows the code that roulette uses in order to demonstrate the 'randomness'.
Answer: javascript is client side, it runs in your local browser.  The only use you might have is to have a page you have written, with javascript, to take a snapshot, or parse through the roulette site page and extract the wheel numbers which you could then perform your analysis on. The wheel numbers are coming from their server (not from javascript.)  If this a real (money) site, it won't work, the numbers will be random enough such that any advantage you might (read: won't) extract will be more than offset by the enormous 5.5% house edge on the bets. That feeling in your in your gut is simply you randomly being correct a couple of times. Your time would be better spent writing a limit poker machine learning model.
Comment: Now that I remember, there is a chrome extension that predicts the color coming out but AFTER the countdown reach to 0, how is it possible? Is it possible to take advantage and edit that extension to predict before the wheel runs?
Comment: Is this a real money site, or just somebody's for-fun javascript roulette game?
Comment: It's a real one. I started with a free dollar from the site and made 80
Comment: Here's some free advice: 1) You will never beat roulette in the long run online or in a casino.  2) That code they showed you regarding how they generate random numbers may be bogus.  Don't forget they know your bet, you don't know their code.  3) It's in their best interest for you to feel like you can win. 4) Go ahead and try and cash out that $80 bucks, see just how easily they will cash you out.  You cannot win, and you shouldn't try. Best of luck.
Comment: What about the extension I'm talking about? I tried it and its 100% accurate. Can it be modified for earlier prediction? How did the guy coded it?
Comment: If it is a javascript chrome extension you should look at his or her code.
Comment: Alright, will do it when I'm back home. Thanks for your time
Comment: The add on probably reads the server response string, possibly an ajax response, as xml or even plain text.  After it has left the server it's no longer secret.  It then parses that response and "predicts" the number milliseconds before the page element is updated, or forces the page to delay it's update as a kind of magic trick effect.


D'Alembert's Solution

Question: How are these results obtained in d'Alembert's Solution to the $1+1$ wave equation?
After getting, $\frac{1}{c}\psi(c)=f'(x)-g'(x)$ we integrate from $a$ to $x$ and we get
$$f(x)-g(x)=\frac{1}{c}\int_{a}^{x}\psi(s)\,ds.$$
My question is: Why do we integrate it from $a$ to $x$?
I think we require answer in variable $x$, that's why we integrate..
Comment: $a$ is an arbitrary parameter, corresponding to the integration constant. This is similar to the usual 'indefinite integral' notation, but more coherent: $$\frac{1}{c} \int \psi(x) dx +C$$
Answer: The parameter $a$ is arbitrary.  However, the author was a bit careless with an intermediate step.
Note that from $f'(x)-g'(x)=\frac1c\psi(x)$ we have for any constant $a$
$$f(x)-g(x) -(f(a)-g(a))=\frac1c \int_a^x \psi(x')\,dx'\tag1$$
Then, since $f(x)+g(x)=\phi(x)$ we see that
$$f(x)=\frac12\phi(x)+\frac1{2c}\int_a^x \psi(x')\,dx'+f(a)-g(a)\tag 2$$
and
$$g(x)=\frac12 \phi(x)-\frac1{2c}\int_a^x \psi(x')\,dx'-(f(a)-g(a))\tag 3$$

In the referenced development, the author omitted the term $f(a)-g(a)$ from the expressions for $f(x)$ and $g(x)$.  However, these terms cancel in the final answer.

Finally, from $u(x,t)=f(x+ct)+g(x-ct)$ we find that
$$u(x,t)=\frac12\left(\phi(x+ct)+\phi(x-ct)\right)+\frac1{2c}\int_{x-ct}^{x+ct}\psi(x')\,dx'$$
and the term $f(a)-g(a)$ is absent as expected.
Comment: Thanks for details... but why do you integrate it from $a$ to $x$ ? Can't we write $f(x)-g(x)=\frac{1}{c}\int{\psi(x)\,dx}+K$.
Comment: @Goldy One can write $f(x)-g(x)$ in terms of an arbitrary antiderivative of $\psi$.  But then, how does that lead to the coveted solution?

D'Alembert's Solution


Search API Database Search score calculation

Question: I'm trying to understand how the Search API Database Search calculates the score for a search result. I understand Solr uses the Lucene scoring model and there's also command that can be used to output the actual calculation (debugQuery=true).
Is there documentation and/or a debug command I could use to understand how the engine is coming up with the score for a result?
Answer: When you use debugQuery=true in a query, you can see all debug informations and how solr calculate scores for the result documents.


How to pass a custom error message to a jasmine matcher?

Question: In all the testing frameworks I have used, there is an optional parameter to specify you own custom error message.
This can be very useful, and I can't find a way to do this out of the box with jasmine.
I've had 3 other developers ask me about this exact functionality, and when it comes to jasmine I don't know what to tell them.
Is it possible to specify your own custom error message on each assertion ?
Answer: Update 2022; Use .withContext(...) method instead of below (as optional parameter is deprecated).

Jasmine already supports optional parameter in all matchers (toBe, toContain, and others), so you can use:
expect(true).toBe(false, 'True should be false').

Then in output it will look like this:
Message:
    Expected true to be false, 'True should be false'.

Link to commit (this is not described in documentation):
https://github.com/ronanamsterdam/DefinitelyTyped/commit/ff104ed7cc13a3eb2e89f46242c4dbdbbe66665e
Comment: It doesn't work with `toEqual` in Jasmine 3.6.3 for some reason
Comment: @Finesse not just that, all optional parameters are deprecated.
Answer: If you take a look at the jasmine source code you will see that there is no way to set the message from outside a matcher. For example the toBeNaN matcher.
/**
 * Matcher that compares the actual to NaN.
 */
jasmine.Matchers.prototype.toBeNaN = function() {
  this.message = function() {
      return [ "Expected " + jasmine.pp(this.actual) + " to be NaN." ];
  };

  return (this.actual !== this.actual);
};

As you can see the messages is hard coded into the matcher and will be set when you call the matcher. The only way I can think of to have your own messages is to write your matcher like described here
Comment: If you want add more details to jasmine hardcoded message - all matchers have optional parameter for that - check @Xotabu4 answer for more detials
Answer: Chain-call withContext() right after expect(). Example:
expect(myValue)
  .withContext("This message will be printed when the expectation doesn't match")
  .toEqual({foo: 'bar'});

Answer: This issue is tracking interest in implementing custom error messages using a .because() mechanism.
In the meantime, avrelian has created a nice library which implements custom error messages using a since() mechanism – jasmine-custom-message.
Answer: Yes, it can be done.
You may define a custom matcher in global scope, overriding the error message in jasmine as below:
beforeEach(function () {
    jasmine.addMatchers({
        toReport: function () {
            return {
                compare: function (actual, expected, msg) {
                    var result = {pass: actual == expected};
                    result.message = msg;
                    return result;
                }
            }
        }
    });
});

Comment: Excellent, that's exactly what I was looking for, thank you!


Discrete maths/set theory question

Question:
*22. Suppose $\lvert A \rvert=n$, and let $F=\{f \mid \,f \text{ is a one-to-one, onto function from } I_n \text{ to } A\}.$
  $I_n=\{i∈Z^+ \mid i≤n\}$. $\lvert A\rvert$ is the cardinality of A.
(a) Prove that $F$ is finite, and $\lvert F\rvert=n!$. (Hint: Use induction on $n$.)
(b) Let $L = \{ R \mid \, R \text{ is a total order on } A \}$. Prove that $F \sim L$, and therefore $\lvert L\rvert= n!$.
(c) Five people are to sit in a row of five seats. In how many ways can they be seated?

From  http://users.metu.edu.tr/serge/courses/111-2011/textbook-math111.pdf p.g. 314.  I've seen answers and don't fully understand.  My main issue is part (a) but might as well give answer to all.  Can anyone give a clearer write up of the answer.  Alternative methods also welcome.
UPDATE:  I need help with the below answer.  I don't how to prove that $h$ is one-to-one based on the suggestion.  Why is $(f(i), g(i))$ an element of $h(f)$ and not $h(g)$?
Comment: "Alternative methods" ti what ?
Comment: @MauroALLEGRANZA from his source I believe that $I_n = \{i \in \mathbb{Z}^+ | i \leq n\}$
Comment: In a nutshell, a function $f$ is a way to order the set $A$ with $n$ elements: how many ways we have to order it ?
Answer: To prove (a) using induction over $n$:
Base: $n = 1$. So we have: $|A| = 1$, or $A = \{ a_1 \}$ for some object $a_1$, and we have $I_1 = \{ 1 \}$. Then there is only $1$ function $f$ possible from $I_1$ to $A$, namely $f(1) = a_1$. Thus, $|F| = 1 = 1!$. Check!
Step: Assume (inductive hypothesis) that $|F| = k!$ for some $k$.  Now let's use that to show $|F|= (k+1)!$ in the case of $k+1$.
OK, so we have $|A|=k+1$, i.e. $A = \{ a_1, a_2, ..., a_k, a_{k+1} \}$. We also have $I_{k+1} = \{ 1,2,3,..., k, k+1 \}$. Now, how many one-to-one and onto functions are there from $I_{k+1}$ to $A$?  Well, let's do this by first mapping $k+1$ to an element in $A$, and then mapping all the other numbers $1$ through $k$.
So, what can $f(k+1)$ be?  Given that this is the first object we map, all options are open, so it can be mapped to any element in $A$, so there are $k+1$ options: $f(k+1) = a_1$, or $f(k+1) = a_2$, or ... or  $f(k+1) = a_{k+1}$. Now, once we have fixed $f(k+1)$, there are $k$ elements left in $A$ that all the others numbers $1$ through $k$ need to be mapped to in a one-to-one and onto way. Or, maybe a little more cleanly: if $f(k+1) = a_i$, then the set $A' = A \setminus \{ a_i \}$ will have $k$ elements, i.e. $|A'|=k$. So, we can apply our inductive hypothesis: there will be $|F|=k!$ ways to map elements $1$ through $k$ (i.e. $I_k$) to $A'$.
So, since there are $k+1$ ways to map $k+1$ to an element in $A$, and $k!$ ways to map all the other numbers $1$ through $k$ to the rest of $A$ in a one-to-one and onto way, there are $(k+1)*k! = (k+1)!$ ways to map $I_{k+1}$ to $A$ in a one-to-one and onto way. Check!
Comment: Thanks for that, can you have a quick look at the issue i edited above?  It concerns part (b) and proving h is one to one.
Answer: For part ($b$):
Let $X := \{j \in I_n \mid f(j) \neq g(j)\}$; observe that $X \neq \varnothing$ (because $f \neq g$ by assumption), so it has minimum (being a non-empty subset of $\mathbb N$). Define, then, $i := \min X$ (in particular $i \in X$); we have that $(f(i), g(i)) \in h(f)$ if and only if (using the definition of $h(f)$) $f^{-1}(f(i)) \leq f^{-1}(g(i))$, that is (since $f$ is bijective) if and only if $i \leq f^{-1}(g(i))$. To see that this holds, we show that $f^{-1}(g(i)) \in X$: in facts, $f(f^{-1}(g(i))) = g(i) \neq g(f^{-1}(g(i)))$, where the last inequality holds because if it were $g(i) = g(f^{-1}(g(i)))$, since $g$ is injective we would get $i = f^{-1}(g(i))$, and since $f$ is a bijective function we would obtain $f(i) = f(f^{-1}(g(i))) = g(i)$, which contradicts the fact that $i \in X$. Thus $f(f^{-1}(g(i))) \neq g(f^{-1}(g(i)))$, and so $f^{-1}(g(i)) \in X$; then $i \leq f^{-1}(g(i))$ being $i$ the minimum of $X$ (more precisely, we have $i < f^{-1}(g(i))$ since we just proved that equality leads to a contradiction), and so we deduce that $(f(i), g(i)) \in h(f)$.
In a similar way, we can prove that $(f(i), g(i)) \notin h(g)$: first, we have $(f(i), g(i)) \notin h(g) \iff g^{-1}(f(i)) > g^{-1}(g(i)) \iff g^{-1}(f(i)) > i$, so we can prove that $g^{-1}(f(i)) \in X \setminus \{i\}$. This is true because $i = g^{-1}(f(i))$ leads again to the contradiction $g(i) = f(i)$, so $i \neq g^{-1}(f(i))$; then $g(g^{-1}(f(i))) = f(i) \neq f(g^{-1}(f(i)))$. Thus $g^{-1}(f(i)) \in X \setminus \{i\}$, which means that $g^{-1}(f(i)) > i$, and so we conclude $(f(i), g(i)) \notin h(g)$.

Discrete maths/set theory question


Função upload multi attchements

Question: Estou a tentar criar uma função para fazer upload de vários ficheiros ao mesmo tempo mas mesmo só com um obtenho um erro.
O que poderei estar a programar mal?
'FILE DIALOG OPENS UPLOAD PANEL
Private Sub Comando715_Click()
Call Selectfile
End Sub

A função criada é a seguinte:
Public Function Selectfile() As String
Dim Fd As FileDialog
Set Fd = Application.FileDialog(msoFileDialogOpen)
With Fd
.AllowMultiSelect = False
.Title = "Por favor selecione as fotos desta peça a anexar"
If .Show = True Then
    Selectfile = .SelectedItems(1)
    Me.Anexo412 = Selectfile
Else
    Exit Function
End If
Set Fd = Nothing
End With
End Function

O erro que me dá no VBA está na seguinte linha
Dim Fd As FileDialog

Alguém me poderá ajudar a completar o código?
Answer: O obejeto FileDialog é fornecido pela biblioteca Microsoft Office [Nº da versão] Object Library. Provavelmente a referência não foi definida ou está corrompida.
Para ativar:
Editor VBA > Ferramentas > Referências

E marque a biblioteca.
Comment: Resolveu esse problemas contudo aparece um outro erro que passo a colocar cá.
`Me.Anexo412 = Selectfile`

O erro especificado é:
**Erro em tempo de execuçã '438':**
**O objeto não aceita esta propriedade ou método**
Comment: O ficheiro que estou a tentar carregar no `Anexo412` é um ficheiro **.jpeg**, como posso restringir o tipo de ficheiros que posso seleccionar, para não seleccione ficheiros de tipos que sejam indevidos?
Comment: Você precisa adicionar o anexo selecionado a alguma propriedade do obejto `Anexo412`. Lista completa de propriedades [aqui](https://msdn.microsoft.com/en-us/library/bb243266(v=office.12).aspx). Provavelmente é a `FilelName`. Ficaria assim: `Me.Anexo412.FileName = Selectfile`
Comment: Obrigado já esta exportar para o campo definido.
O codigo actual é:
Comment: @ Lúcio Rubens
'FILE DIALOG OPENS UPLOAD PANEL
Private Sub Comando715_Click()
Call Selectfile
End Sub
'FUNÇÃO CAIXA DE SELEÇÃO
Public Function Selectfile() As String
Dim Fd As FileDialog
Dim Filtro As FileDialogFilters
Set Fd = Application.FileDialog(msoFileDialogOpen)
With Fd
    'FILTRO DE IMAGENS
    Set Filtro = .Filters
    With Filtro
    .Clear
    .Add "Imagens", "*.jpeg;*.jpg"
    End With
    'NÃO PERMITIR MULTI-SELEÇÃO
    .AllowMultiSelect = False
    'DEFINE O NOME DA CAIXA DE SELEÇÃO
    .Title = " Por favor introduza as fotos da peça"
    If .Show = True Then
Comment: Este é o resto do codigo
    **'CODIGO DE COLOCAÇÃO DE ANEXO EM FORMULÁRIO
        Selectfile = .SelectedItems(1)
        Me.Anexo412.DefaultPicture = Selectfile
    Else
    MsgBox "Clicou no botão cancelar ao escolher imagem."
        Exit Function
    End If
    Set Fd = Nothing
End With
End Function**
Comment: Será que me pode ajudar a fazer com que esta função suporte multi selecção e carregar até 8 anexos com a mesma função.
Falta apenas esse pequeno pormenor para estar resolvida a minha questão.
Comment: O ideal é você criar uma nova pergunta, postando seu código atual.. Pois a dúvida dessa pergunta foi sobre o erro no objeto. @FredericoOliveira
Comment: E por favor, marca como "aceito" a resposta, para ajudar outros usuários com o mesmo problema!
Comment: Como faço para "aceitar a resposta"?
Comment: Faça um [tour](http://pt.stackoverflow.com/tour) para entender como o StackOverflow funciona. Mas para aceitar basta clicar no ícone ao lado da resposta
Comment: (http://pt.stackoverflow.com/questions/72684/carregar-multi-attachements-em-varios-anexos-em-formul%C3%A1rio)

Função upload multi attchements


Criar janela modal

Question: Estou começando um app:
import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
  View,
  StatusBar
} from 'react-native';
import Button from 'react-native-button';

import { Actions } from 'react-native-router-flux';

export default class ouvidoria extends Component {
  render() {
    return (
      <View style={styles.geral}>

        <StatusBar
          //hidden
          backgroundColor='#005288'
        />

        <View style={styles.botao}>
          <Button
            onPress={() => { Actions.formaanonima(); }}
            containerStyle={{ padding:10,
                              height:50,
                              width:300,
                              overflow:'hidden',
                              //borderRadius:4,
                              justifyContent: 'center',
                              alignItems: 'center',
                              backgroundColor: '#FFB504',
                              elevation: 10,
                              }}
            style={{fontSize: 24,
                    color: '#000'
                    }}>
            Cadastrar Manifestação
          </Button>
        </View>

      </View>
    );
  }
}

const styles = StyleSheet.create({
  geral: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#005288',
  },
  botao: {

  }
});

Procurei e não consegui encontrar como fazer para abrir janelas.
Gostaria que quando o usuário apertasse no botão abrisse uma janela perguntando se este já possui cadastro ou não, apenas com os botões de sim e não para decidir qual rota seguir.
Porém não encontrei este tipo de função no React-native nem em material de terceiros.
Answer: Um exemplo simples
Alert.alert(
  'Alert Title',
  'My Alert Msg',
  [
    {text: 'Ask me later', onPress: () => console.log('Ask me later pressed')},
    {text: 'Cancel', onPress: () => console.log('Cancel Pressed'), style: 'cancel'},
    {text: 'OK', onPress: () => console.log('OK Pressed')},
  ],
  { cancelable: false }
)

Voce pode ver mais aqui
Comment: Sabe se é possível editar a janela de alert?
Comment: O Alert não tem style configurável, pois ele usa o alert nativo de cada plataforma. Você pode usar o [Modal](https://facebook.github.io/react-native/docs/modal.html) do próprio React Native se quiser customizar a janela.

Criar janela modal


changing keys in a solo

Question: Let's say I'm playing in C and the progression is I ii V iii IV V I.
When the IV (Fmaj) is playing, what are your thoughts on what notes I can use.
I can obviously use anything in C which will sound natural in the mood of the song. However can I just ignore that and use the F major scale.
Since there is only one note different between the scales it should always sound natural right?
Comment: It wouldn't sound natural, but it would give you a pretty satisfying result.
Comment: http://music.stackexchange.com/questions/47745/lead-guitar-stay-in-single-key may be of interest.
Answer: There's the difference between being IN a key and ON a particular chord. Here, you're IN C, but ON F. All the C major notes will work, although as you're probably aware, some work better than others, and it depends where in the bar and also what order and length each is played.And also which chors precede and follow that bar. In your example, it's G, which feels like it'll lead back to I (C), which it does. So the melody, of any quality, doesn't want to hint at modulating to IV, 'cos that's not where the song is heading.
The only difference in the F notes is the Bb as opposed to the B natural. That is a pivotal note, belonging often in a C7 chord. Which, I'm sure you're aware, is the one used to lead on to F, funnily enough.So, by incorporating the Bb in a solo, you're inferring a change TO F, but you're already on it. At the end of the day, it's really down to the soloist, and the other notes, as I said earlier, but I think B is a better fit more times than Bb. You could also say that on a V chord (G), you should/could/would use F#, as that's the differring note from G.
Listen to 'Moon River', bar 3. Hank puts an F chord and writes a B natural over it, at the important beginning of that bar. Not a Bb.
Comment: Tim I really like this answer, thank you for your time and considered answer, it's charitable for us who are still trying to grasp simple concepts

changing keys in a solo


Duplicate webform data to second database?

Question: I want to duplicate the results from the webform module to a second database.
Is there a convenient way to do that, or will I need to manually write all the queries to store and retrieve data?
Comment: Thanks Letharion for re-framming the question, i exaclty wanted to to this.
Answer: I wouldn't try to tackle this at the Drupal level to be honest, it'll be a lot more trouble than it's worth.
If it was me I'd just add a trigger on the webform table that runs a stored procedure to copy the data into the second database.
There might be something you can do with Replication, but I'm not sure if it's granular enough to go down to the table level.


Set empty input field to ng-invalid on submit using AngularJS?

Question: I want to set input field to ng-invalid if a user clicks submit and the form fields are empty using AngularJS. I know a directive can be used to custom form validation and using $setValidity to manually set the input field but I'm not sure I need a directive to just highlight the empty/required fields on submit. Any help would be greatly appreciated. Thank you.
Here is the code I am working with:
HTML
<form name="SignUpForm ng-submit="submitUser()" novalidate>
<input type="text" name="dob" ng-model="dob" placeholder="Date of Birth" required />
Please provide a valid date of birth
<input type="text" name="email" ng-model="email" ng-pattern="/^([0-9a-zA-Z]([-\.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$/" placeholder="Email" required />
Please provide a valid email address
<button type="submit">Submit</submit>
</form>

SASS/CSS
input {
&.ng-valid.ng-dirty {
color: #fff;
background-color: rgba(146, 253, 156, 0.5);
border-color: #92fd9c;
box-shadow: inset 2px 2px 2px #92fd9c;
}
&.ng-invalid.ng-dirty {
color: #850000;
background: rgba(254, 186, 186, 0.5);
border: 1px solid #850000;
}

AngularJS
$scope.submitUser = function() {
if ($scope.signUpForm.$valid) {
// Set form values & construct data to send
} else {
$scope.response = "Please fill in the required fields";
}

Answer: I'm not sure I completely follow, but does this do what you want?
Plunker:
http://plnkr.co/edit/L5qzEJRKkdGogsE7IzAr?p=preview
HTML:
<form name="signUpForm" ng-submit="submitUser()" novalidate>
<input type="text" ng-class="{ errorinput: submitted && signUpForm.dob.$invalid }" name="dob" ng-model="dob" placeholder="Date of Birth" required />
Please provide a valid date of birth

<input type="text" name="email" ng-class="{ errorinput: submitted && signUpForm.email.$invalid }" ng-model="email" ng-pattern="/^([0-9a-zA-Z]([-\.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$/" placeholder="Email" required />
Please provide a valid email address

<button type="submit">Submit</button>
</form>

Javascript:
$scope.submitUser = function() {
  if ($scope.signUpForm.$valid) {

  } else {
    $scope.submitted = true;
  }
}

Answer: Add a ng-class into the specific input like textbox and set an invalid class on HTML. I am using kendo-UI so, I set k-invalid: true when ever it fails the condition.
<input ng-class="{'k-invalid': (condition === false)}" required>
this will highlight the input value as soon as the condition is false.


A question on gauge norm on Orlicz space

Question: I was reading Empirical Processes from "Weak Convergence and Empirical processes" by Van Der Waart and Jon Wellner. There I was studying a norm on a space of random variables defined as follows:
Let $\psi$ be a monotone nondecreasing, convex function with $\psi(0) = 0$ (*). The gauge (Luxemburg) norm of an integrable random variable X wrt $\psi$ is given by
$$\|X\|_{\psi} = \inf \left\{u>0: \mathbb{E}\left[\psi\left(\frac{|X|}{u}\right) \right] \leq 1\right\}$$
As an exercise, the book asks to prove that if $1\leq p\leq q$, then
$$\|X\|_{\psi_p} \leq \left(\log 2\right)^{p/q} \|X\|_{\psi_q}$$
where $\psi_p = e^{x^p}-1$ and all logs are natural logs.
My question is how to go about it. I have succeeded in proving the following results which may turn out to be useful here:
a) If $\psi$ and $\phi$ are two functions satisfying the requirement (*), and $\psi \leq \phi$, then $\|X\|_{\psi} \leq \|X\|_{\phi}$.
b) Given a constant $C \geq 1$, $\|X\|_{C\psi} \leq C\|X\|_{\psi} $
c) For $p \geq 1$, $(\log2)^{1/p}\|X\|_{\psi_p}$ is monotone nondecreasing in p. Note: $\psi_p$ as defined above.
d) For $\psi = x^p$, it is the standard $L_p$ norm of X.
I figured it would follow from (c) since the book hints at that but wasn't having much luck with it. I even tried splitting the domain of $e^{x^p}$ into two parts, $x\geq 1$ and $0 \leq x < 1$ and tried manipulating but that got me nowhere.
I appreciate any hints, ideas and even answers on this one.
Please note: One can associate several equivalent norms to an Orlicz space. This post is about the gauge (aka Luxemburg norm), as opposed to the Orlicz norm ( itself a special instance of Amemiya norm), see
Hudzik, Henryk; Maligranda, Lech, Amemiya norm equals Orlicz norm in general, Indag. Math., New Ser. 11, No.4, 573-585 (2000). ZBL1010.46031.
Answer: In the book, there is a hint, which is the following:

The function $\phi$ for which $\psi_p(x(\log 2)^{1/p})=\phi(\psi_q(x(\log 2)^{1/q}))$ is concave and satisfies $\phi(1)=1$ for $q\geqslant p$. Use Jensen's inequality.

The role of the function $\phi$ is to make a link between what is integrated when we consider $E[\phi_p(|X|/u)]$ and $E[\phi_q(|X|/u)]$ by a function which fulfills
the conditions of Jensen's inequality.
Exercice 2 tells us that the constant is optimal taking $X=1$.


Como fazer com que o textarea aumente de altura automaticamente até um certo limite?

Question: Gostaria de saber qual a melhor maneira de fazer com que o textarea aumente de altura automaticamente até o limite de 500px quando o usuário entrar com conteúdo.

Não utilize outra biblioteca além do Jquery.

CSS:
textearea{
    resize: none; /* impede que o próprio usuário altere o tamanho do textarea */
    width:300px;
    height:100px;
    overflow-y: auto;
}

Comment: tem um plugin jquery q faz isso
Comment: @user3230262 E qual é o plugin? Já vi que a resposta é longe de ser trivial, então referências externas ajudariam bastante...
Answer: Sempre que o textarea for editado, por qualquer meio (teclado, mouse, Ctrl+V, etc), verifique se seu tamanho na tela é menor que o tamanho do seu conteúdo real (i.e. o conteúdo que está sendo servido pela barra de rolagem) e, enquanto for, aumente o tamanho do elemento.
$("textarea").bind("input", function(e) {
    while( $(this).outerHeight() < this.scrollHeight +
                                   parseFloat($(this).css("borderTopWidth")) +
                                   parseFloat($(this).css("borderBottomWidth"))
           && $(this).height() < 500 // Altura máxima
    ) {
        $(this).height($(this).height()+1);
    };
});

Fonte: essa resposta no SOen.
Exemplo no jsFiddle. Notas:

Se você atribuir programaticamente o conteúdo do textarea, deverá invocar o código acima manualmente (pois o input não faz isso pra você);
O código acima talvez possa ser melhorado para evitar esse loop que incrementa de um por um, mas como a resposta original fazia assim (e estou sem tempo pra testar as alternativas) preferi deixar como estava.

O uso de outerHeight em vez de simplesmente height é para levar em conta o padding (e opcionalmente também a margin) em vez de se considerar somente a altura do conteúdo. Talvez por isso o incremento de um em um, já que caso contrário o cálculo seria mais complexo (e na prática, não reparei nenhum problema na performance percebida).

Minha resposta alternativa (no histórico de edição) não funciona em todos os casos, por diversos motivos. Minhas tentativas de calcular o tamanho do conteúdo por outros meios (ex.: usando um elemento auxiliar) também não tiveram sucesso, de modo que essa foi a solução mais completa e simples que achei.
Comment: Gostei da sua solução pelo detalhe que evita a barra de rolagem aparecer enquanto o tamanho do textarea não atingir o 500px, por isso irei atribuir como melhor resposta, apesar de não funcionar no IE. Ainda estou estudando ambos os códigos para realizar melhorias, obrigado pela colaboração.
Answer: Aqui fica outra ideia:
$('#texto').on('keyup onpaste', function () {
    var alturaScroll = this.scrollHeight;
    var alturaCaixa = $(this).height();

    if (alturaScroll > (alturaCaixa + 10)) {
        if (alturaScroll > 500) return;
        $(this).css('height', alturaScroll);
    }
});

Exemplo
Este código corre cada vez que uma letra é inserida (quando a tecla é solta) ou quando texto é copiado para o textarea com o evento onpaste.
Quando a tecla é levantada o código lê a altura do Scroll e da caixa. Se o scroll fôr maior então faz a caixa aumentar até ao limite de 500.
Como o @mgibsonbr referiu o evento input tem vantagens sobre o keyup, talvez boa ideia usar os três. O input tem a desvantagem de não ser aceite nalguns browsers. O IE sendo um deles.
Comment: @mgibsonbr, boa sugestão! Juntei essa ideia à resposta, obrigado e referí que o IE (para não fugir à tradição) nao lida bem com o `input`.
Comment: A vantagem do `input` sobre `keyup` (em teoria, pelo menos) é que se você segurar uma tecla e não soltar mais, o `textarea` vai sendo preenchido mas a altura não aumenta. E se ela passar de `500` enquanto se está fazendo isso, ela não aumenta mais - fica com a que estava naquele momento.
Comment: Não sei se você e o @mgibsonbr classificam como reparo técnico (gambiarra) isso, mas eu usaria uma aproximação das mais simples possíveis, e um timer para fallback (levíssimo, de 3 segundos pra cima).
Comment: @Bacco Acho que depende dos seus objetivos. Eu gostei do código da minha resposta porque é bastante preciso e não dá nenhum glitch visual. Mas com certeza muita gente ficaria hororrizada ao ver um loop que incrementa de um em um...
Comment: @mgibsonbr agora vocês precisam inventar um que diminua se o texto for cortado :)
Answer: Fiz uma pequena alteração para ele voltar ao tamanho padrão se a pessoa desistir de escrever e apagar o que tinha escrito deixando o textarea vazio.
No meu caso a altura é de 40px.
$('textarea[name="responder"]').on('keyup change onpaste', function () {
    var alturaScroll = this.scrollHeight;
    var alturaCaixa = $(this).height();

    if (alturaScroll > (alturaCaixa + 10)) {
        if (alturaScroll > 500) return;
        $(this).css('height', alturaScroll);
    }

    if( $(this).val() == '' ){
        // retonando ao height padrão de 40px
        $(this).css('height', '40px');
    }
});

Infelizmente não consegui fazer ele diminuir gradativamente quando a pessoa vai deletando letra por letra, mas no meu caso já foi o suficiente.
Espero que isso possa ajudar mais alguém e obrigado pela ajuda que me deram com este código.
Answer: //Dei uma alterada para pegar automaticamente todos os textboxes do formulário e fazer o resizer.
function ResizeTextArea(){
    for (var j=1; j < form.length-1; j++){
        if (form[j].type=="textarea"){

            txtBox = form[j];
            nCols = txtBox.cols;
            sVal = txtBox.value;
            nVal = sVal.length;

            nRowCnt = 1;

            for (i=0;i<nVal;i++){
                if ((sVal.charAt(i).charCodeAt(0) == 13) || (sVal.charAt(i).charCodeAt(0) == 10)){
                    nRowCnt = nRowCnt +1;
                }
            }

            if (nRowCnt < (nVal / nCols)) {
                nRowCnt = 2 + (nVal / nCols);
            }
            if (nVal == 0){
                nRowCnt = 1;
            }
            txtBox.rows = nRowCnt;
        }
    }
}

Answer: Solução completa com altura mínima e máxima e resolvendo problemas com scroll:
var textarea =
{
    tornarFlex:
        function (id_textarea, altura_minima, altura_maxima)
        {
            var textarea = document.getElementById(id_textarea);
            if (typeof altura_minima == 'undefined')
            {
                altura_minima = textarea.offsetHeight;
            }
            if (typeof altura_maxima == 'undefined')
            {
                altura_maxima = 0;
            }
            textarea.style.height = altura_minima + 'px';
            textarea.addEventListener('keyup', new Function("textarea.ajusta('" + id_textarea + "'," + altura_minima + ", " + altura_maxima + ");"));
        },
    ajusta:
        function(id_textarea, altura_minima, altura_maxima)
        {
            var textarea = document.getElementById(id_textarea);
            while
            (
                textarea.offsetHeight < textarea.scrollHeight
                && (!altura_maxima || textarea.offsetHeight < altura_maxima)
            )
            {
                textarea.style.height = (textarea.offsetHeight + 1) + 'px';
            };
            if (textarea.offsetHeight < altura_maxima)
            {
                textarea.style.overflowX = 'hidden';
                textarea.style.overflowY = 'hidden';
            }
            else
            {
                textarea.style.overflowX = 'visible';
                textarea.style.overflowY = 'visible';
            }
        }
};

textarea.tornarFlex(id_elemento, 20, 100);


How to set filter by object in tableview without search bar?

Question: I have a tableview and I want to add a button that will filter the data by the given option. For example, I want to display only data that contains a "Attending" in the table.
Here is my code:
 func filterBy(){
    let addEvent = UIAlertController(title: "Sort by:", message: "Sort guests", preferredStyle: .alert)
    let subview = (addEvent.view.subviews.first?.subviews.first?.subviews.first!)! as UIView
    let shapes = UIView()
    shapes.layer.cornerRadius = 30
    shapes.layer.borderWidth = 5
    shapes.layer.borderColor = #colorLiteral(red: 0.9843137255, green: 0.8196078431, blue: 0.8509803922, alpha: 1)
    subview.backgroundColor = #colorLiteral(red: 0.9607843137, green: 0.9333333333, blue: 0.9176470588, alpha: 1)
    subview.tintColor = #colorLiteral(red: 0.9843137255, green: 0.8196078431, blue: 0.8509803922, alpha: 1)
    addEvent.view.tintColor = #colorLiteral(red: 0.4431372549, green: 0.4431372549, blue: 0.4431372549, alpha: 1)

    let addSortAction = UIAlertAction(title: "Attending", style: .default) { (action) in
        let sortedBy: () = self.guestsList.sort(by: { $0.attendingStatus ?? "" > $1.attendingStatus ?? ""})
       print(sortedBy)
        self.guestsTableView.reloadData()
    }
    let cancelAction = UIAlertAction(title: "Cancel", style: .default)
    addEvent.addAction(addSortAction)
    addEvent.addAction(cancelAction)
    present(addEvent, animated: true, completion: nil)
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return guestsList.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "guestCell", for: indexPath) as! GuestTableViewCell
    let guest: GuestModel
    guest = guestsList[indexPath.row]

    cell.guestNameLabel.text = guest.guestName! + " " + guest.guestFamilyName!
    cell.attendingLabel.text = guest.attendingStatus
    cell.menuLabel.text = guest.menuStatus
    cell.ageLabel.text = guest.ageStatus
    cell.tableLabel.text = guest.tableNo

    return cell
}

The model:
class GuestModel {

    var guestName: String?
    var attendingStatus: String?
    var menuStatus: String?
    var ageStatus: String?
    var tableNo: String?
    var id: String?
    var guestFamilyName: String?
    var guestPhoneNumber: String?
    var guestEmail: String?
}

Comment: Can you post your table view data source and delegate methods? And your list item model class? I don't understand why you are creating a dialog to sort your values while you need to filter them.
Comment: @luca_999 I was trying first to sort, but now I need to filter values, and because I'm new in swift I don't know how to filter them.
Comment: Ok, still, Can you post your table view data source and delegate methods? And your list item model class?
Comment: @luca_999 I edited the question. There is data source and delegate.
Answer: In order to achieve what you want you could use three global variables

The full list that you initialize at the beginning (guestsList)
The filtered list, used as table view data source (filteredGuestsList)
The searched string, which applies the filter to the list (in my case a considered that you'll apply a filter to the guestName property)

The filterBy method needs only to update the searched value, and needs to be called everytime you want to clear or update the searched value.
private var guestsList = [GuestModel]() {
    didSet {
        filteredGuestsList = guestsList
    }
}
private var filteredGuestsList = [GuestModel]() {
    didSet {
        guestsTableView.reloadData()
    }
}
private var search = "" {
    didSet {
        filteredGuestsList = search != "" ? guestsList.filter {
            $0.guestName.uppercased().contains(searchText.uppercased())
        } : guestsList
    }
}

func filterBy(_ text: String) {
    search = text
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return filteredGuestsList.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "guestCell", for: indexPath) as! GuestTableViewCell
    let guest = filteredGuestsList[indexPath.row]

    cell.guestNameLabel.text = guest.guestName! + " " + guest.guestFamilyName!
    cell.attendingLabel.text = guest.attendingStatus
    cell.menuLabel.text = guest.menuStatus
    cell.ageLabel.text = guest.ageStatus
    cell.tableLabel.text = guest.tableNo

    return cell
}


Where to find NHibernate Jet driver

Question: I don't know if it's just me, but I just can't seem to find the NHibernate Jet driver anywhere.
I have not yet looked into the source, but looking at the main project files or the NH Contrib files, did not give me any results.
Enough time wasted, who can show me the way?
Thanks!
Answer: You can find more information about configuring NHibernate to work with MS Access in this post from my blog: NHibernate and MS Access - it's simple, but...
Answer: You can get the Jet Driver on NuGet now:
<code>PM> Install-Package NHibernate.JetDriver
</code>
It seems to work out the versions automatically.
Answer: It is in NH Contrib, you must have missed it.  It's called NHibernate.JetDriver
Answer: here is the svn url, you can check out the entire source and compile the newest dll
https://nhcontrib.svn.sourceforge.net/svnroot/nhcontrib/trunk/src/NHibernate.JetDriver

Where to find NHibernate Jet driver


Optimal way of join with counting Arango

Question: I wanted to write a most efficent query in Arango Query Language working like join with counting.
In database I have Users, Tags and userTag collections. Users and Tags are connected by 'edge' stored in userTag.
I want to list all Tags (with data from Tags collection) and to each tag - number of users connected to Tag.
What I have (it works):
FOR tag in tags
    let forOneTag = (
      FOR v, e, p IN 1 OUTBOUND tag
      ANY userTag
        RETURN {e}
    )
    RETURN {tag: tag.tagname, numberOfUsers: LENGTH(forOneTag)}

I feel it is not the most efficient way regarding time and memory.
Is there more 'arangoic' way of doing it?
Answer: Your query is already good. One small optimisation: Use RETURN e instead of RETURN {e}, you don't have to wrap e inside a document because it's already a document.
FOR tag in tags
  let forOneTag = (
    FOR v, e, p IN 1 OUTBOUND tag
      ANY userTag
      RETURN e
    )
  RETURN {tag: tag.tagname, numberOfUsers: LENGTH(forOneTag)}

Alternatively you could use the following query. These query is more performant but only returns tags which has at least one connected user.
FOR tag in tags
  FOR v, e, p IN 1 OUTBOUND tag
    ANY userTag
    RETURN {tag: tag.tagname, numberOfUsers:LENGTH(p.edges)}

Answer: If you only need the count of outbounds from Tags to your Users and have fairly limited number of relations in your userTags Relation collection, you can do something like this
FOR tag in Tags
  let usersOutBound = (
    FOR relation in userTag
      FILTER relation._from == tag._id
      return relation
  )
  return {tag: tag.tagname, numberOfUsers: LENGTH(usersOutBound)}


Como selecionar aleatoriamente uma linha de cada grupo no MySQL

Question: Suponha que eu tenha uma tabela assim:
item   | group
-------+--------
item a | group z
item b | group y
item c | group y
item d | group x
item e | group z
item f | group x

E que agora eu queira selecionar aleatoriamente um único item para representar cada grupo, de modo que, após a reordenação aleatória e o agrupamento, o resultado fique assim:
item   | group
-------+--------
item b | group y
item d | group x
item e | group z

Ou assim:
item   | group
-------+--------
item b | group y
item a | group z
item d | group x

Ou assim:
item   | group
-------+--------
item f | group x
item e | group z
item c | group y

Tudo embaralhado e agrupado. Como posso fazer isso?
PS1: Note que:
- hora o grupo x está associado ao item d e outrora ao item f;
- hora o grupo y está associado ao item b e outrora ao item c;
- hora o grupo z está associado ao item a e outrora ao item e;
PS2: Se for possível seguir a linha de raciocínio desse post aqui, é melhor: Selecionar a primeira linha de cada grupo em MySQL senão, sem problema nenhum!
PS3: Já vi explicações similares usando o comando HOVER e PARTITION. Mas esses comandos não existem no MySQL. Então, preciso de ajuda mesmo.
Answer: Resolvendo
Uma forma de fazer:
select (select t2.item from tabela t2
        where t2.grupo = t1.grupo order by rand() limit 1) as item,
t1.grupo
from tabela t1
group by grupo
order by rand()

Explicando
O que fiz foi uma sub-query que busca de forma randômica na mesma tabela, referenciando o grupo, assim gerando uma lista randômica.
Nessa lista gerada, agrupo pelo grupo, e ordeno de forma randômica.

Observações

Caso fizer a execução de parte da sub-query, verá que irá trazer as vezes duplicado, mas não importa, pois a última query que será o filtro final.

Substituí o nome do campo group para grupo para poder simular, pois em alguns cenários pode dar erro devido group ser palavra reservada.

Veja funcionado no: SQL Fiddle ou DB Fiddle
Comment: Boa dev! Super agradeço a sua ajuda!!!


What is the difference between a multi-label and a multi-class classification?

Question: What is the difference between multi-label classification and multiclass classfication.  Speficially, what is the difference between a label and a class?
Please provide a clear example.
"Multiclass classification should not be confused with multi-label classification, where multiple labels are to be predicted for each instance." -wikipedia  ... was not very helpful.
Answer: Based on the sentence you quoted, each item belongs to one class but can have several labels.
Imagine you have animals like a fox, a chicken and a common European viper. A multi-class classification problem would be assigning them to a family:
Fox            Canidae
Chicken        Phasianidae
Viper          Viperidae

In phylogeny, any species only has one family (that's by design) so that an animal cannot belong to more than one family.
A multi-label classification problem would be assigning them random characteristics:
Fox            Warm-blooded, furred
Chicken        Warm-blooded, feathered
Viper          Cold-blooded

Each animal can have several labels and the labels do not form a set of mutually exclusive categories.
Comment: Oh, I hadn't thought of modeling a problem like that. The quote I provided was the only instance (sadly) describing the two together that I could find. In this instance, its seems that a class is entered into the multi-label classification network, whose inputs should be able to handle the feature-set for all types of desired animals. Understanding the difference between a label and a class was the most help. If there are other types of multi-label models other than the one described in your answer (which sounded like it was based on my quote), please elaborate. Otherwise, thank you.
Comment: @poorly_built_human My example was not very good, I tried to use animals in both cases but things like cold-blooded vs. warm-blooded or furred vs. feathered can be treated as separate multi-class classification problems. The canonical multi-label classification problem would be identifying topics in a text.
Comment: Thank you again. I'm seeing classes as generally being mutually exclusive (from an organizational POV), while labels are not mutually exclusive. Likewise, a class is a larger group where an item is either "in it" or not, and a label is an attribute of a class for which many can exist. You might try and classify text into a particular "class", such as History, Science and Literature, and then give labels to these classes such as "Science: Biology" and "Science: Geology". Or even more specific labels (or combination thereof) such as "Science: Geology: Europe" and "Science: Geology: Africa".


Script not working on page load, but working from console

Question: I wrote a script that's running from ebay listing iframe. It's working fine, it runs on $(document).ready(), sends an AJAX request to a remote server, gets some info, manipulate the DOM on 'success' callback, everything working perfect...
However, I added a piece of code, which should get the document.referrer, and extract some keywords from it, if they exist. Specifically, if a user searches ebay for a product, and clicks on my product from the results, the function extracts the keywords he entered.
Now, the problem is, that function is not running on page load at all. It seems like it blocks the script when it comes to that part. This is the function:
function getKeywords(){
    var index = window.parent.document.referrer.indexOf('_nkw');

    if (index >= 0){
        var currentIndex = index + 5;
        var keywords = '';
        while (window.parent.document.referrer[currentIndex] !== '&'){
            keywords += window.parent.document.referrer[currentIndex++];
        }
        keywords = keywords.split('+');

        return keywords;
    }
}

And I tried calling two logs right after it:
console.log('referrer: ' + window.parent.document.referrer);
console.log(getKeywords());

None of them is working. It's like when it comes to that 'window.parent.document.referrer' part, it stops completely.
But, when I put this all in a console, and run it, it works perfectly. It logs the right referrer, and the right keywords.
Does anybody know what might be the issue here?
Comment: Is the parent window in a different domain? That limits what you're allowed to access in it.
Comment: I don't think so. It's an ebay listing html, it should be served from the same domain.
Answer: The reason it is working on the console is because your window object is the outer window reference and not your iframe. Besides that, on the console:
window.parent === window
  // ==> true

So, on in fact you are running window.document.referrer and not your frame's window.parent.document.referrer.
If you want to access your frame's window object you should something like
var myFrame = document.getElementsByClassName('my-frame-class')[0];
myFrame.contentWindow === window
  // ==> false
myFrame.contentWindow.parent.window === window
  // ==> true

This might help you debug your problem, but I guess the browser is just preventing an inner iframe from accessing the parent's window object.
Comment: I am not sure I fully understand you. I want to access iframe's parent window. The iframe holds the html code for the listing template and my javascript code. But, I want to access the parent window, and it's refferrer.
Comment: The code you are running on the console has a different scope from the code running in an `iframe`, so you can execute somethings on the console that have different behaviour from the code running inside the `iframe`.


Find equation of line through two points (1,3,-4) and (3,2,1)

Question: Find equation of the line through two points $(1, 3, -4)$ and $(3, 2, 1)$
I know the correct answer is $[3, 2, 1] + t[2, -1, 5]$
but according to this video the answer should be the first point $[1, 3, -4] + t[2, -1, 5]$
Does it matter which point I use?
Comment: Just to be picky... the equation is not $[3, 2, 1] + t[2, -1, 5]$.  This is not an equation at all because it doesn't have an equals sign.  The equation is actually $[x,y,z]=[3, 2, 1] + t[2, -1, 5]$.
Comment: does not matter
Comment: There's no such thing as _the_ equation of a line.
Answer: It doesn't matter. If the line is going through both points, it doesn't matter which is your starting.
$[3, 2, 1] + t_1[2, -1, 5]$
$[1, 3, -4] + t_2[2, -1, 5]$
To show these are equivalent consider $t_2=t_1+1$ then
$[1, 3, -4] + t_2[2, -1, 5] = [1, 3, -4] + (t_1+1)[2, -1, 5] = [1, 3, -4] + t_1[2, -1, 5] + [2, -1, 5] = [3, 2, 1] + t_1[2, -1, 5]$
Comment: @Leucippus Actually it does answer the question "does it matter which point I use?"
Comment: It does in fact answer the question.  Answerer is encouraged to expand his answer showing why the two lines are the same.
Answer: Take the difference of the two vectors (to get the direction vector),  and use either point to parametrize the line:  $\{(1,3,-4)+t(2,-1,5):  t\in\Bbb R\}=\{(3,2,1)+t(2,-1,5):  t\in\Bbb R\}$.


$\mathbb{Q}(\alpha)=\mathbb{Q}(\beta)$ if $\alpha, \beta$ are algebraic over $\mathbb{Q}$ of degree $2$ and $\alpha +\beta$ is a root of a quadratic.

Question:
If $\alpha, \beta$ are algebraic over $\mathbb{Q}$ of degree $2$ and $\alpha +\beta$ is a root of a quadratic polynomial over $\mathbb{Q}$, then prove that $\mathbb{Q}(\alpha)=\mathbb{Q}(\beta)$.

I'm stuck at showing the above statement. I think we have to show that $\alpha$ can be written as $p+q\beta$ or vice versa. But I just can't seem to show that.
I tried something as shown below but got nowhere:
If $g(x)$ is the polynomial of $\alpha+\beta$,
$g(x)=f(x)Q(x)+R(x)$ where $f(x)$ is the polynomial of $\beta$
Ideas Anyone?
Answer: By the hypotheses, you have six rational numbers $a_0,a_1,b_0,b_1,c_0,c_1$
such that
$$
\alpha^2+a_1 \alpha +a_0=0 \tag{1}
$$
$$
\beta^2+b_1 \beta +b_0=0 \tag{2}
$$
$$
(\alpha+\beta)^2+c_1(\alpha+\beta) +c_0=0 \tag{3}
$$
Now, (3)-(1)-(2) yields :
$$
2\alpha\beta+(c_1-a_1)\alpha+(c_1-b_1)\beta +c_0-a_0-b_0=0 \tag{4}
$$
or equivalently,
$$
\beta=\frac{-(c_1-a_1)\alpha}{2\alpha+c_1-b_1},
\alpha=\frac{-(c_1-b_1)\beta}{2\beta+c_1-a_1} \tag{5}
$$
Note that the denominators are nonzero because $\alpha$ and $\beta$ have degree $2$. Clearly, (5) implies $ {\mathbb Q}(\alpha) = {\mathbb Q}(\beta)$.
Comment: This is a good solution!
Answer: We feel like there should be some correction to the following solution. However, because a good time have past since then (a few years), we decided to write a completely rewritten answer.

Suppose that the numbers $\alpha$, $\beta$, $\alpha+\beta$ are algebraic over $\mathbb{Q}$ with algebraic degree $2$ and $\mathbb{Q}(\alpha) \neq \mathbb{Q}(\beta)$.
Since $K=\mathbb{Q}(\alpha,\beta)$ is the splliting field of the product of the irreducible polynomials of $\alpha$ and $\beta$, it is normal and hence, Galois. Regarding the tower $K-\mathbb{Q}(\alpha)-\mathbb{Q}$, $[K:\mathbb{Q}]=4$ and hence the Galois group is of order $4$ and abelian.
The Galois group $G=\mathrm{G}(K/\mathbb{Q})$ has two elements, say $\sigma$ and $\tau$ which fixes $\mathbb{Q}(\alpha)$ and $\mathbb{Q}(\beta)$, respectively and generate $G$. Note that $\sigma$ fixed the conjugate $\overline{\alpha}$ also and since $\tau(\alpha) = \overline{\alpha}$. The similar fact holds for $\beta$.
Since $\tau \sigma \neq 1, \tau, \sigma$, we have $G = \left\{ 1,\tau, \sigma , \tau \sigma =\sigma \tau \right\}$.
Let $\eta \in G$ be such that $<\eta> = \mathrm{G} (K/\mathbb{Q}[\gamma])$. Then $\eta$ is of order two and $\eta \neq \tau$, $\eta \neq \sigma$. Hence $\eta = \sigma \tau$.
But then $\eta (\gamma) = \sigma \tau (\alpha + \beta) = \overline{\alpha} + \overline{\beta}$, so $\eta(\gamma) = \gamma$ implies $\sigma(\beta) + \tau(\alpha) = \alpha + \beta$.
Now $\tau(\gamma)$ and $\sigma(\gamma)$ are both the conjugate of $\gamma$ and $\gamma$ is of degree $2$. Hence they are same.
Therefore, from $\tau(\alpha + \beta) = \sigma(\alpha+\beta)$, we have  $\tau(\alpha)-\sigma(\beta) = \alpha - \beta$, and together with  $\sigma(\beta) + \tau(\alpha) =\alpha+\beta$, $\tau(\alpha)  = \alpha$ which is an absurdity. Hence $\mathbb{Q}(\alpha) = \mathbb{Q} (\beta)$이다.

Below is the former answer given a few years ago.

Let $\alpha, \beta \in \mathbb{C}$ be algebraic with degree $2$ such that $\alpha +\beta$ is also algebraic of degree $2$. Suppose that $\mathbb{Q}(\alpha) \neq \mathbb{Q}(\beta)$. Then we have the following non-trivial stack of Galois extensions; $\mathbb{Q}(\alpha, \beta) \supset \mathbb{Q}(\alpha), \mathbb{Q}(\beta) \supset \mathbb{Q}$. Therefore the Galois group consists of four elements which is generated by $\sigma$, $\eta$ which fixes $\mathbb{Q}(\alpha)$, $\mathbb{Q}(\beta)$, respectively. Note that applying elements of the Galois group on $\gamma=\alpha + \beta$, we have four different element, $\gamma$, $\sigma(\gamma)$, $\eta(\gamma)$, $\sigma(\eta(\gamma))$. Therefore, the minimal polynomial of $\alpha + \beta$ has degree four which contradicts to the fact that $\alpha+\beta$ is of degree $2$. This completes the proof.
Comment: How do you know that the Gal group consists of 4 elements?
Comment: @Jhon Doe $\mathbb{Q}(\alpha, \beta)$ has intermediate fields. Two successive extensions are of degree at least two.
Comment: Oh, you mean the Galois group contains the four elements $1$, $\sigma$, $\eta$, and $\sigma\eta$, but these elements are not necessarily all the elements of the group?
Comment: @seoneo To show that Gal group has 4 element don't you have to show that the minimal polynomials of $\alpha$ and $\beta$ are separable?
Comment: @JhonDoe  I think in characteristic $0$, the minimal polynomials are always separable.
Comment: Oh right i completely forgot thanks
Comment: @seoneo wait how do you know that function values of $\alpha+\beta$ are distinct?
Comment: @Zvi $f(\alpha+\beta)=\alpha_1+\beta_1,\alpha+\beta,\alpha_1+\beta,\alpha+\beta_1$ We know that $\alpha+\beta \neq \alpha_1+\beta$ and $\alpha+\beta \neq \alpha+\beta_1$ but $\alpha+\beta_1$ could equal $\alpha_1+\beta$
Comment: @Jhon Doe Good point. It needs further explanation. I will consider but not right now since I'm driving. I'm sorry.
Comment: @Jhon Doe Suppose that any two of them identical. That means gamma is fixed by one of nontrivial member of the Galois group. Recall that sigma and eta has oeder two. So for instance  if eta gamma= sigma gamma, then gamma is fixed by eta sigma meaning that gamma is rational.
Comment: Thanks. I showed by contradiction the there are at least 3 different values which suffices. Suppose the example above holds then $\alpha_1+\beta_1\neq \alpha+\beta$ else $\beta_1=\beta$
Comment: 'At least three' argument also looks good.
Answer: Here is an alternative but longer approach.  Let $a(x)$, $b(x)$, and $c(x)$ be monic quadratic polynomials in $\mathbb{Q}[x]$ whose roots are $\alpha$, $\beta$, and $\gamma:=\alpha+\beta$, respectively.  By the condition that $\alpha$ and $\beta$ are algebraic over $\mathbb{Q}$ with degree $2$, we see that $a$ and $b$ are irreducible over $\mathbb{Q}$.  If $c$ is reducible over $\mathbb{Q}$, then $\alpha+\beta=\gamma$ is rational, so it is obvious that $\mathbb{Q}(\alpha)=\mathbb{Q}(\gamma-\alpha)=\mathbb{Q}(\beta)$.  We now assume that $c$ is irreducible over $\mathbb{Q}$.
Write $p(x)$ for $a(x-\beta)\ a(x-\bar{\beta})\in\mathbb{Q}[x]$, where $\bar{\beta}$ is the other root of $b(x)$.  Clearly, $p(\gamma)=0$.  So, $c$ divides $p$ because $c$ is irreducible.  Now, if $\bar{\alpha}$ is the other root of $a(x)$, then
$$p(x)=(x-\alpha-\beta)(x-\bar{\alpha}-\beta)(x-\alpha-\bar{\beta})(x-\bar{\alpha}-\bar{\beta}).$$
Hence, there are three possibilities.
Case 1: $c(x)=(x-\alpha-\beta)(x-\bar{\alpha}-\beta)=a(x-\beta)$.  Since $a$ has rational coefficients, this implies that $\beta\in\mathbb{Q}$, a contradiction.
Case 2: $c(x)=(x-\alpha-\beta)(x-\alpha-\bar{\beta})=b(x-\alpha)$.  Since $b$ has rational coefficients, this implies that $\alpha\in\mathbb{Q}$, a contradiction.
Case 3: $c(x)=(x-\alpha-\beta)(x-\bar{\alpha}-\bar{\beta})$.  Therefore, we have $$\alpha\bar{\alpha}+\beta{\bar{\beta}}+(\alpha\bar{\beta}+{\bar{\alpha}}\beta)=(\alpha+\beta)(\bar{\alpha}+\bar{\beta})\in\mathbb{Q}.$$
Since $\alpha\bar\alpha$ and $\beta\bar\beta$ are rational, we get
$$\alpha\bar{\beta}+{\bar{\alpha}}\beta\in\mathbb{Q}.$$
Thus, $$\alpha(B-\beta)+(A-\alpha)\beta\in\mathbb{Q}$$
if $A=\alpha+\bar{\alpha}\in\mathbb{Q}$ and $B=\beta+\bar\beta\in\mathbb{Q}$.  So, $\alpha\beta$ is in the rational span of $1$, $\alpha$, and $\beta$.  This means $$\big[\mathbb{Q}(\alpha,\beta):\mathbb{Q}\big]\leq 3.$$
But $$\big[\mathbb{Q}(\alpha,\beta):\mathbb{Q}\big]=\big[\mathbb{Q}(\alpha,\beta):\mathbb{Q}(\alpha)\big]\ \big[\mathbb{Q}(\alpha):\mathbb{Q}\big]=2\ \big[\mathbb{Q}(\alpha,\beta):\mathbb{Q}(\alpha)\big].$$
The only even positive integer less than or equal to $3$ is $2$, so
$$2\ \big[\mathbb{Q}(\alpha,\beta):\mathbb{Q}(\alpha)\big]=2$$
or
$$\big[\mathbb{Q}(\alpha,\beta):\mathbb{Q}(\alpha)\big]=1.$$
This shows that $\beta\in\mathbb{Q}(\alpha)$.  Thus, $\mathbb{Q}(\alpha)=\mathbb{Q}(\beta)$.


How did i get oracle particular table's column history?

Question: How did I get particular table's column history ?
e-g
<code>table name :employee
column name     column adddate    column modifydate
empname           08/07/15            09/08/15
empcode           08/07/15            01/08/15
empsal            08/07/15            10/09/15
</code>
when particular data type or its length or new column(field) added to a table.
Comment: Maybe you need DDL triggers?
Answer: Yes, you can do it using DDL triggers if you want to track schema object level details , also it is better to fine tune your auditing.
create table .ddl_audit
 (
    os_user_name     varchar2(255),
    current_user     varchar2(255),
    host                varchar2(255),
    terminal            varchar2(255),
    ddl_type         varchar2(255),
    owner            varchar2(30),
    object_type      varchar2(255),
    object_name      varchar2(128),
    system_event        varchar2(20),
    ddl_sql_stmt        varchar2(2000),
    ddl_date         timestamp
 );
create or replace TRIGGER audit_ddl_trg AFTER ddl ON .schema
  DECLARE
    sql_text ora_name_list_t;
    v_stmt VARCHAR2(2000);
    retval pls_integer;
  BEGIN
    retval := ora_sql_txt(sql_text);
    FOR i IN 1..retval
    LOOP
      v_stmt := v_stmt || sql_text(i);
    END LOOP;
    INSERT
    INTO .DDL_AUDIT
      (
        os_user_name,
        current_user,
        host,
        terminal,
        ddl_type,
        owner,
        object_type,
        object_name,
        system_event,
        ddl_sql_stmt,
        ddl_date
      )
      VALUES
      (
        sys_context('USERENV','OS_USER') ,
        sys_context('USERENV','CURRENT_USER') ,
        sys_context('USERENV','HOST') ,
        sys_context('USERENV','TERMINAL') ,
        ora_dict_obj_type,
        ora_dict_obj_owner,
        ora_dict_obj_type,
        ora_dict_obj_name,
        ora_sysevent,
        v_stmt,
        SYSTIMESTAMP
      );
  END;
-- use same app schema to
create table t1(c1 int,c2 varchar(10));
-- make more changes
alter table t1 add c3 varchar2(50);
query the ddl_audit table sorted by ddl_date ...
Note:- Make sure to grant necessary privileges.
Comment: Thank you for valuable reply.


Determine whether a field has changed during hook_node_submit

Question: Basically I need a way of checking whether a node field changed during some event hook...I am using hook_node_submit() but this doesn't seem to work:
$form['field_status']['und']['#value'] !== $node->field_status['und'][0]['value']

Produces equality all the time...any suggestions on which hook and how I would check equality when I know a value has changed it should fire off an email...
Alex
Comment: If you use `hook_node_update()` you should have access to `$node->original` (copy of the original object). Not sure if it's available in `hook_node_submit()`
Answer: As said from @Clive, the only way is to compare the value in $node with the value contained in $node->original.
As far as I can see, that value is only available in hook_node_update(), hook_node_presave() and every hook invoked from node_save() which receive the saved node as argument (but only when a node is updated), since entity_load_unchanged() is called from node_save() (which also unset $node->original before exiting). If you need it in hook_node_submit() you could simply add the following code in your implementation.
if (!empty($node->nid) && !isset($node->original)) {
  $node->original = entity_load_unchanged('node', $node->nid);
}

Since you are checking for field properties, the other, more general, hook would be hook_field_attach_submit(hook_field_attach_submit($entity_type, $entity, $form, &$form_state)). With this hook, $entity would contain the field value before the node has been edited, and $form_state contains the submitted values.


How can I manage site translations in code?

Question: I have a site with multiple translations, including a heavily customized version of the default Drupal "English."  (The use case requires that a lot of the help text and labels throughout Drupal be changed.)
I am using the Features module to manage deployment.  However, I can't find a way to manage translations in code.
Currently, I visit the Languages page, click export, download the .po file for each type (built-in interface, node types, taxonomy) for each language, and then commit these downloaded files to code.  This seems extremely inefficient compared to working with Features.
I looked for a Drush command to help but the 5.0-rc3 version which I'm using doesn't have any i18n-related commands.
How can I manage site translations efficiently in code?
Comment: Are you saying you hacked core and replaced the text with new text?
Comment: No, I created a custom language called "English," enabled it as the default, and disabled the built-in English.
Answer: I had the same problem and had a look at the module Features Translation. However, there were some downsides to it. Don't know exactly what is was. From what I can remember is that when I import a feature, for example the menu link labels are imported in the built in interface. So it doesn't help to import the translations for Menu Items because the source labels are not available there but in the Built In interface. But maybe I am wrong, tried so many things I can really recall what I did.
But you can have a look at it, maybe it works for you.
Tell us when you have found a suitable solution. I am curious.
Comment: Decent progress has been made on this module:  http://thereisamoduleforthat.com/content/features-and-i18n-configuration-management-oh-my-part-1
Answer: Drush 5.x, at least as of right now, doesn't have anything to help in this area.
Instead, I used Selenium IDE to automate a workflow for an admin account of logging in and importing the translations for each language.  Exports must still be performed manually, which is a pain, but at least it's slightly faster than before.  (Selenium IDE cannot be used to handle the exports because it's impossible to take over the downloading of files with Javascript.)
Comment: Here's a great new approach: http://drupal.stackexchange.com/a/34552/5147


Tag merger request: moving and relocation

Question: Please merge the tags:

relocation
moving
Answer: The moving tag was moved to relocation


Wait for async task to finish if you know that it's called n times

Question: In this project I use Foursquare API to get some venues and one photo from each venue. When I have those data, I'm reloading the TableView to display all the info.
First I collect the venues and secondly for each venue, I m taking a photo from foursquare API.
I m using the RestKit library for this project and I'm calling this method n times (one time for each venue). When it's finishing I want to display all those photos I have taken to my table view.
- (void)requestVenuePhoto:(Venue *)thisVenue{
  //...
  //...
  [[RKObjectManager sharedManager] getObjectsAtPath:objectPath parameters:queryParams success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult)
  {
    [self.photos addObjectsFromArray:mappingResult.array];
    //[self.tableView reloadData];

  } failure:^(RKObjectRequestOperation *operation, NSError *error) {
    NSLog(@"What do you mean by 'there is no photos?': %@", error);
    dispatch_group_leave(resolveVenuePhotos);
  }];
}

The problem is that I can't use the dispatch_group_leave because is'not called one time only.
Is there any way to do this nicely?
Update, now I'm using a counter to solve the problem:
[[RKObjectManager sharedManager] getObjectsAtPath:objectPath parameters:queryParams success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult)
{
    [self.photos addObjectsFromArray:mappingResult.array];
    venuesPhotoCounter++;
    if (venuesPhotoCounter == _venues.count)
    {
        [self.tableView reloadData];
    }

} failure:^(RKObjectRequestOperation *operation, NSError *error) {
    NSLog(@"What do you mean by 'there is no photos?': %@", error);
}];

Comment: Why do you reload the tableview only once all pictures have been downloaded? Reload it as soon as you have the list of items, and then load images in the `tableView:cellForItemAtIndexPath:` datasource method (or even in your custom cell's code). This will allow data to be displayed as soon as it is received, providing a better user experience.
Comment: Didn't get why you can't use `dispatch_group_leave`? May be you can use `dispatch_group_enter`?
Comment: The point is that I don't think so that the dispatch_group_enter/leave is the good practice for that, because is not one time only task to notify the table view to reload the data. Correct me if I'm wrong.
Comment: @johnmast I don't understand your concern here. The normal use of enter/leave is to call enter once for each task and leave for each task. So you'd want to call enter before calling `getObjectsAtPath:...` and leave at the end of the success and failure blocks. When your leaves equal your enters, the group is done.
Comment: @jcaron that is what I want to do in this project. It will be nice if you have the time to answer with code and comment it below!
Comment: @RobNapier yes I know how to use this dispatch enter/leave and I know that this is not the solution I want, so that is the reason I ask this question. Because I want somehow to do what the jcaron said above.
As you can see now I update my code. Please answer me if this is a good solution.
Comment: @jcaron Thank you for the reminder, I' m working for a solution based on your answer.. I hope soon I came back with a snippet code!
Answer: This is not a direct answer to your question, but I think it will resolve your issue.
You should not load all the pictures and only then reload the table. You should:

load the list of items, and in your completion handler, reload the table (make sure the reload happens on the main thread if you completion handler runs on a background thread).
then, in the tableView:cellForItemAtIndexPath: method of your tableview datasource, start loading the image for the requested item. Also make a note of the current indexPath (often just the row), for instance in the tag of the cell, or in a custom cell property. In the completion handler for that request, decode the image (in the background), then assign it to your cell (on the main thread), after having check that the cell is still for the same indexPath (i.e. the cell has not been reused).

Example using standard NSURLSession (based on a single section, and data being in an _items instance variable):
- tableView:(UITableView *)tableView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    MyItem *item = _items[indexPath.row];
    MyCustomCell *cell = (MyCustomCell *)[tableView dequeueReusableCellWithIdentifier:@"whatever"];
    // configure the rest of the cell: labels, etc.
    cell.tag = indexPath.row;
    [[[NSURLSession sharedSession] dataTaskWithURL:item.url
                                 completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
    {
        // Remember this runs on a background thread
        if (cell.tag == indexPath.row && !error && data)
        {
            UIImage *image = [UIImage imageWithData:data];
            dispatch_async(dispatch_get_main_queue(),^
            {
                cell.myImageView.image  = image;
            });
        }
    }] resume];
}

Answer: Apple has uploaded a project called "LazyTableImages" available here
. So I wrapped it up and made some paradigms which should probably fit your use-case.
 - (void)startDownload
    {
        NSURLRequest *request = [NSURLRequest requestWithURL:self.venue.imageURL];

        // create an session data task to obtain and download the app icon
        _sessionTask = [[NSURLSession sharedSession] dataTaskWithRequest:request
                                                       completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

            // in case we want to know the response status code
            NSInteger HTTPStatusCode = [(NSHTTPURLResponse *)response statusCode];

            if (error != nil)
            {
                if ([error code] == NSURLErrorAppTransportSecurityRequiresSecureConnection)
                {
                    // if you get error NSURLErrorAppTransportSecurityRequiresSecureConnection (-1022),
                    // then your Info.plist has not been properly configured to match the target server.
                    //
                    abort();
                }
            }

            [[NSOperationQueue mainQueue] addOperationWithBlock: ^{

                // Set appIcon and clear temporary data/image
                UIImage *image = [[UIImage alloc] initWithData:data];
                if (HTTPStatusCode == 200) {
                    if (image.size.width != kAppIconSize || image.size.height != kAppIconSize)
                    {
                        CGSize itemSize = CGSizeMake(kAppIconSize, kAppIconSize);
                        UIGraphicsBeginImageContextWithOptions(itemSize, NO, 0.0f);
                        CGRect imageRect = CGRectMake(0.0, 0.0, itemSize.width, itemSize.height);
                        [image drawInRect:imageRect];
                        self.venue.image = UIGraphicsGetImageFromCurrentImageContext();
                        UIGraphicsEndImageContext();
                    }
                    else
                    {
                        self.venue.image = image;
                    }
                }
                else {// If anything goes wrong we should use a placeholder image
                    self.venue.image = [UIImage imageNamed:@"Placeholder.png"];
                }

                // call our completion handler to tell our client that our icon is ready for display
                if (self.completionHandler != nil)
                {
                    self.completionHandler();
                }
            }];
        }];

        [self.sessionTask resume];
    }

Comment: I study the sample code from Apple that you posted above and I implement your code! And it works like a charm! Thank you!


Missing required icon file. The bundle does not contain

Question: This is the error message:

ITunes Store operation failed. Missing required icon file. The bundle
  does not contain an app icon for iPhone / iPod Touch of exactly
  "120x120" pixels, in .png format for iOS versions >= 7.0.

I have this problem while submitting my app to the app store, I face this problem while validating my project and I tried all the answers here in stackoverflow but the error is same .
Comment: it will be better to post the screenshot of xcasset of icon
Comment: *Does* your bundle contain an app icon as described?
Comment: possible duplicate of ['Missing recommended icon file - The bundle does not contain an app icon for iPhone / iPod Touch of exactly '120x120' pixels, in .png format'](http://stackoverflow.com/questions/18736954/missing-recommended-icon-file-the-bundle-does-not-contain-an-app-icon-for-iph)
Answer: Open your project's General Preferences in Xcode, and make sure that your App Icons Source is the Asset Catalog named "AppIcon":

Then, in the project navigator, click Images.xcassets, click AppIcon, and then drag and drop your icons into the required places. If AppIcon is not shown, you'll have to right click and choose "New App Icon" and then select the proper icons from the inspector on the right:

Once you've done this, your icons should show up where they're supposed to.
Comment: @ZeeshanAhmadKhalil Did you assign your 60x60 to a 3x slot? If so then your image needs to be 3 times the size it asks for eg 60x60 in a 3x slot becomes 20x20 for a 3x device while a 180x180 at 3x becomes 60x60. If you're not sure then playing around with image sizes is a good way to trial & error it out.
Comment: yes maybe that was the problem and my icons folder name was AppIcon-1, and I changed it to AppIcon and changed App Icon Source to AppIcon.
Comment: Glad everything works now! If this answer was the correct one, please click the check to mark it as correct!
Comment: Another important note (esp for ionic users), MAKE SURE that you click through EACH and every image to make sure the size of the actual image matches the size of the role it's assigned to. If not, Apple will give you some archaic answer that will make your life miserable.
Comment: @Jacksonkr I have added an icon of size 60x60 but when I click on that it shows 20x20 on right side!
Comment: @Jacksonkr I got it now, this wasn't the issue the issue was with icon names.
Comment: I followed the exact same steps. Drag&Drop works fine and all icons are where they belong to but (1) the small favicon is still showng the placeholder icon and (2) on Appstore Connect Upload Apple gives me an error that the 120px image is missing.
Answer: Right click on AppIcon xcassets, then you can see new app Icon.
It will show you New App Icon, then it will show you all required icon, and you need to fill everything needed there and remove current one.
Answer: Please change your development target 6.0 to 7.0  in your xcode and start new archive its working successfully.
Answer: Just had same problem and post answer in case someone like me, stumbles over here. Using Xcode 8.3.3 and wanted to use AppIcon in Assets catalogue. Tried all sorts of Stack Overflow answers without success.
Finally learned about a deep clean step from Ken/Apple Forum:

removed all icon files, whether from resources (delete - trash) or appicon file (select - remove selected items); removed even assets folder
deep cleaned (Use the Product menu w/option key pressed, then choose to 'clean build folder')
added a new asset catalogue and called it "Assets" right clicked in Assets folder and added new app icon set - changed that one in inspector to be for iOS >=7
triple checked all my icon files OUTSIDE of Xcode (all were already png files of right resolution, but some had still colour profile attached from photoshop elements or did have indexed colour instead of RGB profile. so I made sure I only save a png file without colour profile and from a background layer) - not sure that was necessary
archived the build from Product menu
validated and uploaded the build from Window - Organizer
Answer: I was facing this error while uploading app to AppStore

Missing required icon file - The bundle does not contain an app icon
  for iPad of exactly '76x76' pixels, in .png format for iOS versions >=
  7.0.
Missing required icon file - The bundle does not contain an app icon
  for iPad of exactly '152x152' pixels, in .png format for iOS versions
  = 7.0.

I solved it by adding this script at the end of Podfile
post_install do |installer|
    copy_pods_resources_path = "Pods/Target Support Files/Pods-TargetName/Pods-TargetName-resources.sh"
    string_to_replace = '--compile "${BUILT_PRODUCTS_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}"'
    assets_compile_with_app_icon_arguments = '--compile "${BUILT_PRODUCTS_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" --app-icon "${ASSETCATALOG_COMPILER_APPICON_NAME}" --output-partial-info-plist "${BUILD_DIR}/assetcatalog_generated_info.plist"'
    text = File.read(copy_pods_resources_path)
    new_contents = text.gsub(string_to_replace, assets_compile_with_app_icon_arguments)
    File.open(copy_pods_resources_path, "w") {|file| file.puts new_contents }
end

Install your Podfile again, may it should help.

P.S. Remember TargetName in above script should be your Projects'
  Target Name. e.g. if your target name is MyAppName then you should
  replace TargetName in above script as MyAppName