Discarding the superscript for turnstile in Kleene's Introduction to Metamathematics [1952]

Question: In Kleene's IM page 149 the reader is asked to supply the details for the following two examples.
Example 5. Given $A(x) \vdash B$ and $A(x) \vdash \lnot B$ with x held constant, then $\vdash \lnot A(x)$ and $\vdash \forall x \lnot A(x)$.
Example 6. Given $A(x) \vdash^x B$ and $A(x) \vdash^x \lnot B$ with x not necessarily held constant, then $\vdash \lnot \forall x A(x)$.
I think that the proofs go roughly like below also see this question and answer:
For example 5:

$A(x) \vdash B$ - given
$A(x) \vdash \lnot B$ - also given
$\vdash \lnot A(x)$ - by negation introduction (on 1 and 2) page 99
$\lnot A(x) \vdash^x \forall x \lnot A(x)$ - by generality introduction page 99
$\vdash \lnot A(x) \vdash^x \forall x \lnot A(x)$ - from 3 and 4 we have this chain
$\vdash \forall x \lnot A(x)$ - from 5 (notice the lack/discharge of superscript, i.e. $\vdash$ instead of $\vdash^x$, that's one example of discharge)

For example 6:

$A(x) \vdash^x B$ - given
$\forall x A(x) \vdash A(x)$ - by generality elimination page 99
$\forall x A(x) \vdash A(x) \vdash^x B$ - from 1 and 2 we have this chain
$\forall x A(x) \vdash B$ - from 3 (notice the lack/discharge of superscript, that's the second example of discharge)
$\forall x A(x) \vdash \lnot B$ similarly from the other given deduction
$\vdash \lnot \forall x A(x)$ - by negation introduction (on 4 and 5)

The superscript was discharged twice:

in step 6 for the proof of example 5
in step 4 for the proof of example 6

What's the justification for this discharge of the superscript? (Or are there similarly simple proofs that don't involve this discharge?)
Comment: Re.Ex.5: the "discharge" in step 6 is due to the fact that there are no more assumptions (nothing on the left of the $\vdash$ symbol). Thus, the superscript is no more needed.
Comment: Re.Ex.6: IMO, the discharge will occur only at step 6 (same reason as above).
Comment: I agree with your comment re.Ex.5.
More specifically, the way I understand it is that the superscript meaning is that the variable was varied as per the definition on page 95 that says that y is varied in a deduction for some assumption if a) the variable occurs free in the assumption and b) the deduction contains an application of rule 9 or 12 with respect to the variable on a formula depending on the assumption.
So no assumption on the left of turnstile means variable not varied.
Comment: But I disagree your comment re.Ex 6, I don't think the discharge occurs at step 6. I might be wrong and I appreciate your feedback, but I think it is discharged at step 4 because $x$ is not varied because it does not occur free in $\forall x A(x)$ (i.e. condition a) is not met for the superscript to be needed)
Comment: And again, I'm happy to corrected, but I think your answer to Ex.6 in https://math.stackexchange.com/questions/581663/examples-from-kleenes-introduction-to-metamathematics-1952-intro-and-elimi has mistakes: if truly your step 4) has superscript i.e. $\forall x A(x) \vdash^x B$ then you cannot apply $\to$-introduction to get step 5) because that requires that the free variables are held constant for the discharged assumption. It's just that $x$ is not free in $\forall x A(x)$ as whatever is free in $A(x)$ is now bound by the $\forall x$ therefore your step 4) does not have the superscript etc.
Comment: I don't have your book, but to clarify your thought, you can design concrete formulas for A(x) and B according to your example 5 & 6, respectively. Your example 5 is treating x as a common parameter in both antecedents of your sequents, while your example 6 is treating x as 2 independent variables... For example for the harder example 6, you can let $A(x): x=2, B: x^2 \ge 1$ for 1st sequent, $A(x): x=0$ for 2nd sequent then you'll see immediately that unlike example 5, here you may satisfy both sequents (no magic at all simply b/c here entailment can be dependent on the value x ranges over).
Comment: There are useful similar posts on this site... The issue is that Kleene's book has no semantics, but there is implicitly an "intuitive" semantics. $A(x) \vdash^x B$ is "equivalent" to $\forall x A(x) \vDash B$ while the lack of superscript $A(x) \vdash B$ means that the variable $x$ must be interpreted as a constant along the whole proof. This corresponds to the modern approach to free variables with variable assignment functions.
Comment: The various restrictions on quantifier inference rules are a "cumbersome" attempt to manage the interplay between "unrestricted" Gen rule: $A(x) \vdash \forall x A(x)$ and Deduction Th. If we want an unrestricted Gen rule, like Principia Mathematica and Mendelson's textbbok) we have to be careful with DT in order to avoid the fallacious $\vdash (x=0) \to \forall x (x=0)$.
Comment: @MauroALLEGRANZA are you sure $A(x) \vdash^x B$ is "equivalent" to $\forall x A(x) \models B$? In his example 6, Kleene writes "Given $A(x) \vdash^x B$ and $A(x) \vdash^x \lnot B$ with $x$ not necessarily held constant...", so seems to me as a non-trivial assumption in this example, the $x$-dependent inference here doesn't mean it must be the case for all variables in the domain, otherwise these 2 assumptions are immediately inconsistent by LNC (law of non-contradiction)...
Comment: @mohottnad to be honest at this point I can't clarify directly the equivalence question. I found that this answer https://math.stackexchange.com/a/580692/643181 was very good to clarify differences in approaching free variables. In particular the examples above 5 and 6 are from a subchapter called "Interpretation of formulas with free variables" where Kleene also list the choices between the generality and the conditional interpretation.
Comment: @mohottnad as far as particular examples for Ex 6. the closest I can is as follows $b \ne 0 \vdash^b 0\ne 0$ which he uses in Ex 3 and 4 the same subchapter page 149 where b is definitely varied (i.e. not held constant). And because $a = a$ can be proven from axioms, by introducing a dummy assumption $b \ne 0 \vdash 0 = 0$. So we have $A(x)$ is $x \ne 0$, $B$ is $0 = 0$, and we end up with $\vdash \lnot \forall b b \ne 0$
Comment: Though in the end I'd like to know:
- are my proofs correct as per Kleene's 1952?
- in particular with the places where I discard the superscript, do I do it at the right places (e.g. I seem to do it at different places for Ex 6. than @MauroALLEGRANZA)
Comment: thx for your elaboration and further ref, and certainly we're near the end. In this book apparently free variable has the *generality interpretation* when there's superscript for turnstile while only acts as an arbitrary constant (term) when there's no superscript. So both your examples are direct explosions from trivial inconsistency assumptions, but the key is the difference of the *order* of negation connective and universal quantifier for these 2 situations emphasized by Kleene when you want to do universal introduction as conclusion. So your example 5 doesn't need to introduce superscript
Comment: ... it's essentially same as usual universal introduction. For your example 6, there's no need of such a concept called "superscript discharge". You should just view superscript as general universal quantified formula $\forall x A(x) \vdash...$ as modern version, then the key is the place of negation when you reach conclusion via RAA...
Answer: The superscript notation $\vdash^x$ is introduced by Kleene to keep track of the application of postulate Rule 9 and 12 with regards to the superscript variable $x$ for an assumption formula, when the deduced formula depends on the assumption. It is a bit ambiguous because it does not identify the assumption formula, but that's usually clear from context (e.g. when there is just one assumption formula). The reason for tracking is to ensure that we meet (or not meet) restrictions to rules, such as the deduction theorem, reductio ad aburdum, where they require that the discharged formula is not varied.
Now the definition for varied involves: an assumption, a variable free in the assumption, a dependent formula in a deduction and the application of Rule 9 or 12 for the variable, assumption to the dependent formula.
So the tracking via the superscript is not required, can be discharged, for some circumstances like:

there is no assumption (step 6 example 5 above)
the variable does not occur free (e.g. 4 in example 6 above, $x$ is not free in $\forall x A(x)$ because $\forall x$ bounds all free occurrences of $x$ in $A(x)$

In fact Kleene uses the discharge mechanism for the two circumstances above for Example 2 at step 2 and Example 3 at step 3 (IM same page 149)


Ample line bundles and dimension of a proper variety

Question: Let $Y$ be a proper variety over a field $k$. Suppose that $\mathcal{L}$ is an ample line bundle on Y and suppose that $\mathcal{L}$ is isomorphic to the trivial bundle. What can I conclude about the dimension of the variety?
From the assumption I can (hopefully) deduce that the trivial bundle $\mathcal{O}_Y$ is not only ample: it is indeed very ample (relative to Spec$(k)$), so that there is an immersion $i\colon Y \to \mathbb{P}^n$, for some $r$ such that $\mathcal{O}_Y \cong i^{*}(\mathcal{O}(1))$. My feeling is that this should imply that the variety is affine - that forces the dimension of $Y$ to be $0$, being proper - but I don't see a proof.
Thank you!
Answer: The assumption that the structure sheaf is ample means that $Y$ is quasi-affine (see for example Proposition 5.1.2 in EGA II), which is equivalent to the canonical morphism $i:Y\to\mathop{\mathrm{Spec}}(\mathcal{O}_Y(Y))$ being an open immersion. Now $Y$ being proper implies that $i$ is proper and hence it is a closed immersion. Therefore $Y$ is indeed affine.
Comment: Thank you for the answer. I actually missed the cited result in EGA II.
Comment: ....................nice.


beautifulsoup with an invalid html document

Question: I am trying to parse the document http://www.consilium.europa.eu/uedocs/cms_data/docs/pressdata/en/ecofin/5923en8.htm.
I want to extract everything before Commission:.

(I need Beautifulsoup because the second step is to extract countries and person names)
If i do:
import urllib
import re
from bs4 import BeautifulSoup
url="http://www.consilium.europa.eu/uedocs/cms_data/docs/pressdata/en/ecofin/5923en8.htm"
soup=BeautifulSoup(urllib.urlopen(url))
print soup.find_all(text=re.compile("Commission"))

The only result I get is :
[u'The Governments of the Member States and the European Commission were represented as follows:']

This is the first occurrence of the word, but not the line I am looking for. I think it's because the document is not valid, but not sure. If I look at the source code :

Commission:

But if I do a print of soup, I can see the text, with tags reordered:
Commission

How can I get this element "Commission:"?
I am using python 2.7 and Beautifoulsoup 4.3.2.

EDIT: SOLVED!
As suggested alecxe, I replaced the line:
soup=BeautifulSoup(urllib.urlopen(url))

with
BeautifulSoup(urllib.urlopen(url), 'html.parser')

It works now :).
Thanks to everyone.

