Is there an example of nonassociative arithmetic addition?

Question: Are there any clear, accepted examples of operations that are appropriately defined as "addition" but are not associative? Although I can find references to abstract discussions of arithmetic systems with nonassociative addition behind paywalls (Non-Associative Arithmetics, I.M.H. Etherington 1949) or in obscure books (Arithmetic in a Number System with Completely Nonassociative Addition, Mary Bearden Williams 1958) that are not available to me, I cannot find any examples of such operations.
For comparison, a clear example of nonassociative multiplication is the cross product of vectors in three-dimensional Euclidean space.
Machine floating point arithmetic is sometimes posited as an example of nonassociative addition or multiplication, but this seems a rather crude example because the lack of associativity is due to implementation-specific rounding errors, not an intrinsic nonassociativity of adding or multiplying real numbers.
Comment: By "addition," are you referring to the symbol "+" precisely? The symbol is arbitrary, and in mathematics "+" is typically reserved for associative and commutative operations.
Comment: Addition, multiplication are named given to operations... If you are talking about non associative operations, you already gave good example (vector cross product). If you are talking about addition, the way people use this term, refer to @mixedmath answer.
Comment: @mixedmath That makes sense...but then what would an entire book about ["Arithmetic in a Number System with Completely Nonassociative Addition"](https://books.google.com/books?id=4M71PgAACAAJ) be discussing?
Comment: @JoshuaHonig What Martigan and mixedmath say is true but there are two other aspects : 1) in rings, fields and their generalizations (i.e. modules, near-ring, near-fields, k-, there are at least two binary operations, and by analogy with the classical situation, one operation is called addition and the other multiplication. 2) addition is typically associated with the idea of the magnitude of the result being close to the magnitude of the larger of the elements being combined and multiplication with expansion of magnitude (analogy to the area, the volume, a list of possibilities etc.)
Comment: @JoshuaHonig To answer your comment question, I read the thesis by Williams and she gives flesh to the skeletal outline provided by Trevor Evans in his 1957 paper on Nonassociative Number Theory before concluding that any interesting/nontrivial properties of his system lay beyond the scope of common practice.
Answer: As explained in the comments by several contributors, in most standard definitions of mainstream algebraic structures and applications, addition is supposed or defined to be associative (even in near-rings, the first operation is supposed to form a group). It is a useful convention to follow but one can define and study algebras with one, two or more internal binary operations (and even-ary operations) without this restriction but it is wise to use other names.
The two references you found are related to a line of research called "genetic algebra" by some, also "evolution algebra". See MSC 2010 subject 17D92, 17DXX started mainly in the forties by Etherington.
One of the main ideas is the combination/fusion/recombination of two gametes two make one new organism (that's close to an addition, but is non-associative since the order in which your ancestors reproduce matters) as well as the idea of seing familiar numbers as projection of trees. Etherington's name is now associated with various families of trees or equivalently to certain kinds of parenthesizing schemes.
See the Wikipedia entry for basic references on Genetic Algebra.
You might also be interested in other non-classical algebraic structures such as (planar) ternary rings, k-loops, operads but also, even if it is mainly associative, Tropical Mathematics.
Answer: Concatenation can be considered a type of 'addition', but concatenation of morphemes is not associative, a counterexample to associativity being the fact that 'un(peeled)' and '(unpeel)ed' are antonyms (which is what is behind the fact that 'unpeeled' is an auto-antonym).
Answer: Neofields may count. Here is a link to a paper I found that discusses them. Interestingly, it mentions Trevor Evans, the author of the article that the undergraduate work of Mary Bearden Williams built upon.
"The concept of a neofield was first introduced and developed by
L.J. Paige in 1949.  Paige hoped to use this structure as the co-ordinate system for
a finite projective plane and so to construct new planes, poss
ibly of non-prime-
power order.  It turns out, however, that a more natural struc
ture to look at
is a left neofield because, as was shown by Hsu and Keedwell
 in a paper
published in 1984, left neofields are co-extensive with orthomorphisms and near
orthomorphisms of groups. (The present author discovered later that the Ph.D.
thesis of C.P. Johnson, a student of the late Trevor Evans, which was submitted
in 1981 contains essentially the same idea.)"


Ansible Post Tasks Execution Condition

Question: I'd like to know, in which condition an Ansible post_task will be executed? If the pre-tasks or roles had any failure, would the post-tasks be executed?
For example, I'd like to clean up the server if and only if it is stopped. In the following script, will the server_dir be removed if server is not stopped correctly?
---

- hosts: webservers

  pre_tasks:
    - shell: echo 'stopping server...'

  roles:
    - { role: stop_server }

  post_tasks:
    - file: path="{{ server_dir }}" state=absent

Answer: Tasks under post_tasks will not be executed when the previous tasks failed (meaning that the return code of the task isn't 0). That is the default behavior of Ansible and part of the design of Ansible:

Ansible is actually designed to be a "fail-fast" and ordered system [...]

Ansible test_strategies
fail-fast means Ansible will stop the execution of the whole play as soon as one task fails (as long as you don't set ignore_errors: True parameter for the task.)
The documentation on post_tasks is incomplete but if you write yourself a small test playbook and role you will see that Ansible behaves as expected.
Which makes sense because you might want to use pre_tasks and post_tasks to remove and add a node from and to a cluster and you don't want your node to be added to a cluster when the role didn't executed without errors.

Ansible Post Tasks Execution Condition


The value of $y=\frac{x}{1+x}$, where $x={{\omega^{2009}}^{2009}}^{. ...\text{upto}\;2009\;\text{times}}$

Question:
Let $y=\frac{x}{1+x}$, where
  $$x={{\omega^{2009}}^{2009}}^{. ...\text{upto}\;2009\;\text{times}}$$
  and $\omega$ is a complex cube root of $1$. Then $y$ is
$a) \omega;\quad b)-\omega;\quad c)\omega^2; \quad d)-\omega^2.$

My attempt:
We have $\omega^{2009}=\omega^2$. Now taking $2009$ power in both side gives ${(\omega^{2009}})^{2009}={(\omega^2)}^{2009}={(\omega^{2009})}^{2}=\omega.$
But ${\omega^{2009}}^{2009}\neq{(\omega^{2009}})^{2009}$, since ${a}^{m^n}\neq a^{mn}$.
I am stuck here. So give me only hints.
(If it is required to change the tags of the problem then please feel free to change it)
Comment: The value of $\omega^n$ depends only on the residue of $n$ modulo 3. The value of $2009^m$ modulo 3 depends only on the residue of $m$ modulo 2.
Comment: related https://math.stackexchange.com/questions/2251030/evaluating-a200920092009-text2009-times?rq=1
Comment: Ok.. I understood. Thanks
Comment: If you understand, Saheb, let me encourage you to write it up and post it as an answer.
Comment: Yes. It will be greatful if you post as an answer.
Comment: If you want to be sure I see a comment intended for me, Saheb, you have to put @Gerry in it. But I thought that you understaood how to do the problem, which is why I encouraged *you* to write up and post an answer.
Comment: Today would be a good day to do that, Saheb.
Answer: We have $2009 \equiv - 1(mod\;3)$. Also ${{{2009}^{2009}}^{2009}}^{...}$ is odd.
Therefore $${{2009}^{2009}}^{. …\text{upto}\;2009\;\text{times}}\equiv - 1(mod\;3).$$
$\therefore{{2009}^{2009}}^{. …\text{upto}\;2009\;\text{times}}=3k-1$ for some integer $k$.
Thus $$x={{\omega^{2009}}^{2009}}^{. …\text{upto}\;2009\;\text{times}}=\omega^{3k-1}=\omega^{-1}=\omega^2.$$
$$\therefore y=\frac{x}{1+x}=\frac{\omega^2}{1+\omega^2}=\frac{\omega^2}{-\omega}=-\omega.$$


Asterisk Dial Plan - redial with 44 or 0 (UK numbers)

Question: Have an issue with the redial numbers.
Outgoing line is configured to the digit 0, so on the dial plan it is set to "0|." (without the quotes).
Now all missed calls from the UK, starts with 44 on the IP Phone.
If i hit redial, it refuses the connection as expected.
What do i need too add, that when it sees 44, it either replaces it back with 44 or add additional 0.
I am using Elastix for front end management.
Answer: Just add second rule for 44., and put it on first place.
that way it will use first rule for 44XXXXX and use ur current rule for all other.
Comment: this is a moment where i say D'oh! Danke! i could have sworn i tried this first and didn't work!


How to set variables in an installation profile?

Question: I cannot find any documentation on the variables[] array in an installation profile info file. I can set some variables successfully in that file and others give me an invalid format error when I visit the settings page to check them after the install. The ones that I would like to set are:
variables[site_403] = <front>
variables[user_cancel_method] = user_cancel_block
variables[update_check_frequency] = 7
variables[update_notification_threshold] = security
variables[update_notify_emails] = email@example.com

In Drupal the source it looks like update_notify_emails is probably an array. Is there a way to make this setting an array via this .info file? I am trying to set these using the info file or the install hook rather than exporting the variables as features using a strongarm.inc due to these best practice recommendations linked on this distribution developers guide page.
Answer: You should be able to set these in the .install file in your profile. I've struggled with this well, and the .install seems to be the best way to do it.
<?php
/**
 * Implements hook_install().
 *
 * Performs actions to set up the site for this profile.
 *
 * @see system_install()
 */
function customProfile_install() {
  /*
    Other cool functions...
   */

  variable_set('site_403','<front>');
  // etc....
}

Comment: Agreed. Since I posted this I have written 2 or 3 .install files and at least the php code is well documented while the .info file is not.


Smallest overlapping circles containing unit circles in each section

Question: This is a question inspired by the number of arrangements of n circles in the affine plane which was discussed on Numberphile.
One way of overlapping 3 circles looks like this:

My informal question is: what are the sizes of the 3 smallest circles for this arrangement subject to the limitation that each section is large enough to enclose a unit circle?
The answer perhaps looks like this:

That is approximate (and possibly wrong!). In my drawing the 2 lower circles have radius 2, which is clearly the smallest they can be and still enclose 2 distinct unit circles. The upper circle has a radius of... a bit more than 2.
I think that to be well-defined, we must specify that we're looking for the smallest total area. What are the radii of circles which form the arrangement of circles that cover the minimum total area, subject to the constraint that each of the 5 sections encloses a unit circle?
If anyone can answer the question, that would of course be great. But I'd also appreciate any useful partial answers, since I'm really not sure how to attack the problem.
Note: In the overlapping circles problem, circles cannot be tangent. I'm not worried about that detail in the question I'm posing here. If the smallest arrangement includes 2 circles that touch in a tangent point (as I suspect it does), then the answer should more accurately be thought of as the limit as the circles get arbitrarily close.
Answer:
Since we are looking for the limit, we will solve for the situation where the two bottom circles are actually tangent.
Assuming the large middle circle has radius $R$, the lengths are calculated and labeled in the picture in terms of $R$. In the red triangle we have $$2^2+(\sqrt{5}-R+1)^2=R^2$$ which gives $R=\sqrt{5}$
Comment: Thanks for your answer here. It's really nice!
I'm now relatively confident that this is indeed the *optimal* configuration... though I have not proven this. It's hard to see how circles smaller than 2, 2, √5 could overlap to form 5 regions like these each containing a unit circle.