EDIT: similar problems
I have founs similar problems with the same solution:
Beautiful Soup 4 find_all don't find links that Beautiful Soup 3 finds
Beautiful Soup findAll doen't find them all
Comment: But running this script I'm getting total 9 strings: the second one is the one mentioned here.
Comment: Ok we don't get the same results. Is it because of my version of python / Beautifoulsoup?
Comment: I ran exactly what is written in your post, bs4 and python 2.7.
Answer: If you want everything before the tag with "Commision:" value. You could just do it without beatifulsoup... and just treat it lika a string variable and search for the right keyword and drop the rest of the string.
But when I run your code I get following:
[u'The Governments of the Member States and the European Commission were represe
nted as follows:', u'Commission', u'The Council held an orientation debate on ke
y economic policy issues with a view to giving guidance to the Commission on the
 questions Ministers wish to be addressed in the broad economic policy guideline
s 1998/99 for which the Commission will present its recommandation later in the
Spring. It was noted that the forthcoming guidelines are of particular importanc
e given the start of stage 3 of EMU.', u'The debate was based on an assessment o
f the economic situation and outlook in the Community carried out by the Commiss
ion and the Economic Policy and Monetary Committees.', u"The Council held an ori
entation debate on the Commission's Communication setting out a possible Communi
ty framework allowing Member States to experiment with reduced VAT rates for lab
our-intensive services in order to boost employment in small businesses without
distorting international competition. ", u'This Communication was tabled by the
Commission as a follow-up to the Employment European Council of last November in
 Luxembourg, which concluded that, in order to make the taxation system more emp
loyment-friendly, "Member States will examine, without obligation, the advisabil
ity of reducing the rate of VAT on labour-intensive services not exposed to cros
s-border competition".', u"In conclusion, the Council invited Coreper to examine
 the technical questions arising from today's debate and to report back to it wi
th a view to deciding on a possible request to the Commission to submit a propos
al in this area. ", u"This technical examination should be carried out, taking i
nto account the criteria indicated in the Commission's Communication for a reduc
ed VAT rate, on the following questions :", u'An initial trial period running un
til the year 2002 should identify the best method for allocating FISIM. At the e
nd of this period, the Commission will assess the results of the trial period an
d decide, by means of a comitology procedure, on the final methodology to be app
lied. However, a unanimous decision by the Council would be needed in order to u
se the new methodology in budgetary calculations on other Community policies and
 notably concerning "own resources".']

Comment: It's not a good solution because I want to process the extracted html (I want to extract countries and person names).
Comment: You did not state that criteria.
Comment: You wrote "I want to extract everything before Commission:. " I just gave you a working solution to that statement.
Comment: Ok sorry, I just added it in my first post, my mistake (I didn't downvoted you).
Comment: Ok we don't get the same results. Is it because of my version of python / Beautifoulsoup?
Comment: I tested it on a clean install of Python 2.7.6 and Win 8 and did pip install beautifulsoup4.
Answer: Iterate over p elements and stop when you find a text starting with Commission:
import urllib
from bs4 import BeautifulSoup

url="http://www.consilium.europa.eu/uedocs/cms_data/docs/pressdata/en/ecofin/5923en8.htm"
soup=BeautifulSoup(urllib.urlopen(url))

for item in soup.find_all('p'):
    if item.text.startswith('Commission'):
        break
    else:
        print item.text

It prints everything before Commission:
The Governments of the Member States and the European Commission were represented as follows:
Belgium:
...
Ms Helen LIDDELL            Economic Secretary to the Treasury
* * *

Comment: @rom do you have `html5lib` installed? If not, try to install it and rerun the code. Also, try replacing `soup=BeautifulSoup(urllib.urlopen(url))` with `soup=BeautifulSoup(urllib.urlopen(url), 'html.parser')`.
Comment: Trying to run your code... I have the error: `File "/usr/local/lib/python2.7/dist-packages/bs4/element.py", line 1198, in descendants
    current = current.next_element
AttributeError: 'NoneType' object has no attribute 'next_element'`
Comment: It works :). I just added 'html.parser' as you suggested and now I have the same results as everyone :D. Thank you very much.


Is this a good way to structure model on an MVC application?

Question: This is more a "Am i doing it right?" question.
I am using a MVC framework ( Zend Framework )  and was wondering if this is the best way to structure a model.
In this case i have an user groups model and, after coding for sometime, i realized that on my controllers i was repeating some stuff like a query to return visible groups.

$model->fetchAll( array(
     'enabled = 1',
     'visible = 1'
) );

In order to reduce code repetition, i created a method on this model that returns the query for visible groups.
Based on this same situation, i also created many other methods like hidden groups, disabled groups etc.
Is this the best way to avoid code duplication? My concern is that if i kept inserting that code on controllers i would have a big headache if the business rule for visible group changes in the future.
At the same time i am also concerned that, if i follow this new approach, i will end up with a bloated model full of methods to return queries.
How do you deal with this kind of situation?
Thanks for your help!
Answer: if u are writing queries to fetch data in controllers where is Model layer of mvc then?. i would write a seperate layer that would get, add, edit etc. my domain models. u can have a look at repository pattern in php here.


Fazer com que um START TRANSACTION não reserve o ID das tabelas envolvidas, em caso de falha no insert

Question: Olá amigos desenvolvedores,
Montei um script transaction para inserir valores em 2 tabelas diferentes, coloquei um or die no fim de cada INSERT, para que a inserção de dados não ocorra na segunda tabela, caso ocorra um erro na inserção da primeira.
O que tem me incomodado é que mesmo que ocorra um erro na inserção dos dados e o processo morra (não inserindo os dados no banco), ainda assim a ID das tabelas é reservada, fazendo com que em um próximo INSERT bem sucedido, a ID não esteja sequencial em relação ao registro anterior.
OBS: As duas tabelas tem auto_increment na ID.
Existe alguma forma de resolver esse problema?
Segue abaixo um exemplo do meu código:
    $mysqli->query('START TRANSACTION') or die($mysqli->error);

    $sql = "INSERT endereco (logradouro, numero, complemento, bairro, cidade, uf) VALUES ('".$logradouro."','".$numero."','".$complemento."','".$bairro."','".$cidade."','".$uf."')";
    $query = $mysqli->query($sql) or die($mysqli->error);
    $idEndereco = $mysqli->insert_id;

    $sql = "INSERT contato (email, telefone, telefone_adicional) VALUES ('".$email."','".$telefone."','".$telefoneAdicional."')";
    $query = $mysqli->query($sql) or die($mysqli->error);
    $idContato = $mysqli->insert_id;

    $mysqli->query('COMMIT') or die($mysqli->error);

Answer: Isso é uma característica do AUTO INCREMENT, segundo a própria documentação:

"Lost" auto-increment values and sequence gaps
In all lock modes (0, 1, and 2), if a transaction that generated auto-increment values rolls back, those auto-increment values are "lost". Once a value is generated for an auto-increment column, it cannot be rolled back, whether or not the "INSERT-like" statement is completed, and whether or not the containing transaction is rolled back. Such lost values are not reused. Thus, there may be gaps in the values stored in an AUTO_INCREMENT column of a table.

Fonte
Em resumo: em qualquer modo de bloqueio (0, 1 e 2), se uma transação que gerou um valor do auto-increment falhar, esses valores serão perdidos. Esses valores não podem ser reutilizados. Assim, poderá haver lacunas nos valores armazenados na coluna AUTO_INCREMENT da tabela.

Uma fez que você gera o AUTO INCREMENT você não pode reverter os valores já gerados, segundo a própria documentação, o que reduz as chances disso realmente ser possível. Não vejo absolutamente nenhum problema em haver lacunas, "deixar de ser sequencial".
Comment: Agradeço pela resposta Inkeliz!


Parse XML and populate in List Box

Question: I've posted the same question here and I've also got couple of good answers as well. While I was trying the same answers, I was getting compilation errors. Later I got to know that we are using .NET 2.0 and our existing application has no references to LINQ files.
After searching in SO, i tried to figured out partly:
public partial class Item
    {
        public object CHK { get; set; }
        public int SEL { get; set; }
        public string VALUE { get; set; }
    }

Parsing:
        XmlDocument doc = new XmlDocument();
        doc.LoadXml("<LISTBOX_ST>
             <item><CHK></CHK><SEL>00001</SEL><VALUE>val01</VALUE></item>
             <item><CHK></CHK><SEL>00002</SEL><VALUE>val02</VALUE></item>
             <item><CHK></CHK><SEL>00003</SEL><VALUE>val03</VALUE></item>
             <item><CHK></CHK><SEL>00004</SEL><VALUE>val04</VALUE></item>
             <item><CHK></CHK><SEL>00005</SEL><VALUE>val05</VALUE></item>
                   </LISTBOX_ST>");
       List<Item> _lbList = new List<Item>();
       foreach (XmlNode node in doc.DocumentElement.ChildNodes)
        {
            string text = node.InnerText; //or loop through its children as well
            //HOW - TO - POPULATE THE ITEM OBJECT ??????
        }
       listBox1.DataSource = _lbList;
       listBox1.DisplayMember = "VALUE";
       listBox1.ValueMember = "SEL";

How to read two child nodes - SEL and VALUE of node  and populate the same in the new Item DTO??
Answer: You could do it just like this:
    XmlDocument doc = new XmlDocument();
    doc.LoadXml(@"<LISTBOX_ST>
     <item><CHK></CHK><SEL>00001</SEL><VALUE>val01</VALUE></item>
     <item><CHK></CHK><SEL>00002</SEL><VALUE>val02</VALUE></item>
     <item><CHK></CHK><SEL>00003</SEL><VALUE>val03</VALUE></item>
     <item><CHK></CHK><SEL>00004</SEL><VALUE>val04</VALUE></item>
     <item><CHK></CHK><SEL>00005</SEL><VALUE>val05</VALUE></item>
     </LISTBOX_ST>");

    List<Item> _lbList = new List<Item>();
   foreach (XmlNode node in doc.DocumentElement.ChildNodes)
    {
        string chk = node.ChildNodes[0].InnerText;
        int sel = int.Parse(node.ChildNodes[1].InnerText);
        string value = node.ChildNodes[2].InnerText;

        Item item = new Item();
        item.CHK = chk;
        item.VALUE = value;
        item.SEL = sel;

        _lbList.Add(item);
    }
   listBox1.DataSource = _lbList;
   listBox1.DisplayMember = "VALUE";
   listBox1.ValueMember = "SEL";

Parse XML and populate in List Box


Discriminant when coefficient of x^2 == 0.

Question: $f(x)=4kx^2+(4k+2)x+1$
So the discriminant is
$b^2-4ac$ making
$(4k+2)^2-4(4k)(1)$
which simplifies to
$16k^2+16k+4-16k$
which simplifies to
$16k^2+4$
A question states that when k=0, f(x) cannot have two distinct roots, which I get as f(x) become $2x+1$ which is linear, and when you sub 0 into the discriminant it equals 4 which seems to suggest it has 2 real roots, why is this not the case?
$16(0)^2+4 = 4$
Comment: The discriminant is simply not applicable when $k = 0$, because the underlying function is not a quadratic.
Answer: The concept of discriminant works when we are dealing with a quadratic equation and an equation is quadratic if and only if it is of the form $ax^2+bx+c$ with $a\ne 0$. So the moment you make $a=0$ you are not allowed to use the concept of discriminant.


How can I determine whether PC1 or PC2 is more effective to separate enzymes and non enzymes for the CD proteins?

Question:
The score plot from the PCA is represented in the diagram. I performed the Mann Whitney U test for the Scores values for enzymes( blue dot in score plot) and non-enzymes ( red dot) for both PC1 and PC2. I found out that for both Pc1 and PC2, the enzymes and non-enzymes values were significant( both had p-value 0.00). Is there and way to find out by mann whitney U test ( by considering U value or any other values, whether PC1 or PC2 is more effective to seperate enzymes or non-enzymes?
Answer:
Is there and way to find out by mann whitney U test ( by considering U value or any other values, whether PC1 or PC2 is more effective to seperate enzymes or non-enzymes?

Yes.
I don't know if this is really what you ought to do, but to answer your question, recall that the U-statistic is related to the AUC (Area Under the Receiver Operator Characteristic), which is a metric of binary "separation" over a continuous score. See here: wikipedia link.
$$AUC={U\over n_1\cdot n_2}$$
The higher the AUC, the bigger the separability of labels in the given continuous score.


Slow Loading Forms (submission ok)

Question: Hello i was wondering if anyone could suggest anything for me with this problem i have with my forms. (add/node) Ive turned CCK and all my modules off but still when i go to the node/add page the form is taking ages to load (20secs+) even for a simple submission form with no fields etc.
Generally my website http://onlinebanter.com runs ok and i do my best to keep my module lust down.
Is there any code or diagnostic tools i could use to see why my forms are talking so long to load.
Thanks
Answer: I found that it was because i was using an old version of pressflow it must have had some security problems with the other modules. Updated and things running like a dream :)

Slow Loading Forms (submission ok)


creating a variable from sed output

Question: I am banging my head against the keyboard on this simple piece of code.
#!/bin/bash
connstate="Connected"
vpnstatus=$(/opt/cisco/anyconnect/bin/vpn state | (grep -m 1 'state:'))
echo $vpnstatus
vpnconn=$(echo $vpnstatus | sed -e 's/>>\ state: //g' | sed "s/ //g")
echo "$vpnconn"  "$connstate"
if [ "$vpnconn" = "$connstate" ];then
   echo $vpnconn
   else echo "this script still fails"
fi
echo done

This is the output from the above code:
>> state: Connected
Connected Connected
this script still fails
done

I believe the issue revolves around the vpnconn=$ if I comment that section of code out and fill the variable vpnconn="Connected" this code works fine. Something with how the sed is working on the input from vpnstatus and outputting the results to vpnconn is making what looks like a correct result incorrect when doing the compare in the if then.
I have tried splitting up the vpnconn line into two separate lines and that did not change anything, I took out the sed "s/ //g" and replaced it with a trim -d ' ' and that did not change the results. I know this is something small in this tiny piece of code that I am missing.
Comment: I suspect it's a whitespace issue. Try replacing `sed "s/ //g"` with `sed "s/[[:space]]//g"`?
Comment: Folks, we have a winner....

I suspect it's a whitespace issue. Try replacing sed "s/ //g" with sed "s/[[:space]]//g"? – tsm

Give this person a kewpie doll.

and pjh gets a nice handshake for the correction of tsm
Comment: What if the `$vpnconn` has some escape character in it which is suppressed by echo? like `\n` for example?
Comment: I also think that the most likely problem is invisible characters in `$vpnconn`.  To see what is really there, replace `echo "$vpnconn"  "$connstate"` with `printf '%q %q\n' "$vpnconn"  "$connstate"`.  The fix suggested by @tsm should work, with a small modification: use `[[:space:]]` instead of `[[:space]]`.
Answer: Did you try?
vpnconn=$(echo "$vpnstatus" | awk '{print $3}')

Something like:
vpnstatus=$(/opt/cisco/anyconnect/bin/vpn state|grep -m 1 'state:'|awk '{print 3}')

should do the work.

creating a variable from sed output


Django dynamic list comprehension filtering between dates

Question: I am using comprehension to filter dynamically between multiple from-to date inputs.
If one of the two has no value, the search should still work.
How can I apply the below logic using django range operator?
What I really want is to be able to pass in the filtering qs = qs.filter(**filters) and convert it to qs = qs.filter(date_from1__lt=whatever)
def mail_search(request):
    today_date = datetime.now()

    qs = MailAllocation.objects.filter(cmp_id=cmp_id)

    """comprehension: build a dictionary and use it for filtering queryset dynamically"""
    filters = {
    key: value
    for key, value in request.POST.items()
    if key in ['date_from1','date_to1','date_from2','date_to2','date_from3','date_to3']
    }

    qs = qs.filter(**filters).order_by('-creation_date')

    context={
    'dfs_search_results':qs,
    }
    return render(request,'mail_search_results.html',context)

Answer: You can use Q objects to chain up your queries so each of your keys will get simplified to the following :-
from django.db.models import Q

q1 = Q(creation_date__range=(date_from1, date_from2))
// Build other queries similarly

qs = qs.filter(q1 | q2 | q3)  // The | is the OR operator


Why is the population standard deviation approximated as the sample standard deviation?

Question: This question addresses calculating a p value from the mean and standard deviation statistics of a sample. I understand that the -general- philosophy is to divide the sample standard deviation by the root of the sample size to get the standard deviation of the sampling distribution, using the assumption that the standard deviation of the sample is roughly equal to the standard deviation of the hypothetical larger population. Then one calculates a z-score from the number of standard deviations of the sampling distribution to calculate what percent of the time the observed result would have occurred by random chance. I understand that the particular formula for the sampling distribution standard deviation depends on the particular statistic, say difference of means is a different formula.
The texts and videos that I've looked at use language like "the sample standard deviation is the best number we have available to estimate the population standard deviation." I just don't find that explanation satisfying.
This approach hinges on the validity of estimating the standard deviation of the entire population as being approximately equal to the standard deviation of the representative sample. However, we don't make the same assumption that the mean of the population is the approximately equal to the mean of the sample. At some level, it feels like the final result of significance or non-significance is only self-validating or checking for self-consistency of an assumption that is baked into the methodology.
So to restate, why is the sample standard deviation a good approximation of the population standard deviation, but the sample mean is not a good approximation of the population mean? I found online an equation for standard deviation of the sampling distribution of standard deviations:
standard error of standard deviation = .71 sample standard deviation / root N.
Does the relative narrowness of the standard error compared to standard deviation play a role in justifying the approximation?
Thank you
Comment: "why is the sample standard deviation a good approximation of the population standard deviation, but the sample mean is not a good approximation of the population mean?" Where have you seen it asserted that the sample mean is not a good approximation of the population mean? It is often used as an estimator of a population mean.
Comment: I've wondered the same thing.  We may consider the sample mean the best available estimate of the population mean.  But we know it's not perfect, so we want to quantify our uncertainty with a p-value or CI.  So we do so by *estimating* the standard error, with the very same data we don't entirely "trust".
Comment: @Michael When a class shifts from teaching a z test with population standard deviation known to a t test using the sample standard deviation, sometimes unfortunate language like this is used that creates a seemingly illogical inconsistency between how the mean and standard deviation are described and used. The treatment of the sd as a nuisance parameter when testing a mean seems to further the confusion. Some of the handwaving done to transition from the ztest to the ttest without getting into technical details likely leads to confusion as well.
Comment: "I just don't find that satisfying". It is not satisfying, indeed. The problem is that the text you're using is not advanced enough to formally justify/prove the statement. You will find proofs for statements like those in mathematical statistics textbooks. Check, for example, Statistical Inference by Casella & Berger.
Comment: You wrote "However, we don't make the same assumption that the mean of the population is the approximately equal to the mean of the sample." That is simply not true. If you could tell us what caused you to think we do not use the sample mean to estimate the population mean, maybe your question could be understood.
Comment: @jsk : "When a class shifts from teaching a z test with population standard deviation known to a t test using the sample standard deviation, sometimes unfortunate language like this is used that creates a seemingly illogical inconsistency between how the mean and standard deviation are described and used." $${}$$ Unfortunate language like WHAT? If I had any idea specifically what "language" you had in mind, I might be able to understand what you're saying.
Answer: I'm answering my own question but I think that I have an intuitive justification for why the sample standard deviation reflects the population standard deviation.
As our sample size becomes larger and larger, it better reflects the population, and thus the variation of the population.  I realize that we could say the same for the sample mean, but at least for the case of flipping coins, the sample s.d. seems to tend adhere more towards the pop s.d. compared to sample mean.
Suppose we have a true 50 50 coin: p=0.5 q=0.5.  Half of all flips in the coin's history (q = 0.5) give tails = 0, and half of all flips in the coin's history (p = 0.5) give heads = 1.  The population mean of all flips in coin's history = 0.5, and Standard Deviation = root (0.5*0.5) = 0.5.
if flip 10 times and get q=0.6, p=0.4 for 1 sample
then sample mean = 0.4, SD = root (0.6 x 0.4) = 0.490
sample mean has decreased 20% from pop mean, but SD decreased 2%
if flip 10 times and get q=0.7, p=0.3 for 1 sample
then sample mean = 0.3, SD = root (0.7 x 0.3) = 0.458
sample mean has decreased 40% from pop mean, but SD decreased 10%
if flip 10 times and get q=0.8, p=0.2 for 1 sample
then sample mean = 0.2, SD = root (0.8 x 0.2) = 0.4
sample mean has decreased 60% from pop mean, but SD decreased 20%
suppose flip 10 times and get q=0.9 p = 0.1 for 1 sample
then sample mean = 0.1, SD = root (0.9 * 0.1) = 0.3
sample mean has decreased 80% from pop mean, but SD decreased 40%
This scenario shows that over the vast majority of the sampling distribution of possible sample means of 10 flip outcomes, the sample standard deviation does not stray too far from 0.5, even though the sample mean can vary much more
Comment: This is not a good example of a general behavior because the possible outcomes are so limited.  More generally, the variation in the sample mean has a magnitude proportional to the square root of a *second* moment while the variation in the sample variance has a magnitude proportional to the square root of a *fourth* moment.  It therefore is essential to consider the magnitudes of the first, second, and fourth moments of the underlying distribution.
Comment: Thank you for the comment, that is helpful to me.
Answer: No matter the shape of the population distribution, the Central Limit Theorem holds that the sampling distribution of the sample means (and sample variances) approaches a normal distribution as the sample size $T$ (number of observations or data points) gets larger, especially for sample sizes over 30. As you take more samples, the sample distribution graph will look more like a normal distribution, and so on average, the sample moments will be the population moments as $T\uparrow$. (If you add up the means or standard deviations from all of your samples and find the average, that average will be close to the actual moments for the population.)
Comment: The conclusion about the "sample distribution graph" is incorrect.  That's not what the CLT says and the world abounds with counterexamples: as the sample size increases, the empirical distribution of the sample approximates the *underlying distribution,* which is rarely Normal.
Comment: You wrote "as $T\uparrow$", but you never said what "$T$" is. $\qquad$


Representation of $S_3$ on $\mathbb{C}^6$.

Question: I am asked to decompose $S_3$ into its irreducible unitary representations, on $\mathbb{C}^6$.
I wonder how does this differ from analysis the given in the next paper?:
http://users.jyu.fi/~laurikah/REP/REPtext2010_2.pdf
(pages 50-51).
Thanks.
Answer: What you are asking for is a decomposition of the regular representation of $S_3$ (I suppose). The answer is, in general, that every possible irreducible representation occurs with the multiplicity equal to its dimension. So in this case the trivial and the sign representation both once, the two-dimensional irreducible representation (action on a triangle) twice.


Is there a somewhat official or usually accepted classification of math subjects?

Question: We have algebra, topology, calculus... but we all know that these are very vague and very general way to classify math. I came up with this question when I first saw ArXiV`s paper's categories and initially thought that was an already good enough way to classify math knowledge but over time I started thinking it was incomplete.
Comment: lol , nice pun ! :D
Comment: No, not calculus: Real Analysis. The closest to an "official" list is https://mathscinet.ams.org/mathscinet/msc/msc2020.html
Comment: A graphical representation of mathematics as a whole is given here: https://math.stackexchange.com/questions/2939721/a-graphical-representation-of-mathematics-as-a-whole
Answer: Yes, there is a classification by the AMS. The list is way too long to be posted here but can be found in https://zbmath.org/static/msc2020.pdf. Please also check this link https://msc2020.org/
Enjoy :)
Answer: While I don't think either of the words official or semi-official are appropriate, you might be interested in the widely used classification system of Mathematical Reviews. It evolves over time, and was last updated in 2020.


Calling scripts without specifying the path already set in the bashrc file

Question: I added the following $PATH to my ~.bashrc file.
ANTSPATH=/home/3rdparty/ANTs/antsbin/bin
export ANTSPATH

However, I would like to be able to call the scripts in the bin directory without having to specify $ANTSPATH in terminal.
Now I have to use:
$ANTSPATH/script <input> <output>

and I would like to be able to simply do:
script <input> <output>

How can I achieve this?
Thank you in advance.
Answer: Add it in $PATH
export PATH=$PATH:/home/3rdparty/ANTs/antsbin/bin

Comment: Fantastic! I knew it was something very simple.


MongoDB find() to only return results when a certain parameter is set

Question: Looking through the docs here I can't find anything that matches this query. For instance, say I want to do a lookup of the collection products which only returns results for which the parameter maker != undefined. Example set:
[{
    name: 'Obj1',
    maker: 'Maker1'
}.{
    name: 'Obj2'
}.{
    name: 'Obj13',
    maker: 'Maker2'
}]

In the example above, only objects 1 and 3 should be returned.
From the docs, I thought maybe projections might be what I was looking for but this just returns certain fields, rather than limiting results to whether certain field exist.
How can I achieve this?
Answer: Use the $exists operator to select documents that contain a particular field:
db.products.find({maker: {$exists: true}})


VisualSVN Server , Windows 7 and Apache Problem

Question: I am running Visual SVN Server(with Apache) on a Windows 7 computer and network. After about 15-20 minutes of my first commit/update, I am unable to access the repository via Tortoise SVN.
The error message I get is:
OPTIONS of "https://jason/svn/repository1": could not connect to server (https://jason)
Restarting the Visual SVN Server service helps sometimes but fails quite often. The only sure-shot way to get it working is to restart the computer. The server - https://jason is also not accessible via the browser when I get this error
1) I tried reinstalling Windows 7, Visual SVN server and Tortoise SVN but I still keep getting this error.
2) I searched several forums but I dont seem to be able to find an answer.
Please help.
Answer: Try setting up VisualSVN to use port 8443.
Sometimes when you are using two web servers on the same machine there are port conflict.
Answer: If you've installed VisualSVN on the default port (80) you'll be running into conflicts with Windows 7's built-in services that grab that port for themselves. The easy answer is to use a different port.
The more difficult answer, but possibly the better one, is to disable http.sys, which is a web-services thing Microsoft kindly bundled into the kernel to let .NET WCF apps run a bit easier. (like thanks, MS!)
To disable it:
edit the value Start in this key, and set it to 0. reboot.
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\HTTP


Convert enum member to corresponding text

Question: In Kotlin I have an enum as follows:
enum class MediaType() {
    AUDIO,
    VIDEO,
    ARTICLE;
}

I would like to add either a function or some property that allows an enum member to be converted to some corresponding text. For example:
var mediaType = MediaType.AUDIO
var text = mediaType.toText() // returns the string "MP3"

mediaType = MediaType.VIDEO
text = mediaType.toText() // returns the string "mpeg"

While I can add the toText function to the MediaType class, I am not sure how that function references the value it is set to.
Answer: You can add a property to the enum...
enum class MediaType(val text: String) {
    AUDIO("mp3"),
    VIDEO("mpeg"),
    ARTICLE("text");
}

And then use it like this:
println(MediaType.AUDIO.text)

If you'd like a toText() function rather than a property, that can be added as well, but probably isn't as idiomatic:
enum class MediaType(private val text: String) {
    AUDIO("mp3"),
    VIDEO("mpeg"),
    ARTICLE("text");

    fun toText(): String = text
}

Update:
Another way is to add an extension function and keep this logic outside the enum entirely:
fun MediaType.toText(): String =
    when(this) {
       MediaType.AUDIO -> "mp3"
       MediaType.VIDEO -> "mpeg"
       MediaType.ARTICLE -> "text"
    }

Comment: @AndroidDev Enums are objects and can have any internal state. Not having a constructor is not an indicator of better code; this is generally an accepted practice (see the [planet](https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html) enum sample). Additionally manually switching on an enum when you have access to its internal state is prone to mistakes as it is very possible to leave out a constant, etc.
Comment: Also, enums already have a constructor, the JVM uses it to create singleton instances of each value. Even with adding a value to expose as a property, the JVM is calling the constructor - not you. You aren't adding a constructor that isn't already there by adding a property to it. I feel that the first solution I put is the most idiomatic (won't confuse other Kotlin developers).
Comment: But you're adding a parameter to the constructor. But I don't want a constructor. I want to just set a value like this: var mediaType = MediaType.AUDIO
Comment: @AndroidDev - See my update. You can do this with an extension function as well, which would leave your enum as-is and externalize the mapping of enum to String.
Comment: OK, I like your solution and will give you the selected solution although I just tried out my solution and actually like it better.
Comment: @AndroidDev why would the constructor be an issue? This is the most efficient (and arguably elegant) way of doing it, not just in Kotlin. You said you aren't sure how the "function references the value it is set to"; with this solution you don't _need_ that because it is a property of the enum itself.
Comment: Why would you add a constructor when you don't need it? See my solution above. It uses no constructor.
Answer: enum class MediaType() {
    AUDIO,
    VIDEO,
    ARTICLE;

    fun getMemberText() = when (this) {
        AUDIO -> "mp3"
        VIDEO -> "mpeg"
        else -> "text"
    }
}


What is the distribution of the difference between two random numbers?

Question: I have a big bag of balls, each one marked with a number between 0 and $n$. The same number may appear on more than one ball. We can assume that the numbers on the balls follow a binomial distribution.
Now I pick a random ball from the bag, read its number $x$ and put the ball back. Then I pick a second random ball from the bag, read its number $y$ and put it back.
I compute $z = |x - y|$. What is the distribution of $z$?
My calculations led me to the result that it's a chi distribution with one degree of freedom (or better, its discrete equivalent). To obtain this result, I used the normal instead of the binomial. I wonder if this result is correct, and how it can be obtained without approximating the binomial with the normal.
Comment: *"I have a big bag of balls, each one marked with a number between 1 and n"* So the distribution of the numbers on these balls (and how many balls there are in total) is not specified completely? Or do you just want to ask, in a very indirect way, the distribution of the difference of two independent and similar  binomial distributed variables? (note: picking a ball from a bag with balls that have numbers which are binomial distributed, is not the same as picking independent binomial distributed variables, imagine for example the case of one single ball in the bag).
Comment: There is no such thing as a chi distribution with zero degrees of freedom, though.  Yours is (very approximately) $\sqrt{2p(1-p)n}$ times a chi distribution with one df. The approximation may be poor near zero unless $p(1-p)n$ is large.
Comment: ...... this latter one, the difference of two binomial distributed variables, is not easy to express.  You could see it as the sum of a categorial variable which has:

$$p(x) = \begin{cases} p(1-p) \quad \text{if $x=-1$} \\
1-2p(1-p) \quad \text{if $x=0$} \\
p(1-p) \quad \text{if $x=1$} \\\end{cases}$$ This is also related with the sum of dice rolls.
Comment: Related https://math.stackexchange.com/questions/562119/difference-of-two-binomial-random-variables and https://math.stackexchange.com/questions/1065487/difference-between-two-independent-binomial-random-variables-with-equal-success/1171684
Comment: The distribution cannot possibly be chi-squared because it is discrete and bounded.  Possibly, when $n$ is large, a *chi* distribution would be a decent approximation, depending on your purpose.
Comment: @whuber: you're right, sorry. I meant _chi_ distribution, not chi-squared. Don't know why I wrote that...
Comment: @MartijnWeterings: how many balls are in the bag is not specified completely, that's right. The distribution of the numbers is given in this sense: the probability of picking a ball with number $x$ is distributed like $\text{Binom}(n, p)$ (for some $p$). I hope this clarifies my question!
Comment: You can divide your problem in two parts. You have a small probability $\frac{1}{n_{balls}}$ that $y$ is the same ball as $x$ in which case the difference is zero. You have another probability that $x$ and $y$ are not the same balls in which case the difference is according to the distribution of two similar and independent binomial distributed variables.....
Comment: @MartijnWeterings The difference will typically be zero with much greater probability than that, because to achieve a binomial distribution there will be many pairs of *different* balls that have the same numeric label.  For $p$ near $1/2,$ $n$ has to be quite large before the chance of a zero difference becomes appreciably small.
Comment: @whuber, you are right, but I was seeing it as a mixture distribution where the one distribution (that occurs with probability 1/n) is *always* zero, and the other distribution (that occurs with probability 1-1/n) is sometimes zero. So indeed the probability of zero is larger than 1/n. The main point of my comment is that you can divide the problem into a simple mixture distribution and then the (difficult) core problem is to solve that difference of two binomial distributed variables.
Comment: @MartijnWeterings Thank you for the explanation.  As far as the core problem goes, use the probability generating function, which has a simple form.  (*How* you use it will depend on how you prefer to express the distribution.)
Comment: The complexity that I am thinking about is whether one can simplify the expressions resulting from it (these expressions should be some summation of some sort).
Comment: I'd also wonder how it is known, if some numbers can be repeated, that the numbers on the balls are between 1 and $n$.  Is it because all the balls have been examined and 1 is the smallest numbered ball in the bag and $n$ is the largest numbered ball known to be in the bag or is it just known that numbers between 1 and $n$ *could have* been assigned to balls?
Answer:
Difference of two independent binomial distributed variables with the same parameters

I have a big bag of balls, each one marked with a number between 1 and n. The same number may appear on more than one ball. We can assume that the numbers on the balls follow a binomial distribution.
Now I pick a random ball from the bag, read its number x
  and put the ball back. Then I pick a second random ball from the bag, read its number y and put it back.

The core of this question is answered by the difference of two independent binomial distributed variables with the same parameters $n$ and $p$. Let's phrase this as:
Let $X \sim Bin(n,p)$, $Y \sim Bin(n,p)$ be independent. Let the difference be $Z = Y-X$, then what is the frequency distribution of $\vert Z \vert$?
The more general situation has been handled on the math forum, as has been mentioned in the comments.
You can solve the difference in two ways.

Approximation with a normal distribution that has the same mean and variance. You have $\mu_X=\mu_y = np$ and $\sigma_X^2 = \sigma_Y^2 = np(1-p)$ and related $\mu_Z = 0$ and $\sigma_Z^2 = 2np(1-p)$ so you can approximate $Z \dot\sim N(0,2np(1-p))$ and for $\vert Z \vert$ you can integrate that normal distribution. $$P(\vert Z \vert = k) \begin{cases} \frac{1}{\sigma_Z}\phi(0) & \quad \text{if $k=0$} \\
\frac{2}{\sigma_Z}\phi(\frac{k}{\sigma_Z}) & \quad \text{if $k\geq1$}  \end{cases}$$
which is close to a half normal distribution or chi distribution as you call it, except that the point $k=0$ does not have the factor 2.
Compute a sum or convolution taking all possible values $X$ and $Y$ that lead to $Z$. The probability for  $X$ and $Y$ is:
$$f_X(x) = {{n}\choose{x}} p^{x}(1-p)^{n-x}$$
$$f_Y(y) = {{n}\choose{y}} p^{y}(1-p)^{n-y}$$
The probability for $Z=z \geq 0$ is
$$f_Z(z) = \sum_{k=0}^{n-z} f_X(k) f_Y(z+k)$$
and related
$$P(\vert Z \vert = k) \begin{cases} f_Z(k) & \quad \text{if $k=0$} \\
2 f_Z(k) & \quad \text{if $k\geq1$}  \end{cases}$$
The sum can also be expressed with a generalized hypergeometric function. The function $f_Z(z)$ can be written as:
$$f_Z(z) =  \sum_{k=0}^{n-z} \frac{(n!)^2 p^{2k+z} (1-p)^{2n-2k-z}}{(k)!(k+z)!(n-k)!(n-k-z)! }  $$
or as a generalized hypergeometric series
$$f_Z(z) =  \sum_{k=0}^{n-z} { \beta_k \left(\frac{p^2}{(1-p)^2}\right)^{k}}  $$
with $$ \beta_0 = {{n}\choose{z}}{p^z(1-p)^{2n-z}}$$
and $$\frac{\beta_{k+1}}{\beta_k} = \frac{(-n+k)(-n+z+k)}{(k+1)(k+z+1)}$$
such that we can write $f_Z(z)$ in terms of a hypergeometric function
:
$$f_Z(z) = {{n}\choose{z}}{p^z(1-p)^{2n-z}}  {}_2F_1\left(-n;-n+z;z+1;p^2/(1-p)^2\right)$$
if $p=0.5$ (ie $p^2/(1-p)^2=1$ ) then the function simplifies to
$$f_Z(z) = {{2n}\choose{z+n}}p^{2n}$$
and we could say if $p=0.5$ then $Z+n \sim Bin(2n,0.5)$.
This result for $p=0.5$ could also be derived more directly by $$f_Z(z) = 0.5^{2n} \sum_{k=0}^{n-z} {{n}\choose{k}}{{n}\choose{z+k}} = 0.5^{2n} \sum_{k=0}^{n-z} {{n}\choose{k}}{{n}\choose{n-z-k}} = 0.5^{2n} {{2n}\choose{n-z}}$$ using Vandermonde's identity

computational example:
Below is an example of the above results compared with a simulation. The small difference shows that the normal approximation does very well.

library(hypergeo)

n <- 30
z <- 0:n
p <- 0.6

# simulate
set.seed(1)
ns <- 100000
X <- rbinom(ns,n,p)
Y <- rbinom(ns,n,p)
Z <- abs(X-Y)

# compute 1 exact
beta0 <- factorial(n)*p^z*(1-p)^(2*n-z)/factorial(n-z)/factorial(z)
ps1 <- beta0*Re(hypergeo(-n,-n+z,z+1,p^2/(1-p)^2))

# compute 2 normal approximation
ps2 <- dnorm(z,0,sqrt(2*n*p*(1-p)))

# plot
hist(Z,breaks = c(z,n+1)-0.5, freq=0, main = "Histogram of simulation compared with computed frequencies \n Bin(30,0.6)")
points(z,Re(ps1)*c(1,rep(2,n)),pch=21,col="black",bg="white",cex=1)
points(z,ps2*c(1,rep(2,n)),pch=3,col="black",bg="white",cex=1)

legend(15,0.20,c("computed exact probability","computed normal approximation"),
       pch=c(21,3),cex=c(1,1))

Mixture distribution

I bought some balls, all blank. I take a binomial random number generator, configure it with some $n$ and $p$, and for each ball I paint the number that I get from the display of the generator. Then I put the balls in a bag and start the process that I described.

In the case that the numbers on the balls are considered random variables (that follow a binomial distribution). Then the frequency distribution for the difference $X-Y$ is a mixture distribution where the number of balls in the bag, $m$, plays a role.
You have two situations:

The first and second ball that you take from the bag are the same. This situation occurs with probability $\frac{1}{m}$. In this case the difference $\vert x-y \vert$ is equal to zero.
The first and second ball are not the same. This situation occurs with probability $1-\frac{1}{m}$. In this case the difference $\vert x-y \vert$ is distributed according to the difference of two independent and similar binomial distributed variables.

The above situation could also be considered a compound distribution where you have a parameterized distribution for the difference of two draws from a bag with balls numbered $x_1, ... ,x_m$ and these parameters $x_i$ are themselves distributed according to a binomial distribution.
computational example
Below is an example from a result when 5 balls $x_1,x_2,x_3,x_4,x_5$ are placed in a bag and the balls have random numbers on them $x_i \sim N(30,0.6)$. The probability for the difference of two balls taken out of that bag is computed by simulating 100 000 of those bags. (note this is not the probability distribution of the outcome for a particular bag which has only at most 11 different outcomes)

library(hypergeo)

n <- 30
z <- 0:n
p <- 0.6
nb <- 5

# simulate   (make ns bags, and sample from them)
set.seed(1)
ns <- 100000
bags <- matrix(rbinom(ns*nb,n,p),ns)
X <- apply(bags,1, function(x) sample(x,1))
Y <- apply(bags,1, function(x) sample(x,1))

Z <- abs(X-Y)

# compute 1 exact
beta0 <- factorial(n)*p^z*(1-p)^(2*n-z)/factorial(n-z)/factorial(z)
ps1 <- beta0*Re(hypergeo(-n,-n+z,z+1,p^2/(1-p)^2))

# compute 2 normal approximation
ps2 <- dnorm(z,0,sqrt(2*n*p*(1-p)))

# plot
hist(Z,breaks = c(z,n+1)-0.5, freq=0, main = "Histogram of simulation compared with computed frequencies \n 5 balls in the bag with numbers sampled from Bin(30,0.6)")
points(z,(1-1/nb)*Re(ps1)*c(1,rep(2,n))+c(1/nb,rep(0,n)),pch=21,col="black",bg="white",cex=1)
points(z,(1-1/nb)*ps2*c(1,rep(2,n))+c(1/nb,rep(0,n)),pch=3,col="black",bg="white",cex=1)

legend(15,0.20,c("computed exact probability","computed normal approximation"),
       pch=c(21,3),cex=c(1,1))

Comment: Although the question is somewhat unclear (the values of a Binomial$(n)$ distribution range from $0$ to $n,$ not $1$ to $n$), it is difficult to see how your interpretation matches the statement "We can assume that the numbers on the balls follow a binomial distribution."  That's a very specific description of the frequencies of these $n+1$ numbers and it does not depend on random sampling or simulation.
Comment: @whuber: of course reality is up to chance, just like, for example, if we toss a coin 100 times, it's possible to obtain 100 heads. Here I'm not interested in a specific instance of the problem, but in the more "probable" case, which is the case that follows closely the model. If you assume that with $n=2$ and $p=1/2$ a quarter of the balls is 0, half is 1, and a quarter is 2, than that's a perfectly valid assumption! That's _exactly_ the assumption that I'm making
Comment: Since the balls follow a binomial distribution, why would the number of balls in a bag ($m$) matter?  Nothing should depend on this, nor should it be useful in finding an answer.  Your example in assumption (2) appears to contradict the assumed binomial distribution.  I wonder whether you are interpreting "binomial distribution" in some unusual way?
Comment: @whuber, consider the case when the bag contains only 1 ball (which is assigned randomly a number according to the binomial distribution). Then $x$ and $y$ will be the same value (even though the balls inside the bag have been assigned independently random numbers, that does not mean that the balls that we draw from the bag are independent, this is because we have a possibility of drawing the same ball twice)
Comment: So, say I wish to experimentally derive the distribution by simulating a number $N$ times drawing $x$ and $y$, then my interpretation is to simulate $N$ *different* bags with each $m$ balls in them and the balls have numbers on them that are independently drawn from a binomial distribution.
Comment: Because the bag is a model for a population.  You can understand it either as being a close approximation--with the approximation made as close as one might wish simply by increasing the numbers of balls--or as containing a Nonstandard infinite number of balls.  Regardless, "following a distribution" and "drawn from a distribution" are such distinct phrases and concepts that we should maintain the distinction and take the OP at his word.
Comment: I think it's neither common nor ambiguous, but I'm sure our experiences vary. The problem statement is explicit: there's a bag of balls and they have numerical labels as described; no sampling was involved or implied. I don't understand what you mean by the "other half" of the question.  BTW, an exact answer is not hard to obtain (if you like Hypergeometric functions).  Just about any demonstration of the approximation will be tantamount to a proof of a special case of the CLT.
Comment: Let's put it this way: I bought some balls, all blank. I take a binomial random number generator, configure it with some $n$ and $p$, and for each ball I paint the number that I get from the display of the generator. Then I put the balls in a bag and start the process that I described. Does it make sense now?
Comment: In that case the number of balls in the bag and the use of the mixture distribution *does* matter.
Comment: Likk, that's still a little vague.  To illustrate the difference, suppose $n=2$ and $p=1/2.$  Your question *appears* to assert that a quarter of the balls are labeled with $0,$ half with $1,$ and a quarter with $2.$ If you use a random number generator, then all we know for sure is the values are among $0,1,2,$ but the exact proportions are up to chance.  In this latter case your question has no definite answer (because of that uncertainty) whereas in the former case it has a unique correct answer. Which question are you trying to ask?
Comment: Thank you for that search Martijn, but I don't find it relevant because in the current setting *no sampling is involved* in creating the box. The OP is simply describing a distribution; they are not describing a sample from a distribution.
Comment: I'm going to exit this dialog, Martijn, because we're making no progress.  There's no reference to sampling in the question and the OP has kindly, and quite clearly, clarified its meaning.
Comment: Whatever the interpretation of the question, the answer should be sufficient to help out. I have added two simulations to clearly show two different interpretations that have been used in the answer.


Entity field query issue to correctly sorting my results

Question: I have field order in my content type, in which I have assigned numeric values for my 21 products in order to sort them in ascending order. Results should be displayed like the below order as I expect:

1
2
3
4
5
6
7
8 and so on to 21.

But products are displaying in the following order:

1
10
11
12
13
14
15 up to 19 then
2
20
21
3
4
5
6 up to 9

I dont know why. Here is my snippet.
 $query = new EntityFieldQuery();
 $query->entityCondition('entity_type', 'node');
 $query->fieldOrderBy('field_order', 'value', 'ASC');
 $query->entityCondition('bundle', 'my_content_type');
 $query->pager(8,0);
 $query->propertyCondition('status', 1);

Comment: Then you got exactly proper results for the field you used - alphabetical sort. Make it Integer and you are good to go. See [here](http://drupal.stackexchange.com/q/23050/16495) if you can't see Integer field type.
Comment: What's the type of `field_order`? Because it looks like it's string, not int, and here you go. Strings are sorted alphabetically., and that's exactly what you got. May it be the case?
Comment: its a text field
Answer: I can't make Molot's comment an answer, but I'll post one for posterity (and to close out this question).
The issue involves your data field type, integer vs. string. When the field is a string, sorting in SQL query will place the rows in lexicographic order, where the first character value is given precedence. When the field is an integer, sorting in SQL query will place the rows in numeric order, where the entire value of the number is used.


C++ If I write a function template and don't request any instantiations of it, will any template functions be generated from it?

Question: just asking a question ive been pondering about in the last chapter of my textbook i read
"If I write a function template and don't request any instantiations of it, will any template functions
be generated from it?"
I believe its false because if you dont ask explicitly through an instantiation then the template cannot be created. Thoughts?
Comment: No. Templates are not code. They are instructions to the compiler on *how* to write functions or classes when it finds invocations or definitions in your code with C++ types in the places where template parameters are in the corresponding template definition(s).
Comment: there are no "template functions", I suppose you mean "..will any functions be generated from it?". If you don't tell the compiler what the template parameters should be, how would it pick them?
Comment: Your intuition is correct. "if you dont ask explicitly through an instantiation then the template cannot be created. "
Comment: It's like doing `#define FOO 7` and never using `FOO` anywhere.  Except templates are part of the core language rather than the preprocessor, so occur at different points in the pipeline.
Answer: A class template by itself is not a type, or an object, or any other entity.
No code is generated from a source file that contains only template definitions.
In order for any code to appear, a template must be instantiated: the template arguments must be provided so that the compiler can generate an actual class (or function, from a function template).
https://en.cppreference.com/w/cpp/language/templates

C++ If I write a function template and don’t request any instantiations of it, will any template functions be generated from it?


Average of the Sum of X in MySQL

Question: I have a table that contains values per user per month.
What I need to find is the average value for the sum of users in each month.
I can't do this:
QUERY
SELECT AVG(SUM(TACMargin))
FROM report_sales_month
WHERE YEAR(date) = 2013
GROUP BY userId

Which I don't think would get me what I want anyway.
If I group by user I get multiple rows (obviously) but I need have an average of these.
Comment: Can you edit your question and provide sample data and desired results?  It is not clear what you really want.
Answer: I think you can do what you want with a subquery:
SELECT AVG(sumtc)
FROM (SELECT SUM(TACMargin) as sumtc
      FROM report_sales_month
      WHERE YEAR(date) = 2013
      GROUP BY month(date)
     ) t;

You can also express this without the subquery:
SELECT SUM(TACMrgin) / count(distinct month(date))
FROM report_sales_month
WHERE year(date) = 2013;

Comment: Thanks, your second example works perfectly and is very easy to integrate with the way I have things set up.
Answer: I'm not sure about what result you're looking for. It may be the query that you want:
SELECT AVG(M.totalTACMargin)
FROM (SELECT R.userId
          ,MONTH(R.date) AS month
          ,SUM(R.TACMargin) AS totalTACMargin
      FROM report_sales_month R
      WHERE YEAR(R.date) = 2013
      GROUP BY R.userId, MONTH(R.date)) M

The subquery provide a list of the total TACMargin grouped by month and by user. Then I get the average of all these results.
Hope this will help you.
Answer: this will help you if you want average per month :
SELECT month(date) , AVG(Value)
FROM report_sales_month
WHERE year(date)=2013
GROUP BY month(date)

Average of the Sum of X in MySQL


A basic question on hypothesis testing

Question: In hypothesis testing a hypothesis is generally defined to be "a statement about the value of a population parameter". For example the mean value of the height of people living in a certain city.
I do not understand how this applies to the classical example of coin tossing. In coin tossing we test the hypothesis that the coin is fair. What is the population here and which parameter of this population is under concern?
Thanks
Answer: Let's say you toss your coin 100 times. Then you count how often you've got heads.
Doing this very often you may draw a graph that shows how often you've got one head, two heads, three heads ...up to 100 heads. Your x-axis is 1 to 100 heads, your y-axis is how often you've got it tossing very very often 100 times your coin.
With a perfect coin, you will find that for the most you have 50 times heads. This will be your parameter of central tendency. But of course sometimes there will be more or less than 50 heads, even using a perfect coin. Of course it very unlikely that you get only one head, when tossing 100 times. How (un)likely it is shows your graph.
When doing an empirical experiment with a specific coin, you may toss 100 times and count how often you really found head. Given the H0 that the coin is perfect, you can determine how likely is, what you found empirically. Just go to your graph and have a look.
The second parameter (spreading) depends on how often you toss your coin each trial. If your trial is not 100 tosses but let's say just 10 tosses, you will get more variance (and of course your mean value is 5 and not 50). So your H0-graph depends on how often you toss each trial.
However, the coins are not central but help to understand the idea. Doing a study you have a concrete number of observations ("tosses per trial") and you can calculate the parameters. You can determine how likely is what you found - given the H0.
Comment: Thank you for your answer but this is not the answer to my question. What is the population in the coin tossing experiment here?
Answer: The probability of seeing H heads from n coin tosses follows the Binomial distribution Bin(n,p) where p is the probability of seeing a head in a given coin toss. The Binomial test can be used to test the number of observed heads from n coin tosses against the expected number assuming the null hypothesis that the coin is fair.
There are plenty of worked examples for such problems, for example one involving rolling a die at http://en.wikipedia.org/wiki/Binomial_test .
Comment: Thank you for your answer but this is not the answer to my question. What is the population in the coin tossing experiment here?
Answer: The population is all the tosses of the coin, the parameter is the frequency of the head/tails parameter. Notice that you won't be able to get a random sampling in these kind of situations and the population varies through time, so the experiment differs in important ways to the first one you presented.
Comment: I agree that there are important differences between the two experiments, nevertheless, the definition of hypothesis is a general one so it must be valid for both experiments I guess. By "all tosses of the coin" do you mean all possible outcomes in n trials. For example if we toss the coin 10 times then there are 2^10 different outcomes.
Comment: The population is the group of observations that you want to know something specific about with some certainty. In the first example it's the population of the city. In the coin example it is all the coin tosses that will ever occur in similar situation with the specific coin. You may have to generalize some variables after the experiments. For example, you may have to say that the population also includes all different coin tossers, even though you only had one. Next, you might want to generalize that the results are valid even in other places than your lab and etc.
Comment: And just to be more specific, no I do not mean all the different outcomes. I mean all the coin tosses after/before and including the 10 coin tosses. The more coin tosses you have the more certain you can be of the exact heads/tails ratio. If you toss only once, you can't be sure at all.

A other way to look at it, even if the coin is perfect there is a chance that it lands 10x tails or whatever... So you need a confidence interval.

A basic question on hypothesis testing


A random censored regression problem?

Question: Assume I have random variables $X$ and $Y$. $X$ is observable; $Y$ is not. We also know that, if $X \leq Y$, $Z = f(X,Y)$ where $Z$ is a third random variable and $f(\cdot)$ is a known function; otherwise $Z$ is missing. $Z$ is also observable (missing or a real number).
Assume I know the distribution of $X$ and I can estimate the distribution of $Z$ from data. I wonder if I can estimate the distribution of $Y$.
My first question is: what is this problem? It is similar to but different from a textbook censored regression problem. Is it a random censored regression problem?
My next question is, is the problem identifiable? I realize that, for any given set of random samples $X_1, X_2, X_3, ...$, there may exist multiple sequences $Y_1, Y_2, Y_3, ...$ that yield the same output $Z_1, Z_2, Z_3,...$. So I guess it will be difficult to find the best solution unless some constraints are imposed. If my guess is right, what are typical constraints people apply?
If we can appropriate apply some constraints to the problem so that we can try to find optimal parameters that minimizes some pre-defined error metric. Hopefully we can "estimate" the distribution of $Y$.
Your suggestions, books, and papers are more than welcome.
Any idea?
Comment: This question is also crossposted on MO: http://mathoverflow.net/questions/77833/a-random-censored-regression-problem
Answer: Consider these two simple situations:

The joint distribution of $(X,Y)$ is uniform on $H^2 = [0,1] \times [0,1]$; $Z=X-Y$.
The joint distribution of $(X, \eta)$ is uniform on $H^2$.  When $X \le \eta$, $Y=\eta$; otherwise, $Y=1$.  Again, $Z=X-Y$.

What is common to both situations are (a) the distribution of $X$ (which is uniform) and (b) the distribution of $Z$ (given that $X \le Y\ $).  Yet--obviously--the distributions of $Y$ differ radically: in the first case $Y$ is uniform, implying $\Pr[Y=1]=0$, whereas in the second case $\Pr[Y=1]=1/2$.
The point is that we are free to modify $Y$ on the set $Y\gt X$ without changing any of the information in the problem.  The information places a (crude) lower bound on the marginal CDF of $Y$, but that's all.
That answers all but the first question.  But given that the solution is so indeterminate, I doubt that problems like this (with such limited information) have been investigated, which addresses the first question.  To make progress, you have to make (parametric) assumptions about the distribution of $Y$ or the joint distribution of $(X,Y)$.
Comment: (+1) A couple other simple examples to consider to see the wide disparity of information available: (**1**) $X \sim \mathcal U[0,1]$ and $Y \sim \mathcal U(1,2]$ with $f(x,y) = x$ and (**2**) $X$ and $Y$ with arbitrary distributions, but $f(x,y) = y$.
Comment: @cardinal Although it doesn't matter, I specified an $f$ that depends on both arguments rather than just one to make it clear that such degeneracies aren't the crux of the matter.  Also, by applying the probability transform, we may as well assume $(X,Y)$ is supported on $H^2$.
Comment: Since, as per the OP, $X$ is observable, then the choice of $Z$ in the answer is equivalent to having all the $(X_i, Y_i)$ pairs on $\{X_i \leq Y_i\}$. Regarding my examples, the first is to show an example in which even in the infinite-data setting, we know next to nothing about the distribution of $Y$. The purpose of the second is that it is essentially equivalent to a standard *left-censored* experiment if the $(X_i,Y_i)$ are iid and independent of one another, for which standard analysis can be brought to bear. (Actually by always knowing $X_i$, we're in slightly better shape than that.)
Comment: @whuber thank you for answering the question. I do have an additional question though: you mentioned that the information places a (crude) "lower bound" on the marginal CDF of $Y$". Are you  using the world "lower bound" literally here? Or are you basically trying to say that the CDF is subject to constraint imposed by what happens when $X<Y$?
Comment: @Haining I mean it literally: for each value $y$ of $Y$, we are given a minimum value for the CDF $F_Y(y)$.
Comment: @whuber do you mean that $Prob(Y\leq y) \geq Prob(Y\leq y \text{ and } X\leq Y)$, and that the latter term is known? Thanks.
Comment: @Haining Yes: it's a simple observation. :-)  No subtlety to it at all.

A random censored regression problem?


Integration by Parts confusion

Question: I am using this video to learn Laplace Transform. The example used is a fairly basic one:
$$
\int_{0}^{\infty}t.e^{-st}dt
$$
Simple enough, you need to integrate by parts.
So, $u = t$ and $v^\prime = e^{-st}$
So, $u^\prime = 1$. Well, according to the video it is $dt$ and I can not understand why. If I differentiate $t$ w.r.t. $t$ then I get 1.
Is there something I am missing ?
Comment: This is just a matter of notation. Many people find it helpful to write $du=dt$ instead of ${du \over dt}=u'=1$. This occurs with all types of substitutions. For example, if $u=t^2, y= \sin x, w=e^{iz}$, then mathematicians commonly write $du=2tdt, dy= \cos xdx$ and $dw=ie^{iz}dz$.
Answer: If $u = t$, then we need $du$, not $\frac{du}{dt}$. $$u = t \implies \dfrac {du}{dt} = 1 \iff du = 1\cdot dt = dt$$
Just as with integration by substitution, when we designate what $u$ will be, we need to know what $du$ is:
$$u = t \implies du = 1\cdot dt = dt$$
Comment: Hello! Yes, I've noticed you haven't been around as much. Good to see you!.
Comment: Ah well, he skipped a step then. . . Hi again, it's been a long time. How r u ? Haven't bothered you in chat lately. Will do so shortly :)
Comment: Yeah, was busy with some programming work. Making some new Android apps :)
Comment: Do you need help with the integral, or are you good now?
Comment: No, am good for now :)
Answer: One of the "tricky" notations in calculus within derivatives is ${dy \over dx}$.  In many cases, this term is used as a literal fraction, such that the pieces $dy = y'$ and $dx = x'$ are separable and can be moved throughout an expression in the process of solving it.  So when you write $u = t$ then take the derivative with respect to $t$, you are actually doing this: ${du \over dt} = {dt \over dt} = 1$.  The video is taking the next step and saying that this implies $du = dt$.

Integration by Parts confusion


Apache authentication from multiple domains in AD

Question: I'm trying to find out if there are any apache modules which would allow me to authenticate from 2 different domains of same forest in AD
I have used AuthLDAPURL , AuthLDAPBindDN but they have limitation , they work well if authentication is happening from single domain but not multiple domains .
Has any one made apache authenticate from multiple domains , if yes which module did you use?
Comment: it'd work better if you showed what you tried, that'd give us a better idea of what you'retrying to achieve.
Answer: You can accomplish this by using authentication aliases using mod_authn_alias. http://httpd.apache.org/docs/2.2/mod/mod_authn_alias.html


Would hook_access() hide content from Views/Solr if returning FALSE?

Question: If I were to setup my own hook_access() and return FALSE based on a few different criteria, would this then hide the content from a view in modules like Views and Apache Solr?
Answer: hook_access() is only called when viewing/editing a single node. For all listings, both in core and views, you need to use the node access system. You also need to use that for node types which are not owned by your module.
Answer: No; I tried and the Views module does not respect hook_access(), at least for drupal 6. Take note that I'm not sure if this is the same for you. Our site has a lot of access modules, like node access, path access, access rules, grant access, I'm not sure about the names due to the madness. With this in mind, I don't really know how hook_access() would behave for a clean drupal site.


unix utility to limit the number of bytes placed into a bash variable

Question: Is there a unix/linux utility, perhaps a shell builtin or an external command, that will limit the number of bytes placed into a bash variable? For example, I want to make sure STRING gets at most 1000 bytes (or some arbitrary number I choose) from the output of the curl (or other) command:
STRING=$(curl -s http://localhost:8010/status?)
Let me edit this to make clear that I'm just using curl as an example, but I'd like this to work with any command.
Answer: Just add -r 0-1000 to your curl commandline, i.e.:
STRING=$(curl -r 0-1000 -s http://localhost:8010/status?)

Or generically you can use head -c 1000, i.e.:
STRING=$(curl -s http://localhost:8010/status? | head -c 1000)

Comment: Ok thanks. But I'm looking for something more generic that will work with any command.
Comment: Why not use the native argument in curl?
Comment: because I don't want to restrict it to curl


Alinhamento html e css

Question: Estou enfrentando algumas dificuldades ao tentar alinhar o seguinte conteúdo

HTML

Logo teste

            TESTE

            Início

            Banner

            Produtos

        Desenvolvido por Endrews.

Informações básicas

 ...

CSS
.content-wrap{
    display: inline-block;
    box-sizing: border-box;
    float: left;
    position: absolute;
    background-color: rgba(241,242,247,1);
    height: auto;
    width: calc(100% - 300px);
    overflow-y: auto;
    min-height: 100%;
    height: 100%;
}
.wrap-user{
    background-color: red;
}
.modal{
    margin-left: auto;
    margin-right: auto;
    width: 100%;
    max-width: 1024px;
}
.inicio{
    box-sizing: border-box;
    width: 100%;
    margin-top: 25px;
}
.header{
    box-sizing: border-box;
    position: relative;
    width: 100%;
    height: 80px;
    font-family: 'Open Sans', sans-serif;
    font-size: 16px;
    color: rgba(255,255,255,1);
}
.logo-para-header{
    float: left;
    display: inline-block;
    box-sizing: border-box;
    width: 300px;
    height: 80px;
    padding-top: 23.889px;
    padding-bottom: 23.889px;
    padding-left: 55px;
    text-align: left;
    background-color: rgba(31,181,173,1);
}
.menu-aside{
    display: inline-block;
    float: left;
    position: relative;
    box-sizing: border-box;
    width: 300px;
    /* Altura mínima de 100% do espaço que sobra, evitando 'overflow' */
    min-height: 100%;
    /* Height auto ajustável pelo navegador */
    height: auto;
    font-size: 20px;
    text-align: left;
    color: rgba(174,178,183,1);
    background-color: rgba(50,50,58,1);
}

Comment: Quais são estas dificuldades? o que você esta tentando fazer? já usou algum sistema de grid ou media queries?
Comment: Bacana, cria um fiddle com o exemplo completo usando as grids e tal que facilita na solução do problema
Comment: Também penso assim, o problema é que sem fornecer as informações básicas para testar e ver o problema fica difícil ajudar
Comment: alinhar o 'teste' à informações básicas, usei sim, e é com ele mesmo que ta dando esse problema, e tentei também media queries, mas a margem e as posições não funcionam
Comment: vai levar muito tempo :/ ta no serv da empresa e só volto segunda, eu queria um ex. funcional pra eu ja ir testando em casa :3
Answer: bastou alterar o display do .header para block.

Alinhamento html e css


What is the correct way to construct categories using Laravel

Question: We have a digital platform whose function is to enable the user to create an online store on his own
We are facing a problem with the categories. They are built in, but they take a very long time to load on the browser
What is the correct way to build it lightly and suitable for server and browser
Screenshot to show the time taken
Comment: Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer.
Answer: If it is rendering by js libraries, maybe using browser localStorage helps you load it faster.
But if you are rendering it by yourself, It is a good practice to store categories as depicted in the image below.

and use caching mechanism to store the menu structure in memory and retrieve it in the front-end so fast.


get TableRow id

Question: I want to get index or id of clicked row in TableLayout. Some of the codes looks:
final TableRow rows = new TableRow(this);
rows.setClickable(true);

Click action of the button, which adds rows to TableLayout
TableRow row = new TableRow(getApplicationContext());
row.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT));
row.setTag(String.valueOf(queue_number));
row.setClickable(true);

if (queue_number % 2 == 0) {
row.setBackgroundColor(getResources().getColor(R.color.blue_grey));
} else {
row.setBackgroundColor(getResources().getColor(R.color.white));
}

TextView row_queue = new TextView(Satish.this);
row_queue.setText(String.valueOf(queue_number));
row_queue.setPadding(6, 6, 0, 6);

TextView row_product_name = new TextView(Satish.this);
row_product_name.setText(product_name.getText().toString());
row_product_name.setPadding(0, 6, 0, 6);

TextView row_unit_of_measurement = new TextView(Satish.this);
row_unit_of_measurement.setText(unit_of_measurement.getText().toString());
row_unit_of_measurement.setPadding(0, 6, 0, 6);

TextView row_price = new TextView(Satish.this);
row_price.setText(price.getText().toString());
row_price.setPadding(0, 6, 0, 6);

TextView row_sum = new TextView(Satish.this);
row_sum.setText(sum.getText().toString());
row_sum.setPadding(0, 6, 0, 6);

row.addView(row_queue);
row.addView(row_product_name);
row.addView(row_unit_of_measurement);
row.addView(row_price);
row.addView(row_sum);
root_table.addView(row);
queue_number++;

And in the click event of rows looks:
rows.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                  Toast.makeText(getApplicationContext(), String.valueOf(v.getId()), LENGTH_LONG).show();
//                client_name.setText(String.valueOf(rows.getChildAt(1)));
//                   TableRow t = (TableRow) v.getParent();
//                Toast.makeText(getApplicationContext(), String.valueOf(t.getId()), LENGTH_LONG).show();
//                for (int id = 0; id < root_table.getChildCount(); id++) {
//                    if (v.getId() == id) {
//                        Toast.makeText(Satish.this, String.valueOf(r[0].getId()), LENGTH_LONG).show();
//                    }
//                }
            }
        });

But this event returns just nothing. I don't know what's the wrong in my codes. I couldn't see mistake.
Any helpful comment/answer appreciated.
P.S I have searched out in the internet about this, but couldn't found the correct solution for this problem. But, maybe this question is possibly duplicate.
Edit
I can replace field rows with row. If I do it there'll be only one TableRow element. So code looks like:
final TableRow row = new TableRow(getApplicationContext());
row.setClickable(true);

Click action of the button, which adds rows to TableLayout
row.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT));
row.setTag(String.valueOf(queue_number));
row.setClickable(true);

if (queue_number % 2 == 0) {
row.setBackgroundColor(getResources().getColor(R.color.blue_grey));
} else {
row.setBackgroundColor(getResources().getColor(R.color.white));
}

TextView row_queue = new TextView(Satish.this);
row_queue.setText(String.valueOf(queue_number));
row_queue.setPadding(6, 6, 0, 6);

TextView row_product_name = new TextView(Satish.this);
row_product_name.setText(product_name.getText().toString());
row_product_name.setPadding(0, 6, 0, 6);

TextView row_unit_of_measurement = new TextView(Satish.this);
row_unit_of_measurement.setText(unit_of_measurement.getText().toString());
row_unit_of_measurement.setPadding(0, 6, 0, 6);