Alterar cor do texto do botão ao clicar

Question: Gostaria de saber como faço pra alterar a cor do texto da escrita do botão quando eu clico nele, eu quero que eu clique no botão e ele saia da cor dourada e fique na cor branca até eu clicar novamente nele, mas o que eu consegui até agora é que ele mude de cor apenas quando o mouse fica em cima. Segue abaixo código css e html que eu fiz até o momento:
css:
#login{
        @extend .table;
        cursor:pointer;
        position:relative;
        width: 100%;
        height: 79px;

        #centralizar_menu{
            @extend .row;
            text-align: center;
            height: 4.8em;}

        &:hover{
            #texto_cliente #titulo{
                display: block!Important;
                @extend .fonte_branca_13;
            }
            background-color: $dourado;
        }

        #texto_cliente{
            width: 100%;
            height: 1.5em;
            padding: 0.5em 0em;

            #titulo{
                @extend .fonte_dourado_13;
            }
        }
    }

HTML:

Login

Comment: você só quer com css? ou quer usar com jquery?
Comment: De preferência apenas com css
Comment: Já tentou usar com a pseudo-classe  ":active" ? ali em cima você usou o hover, que é quando você passa o cursor do mouse.
Answer: Podes usar a pseudo classe
&:active{
   //aqui vem como você quer que ele fique quando for clicado
}

do mesmo modo que você usou a hover
Comment: eu estou usando &:hover, já tentei com &:active, e ele permanece dourado
Comment: quer dizer, ele fica branco apenas quando eu seguro o botão do mouse clicado
Comment: como que eu faria com jQuery?
Comment: @BernardoKowacic, me mostre como ficou o código com &:active. Provavelmente, o que você quer somente com javascript/jquery
Comment: &:active{
                #texto_cliente #titulo{
                    display: block!Important;
                    @extend .fonte_branca_13;
                }
                background-color: $dourado;
            }
Comment: O problema dessa resposta é que ele não vai criar um toggle da classe, vai apenas manter a mudança de cor enquanto o `clique` for mantido. Após soltar, ele irá se perder.
Comment: @CelsomTrindade, então como você acha que poderia ser feito?
Comment: Se você já está utilizando jQuery, dê uma olhada na resposta abaixo, do Pedro Camara Junior, ela deve funcionar como você deseja.
Comment: na realidade não estou usando nenhum jquery nesse site
Answer: Eu usaria jQuery para isso;
var $divLogin = $("#login");
$divLogin.click(function(){
if ($divLogin.hasClass("dourado"))
    $divLogin.addClass("branco").removeClass("dourado");
else
    $divLogin.addClass("dourado").removeClass("branco");
});

Na tua div adicione inicialmente a classe que desejar

Login

E por fim, defina o css para cada classe
.dourado {
    color: yellow;
}

.branco {
    color: white;
}

Basicamente o que é feito é verificar qual classe está ativa na div e trocá-la para a outra.
Answer: Segue opção de botão: OBS: Utilizando Sass:
.botao_licitacao {
    background: #003366;
    border: none;
    box-shadow: none;
    border-radius: 0px;
    height: em(45);
    font-weight: bold;
    &:hover{
        background: #072440;
    }
    span{
        color: #fff;
    }
    p{
        color: #fff !important;
        @extend .fonte_light;
        font-size: 15px;
        text-decoration: none;
        box-shadow: none;
        text-shadow: none;
        width: 100%;
        text-align: center;
        margin: 0px !important;
    }
    &:hover{
        background: #072440;
    }
    &:hover{
        background: #072440;
    }
    &:visited{
        background: #072440;
    }
}

Comment: Caso não utilize sass é só criar a classe com a propriedade ao lado, exemplo: .botao_licitacao p{}
Answer: Meu problema foi igual, mas simples de resolver:
btn{
/*defini o botão*/
}

btn:hover{
/*Como ele vai ficar ao passar o mouse, ou para o mouse encima*/
}

btn:focus{
/*aqui está a resolução aqui define a cor que o botão deve receber depois de clicar*/
}

Alterar cor do texto do botão ao clicar


Modificar TAG Html dentro de um IFRAME com JavaScript

Question: Gostaria de modificar uma tag que está dentro de iframe em minha pagina.
Acho que vai ficar mais claro com o script abaixo:
O tag "streamurl" está dentro do código do iframe.

Comment: É o mesmo domínio?
Comment: Não, estou usando esse código em uma pagina do blogger.
Answer: Podes usar o contentWindow ou contentDocument.
var x = document.getElementById("player_externo");
var y = (x.contentWindow || x.contentDocument);
if (y.document)y = y.document;
var download = y.getElementById('streamurl').innerHTML;
x.src = "https://openload.co/stream/" +download;
alert(download);

Comment: Não está modificando amigo, nem dando o ALERT.
Comment: Veja no console se dá algum erro.
Comment: Uncaught TypeError: Cannot read property 'innerHTML' of null at index.html:8
Comment: O elemento existe?
Answer:

Comment: Sua resposta pode ser melhorada adicionando informações fundamentais. Basta [edit] para adicionar mais detalhes, como citações ou documentação para que outras pessoas possam confirmar que sua resposta está correta. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).


Is there a case where something turned out to be division by zero?