TextView row_price = new TextView(Satish.this);
row_price.setText(price.getText().toString());
row_price.setPadding(0, 6, 0, 6);

TextView row_sum = new TextView(Satish.this);
row_sum.setText(sum.getText().toString());
row_sum.setPadding(0, 6, 0, 6);

row.addView(row_queue);
row.addView(row_product_name);
row.addView(row_unit_of_measurement);
row.addView(row_price);
row.addView(row_sum);
root_table.addView(row);
queue_number++;

In this situation some design problems occur in TableLayout.
Comment: that event returns "nothing" because the id of the row is not setted.
Comment: @juanhl as you see, I'm setting the `id` to each `row`. But how can I *set* the same id to the `rows` ?
Comment: Or how to write the `row` clickEvent in `onCreate()` method? I tried a lot of ways but no result...
Comment: sorry but, seeing your code I think that you never set the id for TableRow view. i see a setTag() maybe you want say that.
Comment: Oh, it's my sorry. Saying `row` I mean the `TableRow row = new TableRow(getApplicationContext());`. Sorry for unclear speech.
Comment: the value of field queue_number is the index of the row?, if it is maybe you can use v.getTag() in your onClick() method
Comment: have a look at this: http://stackoverflow.com/questions/11336117/how-to-click-an-specific-tablerow-within-a-tablelayout
Comment: @juanhl result's same...
Comment: @AwaisKing yes, I visited given link, but again same result :/
Comment: Where do you use "rows" field?, I see "row", "rows" and "root_table" fields
Comment: I used "rows" only in "OnClickListener" method, field "row" I used in setting views to it (in button click action I wrote above). The "root_table" field used another place.
Comment: sorry but I can't understand what you are doing. How I see, there are 2 main elements, the TableLayout and its TableRows, if you want to add rows dinamically with a button, you will create there your TableRow with its own listener and add it to your TableLayout. Too you can set the id or the tag of that view for use it in the listener.
Comment: @juanhl I updated question.
Answer: I found the best solution for my problem.
I moved the following lines from inside of onCreate() to button click event:
final TableRow row = new TableRow(getApplicationContext());
row.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT));
row.setId(Integer.valueOf(String.valueOf(queue_number)));
row.setClickable(true);

if (queue_number % 2 == 0) {
    row.setBackgroundColor(getResources().getColor(R.color.blue_grey));
} else {
    row.setBackgroundColor(getResources().getColor(R.color.white));
}

TextView row_queue = new TextView(Satish.this);
row_queue.setText(String.valueOf(queue_number));
row_queue.setPadding(6, 6, 0, 6);

TextView row_product_name = new TextView(Satish.this);
row_product_name.setText(product_name.getText().toString());
row_product_name.setPadding(0, 6, 0, 6);

TextView row_unit_of_measurement = new TextView(Satish.this);
row_unit_of_measurement.setText(unit_of_measurement.getText().toString());
row_unit_of_measurement.setPadding(0, 6, 0, 6);

TextView row_price = new TextView(Satish.this);
row_price.setText(price.getText().toString());
row_price.setPadding(0, 6, 0, 6);

TextView row_sum = new TextView(Satish.this);
row_sum.setText(sum.getText().toString());
row_sum.setPadding(0, 6, 0, 6);

row.addView(row_queue);
row.addView(row_product_name);
row.addView(row_unit_of_measurement);
row.addView(row_price);
row.addView(row_sum);

root_table.addView(row/*, queue_number*/);

// set onClickListener at runtime. This is working well for me.
root_table.getChildAt(queue_number).setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        TableRow tr = (TableRow) v;
        TextView num, p_n, u_o_m, p, s;