Question: Is there any famous or controversial case in science where the proof was scrutinized and turned out to be an error like a division by zero?
Comment: I don't think Kempe's proof was repairable. Another approach worked. There have been published "proofs" that were wrong and subsequently retracted, but probably never for as simple an error as dividing by zero.
Comment: Interesting! Tks. I will edit the question to remove the word "grotesque". I realize now that it is not adequate
Comment: I loved your links. Pretty much solve my problem. If you post it as a solution, I will accept it! Tks very much
Comment: There's Kempe's "proof" of the four color theorem, which you can read about [here](http://web.stonehill.edu/compsci/lc/four-color/four-color.htm). But I really wouldn't call it a "grotesque error". Just a subtle mistake which completely invalidated the argument.
Comment: In that case, after removing the flawed section the remaining parts of the proof were able to prove that 4 colors suffice. I am looking for something that was completely rejected afterward
Comment: Why would division by zero automatically be an error.  Ask a [wheel](https://en.wikipedia.org/wiki/Wheel_theory).
Comment: https://mathoverflow.net/questions/94742/examples-of-interesting-false-proofs may be of some interest. Also, https://mathoverflow.net/questions/35468/widely-accepted-mathematical-results-that-were-later-shown-to-be-wrong
Comment: And maybe https://mathoverflow.net/questions/879/most-interesting-mathematics-mistake and https://mathoverflow.net/questions/27749/what-are-some-correct-results-discovered-with-incorrect-or-no-proofs and https://mathoverflow.net/questions/257628/theorems-demoted-back-to-conjectures
Comment: Your wish is my command.
Answer: Questions more-or-less closely related to the question here have been asked and answered at MathOverflow, e.g.,
https://mathoverflow.net/questions/94742/examples-of-interesting-false-proofs
https://mathoverflow.net/questions/35468/widely-accepted-mathematical-results-that-were-later-shown-to-be-wrong
https://mathoverflow.net/questions/879/most-interesting-mathematics-mistake
https://mathoverflow.net/questions/27749/what-are-some-correct-results-discovered-with-incorrect-or-no-proofs
https://mathoverflow.net/questions/257628/theorems-demoted-back-to-conjectures


Contextual view -> entity reference target ID

Question: I have the following situation:
I have 2 content types (session and preformance)
Performance has an entity reference to session
I want to create a view that shows me all performances for the session that is referenced by the performance i am looking at right now.
So this is a contextual view that filters on the nid of the performance, and has a relation to the session that is referenced by the viewed performance.
I cannot get the target_id of the session (from field_session on content type performance) to be passed in as a contextual filter.
I tried to use %node:field_session, but that gives me the label of the session, and not the target_id.
I also tried to change the display of the performance content type->field_session to 'entity id', but no luck.
All suggestions are very welcome.
Answer: You need to add the proper Context to the variant.

Then you complete the setup.

And lastly you select it in the panel settings for the Contextual view:
Comment: Dear J.Reynolds, Thanks so much for this very clear explanation!

I did not fully understand where in my view i can find the last stem to select the sessions contextual filter.
I can't seem to find it in my contextual filters config on the view.

Ps: Its a views content pane.
Comment: Dear J.Reynolds,

I figured it out, i think :-)
I now have it working as follows:

On my page variant i added the context as described and added the %session_node:nid in my argument input on pane config.

What i dont understand is that on the context screen of my page variant, when i look at %session_node, i also see fields that are not attached to that content type? (not a problem at this point, but i want to fully understand).

Thanks again!!!


Simple Annihilator Matrix Calculation in Econometrics

Question: While working on Davidson and McKinnon's Econometric Theory and Methods, I was encountered with

where $X = [X_1\  X_2]$, $M_X$ is the annihilator matrix for $X$, $M_1$ is for $X_1$ and so on.
In particular, I couldn't get the second equality.
How can we get $(M_1 - M_x) = M_1X_2(X_2^TM_1X_2)^{-1}X_2^TM_1$?
I tried but couldn't clearly understand how this result works. Can anybody help me? I would greatly appreciate it.
Answer: Write out the definitions: $M_X=I-X(X^TX)^{-1}X^T$, $M_1=I-X_1(X_1^TX_1)^{-1}X_1^T$. Now simplify the r.h.s of your equality, first writing out $(X_2^T M_1X_2)^{-1}=X_2^{-1}M_1^{-1}{X_2^{T}}^{-1}$. Can you finish the problem now?
Comment: I am sorry to keep bothering with this seemingly extremely simple stuff.
Can we assume $X_2, M_1$ are invertible? If we assume so, I get that the LHS is

$$
I - X_1(X_1^TX_1)^{-1}X_1^T - (I  - X(X^TX)^{-1}X^T) = -X_1(X_1^TX_1)^{-1}X_1^T +X(X^TX)^{-1}X^T
$$

while the RHS becomes

$$
M_1X_2(X_2^TM_1X_2)^{-1}X_2^TM_1 = M_1X_2X_2^{-1}M_1^{-1}{X_2^T}^{-1}X_2^TM_1 = M_1.
$$

How can I connect the two?
Comment: What happens if you simplify $M_1-M_X$ using $X:=[X_1,X_2]$?
Comment: I tried but can't figure out what you meant. I guess, for any $X$, we have $(M_1 - M_X)X = M_1X - M_XX = M_1X$. Is it from here that we get $M_1-M_X = M_1$?
Comment: I think you got it. since $X$ is arbitrary, you've shown $(M_1-M_X)X=M_1X$ for any $X$, which gives the desired result.
Comment: If it helps, let $g(X):=(M_1-M_X)X-M_1X$. You've shown that $g(X)=0$.


Generic term for Limits

Question: In calculus we have the concept of a Limit of a function (I mean the one described [there])1.
I consider limits to be something that helps us to consider a function from somewhat another perspective. For example if in a function the value is not defined at some point x, then it might be defined at the limit of that function.
So I am wondering if there is some generic term for entities like limits? Are there any other entities like that in other branches of maths? Can we probably say that limits are also functions, taking other functions as arguments?
Comment: This might be too advanced for you but still you can have a look. https://en.wikipedia.org/wiki/Limit_point
Comment: Nets generalise sequences: https://en.wikipedia.org/wiki/Net_(mathematics)
Comment: Functions (of various kinds) that take other functions as arguments are known as [functionals](https://en.wikipedia.org/wiki/Functional_(mathematics)) - although the usage of this term varies in different disciplines (see the linked article). You can dream up a functional which fills in the discontinuities of a partial function, but I don't think it is of any great interest: in "nature", functions tend to come defined with the "right" domain of definition.
Answer: Yes, you can think of limits as being functions which take in other functions of arguments. Here's an example: Let $H$ be the set of functions defined on $\mathbb{R}$ such that the limit of the function is defined at each point. Of course, continuous functions are contained in $H$. But also, functions which have 'holes' will be contained in $H$ as well.
One can then define a limit as being a function from $H$ to $\mathbb{R}$. Fix $a\in\mathbb{R}$, and define $L_a: H\to \mathbb{R}$ to be the map
$$
L_a[f(x)] = \lim_{x\to a}f(x).
$$
In this way, we are thinking of $L_a$ as being a function which acts on functions and evaluates them as real numbers. I would refer to this object as a functional, which (to my understanding) is just a fancy way of saying this function takes functions as its input and evaluates them as real numbers. Here are some other examples of mappings whose inputs are functions. Some of these will be familiar (assuming you have taken Calculus). I will be less specific with what the domains are from here. For now, just assume that the domain is chosen so that the mapping can actually exist.
\begin{align}
&(1). \text{The maximum operator: } M[f] = \max_{a \leq x \leq b}{f(x)}\\ \\
&(2). \text{The derivative operator: } D[f] =\left.\frac{d}{dx}[f(x)]\right|_{x=a} = f'(a).\\ \\
&(3). \text{The integral operator: } I[f] = \int_a^b f(x)dx.\\ \\
&(4). \text{ For a fixed function } g \text{, set } I_g[f] = I[fg] = \int_a^b f(x)g(x) dx.\\ \\
&(5). \text{ The Laplace Transform: } \mathcal{L}\{f\}(s) = \int_0^\infty f(t)e^{-st}dt. \\ \\
&(6). \text{ The Fourier Transform: } \mathcal{F}[f](s) = \int_{-\infty}^\infty f(x)e^{-2\pi i(s\cdot x)}dx.
\end{align}
So the short answer is, yes. This is just a short list of examples, and these are examples of ones that are relevant to what I do. I'm sure that many other branches of math will have other interesting examples.
Comment: The Expected Value also fits this list pretty well.
Comment: Can you please elaborate on why Expected Value is also functional? Expected value takes random value as an argument. Can we consider random value a function?
Comment: Since these can all be undefined, we should consider them _partial functions_ and not functions proper.  It is incorrect to call $L_a : H \to \mathbb R$ a function.
Comment: The mapping $L_a$ is well-defined on $H$, since $H$ is defined to be the set of functions for which limits exist at each point in $\mathbb{R}$. So by our choice of domain, $L_a$ is certainly a function.

Generic term for Limits


Oracle: Order By Alias, Invalid Identifier error

Question: I'm getting an odd error, that I think I might know the answer to, but still can't seem to fix.  It is saying that "LatestUpdatedDate" is an invalid identifier and I think it is because it runs the ORDER BY statement before it gets to the CASE statement, but that doesn't really make much sense with the way it is structured.  Have any ideas?
SELECT * FROM
(
  SELECT sym.*,
    (
    CASE WHEN shr_last_updt_dt >= trd_last_updt_dt
    THEN shr_last_updt_dt
    ELSE trd_last_updt_dt END
    ) AS LatestUpdatedDate,
    row_number() over ( ORDER BY LatestUpdatedDate DESC ) AS line_number
  FROM trdg_sym sym
  WHERE ((wkly_rpt_dt = :settleDate)) AND ((lower(rpt_type_cd)=lower(:reportType)))
)
WHERE line_number BETWEEN 1 AND 25 ORDER BY line_number

Answer: The aliases will given after generating result set so you can't use them in Windowing functions. You can do this:
SELECT * FROM
(
  SELECT sym.*,
    (
    CASE WHEN shr_last_updt_dt >= trd_last_updt_dt
    THEN shr_last_updt_dt
    ELSE trd_last_updt_dt END
    ) AS LatestUpdatedDate,
    row_number() over ( ORDER BY
     (
        CASE WHEN shr_last_updt_dt >= trd_last_updt_dt
        THEN shr_last_updt_dt
        ELSE trd_last_updt_dt END
     ) DESC ) AS line_number
  FROM trdg_sym sym
  WHERE ((wkly_rpt_dt = :settleDate)) AND ((lower(rpt_type_cd)=lower(:reportType)))
)
WHERE line_number BETWEEN 1 AND 25 ORDER BY line_number

or wrap your subquery to another
SELECT * FROM
(
  SELECT *,
    row_number() over ( ORDER BY LatestUpdatedDate DESC ) AS line_number
  FROM
  (
     SELECT sym.*,
       (
          CASE WHEN shr_last_updt_dt >= trd_last_updt_dt
          THEN shr_last_updt_dt
          ELSE trd_last_updt_dt END
        ) AS LatestUpdatedDate
     FROM trdg_sym sym
     WHERE ((wkly_rpt_dt = :settleDate)) AND ((lower(rpt_type_cd)=lower(:reportType)))
   )
)
WHERE line_number BETWEEN 1 AND 25 ORDER BY line_number

P.S. I don't sure for oacle syntax, but should you give aliases to subquery?
Comment: Thanks.  You confirmed what I thought might be the case.  I have a .NET application which is constructing the query and so re-doing the code would take a lot of work.  I was able to get it working by following the first method you outlined though so I'll mark this as the right answer.  Thanks!!
Comment: Imagine, you have two sub-queries with the same column names and you want to join them. How you would refer to the columns?
Comment: Hey, I thought I would also give the second query a try, but it didn't work.  Can you double check to make sure it works on your end?  I'm getting a `from keyword not found where expected` error.


nginx throws many errors

Question: I have a fresh installation of a nginx server running nextcloud with letsencrypt. I thought I configured everything correctly, but now I thought I could check my logs and voila I got a bunch of errors, which I can´t figure out how to fix :(
I already tried to modify my XYZ.com.conf, but it didn´t work.
Any help is appreciated.
2018/05/04 19:22:09 [error] 4243#4243: ocsp.int-x3.letsencrypt.org could not be resolved (110: Operation timed out) while requesting certificate status, responder: ocsp.int-x3.letsencrypt.org, certificate: "/etc/letsencrypt/live/XYZ.com/fullchain.pem"
2018/05/04 19:22:40 [error] 4244#4244: *87 open() "/etc/nginx/html/status.php" failed (2: No such file or directory), client: XXX.XXX.XXX.XXX, server: XYZ.com, request: "GET /status.php HTTP/1.1", host: "XYZ.com"
2018/05/04 19:22:41 [error] 4244#4244: *87 open() "/etc/nginx/html/owncloud/status.php" failed (2: No such file or directory), client: XXX.XXX.XXX.XXX, server: XYZ.com, request: "GET /owncloud/status.php HTTP/1.1", host: "XYZ.com"
2018/05/04 19:23:05 [error] 4243#4243: *94 open() "/etc/nginx/html/status.php" failed (2: No such file or directory), client: XXX.XXX.XXX.XXX, server: XYZ.com, request: "GET /status.php HTTP/1.1", host: "XYZ.com"
2018/05/04 19:23:05 [error] 4243#4243: *94 open() "/etc/nginx/html/owncloud/status.php" failed (2: No such file or directory), client: XXX.XXX.XXX.XXX, server: XYZ.com, request: "GET /owncloud/status.php HTTP/1.1", host: "XYZ.com"
2018/05/04 19:23:36 [error] 4243#4243: *101 open() "/etc/nginx/html/status.php" failed (2: No such file or directory), client: XXX.XXX.XXX.XXX, server: XYZ.com, request: "GET /status.php HTTP/1.1", host: "XYZ.com"
2018/05/04 19:23:36 [error] 4243#4243: *101 open() "/etc/nginx/html/owncloud/status.php" failed (2: No such file or directory), client: XXX.XXX.XXX.XXX, server: XYZ.com, request: "GET /owncloud/status.php HTTP/1.1", host: "XYZ.com"
2018/05/04 19:24:08 [error] 4243#4243: *108 open() "/etc/nginx/html/status.php" failed (2: No such file or directory), client: XXX.XXX.XXX.XXX, server: XYZ.com, request: "GET /status.php HTTP/1.1", host: "XYZ.com"
2018/05/04 19:24:08 [error] 4243#4243: *108 open() "/etc/nginx/html/owncloud/status.php" failed (2: No such file or directory), client: XXX.XXX.XXX.XXX, server: XYZ.com, request: "GET /owncloud/status.php HTTP/1.1", host: "XYZ.com"
2018/05/04 19:24:40 [error] 4244#4244: *119 open() "/etc/nginx/html/status.php" failed (2: No such file or directory), client: XXX.XXX.XXX.XXX, server: XYZ.com, request: "GET /status.php HTTP/1.1", host: "XYZ.com"
2018/05/04 19:24:40 [error] 4244#4244: *119 open() "/etc/nginx/html/owncloud/status.php" failed (2: No such file or directory), client: XXX.XXX.XXX.XXX, server: XYZ.com, request: "GET /owncloud/status.php HTTP/1.1", host: "XYZ.com"
2018/05/04 19:25:12 [error] 4244#4244: *126 open() "/etc/nginx/html/status.php" failed (2: No such file or directory), client: XXX.XXX.XXX.XXX, server: XYZ.com, request: "GET /status.php HTTP/1.1", host: "XYZ.com"
2018/05/04 19:25:12 [error] 4244#4244: *126 open() "/etc/nginx/html/owncloud/status.php" failed (2: No such file or directory), client: XXX.XXX.XXX.XXX, server: XYZ.com, request: "GET /owncloud/status.php HTTP/1.1", host: "XYZ.com"
2018/05/04 19:25:44 [error] 4243#4243: *136 open() "/etc/nginx/html/status.php" failed (2: No such file or directory), client: XXX.XXX.XXX.XXX, server: XYZ.com, request: "GET /status.php HTTP/1.1", host: "XYZ.com"
2018/05/04 19:25:45 [error] 4243#4243: *136 open() "/etc/nginx/html/owncloud/status.php" failed (2: No such file or directory), client: XXX.XXX.XXX.XXX, server: XYZ.com, request: "GET /owncloud/status.php HTTP/1.1", host: "XYZ.com"
2018/05/04 19:26:16 [error] 4243#4243: *143 open() "/etc/nginx/html/status.php" failed (2: No such file or directory), client: XXX.XXX.XXX.XXX, server: XYZ.com, request: "GET /status.php HTTP/1.1", host: "XYZ.com"
2018/05/04 19:26:16 [error] 4243#4243: *143 open() "/etc/nginx/html/owncloud/status.php" failed (2: No such file or directory), client: XXX.XXX.XXX.XXX, server: XYZ.com, request: "GET /owncloud/status.php HTTP/1.1", host: "XYZ.com"
2018/05/04 19:26:48 [error] 4243#4243: *150 open() "/etc/nginx/html/status.php" failed (2: No such file or directory), client: XXX.XXX.XXX.XXX, server: XYZ.com, request: "GET /status.php HTTP/1.1", host: "XYZ.com"
2018/05/04 19:26:48 [error] 4243#4243: *150 open() "/etc/nginx/html/owncloud/status.php" failed (2: No such file or directory), client: XXX.XXX.XXX.XXX, server: XYZ.com, request: "GET /owncloud/status.php HTTP/1.1", host: "XYZ.com"
2018/05/04 19:27:20 [error] 4243#4243: *154 open() "/etc/nginx/html/status.php" failed (2: No such file or directory), client: XXX.XXX.XXX.XXX, server: XYZ.com, request: "GET /status.php HTTP/1.1", host: "XYZ.com"
2018/05/04 19:27:20 [error] 4243#4243: *154 open() "/etc/nginx/html/owncloud/status.php" failed (2: No such file or directory), client: XXX.XXX.XXX.XXX, server: XYZ.com, request: "GET /owncloud/status.php HTTP/1.1", host: "XYZ.com"
2018/05/04 19:27:52 [error] 4243#4243: *158 open() "/etc/nginx/html/status.php" failed (2: No such file or directory), client: XXX.XXX.XXX.XXX, server: XYZ.com, request: "GET /status.php HTTP/1.1", host: "XYZ.com"
2018/05/04 19:27:52 [error] 4243#4243: *158 open() "/etc/nginx/html/owncloud/status.php" failed (2: No such file or directory), client: XXX.XXX.XXX.XXX, server: XYZ.com, request: "GET /owncloud/status.php HTTP/1.1", host: "XYZ.com"
2018/05/04 19:28:24 [error] 4243#4243: *162 open() "/etc/nginx/html/status.php" failed (2: No such file or directory), client: XXX.XXX.XXX.XXX, server: XYZ.com, request: "GET /status.php HTTP/1.1", host: "XYZ.com"
2018/05/04 19:28:24 [error] 4243#4243: *162 open() "/etc/nginx/html/owncloud/status.php" failed (2: No such file or directory), client: XXX.XXX.XXX.XXX, server: XYZ.com, request: "GET /owncloud/status.php HTTP/1.1", host: "XYZ.com"

EDIT:
XYZ.com.conf
server {
    listen 80 default_server;
    server_name XYZ.com www.XYZ.com;

    root /var/www;

    location ^~ /.well-known/acme-challenge {
        proxy_pass http://127.0.0.1:81;
        proxy_redirect off;
    }
    location / {
        # Enforce HTTPS
        # Use this if you always want to redirect to the DynDNS address (no local access).
        return 301 https://$server_name$request_uri;

        # Use this if you also want to access the server by local IP:
        #return 301 https://$server_addr$request_uri;
    }
}

server {
    listen 443 ssl http2;
    server_name XYZ.com www.XYZ.com;

    #
    # Configure SSL
    #
    ssl on;

    # Certificates used
    ssl_certificate /etc/letsencrypt/live/XYZ.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/XYZ.com/privkey.pem;

    # Not using TLSv1 will break:
    #   Android <= 4.4.40
    #   IE <= 10
    #   IE mobile <=10
    # Removing TLSv1.1 breaks nothing else!
    ssl_protocols TLSv1.2;

    # Using the recommended cipher suite from: https://wiki.mozilla.org/Security/Server_Side_TLS
    ssl_ciphers 'ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!3DES:!MD5:!PSK';

    # Diffie-Hellman parameter for DHE ciphersuites, recommended 2048 bits
    ssl_dhparam /etc/nginx/ssl/dhparams.pem;

    # Specifies a curve for ECDHE ciphers.
    # High security, but will not work with Chrome:
    #ssl_ecdh_curve secp521r1;
    # Works with Windows (Mobile), but not with Android (DavDroid):
    #ssl_ecdh_curve secp384r1;
    # Works with Android (DavDroid):
    ssl_ecdh_curve prime256v1;

    # Server should determine the ciphers, not the client
    ssl_prefer_server_ciphers on;

    # OCSP Stapling
    # fetch OCSP records from URL in ssl_certificate and cache them
    ssl_stapling on;
    ssl_stapling_verify on;
    ssl_trusted_certificate /etc/letsencrypt/live/XYZ.com/fullchain.pem;
    resolver XYZ.com;

    # SSL session handling
    ssl_session_timeout 24h;
    ssl_session_cache shared:SSL:50m;
    ssl_session_tickets off;

    #
    # Add headers to serve security related headers
    #
    # HSTS (ngx_http_headers_module is required)
    # In order to be recoginzed by SSL test, there must be an index.hmtl in the server's root
    add_header Strict-Transport-Security "max-age=63072000; includeSubdomains" always;
    add_header X-Content-Type-Options "nosniff" always;
    # Usually this should be "DENY", but when hosting sites using frames, it has to be "SAMEORIGIN"
    add_header Referrer-Policy "same-origin" always;
    add_header X-XSS-Protection "1; mode=block" always;
    add_header X-Robots-Tag none;
    add_header X-Download-Options noopen;
    add_header X-Permitted-Cross-Domain-Policies none;

    location = / {
        # Disable access to the web root, the Nextcloud subdir should be used instead.
        #deny all;

        # If you want to be able to access the cloud using the webroot only, use the following command instead:
        rewrite ^ /nextcloud;
    }

    #
    # Nextcloud
    #
    location = /favicon.ico {
        log_not_found off;
    }

    location ^~ /nextcloud {
        # Set max. size of a request (important for uploads to Nextcloud)
        client_max_body_size 10G;
        # Besides the timeout values have to be raised in nginx' Nextcloud config, these values have to be raised for the proxy as well
        proxy_connect_timeout 3600;
        proxy_send_timeout 3600;
        proxy_read_timeout 3600;
        send_timeout 3600;
        proxy_buffering off;
        proxy_request_buffering off;
        proxy_max_temp_file_size 1024m;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_pass http://127.0.0.1:82;
        proxy_redirect off;
    }
}

XYZ.com_letsencrypt.conf
server {
    listen 127.0.0.1:81;
    server_name 127.0.0.1;

    location ^~ /.well-known/acme-challenge {
        default_type text/plain;
        root /var/www/letsencrypt;
    }
}

XYZ.com_nextcloud.conf
upstream php-handler {
    server unix:/run/php/php7.0-fpm.sock;
}

server {
    listen 82;
    server_name 127.0.0.1;

    # Add headers to serve security related headers
    # Use 'proxy_set_header' (not 'add_header') as the headers have to be passed through a proxy.
    proxy_set_header Strict-Transport-Security "max-age=15768000; includeSubDomains; always;";
    proxy_set_header X-Content-Type-Options "nosniff; always;";
    proxy_set_header X-XSS-Protection "1; mode=block; always;";
    proxy_set_header X-Robots-Tag none;
    proxy_set_header X-Download-Options noopen;
    proxy_set_header X-Permitted-Cross-Domain-Policies none;

    # Path to the root of your installation
    root /var/www/;

    location = /robots.txt {
        allow all;
        log_not_found off;
        access_log off;
    }

    # The following 2 rules are only needed for the user_webfinger app.
    # Uncomment it if you're planning to use this app.
    #rewrite ^/.well-known/host-meta /nextcloud/public.php?service=host-meta last;
    #rewrite ^/.well-known/host-meta.json /nextcloud/public.php?service=host-meta-json last;

    location = /.well-known/carddav {
        return 301 $scheme://$host/nextcloud/remote.php/dav;
    }

    location = /.well-known/caldav {
        return 301 $scheme://$host/nextcloud/remote.php/dav;
    }

    location /.well-known/acme-challenge { }

    location ^~ /nextcloud {
        # set max upload size
        client_max_body_size 10G;
        fastcgi_buffers 64 4K;

        # Enable gzip but do not remove ETag headers
        gzip on;
        gzip_vary on;
        gzip_comp_level 4;
        gzip_min_length 256;
        gzip_proxied expired no-cache no-store private no_last_modified no_etag auth;
        gzip_types application/atom+xml application/javascript application/json application/ld+json application/manifest+json application/rss+xml application/vnd.geo+json application/vnd.ms-fontobject application/x-font-ttf application/x-web-app-manifest+json application/xhtml+xml application/xml font/opentype image/bmp image/svg+xml image/x-icon text/cache-manifest text/css text/plain text/vcard text/vnd.rim.location.xloc text/vtt text/x-component text/x-cross-domain-policy;

        # Uncomment if your server is build with the ngx_pagespeed module
        # This module is currently not supported.
        #pagespeed off;

        location /nextcloud {
            rewrite ^ /nextcloud/index.php$uri;
        }

        location ~ ^/nextcloud/(?:build|tests|config|lib|3rdparty|templates|data)/ {
            deny all;
        }

        location ~ ^/nextcloud/(?:\.|autotest|occ|issue|indie|db_|console) {
            deny all;
        }

        location ~ ^/nextcloud/(?:index|remote|public|cron|core/ajax/update|status|ocs/v[12]|updater/.+|ocs-provider/.+|core/templates/40[34])\.php(?:$|/) {
            include fastcgi_params;
            fastcgi_split_path_info ^(.+\.php)(/.+)$;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            fastcgi_param PATH_INFO $fastcgi_path_info;
            #Avoid sending the security headers twice
            fastcgi_param modHeadersAvailable true;
            fastcgi_param front_controller_active true;
            fastcgi_pass php-handler;
            fastcgi_intercept_errors on;

            # Raise timeout values.
            # This is especially important when the Nextcloud setup runs into timeouts (504 gateway errors)
            fastcgi_read_timeout 600;
            fastcgi_send_timeout 600;
            fastcgi_connect_timeout 600;
            fastcgi_request_buffering off;

            # Pass PHP variables directly to PHP.
            # This is usually done in the php.ini. For more flexibility, these variables are configured in the nginx config.
        # All the PHP parameters have to be set in one fastcgi_param. When using more 'fastcgi_param PHP_VALUE' directives, the last one will override all the others.
            fastcgi_param PHP_VALUE "open_basedir=/var/www:/tmp/:/mnt/raid/data:/dev/urandom:/proc/meminfo
                upload_max_filesize = 10G
                post_max_size = 10G
                max_execution_time = 3600
                output_buffering = off";

            # Make sure that the real IP of the remote host is passed to PHP.
            fastcgi_param REMOTE_ADDR $http_x_real_ip;
        }

        location ~ ^/nextloud/(?:updater|ocs-provider)(?:$|/) {
            try_files $uri/ =404;
            index index.php;
        }

        # Adding the cache control header for js and css files
        # Make sure it is BELOW the PHP block
        location ~* \.(?:css|js)$ {
            try_files $uri /nextcloud/index.php$uri$is_args$args;
            proxy_set_header Cache-Control "public, max-age=7200";
            # Add headers to serve security related headers
            # Again use 'proxy_set_header' (not 'add_header') as the headers have to be passed through a proxy.
            proxy_set_header Strict-Transport-Security "max-age=15768000; includeSubDomains; preload;";
            proxy_set_header X-Content-Type-Options nosniff;
            #proxy_set_header X-Frame-Options "SAMEORIGIN";
            proxy_set_header X-XSS-Protection "1; mode=block";
            proxy_set_header X-Robots-Tag none;
            proxy_set_header X-Download-Options noopen;
            proxy_set_header X-Permitted-Cross-Domain-Policies none;
            # Optional: Don't log access to assets
            access_log off;
        }

        location ~* \.(?:svg|gif|png|html|ttf|woff|ico|jpg|jpeg)$ {
            try_files $uri /nextcloud/index.php$uri$is_args$args;
            # Optional: Don't log access to other assets
            access_log off;
        }
    }
}

Comment: Did you follow the official instructions for Nextcloud+Nginx (https://docs.nextcloud.com/server/12/admin_manual/installation/nginx.html)? Please show us your corresponding vhost config.

Please make sure that the path to Nextcloud matches the path in your configuration.
Comment: More information needed. Nginx configuration, information about what the application is doing (is it working?), PHP error logs, and anything else you can think of that might provide information.
Comment: Sorry, I added my all my nginx conf files
Answer: Your server block is missing a root directive. Thus the bizarre default /etc/nginx/html is used. Add the missing root directive.
Comment: what do you mean I have, configured a root directive, haven´t I? (root /var/www/;)
Comment: Only in some of your `server` blocks. The second one shown in your post is missing one, and that is where the problem is coming from.
Comment: solved the problem, THX!

nginx throws many errors


distribution of a random variable that depends on another random variable

Question: Let X be a Poisson random variable, $X \thicksim Po(\lambda Y) $ where $Y \thicksim Exp(\alpha)$.
Now I would like to compute the distribution of X.
If I conditionate on $Y=c$, I find $P(X=0|Y=c)=e^{\lambda c}$.
But, in general, how can I compute $P(X=0)?$ I think that I have to take the mean, and so $P(X=0)=E(e^{\lambda y})=\int_{0}^{\infty}e^{\lambda z}\alpha e^{- \alpha z}dz$. But I don't understand why, how can I show the previous equality and how I have to look at this problem.(the variable that I'm studying is a function of random variable or what else..)
Comment: Actually it should be

$X | Y \thicksim Po(\lambda Y)$

and you're looking for the unconditional distribution of X.
Answer: Given $Y$, $X$'s distribution is known. The law of total probiability gives us for $n \in \mathbf N$
\begin{align*}
  \def\P{\mathbf P}\P(X = n) &= \int_0^\infty \P(X = n \mid Y= y)f_Y(y)\, dy
\\
   &= \int_0^\infty \frac{(\lambda y)^n}{n!}\exp(-\lambda y)\alpha\exp(-\alpha y)\, dy\\
   &= \frac{\lambda^n \alpha}{n!}\int_0^\infty y^n \exp\bigl(-(\alpha+\lambda)y\bigr)\, dy
\end{align*}
Now, by induction
$$ \int_0^\infty y^n \exp(-y)\, dy = n! $$
Hence,
$$ \int_0^\infty y^n \exp\bigl(-(\alpha + \lambda)y\bigr)\, dy
 = \frac 1{(\alpha + \lambda)^n} \int_0^\infty z^n \exp(-z)\, \frac{dz}{(\alpha + \lambda)} = \frac{n!}{(\alpha + \lambda)^{n+1}} $$
This gives
$$ \P(X = n) = \frac{\lambda^n \alpha}{(\alpha + \lambda)^{n+1}} = \frac \alpha\lambda \left(\frac{\lambda}{\alpha + \lambda}\right)^{n+1} = \frac{\alpha}{\alpha + \lambda} \cdot \left(1  -\frac{\alpha}{\alpha + \lambda}\right)^{n}  $$
That is, $X$ is geometrically distributed with parameter $\frac{\alpha}{\alpha + \lambda}$.

Addendum: One can see it as follows. $X$ is not a function of $Y$, $X$ is a random variable of its own. But: The information we are given about $X$ is conditioned on $Y$, we have observed $X$ only for known $Y$ values.
Comment: thank you for your attention and for your unswear. But I would like to know, as I wrote in the question, how I have to see this problem...is, in your opinion, a random variable that depend on another random variable? Is a function of random variable? In general, and not only in this specific case, how I have to treat this?
Comment: @andreasvr I see. Added something.


How can I calculate cut-off points from a normal distribution?

Question: I'm trying to calculate the upper percentage points for the 0.99 percentile for samples drawn from a normal distribution, with a sample size of 500. How can I calculate the expected values for skewness, kurtosis, studentized range, which would be expected for a drawing of 500 values?
Comment: When you say "calculate" do you want mathematical formulae, or a way of getting a numerical approximation? (And is this homework?)
Comment: http://en.wikipedia.org/wiki/Student_t
Comment: no this is no homework :P. yes a formula would be nice, I'm somehow unsure how to integrate the sample size here. The objective is to know the approximative numerical value which can be expected, when 500 values are drawn..
Comment: This question appears to contradict itself: are you drawing samples from a normal distribution or a Student t distribution?  Which one?  (PS: You're right: this site is a better choice for the question than the *Mathematica* site.  Once you get your question straightened out here, if you need specific help with MMA in coding a solution you will know precisely what to ask over there as a follow-up.)
Comment: I could do an Confidence interval but i'm somehow missing the standard deviation which would be needed to derive theorethically? I assume it to be close to zero for 500 values for the skewness, respectively to 3 for the kurtosis..?
Comment: OK, you're drawing 500 values (presumably independently) from a Student t distribution.  But what, exactly, are you trying to estimate?  You mention "upper percentage points" and a 99th percentile.  These have nothing to do with expected values of skewness, kurtosis, or studentized range mentioned in the second sentence.  These requests just don't make sense: right now, they're just an unrelated jumble of statistical terms.  Could you perhaps identify *one single thing* you are attempting to accomplish and edit the question to focus on that?
Comment: yes unfortunately that's the problem I have too. It is from a text where there is an empirical distribution for 250 values, where skewness is 0.60, compared to the theoretical one. then they say: "0.6 for skewness exceed the value of the 0.99 fractile of the repsective distribution expexted under normality." With a following table: Upper percentage points: samples of 250 drawn from a normal population: 0.99 --> skewness 0.129. I now try to compute these 0.129..? resp. adapt to 500 values..
Comment: My guess is they show the (simulated) skewness and kurtosis of the distribution of the sample 95th and 99th percentiles (with normal data, n=250).  This is (depending on your sample quantile estimator) the same as the 248th order statistic.  This paper http://www.sciencedirect.com/science/article/pii/S0167715207002143 gives an analytic formula for the k-th moment of the r-th order statistic of a sample of normal data of size n, which technically answers your question (I think).  But it looks complex (Lauricella function of type A?); maybe better off simulating.
Comment: thx a lot i will try to follow the paper. what we tried to do underneath is simulate those percentiles but ended up with much higher values for the percentiles..
Answer: You can always simulate this kind of thing first, e.g. in R
<code>set.seed(1)
samat <- matrix(rnorm(1000000), ncol=500)
means <- rowMeans(samat)
varis <- rowMeans((samat-means)^2)
skews <- rowMeans((samat-means)^3) / varis^(3/2)
kurts <- rowMeans((samat-means)^4) / varis^2  -  3
</code>
and find the quantiles
<code>> quantile(means, probs=c(0.01, 0.5, 0.99) )
          1%          50%          99%
-0.096977914 -0.001302285  0.109797211
>
> quantile(varis, probs=c(0.01, 0.5, 0.99) )
       1%       50%       99%
0.8494985 0.9970259 1.1495887
>
> quantile(skews, probs=c(0.01, 0.5, 0.99) )
          1%          50%          99%
-0.257665499 -0.002052328  0.260948808
>
> quantile(kurts, probs=c(0.01, 0.5, 0.99) )
        1%        50%        99%
-0.4286435 -0.0320487  0.5399296
</code>
and while it is clear that you can probably only treat the first couple of decimal places as useful, it also shows that skewness of 0.60 would be extremely high.  It also suggests that the "skewness 0.129" you quote is rather low for the 99th percentile; I make it nearer 0.35 or 0.36 for a sample of 250 and about 0.26 for a sample of 500.


sdl linking prolem ubuntu

Question: I have Ubuntu 14 LTs I'm trying to compile a simple code using SDL library.but i get the answer:
game.c: In function 'main':
game.c:11:3: warning: format '%s' expects argument of type 'char'but argument 3 has type 'int' [-Wformat=]
fprintf (stderr, "could not initialize SDL: %s\n",  SDL_Get_Error());
^
/tmp/ccMGHXqV.o: In function `main':
game.c:(.text+0xa): undefined reference to `SDL_Get_Error'
collect2: error: ld returned 1 exit status

tis is my program code compiled with:"gcc  game.c -o game  sdl-config --cflags  `sdl-config --libs"
#include <SDL/SDL.h>
#include<stdio.h>
#include<stdlib.h>

/* my firat game program */

int main()
 {

if ((SDL_INIT_VIDEO|SDL_INIT_TIMER|SDL_INIT_EVENTTHREAD)!=0)
fprintf (stderr, "could not initialize SDL: %s\n",  SDL_Get_Error());
printf ("SDL INIZIALIZED\n");
SDL_Surface* screen;

screen = SDL_SetVideoMode(640, 480, 0,  SDL_ANYFORMAT|     SDL_FULLSCREEN);
SDL_WM_SetCaption("MyFirstGame", NULL);

atexit (SDL_Quit);
return 0;
  }``

`
Answer: The correct function name is SDL_GetError(), not SDL_Get_Error(). See http://wiki.libsdl.org/SDL_GetError

sdl linking prolem ubuntu


Add a local task tab for a content type only

Question: Someone can help me ? I want to display a tab only when the content type is 'test'.
Here's my files.
mymodule.routing.yml :
mymodule.check_test:
  path: '/checktest/{node}'
  defaults:
    _controller: '\Drupal\mymodule\Controller\CheckTestController::content'
  requirements:
    _access: 'TRUE'

mymodule.links.task.yml :
mymodule.check_test:
    title: Display tests
    route_name: mymodule.check_test
    base_route: entity.node.canonical

My tab is displayed for every content, i don't know how to filter with my content type...
Thanks :).
Edit :
From mradcliffe's answer,
I've add a mymodule.services.yml :
services:
  access_check.test:
    class: Drupal\mymodule\Access\MyModuleTestAccess
    tags:
      - { name: access_check, applies_to: _access_test }

and a MyModuleTestAccess class with :
public function access(NodeInterface $node)
{
    return AccessResult::allowedIf($node->bundle() === 'test');
}

My edited mymodule.routing.yml :
mymodule.check_test:
  path: '/checktest/{node}'
  defaults:
    _controller: '\Drupal\mymodule\Controller\CheckTestController::content'
  requirements:
    _access_test: ''

Comment: `_access_test: ' ' ` must now be `_access_test: 'true' `.
Comment: It's probably good practice to namespace the service declaration: my_module.access_check.test
Answer: You can use an access check to hide a route.
If the user that will view the tab has the same permission for adding a node of a given type, then simply adding _node_add_access: 'node:MYNODETYPEHERE' would be sufficient. However this is probably not the case.
Instead you can add _custom_access to the route requirements as a method on the controller class.
mymodule.check_test:
  path: '/checktest/{node}'
  defaults:
    _controller: '\Drupal\mymodule\Controller\CheckTestController::content'
  requirements:
    _custom_access: '\Drupal\mymodule\Controller\CheckTestController::checkAccess'
    # It is highly-recommended to always use the default entity access check for
    # an Entity as pointed out by @pwolanin below. Not doing so may lead to
    # undesirable results and potential information disclosure or access bypass
    # vulnerability.
    _entity_access: node.view

And then a corresponding method on the controller (see Access checking on routes for more details). Something like this might work for you (untested).
public function checkAccess($node) {
  return AccessResult::allowedif($node->bundle() === 'my_node_type');
}

Update 2019.08.30: Incorporated @pwolanin's answer into this one in case anyone misses and doesn't read its importance.
Comment: It would be more helpful if you explain what "it" was and what did "not work" specifically so that we can work together to understand and improve. Thank you.
Comment: it does not work actually
Comment: This worked for.
Answer: I'm using Drupal 8.1.2 and both the accepted answer and the answer provided in the edit to the question did not actually work for me and they gave this error:
RuntimeException: Callable "Drupal\mymodule\Controller\CheckTestController::checkAccess" requires a value for the "$node" argument. in Drupal\Component\Utility\ArgumentsResolver->handleUnresolvedArgument() (line 142 of /var/www/html/core/lib/Drupal/Component/Utility/ArgumentsResolver.php).

the problem is that with the entity.node.canonical route, the $node variable seems to not actually link to the node itself, but stays as the ID.
The code that worked for me for the checkAccess method in the controller is:
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Controller\ControllerBase;
use Drupal\node\Entity\Node;

class CheckTestController extends ControllerBase {

    ...

    public function checkAccess($node) {
        $actualNode = Node::load($node);
        return AccessResult::allowedIf($actualNode->bundle() === 'test');
    }
}

Comment: It's maybe because your "$node" var is an interger and not a node entity.
Check your routing and add : "parameters: node: type: 'entity:node'" to explain that your path contain a entity : "path: '/node/{node}/xxxx"
Answer: Also - the answer above is incomplete since it skips a check on access to the node itself.  This is possibly a recipe for an access bypass vulnerability.
I'd think you'd want a route more like:
mymodule.check_test:
  path: '/checktest/{node}'
  defaults:
    _controller: '\Drupal\mymodule\Controller\CheckTestController::content'
  requirements:
    _custom_access: '\Drupal\mymodule\Controller\CheckTestController::checkAcess'
    _entity_access: node.view

Answer: Yes, it's unfortunate that this is the normal/best way to handle this.  We did't think hard enough about this kind of use case when writing the local task code originally.
An alternative (which I have been considering recently) is to use hook_menu_local_tasks_alter() whose purpose is to "Alter local tasks displayed on the page before they are rendered. The downside is that someone could still visit the path and get an unexpected result.
This is a bit sub-optimal since it's out of the OO flow, and you'd have to worry about updating the cache metadata correctly.
Answer: The answer from @mradcliffe is largely correct... if you don't want to load the node then in your mymodule.routing.yml user the options to bring in the node object:
mymodule.check_test:
  path: '/checktest/{node}'
  requirements:
    _custom_access: '\Drupal\mymodule\Controller\CheckTestController::checkAccess'
    _entity_access: 'node.view'
  options:
    parameters:
      node:
        type: 'entity:node'

And then in your controller:
namespace Drupal\mymodule\Controller;

use Drupal\Core\Routing\Access\AccessInterface;
use Drupal\node\NodeInterface;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Access\AccessResult;

/**
 * Checks access for displaying time tab.
*/
class CheckAccess extends ControllerBase {

public function checkAccess(NodeInterface $node) {
return AccessResult::allowedif($node->bundle() === 'my_node_type');
}
}
This will bring in the node object properly so you don't have to load it in your access method and avoid the error mentioned above if you try to call bundle() on the node id.


GWT dispose modal dialog by clicking outside of it

Question: I have a HSV color selector on a dialog and I would like to provide user several ways to dispose the dialog. I have normal buttons and such but I would also like to make it disappear when user clicks outside of it.
Is there a way to do this in GWT?
Answer: You can enable PopupPanel auto hide. When enabled, the popup will be automatically hidden when the user clicks outside of it.
Comment: Ah, simple! I feel bit embarrassed not seeing that myself.


$W$ white balls, $B$ black balls, adding $K$ of the resultant color each iteration

Question: The problem is stated as follows. We have a box with $W$ white balls and $B$ black ones. Repeat $N$ times: each iteration a ball is taken out (uniformly), and put back along with $K$ (constant) more balls of the same color.
The questions:

Prove that the probability to take out a black ball on the $i$-th iteration is independent of $i$. This is intuitive but I was unable to prove it (tried using induction).
Define the sample space and probability function for the problem of repeating the above iteration $N$ times. The sample space is clear to me (binary vectors of length $N$) but the probability function is hard to define in a closed form.

Moreover, I'm surprised that question 2 did not come before question 1 because to solve 1, we must understand the probability space. Or is it a common approach in probability to define how we want the space to "act" and only then define the space along with the distribution function?
EDIT: Solved
Comment: *Express formally* what?
Comment: Maybe you should write up your solution more neatly as an answer, and accept it?
Comment: What have you worked out for (1)? For the very first iteration, can you calculate the probability of drawing a white ball, of drawing a black ball, and the probability of drawing a black or white ball on the next iteration?
Comment: Yes I made sure probabilities in first and seconds iteration are the same but I'm having trouble generalizing it. Is digging into the sum of sums of sums.... formula the correct way to do this?
Comment: yes, 2) is ambiguous
Comment: sorry, check out the edit
Comment: But, what is the "problem" exactly? What is the experiment? Picking a ball at the last iteration? The sequence of colors picked throughout the process?
Comment: Could you say a few words about why you _intuitively_ feel that the probability of drawing a black ball on the $i$-th draw does not depend on $i$?  David Mitra's answer shows (by induction) why this is so, and you probably came up with the same result since you state that "I made sure probabilities in first and seconds iteration are the same" (but failed in extending it). But I am interested why you felt _intuitively_ that the result is true, perhaps even before you showed that the probability is the same on the first and second draws.
Comment: @Leo You are correct, my previous answer was off. I have deleted it. Very sorry.
Comment: @Dilip Sarwate - my intuition tells me that there are just as many cases where it'll be hard to pick a black ball on j-th iteration(because we've added lots of whites) as those where it'll be easier by the time we reach iteration j. So eventually there's some sort of symmetry or balance that leaves us a "clean slate" when we pick out the j-th ball. This is of course intuition alone.
Comment: @David Mitra - thanks for the effort though.
Comment: See also http://math.stackexchange.com/questions/64280/polya-urn-scheme-question/64513#64513
Answer: There are the B and W when the game begins.
For $i = 0,1,\ldots,N$,
define the  random variables
$$B_i ={\rm\ number\ of\ black\ balls\ on\ iteration\ } i$$ and
$$ X_i =\cases{1,& if a  black  ball was drawn on iteration $i$ \cr  0,& otherwise}$$
Our
induction assumption is: $P[X_i = 1] = {B\over W+B}$.
We compute $$ P[X_{i+1} = 1]  =
\sum_{ {\rm admiss.\ } b}  P[B_i = b] \cdot{ b\over i*K+W+B }  ={ E(B_i) \over i*K+W+B}.$$
Here's the magic: $B_i = B +\sum\limits_{j=0}^{i-1}  {K*X_j}$.
Now
$E(X_j) = P[X_j = 1] ={ B\over W+B}$ by the  induction assumption.
So:$$ E(B_i) = E(B)+\sum\limits_{j=0}^{i-1}  {K*E(X_j)=}B + i K{B\over W+B}.$$
Going back to $ P[X_{i+1} = 1]$:
$$\eqalign{
P[X_{i+1} = 1] &={ E(B_i) \over i*K+W+B}\cr & = [ B + i*K*B/(W+B) ] / i*K+W+B \cr &={ B\over B+W}.
}
$$
Having wasted so much time trying to prove this looking at the tedious "tree" of results, I now fully appreciate the elegance brought by linearity of expectation (even when the random variables are dependent)
Comment: Very nice! By the way, when I "TeXified" your post, I added an extra detail when finding $E(B_i)$. I felt it was important to emphasize that linearity of taking expectations was being used.
Comment: @David Mitra - Thanks, it is imporant to mention.
Answer: Here is an informal argument by induction, with j a positive integer.
Inductive statement(j):
<code>  For all w, b, k, (positive integers), the chance of
  drawing a black ball on the j-th draw starting from a
  box with b black balls and w white balls is b/(b + w).
</code>
The case j = 1 is clear.
Suppose correct for j. If a black ball shows on draw 1, the box will then contain (b + k) black balls and w white balls: a new starting box for draws 2 to j + 1. By the inductive assumption, the chance of getting a black ball on the j-th draw from the new box is (b + k)/((b + k) + w). The other case, a white ball shows on draw 1, is handled in the same way: the chance of getting a black ball on the j-th draw is b/(b + (w + k)). In either case, the (j + 1)-st draw of draws 1 to j + 1 is the j-th draw of draws 2 to j + 1. So the chance of black on the (j + 1)-st draw is given by:
[(b + k)/den][chance black on 1st draw]  +  [b/den][chance white on 1st draw]
where den = (b + k) + w = b + (w + k).
The ratio b/(b + w) occurs in both terms. If you remove it, the sum remaining is 1. That does the inductive step.  (Note: the reasoning is informal, and does not make a proof. By similar standards, the first answer is likely not a proof either.)


Delete old data rows in sheet using google forms

Question: I want the sheet that collects data from a google form to delete old data.  I have this script in the sheet but it doesn't seem to run when new data is added via the form.
function onEdit(e) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("1054");
var datarange = sheet.getDataRange();
var lastrow = datarange.getLastRow();
var values = datarange.getValues();// get all data in a 2D array

var currentDate = new Date();
var oneweekago = new Date();
oneweekago.setDate(currentDate.getDate() - 7);

for (i=lastrow;i>=2;i--) {
var tempdate = values[i-1][0];

if(tempdate < oneweekago)
{
  sheet.deleteRow(i);
}

The sheet it is linked to is called 1054.
Do I need to put appscript in the Form?  If so, what would that be?
Comment: You must "install" and "On Form Submit" trigger.  Rename `onEdit(e)` to something else.  `onEdit()` is a "reserved" function name.  You should not use a reserved function name for the "On Form Submit" trigger.  Give it your own unique name.  Then from the code editor, click the "Edit" menu and "Current projects triggers" and add a trigger.
Comment: So I need to put a script on the form that will run the script in the sheet?  How do I do that?
Comment: An "On Form Submit" trigger can be added to a Form a spreadsheet or both.  It's easier to add the "On Form Submit" trigger to a spreadsheet.  It's easier to get the data, and if you want the code to affect the spreadsheet, then it's a more direct relationship.  From the code editor, choose "Help" and then "Documentation"  Search the words "event object"
Answer: I think it would be better to leave the sheet and the form it is attached to alone. Here's what I do on a form that's on my website.
function formSubmitEvent(e)
{
    var ss=SpreadsheetApp.openById('SpreadsheetID');
    var sht=ss.getSheetByName('ResponseReview');//this is another sheet I used for reviewing the responses.
    sht.appendRow(e.values);//I append a row to the ResponseReview sheet
    selfEmail(e.values);//and I send myself an email if my quota is above 75
}

Even if you delete old data on the linked sheet the form will continue adding data where it left off because evidently it keeps track of what the next row is.
In general, I leave the linked sheet alone.  It is true that I built my form in Googgle Apps Script so at some point when I get a lot of responses then I will unlink the form and delete both and rebuild the form by running that script and a new form and sheet will be linked but I will continue my review process in the other sheet which also has the capability to create a Google Doc from the submitted data.  In essence, it doesn't really matter to me where the form wants to put the data because I capture the onFormSubmit trigger and I put into my ResponseReview sheet from the values array.  And I can do anything I want with that sheet without affecting the linkage.


How do I express u and v in terms of the vector space B

Question:
Hi, I understand what the question is asking me but I am very lost on how to do it. It tells me to express  some vector spaces v and u in terms of the basis of V. Will someone help me do that?
Comment: You copied half sentence from the hint, aiming it as your question, and cited it 2 times *wrongly*.. Btw, maybe introducing $u$ in the hint was superfluous.
Comment: You were no help, you should be more like @Gibbs
Comment: In the future, take the time to enter your question as text instead of pasting a picture. Images are neither searchable nor accessible to people using screen readers, not do they show up in summaries. If you want people to take their time to help you, take some time yourself to post a proper question. Being snarky and insulting also isn't going to encourage people to help you.
Comment: Your post was also unhelpful. If you don't like the question thren ignore it or vote it down. @amd
Answer: Actually $v$ and $u$ are vectors. Anyway, I would approach this as follows: let us prove there exists a linear transformation $T \colon V \rightarrow W$ such that $T(v_i) = w_i$ for any $i=1,\dots,n$. Take $v \in V$. We want to define $T(v)$ in such a way that $T$ is linear. We can express $v$ as a linear combination of the basis $\{v_i\}_{i=1,\dots,n}$:
$$v=a^1v_1+\dots+a^nv_n, \quad a^i \in \mathbb{F} \text{ for any } i=1,\dots,n.$$
Therefore, imposing linearity
$$T(v) = T(a^1v_1+\dots+a^nv_n) = a^1T(v_1)+\dots+a^nT(v_n)=a^1w_1+\dots+a^nw_n.$$
This gives the action of $T$ on any vector in $V$.
Comment: Awesome! Thankyou so much!


PhP - How to place different strings into repeating embedding text?

Question: OK so let's say I have a .txt file with the following lines:
Mark
Jane
Ann
How could I make a php code which reads these names line by line and then saves them in a new text file like this:
Hi my name is Mark, what's yours?
Hi my name is Jane, what's yours?
hi my name is Ann, what's yours?
P.S - This is a simplified version of my problem, I actually have a list of URLs that I need to sorround by some XML code and then stack those one on top of another, so it turns out to be one big XML file. The surrounding blocks of XML text are static, they don't change, the only thing that should change is the part where the URL needs to be inserted, of course.
Comment: Have you tried to write some php code yourself? Where did you get into trouble?
Comment: did you try using `explode()` and retrieving the values by array indexing?
Comment: http://www.php.net/manual/en/function.fgets.php
Comment: Well, I've tried making a txt file with the static information, and then reading that text file into a php variable, then doing a substring replace with offset, and then exporting that back to the txt file and then renaming the file to xml, and i guess i could do that in some loop for all the domains, but is there any easier way?
Answer: Open the file, and then read.
<code>$names = file("names.txt");

foreach ($names as $name) {

 printf("Hi My name is %s, What's yours?\n", $name);

}
</code>
Answer: How about this: (result.txt contains your result, and input.txt contains your names)

<code><?php
$filename = "result.txt";
if (!$handleRes = fopen($filename, 'a')) {
         echo "Cannot open file ($filename)";
         exit;
}

$handle = @fopen("input.txt", "r");
if ($handle) {
    while (($buffer = fgets($handle, 4096)) !== false) {
        fwrite($handleRes, "Hi my name is ".chop($buffer).", what's yours?\n");
    }
    if (!feof($handle)) {
        echo "Error: unexpected fgets() fail\n";
    }
    fclose($handle);
}
?>
</code>
Answer: <code>$aString = file_get_contents("text.txt"); // get text from file
$aString = explode("\n", $aString); // split this text with new line character
$aString = array_map('trim',$aString); // remove spacing between left and right
foreach($aString as $index => $strString){  // browse each line
    $aString[$index] = "Hi my name is $strString, what's yours?"; // change to new format
}
$aString = implode("\r\n", $aString); // join array to string
echo $aString;
</code>


Get drupal form structure

Question: I have created content type with CCK in which there are fields like taxonomy, filefield, textfield etc.
Now i want form structure of this content type.
Answer: Try hook_form_alter
function hook_form_alter(&$form, &$form_state, $form_id) {
 // If you can find the $form_id you can print the exact form.
 print_r($form);
}

Comment: just ommited drupal_render_form while returning in my custom function which is exactly same as drupal_get_form() and got the desired outcome...
Comment: @SoniKishan You asked to get the form structure, not the FROM.

Get drupal form structure


TabLayout tabs text not displaying

Question: I am using TabLayout inside a Fragment to display three fixed tabs and the tabs are working but it doesn't show the tab text even after I set the app:tabTextColor attribute in the layout it's still not visible.
NewFragment.java
public class NewFragment extends Fragment {

private RecyclerView mRecyclerView;
private RecyclerView.LayoutManager mLayoutManager;
private RecyclerView.Adapter mAdapter;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    View inflatedView = inflater.inflate(R.layout.new_fragment, container, false);

    TabLayout tabLayout = (TabLayout) inflatedView.findViewById(R.id.tabLayout);
    tabLayout.addTab(tabLayout.newTab().setText("Tab 1"));
    tabLayout.addTab(tabLayout.newTab().setText("Tab 2"));
    tabLayout.addTab(tabLayout.newTab().setText("Tab 3"));
    final ViewPager viewPager = (ViewPager) inflatedView.findViewById(R.id.viewpager);

    LinearLayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
    mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);

    viewPager.setAdapter(new PagerAdapter(getFragmentManager(), tabLayout.getTabCount()));
    viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
    tabLayout.setupWithViewPager(viewPager);
    tabLayout.setTabMode(TabLayout.MODE_FIXED);
    tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {

        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            viewPager.setCurrentItem(tab.getPosition());
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {

        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {

        }
    });

    return inflatedView;
}

public class PagerAdapter extends FragmentStatePagerAdapter {
    int mNumOfTabs;

    public PagerAdapter(FragmentManager fm, int NumOfTabs) {
        super(fm);
        this.mNumOfTabs = NumOfTabs;
    }

    @Override
    public Fragment getItem(int position) {

        switch (position) {
            case 0:
                return new FragmentTab();
            case 1:
                return new FragmentTab();
            case 2:
                return new FragmentTab();
            default:
                return null;
        }
    }

    @Override
    public int getCount() {
        return mNumOfTabs;
    }
}
}

newfragment.xml
<android.support.design.widget.AppBarLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context=".NewFragment">

<android.support.design.widget.TabLayout
    android:id="@+id/tabLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:tabMode="fixed"
    app:tabTextColor="#ffffff"
    app:tabGravity="fill"
    app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"/>

<android.support.v4.view.ViewPager
    android:id="@+id/viewpager"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@android:color/white"/>

</android.support.design.widget.AppBarLayout>

Comment: If anyone is using `TabLayoutMediator`, kindly refer https://stackoverflow.com/a/59060298/14784590 , use `tab.text=`
Answer: The problem is you're calling setupWithViewPager() after setting up your tabs with the addTab() calls, effectively overwriting them.
From the documentation of TabLayout regarding setupWithViewPager():

The tabs displayed in this
  layout will be populated from the ViewPager adapter's page titles.

If you would like to use your TabLayout with a ViewPager, you should override getPageTitle() in your PagerAdapter (and remove the addTab() calls, they are redundant).
For example:
public class ExamplePagerAdapter extends FragmentStatePagerAdapter {

    // tab titles
    private String[] tabTitles = new String[]{"Tab1", "Tab2", "Tab3"};

    public ExamplePagerAdapter(FragmentManager fm) {
        super(fm);
    }

    // overriding getPageTitle()
    @Override
    public CharSequence getPageTitle(int position) {
        return tabTitles[position];
    }

    @Override
    public Fragment getItem(int position) {
        switch (position) {
            case 0:
                return new Tab1Fragment();
            case 1:
                return new Tab2Fragment();
            case 2:
                return new Tab3Fragment();
            default:
                throw new RuntimeException("Invalid tab position");
        }
    }

    @Override
    public int getCount() {
        return tabTitles.length;
    }

    // ...
}

Comment: _/\_ _/\_ You just saved me from quitting the development :P
Comment: Thanks for the taking time and posting this answer. It helped :)
Comment: I was searching for the Same problem Whole day. Thanks! Its resolved.
Comment: Message to Android core team: The documentation on this is insufficient producing timethiefs in development if you are just a little unlucky.
Answer: i added tab text and icon for each tab after calling tabs.setupWithViewPager(viewPager)
    viewPager.setAdapter(new MyViewAdapter(getSupportFragmentManager()));
    TabLayout tabs=(TabLayout) findViewById(R.id.tabs);
    tabs.setupWithViewPager(viewPager);
    tabs.getTabAt(0).setIcon(R.drawable.icon1);
    tabs.getTabAt(1).setIcon(R.drawable.icon2);
    tabs.getTabAt(0).setText(getResources().getText(R.string.tab1));
    tabs.getTabAt(1).setText(getResources().getText(R.string.tab2));

Comment: Will it work If the `tabs.setupWithViewPager(viewPager);` is called after setting the tabs
Answer: I'm using Kotlin and have spent an hour to find the bugs with this code.
var viewPager: ViewPager = view.findViewById(R.id.viewPager)

...

adapter = TabAdapter(fragmentManager!!)
adapter.addFragment(Fragment1(), "Fragment 1")
adapter.addFragment(Fragment2(), "Fragment 2")

viewPager.adapter = adapter

tabLayout.setupWithViewPager(viewpager)

I can compile this with no error, but the tab title is not showing until I realize the viewpager I assigned to the tabLayout is not viewPager (notice the capitalize 'P'). It's not producing error because kotlin will find any matching layout id, in this case "viewpager" which is a ViewPager but on another view.
Comment: `tabLayout.setupWithViewPager(viewpager)` is where people basically forget..
Answer: I wanted to define TabItem in XML instead of doing it programmatically. As you mentioned, this setupWithViewPager() call resets the text and icon of the tab items to null( It uses the same tab object, just resets its content). I used your approach but made it more reusable. Here is my code:
public class TabLayoutUtil {
    public static void setupTabLayoutWithViewPager(TabLayout tabLayout, ViewPager viewPager) {
        ArrayList<Pair<CharSequence, Drawable>> tabsContentCopy= new ArrayList<>();
        for (int i = 0; i < tabLayout.getTabCount(); i++) {
            TabLayout.Tab tab = tabLayout.getTabAt(i);
            tabsContentCopy.add(new Pair<>(tab != null ? tab.getText() : null, tab != null ? tab.getIcon() : null));
        }
        tabLayout.setupWithViewPager(viewPager);
        for (int i = 0; i < tabLayout.getTabCount(); i++) {
            if (i<tabsContentCopy.size()) {
                tabLayout.getTabAt(i).setText(tabsContentCopy.get(i).first);
                tabLayout.getTabAt(i).setIcon(tabsContentCopy.get(i).second);
            }
        }
    }
}

Answer: tabLayout!!.setupWithViewPager(viewpager)
check this line it's pointing to right viewpager or not.
Comment: This does not provide an answer to the question. Once you have sufficient [reputation](https://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](https://stackoverflow.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/late-answers/34394590)

TabLayout tabs text not displaying


How to merge (or rebase) a branch onto its subbranch in github?

Question: I don't have much experience on using Git. In my scenario, we have master branch, newversion branch, and hotfix branch (which is a branch from newversion).
Now, since I've checked out the hotfix branch, there are several other commits have been made on the newversion branch. I want to 'see' those changes in my hotfix branch, so that I can work using the latest changes available, so I get the latest changes and/or don't repeat the same fixes.
I have seen this website that explain about git rebase, but unfortunately it explain about merge master branch into a branch, not from a branch into a subbranch. The word origin, master, and branch confuses me, and I'm not sure how to modify the example below on the website to match my requirement.
git checkout 7.x-1.x  # Check out the "public" branch
git pull              # Get the latest version from remote
git checkout -b comment_broken_links_101026  # topical branch
... # do stuff here.. Make commits.. test...
git fetch origin      # Update your repository's origin/ branches from remote repo
git rebase origin/7.x-1.x  # Plop our commits on top of everybody else's
git checkout 7.x-1.x  # Switch to the local tracking branch
git pull              # This won't result in a merge commit
git rebase comment_broken_links_101026  # Pull those commits over to the "public" branch
git push               # Push the public branch back up, with my stuff on the top

I'm sure this is just a simple matter, I just still not familiar with Git commands and terminologies. I usually uses Github Desktop, but I'm understand that there are some things that needs terminal, especially for special needs like this. Please help. Thanks.
Answer: if you want to merge newversion branch commits into hotfix branch, then you need following steps to do...
git checkout hotfix

git merge newversion

the first command will active hotfix branch & the second command will merge all the latest commits from newversion to hotfix branch.
:-)
Comment: sorry, it wasn't actually my question, but my workmate's question. After I gave her your answer, she forgot to follow me back with the result, and I also forgot to update this question lol. Thanks anyway!
Comment: Oooh, seems it's not as complicated as I think. Let me try it! Thanks!


Any simple way to set one primary key as a foreign key to multiple tables

Question: I have one table
program(p_id(pk), program_name)
and three other tables:
graduate_survey(id(pk),PO1_avg,PO2_avg,program_name,session),
alumni_survey(id(pk),PO1_avg,PO2_avg,program_name,session),

faculty_survey(id(pk),PO1_avg,PO2_avg,program_name,session)...
I have to link the three tables with program table...How to link these tables in MySQL? graduate_survey, alumni_survey, faculty_survey are some forms which is calculated for some specific program...If in the forms graduate_survey, alumni_survey, faculty_survey there is no text box for entering the program_name, but if i made a column name 'program_name' in the database tables, can i enter the program_name by referencing to the program table? Is there will be any join query?
Answer: Use the program id as foreign key in the other tables, like so:
program(p_id(pk), program_name)
graduate_survey(id(pk),PO1_avg,PO2_avg,p_id(fk),session),
alumni_survey(id(pk),PO1_avg,PO2_avg,p_id(fk),session),
faculty_survey(id(pk),PO1_avg,PO2_avg,p_id(fk),session)

You don't really need the program name for the sake of the FK constraints but it's still a nice to have at some point, maybe.
This way you can easily join based on p_id, for instance:
"SELECT * FROM program INNER JOIN graduate_survey ON program.p_id=graduate_survey.p_id WHERE <your condition here>"

Hope this helps.
Comment: To insert value in the graduate_survey after joining how to do that? is there will be insert-select operation?
Comment: The insert statement would look the same after the join. The join doesn't actually join the tables in the db, only in your query result. So an insert statement: 'INSERT INTO 'graduate survey'(`PO1_avg`, `PO2_avg`, `p_id`, 'session') VALUES ('x', 'y', 'z', 'xy')'
Comment: That means first i have to join the table...actually i am doing it in php so its a little bit confusing....let me try it..
Comment: Which part? Please detail what you are trying to do? Insert a program? Insert a new survey for a certain program? or something else?
Comment: suppose in the program table program_name is B.tech IT and p_id is 1. We fill up the survey forms for B.tech IT...Next the survey has done for another program say B.tech EE and p_id is 2...In the survey tables the foreign key p_id will refer to the pk of program table...Now if the B.tech IT again come to fill up the survey form then will the foreign key p_id of  the survey table refer to the p_id of B.tech IT which is 1?
Comment: Insert a new survey for a certain program what i am looking for.....and will the foreign key p_id in the survey_table be Auto Incremented?
Comment: _Now if the B.tech IT again come to fill up the survey form then will the foreign key p_id of the survey table refer to the p_id of B.tech IT which is 1_ Yes, that is correct. One program can have many surveys. You will have to find the p_id of the program that the survey is for and use that p_id when you insert into one of the survey tables. The FK p_id does not auto-increment but always has to be one of the p_id:s in the program table.
Comment: Now the question arise in my mind is there any query that foreign key p_id field automatically takes the p_id  of program table?
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/145148/discussion-between-nge-and-debasish-choudhury).


Containerd.io depends libseccomp2

Question: Hi I'm trying to install docker in my Debian 10 computer and I have a few problems trying to install containerd.io service.
When I'm trying to install using this command I got an error that I need to upgrade a dependency. But If I try to upgrade manually terminal shows me an advice that I'm already using the last version of this package.
sudo apt-get install docker-ce docker-ce-cli containerd.io

Also I tried to follow this tutorial, but it is not compatible with my debian version
docker-ce : Depends: libseccomp2 (>= 2.3.0) but 2.2.3-3ubuntu3 is to be installed

Depends: libseccomp2 (>= 2.4.0) but 2.3.3-4 is to be installed
Answer: I had the same error. I made the wrong Linux distribution. I had chosen Ubuntu instead of Debian. I had to delete the lines with ubuntu in nano /etc/apt/sources.list and I did sudo apt-get update and I installed sudo apt-get install build-essential. It worked for me !

Containerd.io depends libseccomp2


How to use deep-equal (Angular 7)

Question: Auto import by VS Code:
import deepEqual = require('deep-equal');

Doesn't work:

error TS1202: Import assignment cannot be used when targeting
  ECMAScript modules. Consider using 'import * as ns from "mod"',
  'import {a} from "mod"', 'import d from "mod"', or another module
  format instead.

Then I tried to do like this:
import * as deepEqual from 'deep-equal';

error TS2497: Module '"path/@types/deep-equal/index"' resolves to a non-module entity and cannot be imported using this construct.

And like this:
import {deepEqual} from 'deep-equal';

error TS2305: Module
  '"C:/Projects/ManagerServer/Src-LoyaltyCoin.ManagerServer.Core/ManagerWeb/ClientApp/node_modules/@types/deep-equal/index"'
  has no exported member 'deepEqual'.

I haven't got ideas how can I import this. If there's no solution for this, please suggest me another library to compare objects for Angular 7.
Answer: Add the script to your angular.json file :
scripts: [
  "node_modules/deep_import/name.of.minified.file.js"
]

And declare a variable in your component :
import { Component } from '@angular/core';
....
declare const deepEqual: any;

Or, you can find typings for it and install them, and import it like any other dependency :
import * as deepEqual from 'deep-equal';

EDIT Just a syntax issue. I suggest you open the repository and see the syntax. The correct one is
import deepEqual from 'deep-equal';

as you can see in this stackbltiz
Comment: I already installed the @types/deep-equal, but still have error
Comment: Then try `import * as deepEqual from 'deep-equal';` and use it with `deepEqual.deepEqual`
Comment: smth like this https://stackblitz.com/edit/angular-qjrh3q?file=src%2Fapp%2Fapp.component.ts
Comment: @NastyaScherbakova Edited my answer, feel free to check it !
Comment: I see but it doesn't work for me for some reason
"error TS2304: Cannot find name 'deepEqual'."
Comment: As you can see it works on stackblitz, so you probably have another error. Try re-installing the dependencies, see if it resolves the issue !
Comment: error TS1192: Module '"path/node_modules/@types/deep-equal/index"' has no default export.
Comment: only if I change in library file on 'export default' it works, but it's not a solution :(
Comment: Can someone please clarify to me what this line of code does:
``` declare const deepEqual: any;```
We declare a const deepEqual, but how in world will that const connect to deep-equal library ?
Comment: has anyone tried with latest version of deep-equal ?
Comment: @user4676340 - Have you tried with latest version of deep-equal ?
Answer: You may use fast-deep-equal package. It's included as peer dependency by Angular, but don't forget to add it to regular dependencies.
Also, it's the fastest object comparer.
Usage
import equal from 'fast-deep-equal';

equal(a,b); // returns true\false

How to use deep-equal (Angular 7)


Converting Windows.UI.Xaml.Controls.Image to byte[] Windows phone8.1

Question: So to make it simple, I  have a Windows.UI.Xaml.Controls.Image in my C# class that is named MyImage. I would like to convert it to byte[] so that I can store it to my database.I have no idea how to do this since the image is Windows.UI.Xaml.Controls.Image and not System.Drawing.Image so I can't do something like this:
...
 MemoryStream ms = new MemoryStream();
 imageIn.Save(ms,System.Drawing.Imaging.ImageFormat.Gif);
   return  ms.ToArray();

I would appreciate if someone could write down a simple "how to" code to do this because I just can't figure it out.
Comment: did you check this ?http://stackoverflow.com/questions/14539005/convert-base64-string-to-image-in-c-sharp-on-windows-phone  Btw.. I am not sure Gif format file is supported.
Comment: Look into the ImageSource on the Image control.  Use your tools while debugging.
Answer: I believe that you are using a bitmap image then
myImage = new BitmapImage(new Uri("YourImagePath", UriKind.Absolute));
MemoryStream ms = new MemoryStream();
WriteableBitmap wb = new WriteableBitmap(myImage);
wb.SaveJpeg(ms, myImage.PixelWidth, myImage.PixelHeight, 0, 100);
byte[] imageBytes = ms.ToArray();

This works for Windows Phone But if you are writing code for Windows Store App would suggest you to modify it.
myImage = new BitmapImage(new Uri("YourImagePath"));
RandomAccessStreamReference rasr = RandomAccessStreamReference.CreateFromUri(bitmapImage.UriSource);
var streamWithContent = await rasr.OpenReadAsync();
byte[] buffer = new byte[streamWithContent.Size];
await streamWithContent.ReadAsync(buffer.AsBuffer(), (uint)streamWithContent.Size, InputStreamOptions.None);

Comment: But, my image is created in memory. It's not in UI. so, the step myImage = new BitmapImage(new Uri("yourimagepath")) is not valid for me. Can you help me in this?
Comment: Could you share a code snippet of exactly how you are creating in memory.
Comment: Simply,

Image img = new Image();
img.maxDimension = 500;
img.HorizontalAlignment = Stretch.None;

I hope I am clear.
Comment: Any
 thoughts on how to convert this Image() to writablebitmap?