//        num = (TextView) tr.getChildAt(0);
        p_n = (TextView) tr.getChildAt(1);
        u_o_m = (TextView) tr.getChildAt(2);
        p = (TextView) tr.getChildAt(3);
        s = (TextView) tr.getChildAt(4);
//        row_id = Integer.getInteger(num.getText().toString());
        product_name.setText(p_n.getText().toString());
        unit_of_measurement.setText(u_o_m.getText().toString());
        price.setText(p.getText().toString());
        sum.setText(s.getText().toString());
    }
});

queue_number++;

get TableRow id


Why isn't $\mathbb C$ the center of $\mathbb H$ (the ring of real quaternions)?

Question: I don't get what is wrong with my proof below that $Z(\mathbb H) = \mathbb C$.

If $A = \begin{pmatrix} a & b \\ c & d \end{pmatrix} \in M_2(\mathbb C)$ and $A$ commutes with every $x = \begin{pmatrix} \alpha & \beta \\ -\bar \beta & \bar \alpha \end{pmatrix}$ in $\mathbb H$, then:
$$\begin{pmatrix} a & b \\ c & d \end{pmatrix}  \begin{pmatrix} \alpha & \beta \\ -\bar \beta & \bar \alpha \end{pmatrix} =  \begin{pmatrix} \alpha & \beta \\ -\bar \beta & \bar \alpha \end{pmatrix}  \begin{pmatrix} a & b \\ c & d \end{pmatrix}$$
for all $\alpha, \beta \in \mathbb C$, i.e.
$$\begin{pmatrix} a \alpha - b\bar \beta & a\beta + b \bar \alpha \\ c\alpha - d\bar \beta & c\beta + d\bar \alpha \end{pmatrix} = \begin{pmatrix} \alpha a + \beta c & \alpha b + \beta d \\ - \bar \beta a + \bar \alpha c & - \bar \beta b + \bar \alpha d \end{pmatrix}$$
for all $\alpha, \beta \in \mathbb C$.
Plugging in $\beta = 1$ then $\beta = i$, we get from comparing the first entries that $b = c = 0$. This gives $a=d$ and nothing more. Hence $A = \text{diag}(a,a)$, $a\in \mathbb C$. Conversely, any such matrix evidently commutes with all the elements of $\mathbb H$. So
$$Z(\mathbb H) = \left\{ \text{diag}(a,a): a \in \mathbb C\right \} \equiv \mathbb C$$
Answer: What you're missing is that $\operatorname{diag}(a,a)$ is not in $\mathbb H$ at all unless $a$ is real.
Comment: @Cauchy: Because the _center_ of a ring is by definition a set of elements of the ring. What you have found is the _centralizer_ of $\mathbb H$ in $M_2(\mathbb C)$.
Comment: Why does $\text{diag}(a,a)$ have to be in $\mathbb H$ anyway?
Comment: I see.. thanks a lot!
Answer: You want to find the matrices in $\mathbb{H}$ that commute with all matrices in $\mathbb{H}$. So you should start with
$$\newcommand\quat[2]{\begin{pmatrix} #1 & #2 \\ -\overline{#2} & \overline{#1} \end{pmatrix}}
\quat{a}{b}\quat{\alpha}{\beta}=
\quat{\alpha}{\beta}\quat{a}{b}
$$
Hence
$$
\quat{a\alpha-b\bar{\beta}}{a\beta+b\bar{\alpha}}
=
\quat{\alpha a-\beta\bar{b}}{\alpha b+\beta\bar{a}}
$$
that, of course, reduces to
$$
\begin{cases}
a\alpha-b\bar{\beta}=\alpha a-\beta\bar{b} \\[6px]
a\beta+b\bar{\alpha}=\alpha b+\beta\bar{a}
\end{cases}
$$
Plugging in $\beta=1$, we get
\begin{cases}
a\alpha-b=\alpha a-\bar{b} \\[6px]
a+b\bar{\alpha}=\alpha b+\bar{a}
\end{cases}
With $\alpha=0$, we obtain $b=\bar{b}$ and $a=\bar{a}$. Plugging in $\beta=i$ we get $bi=-i\bar{b}$, so $b=-\bar{b}$. Hence $b=0$.
It's known that a matrix of the form
$$
\begin{pmatrix} a & 0 \\ 0 & a\end{pmatrix}
$$
with real $a$ (that is $a=\bar{a}$) commutes with every element of $\mathbb{H}$, actually it commutes with every matrix in $M_2(\mathbb{C})$.


What is the purpose of drush entity-updates?

Question: After updating Drupal 8 modules, I have been warned on the Drupal 8 status page that:

Entity/field definitions: The following changes were detected in the
  entity type and field definitions.

After a bit of Google rummaging, it seems the solution to this is to run drush entity-updates. However I find this a bit strange as it seems to be another command that one needs to remember or incorporate into one's workflow after updating the database, not to mention it didn't seem immediately obvious about how to address the original warning.
What's more, it's often the case that in development you'll have an alert for other actions in the Status page which will mean you won't immediately know if you need to action this.
Can anybody explain what is this warning is for - or rather, why has this feature been introduced into D8, and why isn't it factored into the database update operation but must be run seperately?
Answer: drush entity-updates is a developer tool. If you change entity/field definitions in your custom module you can quickly apply this.
In production this should not happen. If you update a module between official releases, then the update code in the module should handle this.
But in your case you are mentioning that your site is in developing. So there are a lot of things, which could have caused this. Either in your own code or in dev or alpha versions of contrib modules.
I found this example from the CR Write update functions for entity schema updates, automation removed (where there are further examples):
/**
 * Add 'revision_translation_affected' field to 'node' entities.
 */
function node_update_8001() {
  // Install the definition that this field had in
  // \Drupal\node\Entity\Node::baseFieldDefinitions()
  // at the time that this update function was written. If/when code is
  // deployed that changes that definition, the corresponding module must
  // implement an update function that invokes
  // \Drupal::entityDefinitionUpdateManager()->updateFieldStorageDefinition()
  // with the new definition.
  $storage_definition = BaseFieldDefinition::create('boolean')
      ->setLabel(t('Revision translation affected'))
      ->setDescription(t('Indicates if the last edit of a translation belongs to current revision.'))
      ->setReadOnly(TRUE)
      ->setRevisionable(TRUE)
      ->setTranslatable(TRUE);

  \Drupal::entityDefinitionUpdateManager()
    ->installFieldStorageDefinition('revision_translation_affected', 'node', 'node', $storage_definition);
}

Comment: Except that is actually a bad example. if you are a module, you should do very specific updates. Install a new field definition, update an entity type definition. This can go very badly if you update multiple modules or if the module will make another change in the future and you update from an old version. node.install has a number of better update examples.
Comment: Note regarding Berdir's comment: I've removed the bad example and replaced it with one from the change record.
Comment: Just to be clear, the reason that it's a Bad Idea to run entity-updates in production is that it can be destructive. For instance, if you change a field storage uuid, import the changed storage definition, run cron, and then run entity-updates, it will destroy any existing content in that field.
Comment: Modules should be responsible for applying their own schema updates via targeted update hooks. No one should be running the `entity-updates` command on a regular basis, except for early in the development process of sites with custom modules where you don't care about data destruction.
Comment: Initially, this was done automatically as part of updb/update.php. But it doesn't always work, it doesn't support possibly destructive updates when there is data and that caused a lot of problems. If you have data in a field, you can't just call this method, you need to update it yourself, which can be quite complicated. See https://www.drupal.org/node/2554097 for more information
Comment: That makes sense. I'll put a warning in the answer.
Comment: Curious, @danepowell, is it more appropriate to update the module, then run `drush entity-updates` in production? What, in your opinion, would be a good workflow?
Answer: Command "drush entity-updates" has been removed from v 8.7.0
See https://www.drupal.org/node/3034742

Starting with 8.7.0, Drupal core no longer provides support for automatic entity updates. Whenever an entity type or field storage definition needs to be created, changed or deleted, it has to be done with an explicit update function as provided by the Update API, and using the API provided by the entity definition update manager.
Answer: There is a contrib module that takes the place of the original command.
You can install it with
composer require drupal/devel_entity_updates

Enable it with
drush en devel_entity_updates

and run it with
drush entup

https://www.drupal.org/project/devel_entity_updates