plist as persistent storage for storing and retrieving data between closing and restarting app

Question: I am trying to save few property into the plist when the user starts the app for the first time, and then I have to retrieve those data and show it to the user, when the user restart the app, so that I don't have to ask for the same data again.
I am guessing this should be very straight forward, but may be I am missing something.
It would be nice if some one can point me to a sample code for doing the same thing, it would be nice if the code saves and retrieves the data from dictionary to plist and from plist to dictionary.
I looked into the Apple Property List Programming guide and used the code from Reading and Writing Property list data
http://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/PropertyLists/ReadWritePlistData/ReadWritePlistData.html#//apple_ref/doc/uid/10000048i-CH8-SW1
but, when i restart my app, I don't get back the data that I have stored.
*EDIT*
I am adding some code so that some one can point out if I am making any mistake.
I created a plist file "Data.plist" in my project Resources folder.
This is how I save data in one of my view controller
    NSString *path = [[NSBundle mainBundle] bundlePath];
NSString *finalPath = [path stringByAppendingPathComponent:@"Data.plist"];
//NSString *error;

NSMutableDictionary *dict = [NSMutableDictionary dictionary];

[dict setObject:@"xxxxxx" forKey:@"phoneNumber"];
[dict setObject:@"password" forKey:@"password"];
[dict setObject:@"email" forKey:@"email"];

[dict writeToFile:finalPath atomically:NO];

This is how I am reading the the data on the same view controller viewDidLoad method, because I want to load the data from when next time app starts.
    NSDictionary *dictionary;

// read "Data.plist" from application bundle
NSString *path = [[NSBundle mainBundle] bundlePath];
NSString *finalPath = [path stringByAppendingPathComponent:@"Data.plist"];
dictionary = [NSDictionary dictionaryWithContentsOfFile:finalPath];

// dump the contents of the dictionary to the console
for (id key in dictionary) {
    NSLog(@"bundle: key=%@, value=%@", key, [dictionary objectForKey:key]);
}

Before saving to the file i can do "po dict" at gdb and can see there are data in the file
NSLog print following error
Assertion failed: (cls), function getName, file /SourceCache/objc4_Sim/objc4-427.1.1/runtime/objc-runtime-new.m, line 3939.
Because when i load data and do "po dictionary" at gdb it is empty
Answer: -[NSDictionary writeToFile:atomically:] returns YES or NO depending on whether it's successful or not. Are you checking the return value?
If I had to take a guess, I'd say it's because you're writing the file into the application bundle. You should write it elsewhere in the file system; ~/Library/Application Support/<application name> is the usual location.
Edit:
You can check the return value with something like:
BOOL success = [dict writeToFile:finalPath atomically:YES];
if (!success) {
    NSLog(@"Could not write file");
}

Comment: [dict writeToFile:finalPath atomically:NO]; I have to specify NO  or YES when I am writing this statement isn't it, how do I check what is the return value.     But if I write it to file system is it going to be iphone file system, what path should I give is the path ~/Library/Application Support/ is available in iphone too as finally the app has to go to the iphone.
Comment: I updated the answer to show how to check the return value. (Also, if this is for the iPhone, you should tag it with `iphone` or `cocoa-touch`, not `cocoa`.)
Comment: Thanks, I checked  the value of success is true, so which means the log is not getting printed, which means that the data is written in the file
Comment: Actually some other user made the tag has cocoa, i didn't do it


LINQ to Entities How do do a subquery for a field

Question: To save multiple DB calls, and since it is from the same table, I'm looking for one of the fields in my linq query to return an object with 2 fields that are IEnumerable.
I wrote some pseudeocode here that should illustrate what I'm trying to do, but its not valid Linq code.  Anyone know how to make this work?  (Fred & Joe will both be IEnumerable)
    var c = from jobs in model.jobView
                      select jobs.JobID, jobs.NameID, new
                                 {
                                     Fred = from j in model.jobView
                                            select jobs.Field1,
                                     Joe = from k in model.jobView
                                            select jobs.Field2
                                 };

Answer: You want to create an anonymous type and then create another anonymous type within it.
I am guessing there is a typo in your two collections where you use j and k, but select with jobs
 var c = from jobs in model.jobView
         select new
         {
           jobs.JobID,
           jobs.NameID,
           TwoObjects = new
                        {
                          Fred = from j in model.jobView
                                 select jobs.Field1,
                          Joe = from k in model.jobView
                                 select jobs.Field2
                        }
        };


Como por Variável Javascript dentro de um value do html?

Question: Tenho o seguinte código:
console.log(ArmazenaIds);
console.log(ArmazenaEmails);
contaQuantidadeDeEmails = ArmazenaEmails.length;
//listando emails selecionados na div .top
for( c=0; c<contaQuantidadeDeEmails; c++) {

  $('ul').append('
'+ArmazenaEmails[c]+'
');
  // COLOCANDO CADA EMAIL DENTRO DO VALUE PRA ENVIAR PELO FORM
  //USANDO AJAX
  $('#novo').append("<input type='hidden' name='emailzinhos[]' value='aff' /> ");
}

Como faço para colocar o vetor ArmazenaEmails[c] dentro do value='aff', não sei como fazer isso, tentei com + e tá me dando erro de sintaxe, é uma pergunta até fácil só não sei a resposta.
Answer: Você pode concatenar os valores do vetor ArmazenaEmails[c] na string:
for( c=0; c<contaQuantidadeDeEmails; c++) {
  $('ul').append('
'+ArmazenaEmails[c]+'
');
  // COLOCANDO CADA EMAIL DENTRO DO VALUE PRA ENVIAR PELO FORM
  //USANDO AJAX
  $('#novo').append("<input type='hidden' name='emailzinhos[]' value='"+ArmazenaEmails[c]+"' /> ");
}

Neste exemplo, vou retirar o hidden dos inputs para poder visualizar o valor:

ArmazenaEmails = ['firstname.lastname@example.com','firstname.lastname@example.com','firstname.lastname@example.com'];

contaQuantidadeDeEmails = ArmazenaEmails.length;
//listando emails selecionados na div .top
for( c=0; c<contaQuantidadeDeEmails; c++) {
  $('ul').append('
'+ArmazenaEmails[c]+'
');
  // COLOCANDO CADA EMAIL DENTRO DO VALUE PRA ENVIAR PELO FORM
  //USANDO AJAX
  $('#novo').append("<input type='' name='emailzinhos[]' value='"+ArmazenaEmails[c]+"' /> ");
}

Comment: NOSSA ERA ISSO QUE EU TAVA QUERENDOOOOOOO DVD, NÃO SABIA QUE DAVA PRA CONCATENAR ASSIM QUE LEGALLLL
Answer: Com a seleção da tag input com o valor "aff".
Basta adicionar a seguinte instrução:
$('input[value="aff"]').val(ArmazenaEmails[c]);

Ficando assim:
console.log(ArmazenaIds);
console.log(ArmazenaEmails);
contaQuantidadeDeEmails = ArmazenaEmails.length;
//listando emails selecionados na div .top
for( c=0; c<contaQuantidadeDeEmails; c++) {

  $('ul').append('
'+ArmazenaEmails[c]+'
');
  // COLOCANDO CADA EMAIL DENTRO DO VALUE PRA ENVIAR PELO FORM
  //USANDO AJAX
  $('#novo').append("<input type='hidden' name='emailzinhos[]' value='aff' /> ");
  $('input[value="aff"]').val(ArmazenaEmails[c]);
}


Values of $a$ s.t. for all continuous $f$ with $f(0)=f(1)$ there exists $x$ s.t. $f(x+a) = f(x)$

Question:
Determine all $a\in[0,1]$ such that for ${\it every}$ continuous function $f:[0,1]\to \mathbb{R}$ with $f(0)=f(1)$ there exists at least one $x$ where $f(x) = f(x+a)$.

First of all, $a=0,1/2,1$ are obviously good values. Secondly, no $1/2<a<1$ works (look at $f = \sin(2\pi x)$).
I remember trying to solve this several years ago. I think I started by dividing $[0,1]$ into regions where $f\geq 0$ and $f<0$. Then studied each interval and all pairs of intervals with the same sign. However, this seems like a problem that should have a simple solution and I would love to see it.
Answer: The set you're looking for is
$$ \{0\} \cup \left\{\frac{1}{n}\right\}_{n\in \mathbb N}. $$
My proof (not a really "simple" one!) is going to be somewhat "visual"; I'm also going to only consider (WLOG) functions such that $ f(0) = f(1) = 0 $.
If $ a = 1/n $ for a natural number $ n $, you can partition the interval $ [0,1] $ into $ n $ equally broad "bands". Let $ f $ be any continuous function; one can show that if the function is not "overall strictly increasing" ("o.s.i."; I made up this terminology) over each band, in the sense that $ f(ka) < f((k+1)a) \; \forall k $, then $$ (*)\qquad f(x) = f(x+a) $$ for some $ x $. To see this, draw the graph of $ f(x+a) $, by moving the graph of $ f(x) $ forward by $ a $, and notice that the condition $ (*) $ means that the graph of $ f(x) $ should cross that of $ f(x+a) $, which will necessarily happen if the "o.s.i." condition isn't fulfilled (you can convince yourself this is true by either visually picturing the described situation or applying the intermediate value theorem to $ f(x+a) - f(x) $). But clearly, a function satisfying this o.s.i. condition cannot simultaneously satisfy $ f(0) = f(na) = f(1) $. Therefore $ a $ belongs to your set.
On the other hand, if $ a \ne 1/n $ for a natural $ n $, you should be able to explicitly conjure up a function $ f $ for which $ f(x) \ne f(x + a) $ for any $ x \in [0,1] $. I came up with the following: let $ 1 = na + \delta $, with $ 0 < \delta < n $ by the hypothesis on $ a $. I'm going to define the value of $ f $ at certain points, and then $ f $ may be build by simply joining them with line segments.
I'm choosing an arbitrary $ \varepsilon > 0 $ and then setting
$$ \begin{cases}f(ka + \delta) = (n-k)\varepsilon \quad&\mathrm{for}\; k = 0,1,\ldots,n \\ f(ka) = -k\varepsilon \quad&\mathrm{for}\; k = 0,1,\ldots,n.\end{cases} $$ This function should not cross with its own shifted version. The gist is that in this case the above "band partition" isn't able to account for the whole $ [0,1] $ interval, so you can avoid crossing the shifted-function's graph by following a suitably oscillating path.
Comment: @Winther: my bad, index $k$ should run in 0 thru $ n $ for both formulas; if you draw and join the points it should be clear that $ f $, if $a=.49$, is positive on $(0,2(a-\varepsilon)/3) $, then switches sign. Also, it doesn't meet $ f(x+a) $, since the latter's graph is just the former one's shifted upward by $\varepsilon$ ($f$ is in fact tailored so as to have this property).
Comment: Thank you for your answer! I will study it later tonight, but right now I don't see how your last construction can work. Lets try to rule out $a=0.49$. We take $n=2$ and $\delta = 0.02$. The constructed function is stricktly negative on $(0,0.5)$ and therefore all values $a\in (0,0.5)$ are achieved right?
Comment: I have read it now and agree with your solution. In fact, your proof cannot be simpler:) Dropping the unnecessary packaging of it we're left with: i) a simple application of the IVT and ii) a construction of a counter example for the remaining values. It can be compressed to a stringent, but still easy to read, 10 line proof:) Nitpick/cosmetics: $\epsilon$ is not needed and the $f(1)=f(0)=0$ is not needed (never used). Again, thanks for the effort:)
Comment: @Winther: you're right about $ f(0) = 0 $ being unnecessary (I chose it WLOG in order to have an easier-to-write counterexample); how do you get rid of the epsilon, however? You need to pick a positive value for the graph of $ f(x+a) $ to be upshifted by, don't you?
Comment: I meant that $\epsilon$ can be put to $1$ without taking away anything.
Comment: @Winther: Oh, sure, that much is granted.
Answer: Decomposition into Fourier series
\begin{eqnarray*}
f(x) &=&\sum_{k}f_{k}\exp [2\pi ikx],\;x\in \lbrack 0,1] \\
f(x+a) &=&\sum_{k}f_{k}\exp [2\pi ik(x+a)]
\end{eqnarray*}
We must have
\begin{equation*}
\exp [2\pi ika]=1
\end{equation*}
for some $k.$ Fix $k$. Then this is the case for $a=1/n$ for some suitable
integer $n$. Then
\begin{equation*}
f_{k}(x)=f_{k}\exp [2\pi ikx]
\end{equation*}
fills the bill. For real $f(x)$ take the real part of $f(x)$
\begin{equation*}
f(x)=\sum_{k}\{f_{k}\exp [2\pi ikx]+\bar{f}_{k}\exp [-2\pi ikx]\}
\end{equation*}
Comment: I don't think you have read the question properly. I'm looking for the range of $a$ values for which the property holds for *all* $f$.
Comment: Yes, I misunderstood the question.


Recursive convolution of a PDF with itself

Question: I was playing around with some simulations and I am trying to understand and produce an analytical solution for the behaviour I see.
I generated $512$ sets of data, each set containing $10000$ data points. All data sets were drawn from a Rayleigh distribution with the same shape parameter $\sigma$. I label each set $X_{i}$, which has elements $X_{i} = \{x_{j},...,x_{M}\}$, where $M = 10000$.
I then take the average of the data sets as
$$\bar{X}_{N} = \frac{1}{N} \sum_{i}^{N} X_{i} $$
to be explicit, not the average of the $X_{i}$, but the average of the sets. The resulting average still contains $M = 10000$ points. Plotting the averaged data sets gives the histograms, as follows:

What we can clearly see is that as more and more data sets are included in the average, the more normally distributed the resultant data set becomes.
This is to be expected, I think, because of the central limit theorem. Now to my question:
I would like to show this mathematically. I know that the sum of random variables is described by the convolution from the parent distribution of those variables.
I imagine the result to be a two parameter distribution, $F(\sigma, N)$, $\sigma$ being the same shape parameter of the Rayleigh distribution. And $N$ the number of averages, or convolution iterations as per
$$F(x)_{N} = \int_{-\infty}^{+\infty} F_{N - 1}(X) f(x - X) \ dX$$
where $f(x)$ is the original distribution of interest (in my case the Rayeligh).
Is it possible to get such a solution?

I have been able to calculate the first and iterations of the convolution. For the $N = 1$ case of the above convolution integral.
$$\int_{-\infty}^{+\infty} R(X) R(x - X) \ dX = \\ \frac{1}{4 \sigma^{3}}\exp\left(\frac{-x^{2}}{2\sigma^{2}}\right) \left( 2 x \sigma + \exp\left(\frac{x^{2}}{4\sigma^{2}}\right) \sqrt{\pi} \left( x^{2} - 2 \sigma^{2} \right) \rm{erf}(x/2 \sigma) \right)$$
Where $R(x)$ is the Rayleigh distribution. Plotting the above gives a reasonable result if I compare it to my data:
Comment: .. or, more generally, characteristic functions (/Fourier transforms).
Comment: I'm not sure what you mean by a "real solution." There are a great many useful ways to specify distributions, including (but not limited to) the CDF, PDF, MGF, CF, and CGF. For analyzing them, various approximations and asymptotic expressions can be quite useful.  Often it's fruitless to insist on obtaining one version (such as the PDF) but some other version can be extremely simple.
Comment: @JimB are you Mathematica S.E. JimB? Care to provide an answer? I've not come across this technique.
Comment: You have a small typo in the last equation:  $\exp{(-x^2/4\sigma^2)}$ should be  $\exp{(x^2/4\sigma^2)}$.  And that gives you the density for the sum rather than the mean of two i.i.d. Rayleigh random variables.  In short, I think you should follow the advice of the two experts.  If your objective is to obtain the limiting distribution, then using characteristic functions is certainly the better way to go.  If you think you need something close to "exact" distribution for say $N=43$, then comparing the distribution of a huge random sample against the limiting distribution might be adequate.
Comment: If you are trying to show that $\sqrt{N}(\bar{X}-\mu)$ has a normal limiting distribution, then using moment generating functions might be an simpler approach.
Comment: It depends on what you mean by "get such a solution." An expression for its density function would not be tractable, because the Rayleigh is essentially a chi(2) distribution.  Sums of *squares* of Rayleigh variables are easy to work with, but not sums of the variables themselves.
Comment: @Whuber I have added the first stage of such a calculation to my answer.
Comment: I see neither an answer nor a calculation.  The characteristic function method is not going to help get useful explicit answers: see https://en.wikipedia.org/wiki/Chi_distribution for the cf (a polynomial combination of confluent hypergeometric functions).
Comment: @whuber My mistake. My additions are up.
Comment: That's helpful, because it suggests (correctly) that as you continue to perform successive convolutions, the number of terms will increase in proportion to $N.$  You will obtain a sum whose terms themselves become increasingly complicated.  Although that might yield some kind of formula, it's unclear what it could accomplish for any statistical theory or application, which returns us to the issue: what exactly do you mean by "get a solution"?
Comment: @whuber I can't get past the $N = 1$ stage because that is far beyond my pen and paper abilities to solve and Mathematica can' solve it. I wanted a closed form solution, where I have some distribution $F(\sigma, N)$ where I can define the number of convolutions. It occurs to me that this is stupid to wish for as aclosed form solution in this case because the explicit integral would need to be computed for each integer value of $N$. Interestingly a Weibull distribution more or less approximates the behaviour, so works for my simulation purposes. A real solution would have been more satisfying.
Comment: @JimB Nice spot. Maybe I should ask the technicalities over on MM S.E because I'm not sure how to compute the convolution further than the case I have given.
Answer: Here is a quick outline determining the limiting distribution of the sample mean of $X_1,X_2,\ldots,X_n$ as $n\rightarrow \infty$ using moment generating functions.
All of the $X_i$ are independent and have the same distribution:  $X_i \sim \text{Rayleigh}(\sigma)$.  We have $\mu=\text{E}(X_i)=\sigma \sqrt{\pi/2}$.  Let
$$S_n=\sum_{i=1}^n X_i$$
We look at the limiting distribution of
$$Z=\sqrt{n}(S_n/n-\mu)$$
using moment generating functions.  The moment generating function of a Rayleigh distribution is
$$M(t)=\sqrt{\frac{\pi }{2}} \sigma  t \left(\text{erf}\left(\frac{\sigma  t}{\sqrt{2}}\right)+1\right) \exp \left(\frac{\sigma ^2 t^2}{2}\right)+1$$
The moment generating function of $S_n$ is simply $M(t)^n$.  We also know that the moment generating function of $a S_n+b$ (where $a$ and $b$ are known constants) is $e^{b t} M(a t)^n$.  So the moment generating function of $Z=\sqrt{n}(S_n/n-\mu)$ is
$$e^{\sqrt{\frac{\pi }{2}} \left(-\sqrt{n}\right) \sigma  t} \left(\frac{\sqrt{\frac{\pi }{2}} \sigma  t e^{\frac{\sigma ^2 t^2}{2 n}} \left(\text{erf}\left(\frac{\sigma  t}{\sqrt{2} \sqrt{n}}\right)+1\right)}{\sqrt{n}}+1\right)^n$$
Taking the limit as $n->\infty$ we have
$$e^{\frac{1}{4} (4-\pi) \sigma ^2 t^2}$$
for the moment generating function.  As the moment generating function for a normal distrbution with mean $m$ and variance $v$ is
$$e^{m t+\frac{t^2 v}{2}}$$
we see that our limiting moment generating function represents a normal distribution with mean $0$ and variance $\frac{1}{2} (4-\pi ) \sigma ^2$.  What this means is that we can use a normal distribution with mean $\sigma \sqrt{\pi/2}$ and variance $\frac{1}{2} (4-\pi ) \sigma ^2/n$ to approximate the distribution of $\bar{X}=S_n/n$.
As a partial check consider $n=10$.  We can generate a bunch of samples and plot the resulting histogram and approximate density (using Mathematica)
<code>n = 10;
\[Sigma] = 1;
z = RandomVariate[RayleighDistribution[1], {1000000, n}];
z = Mean[#] & /@ z;
Show[Histogram[z, 100, "PDF", Frame -> True,
  FrameLabel -> (Style[#, Bold, 18] &) /@ {"\!\(\*OverscriptBox[\(X\), \(_\)]\)", "Probability density"}],
 Plot[PDF[NormalDistribution[Sqrt[\[Pi]/2] \[Sigma], Sqrt[(4 - \[Pi]) \[Sigma]^2/(2 n)]], x],
  {x, 0.4, 3}, PlotRange -> All]]
</code>
Comment: @whuber I understand. But the OP (in a comment) mentioned "I've not come across this technique." So I gave a few details.
Comment: Because the OP is aware of the CLT, it's unnecessary to reproduce the steps in a proof: it suffices to compute the mean and variance of the sum of $n$ iid Rayleigh variables and apply the CLT.  But I doubt that's what the OP was looking for in an answer.
Comment: I'm going to accept @JimB's answer. This has provided me a lot more information to play with. Thanks!
Comment: If the need is to find pdf values for a particular value of $N$ (given that there doesn't appear to be a nice closed-form solution for $N>2$), then are a few ways to do that.  Here are three:  (1) Take a large random sample and obtain a nonparmetric density estimate (`SmoothHistogram` and `SmoothKernelDistribution`).  (2) Use another distribution that matches say the first 3 moments and use that as an approximation.  The `SkewNormal` distribution might be considered (https://en.wikipedia.org/wiki/Skew_normal_distribution).  (3) Use numerical integration (but only useful for small $N$).


Validar Select jqueryValidate com Materializecss

Question: Encontrei um problema que não estou conseguindo solução a um tempinho, estou trabalhando com o framework MaterializeCSS. Ele possui validação com algumas notações diretas na tag HTML, o que não estou conseguindo é validar é quando tenho uma tag select.
Segue o código:

    <select id="comboBasculante" name="comboBasculante">
        <option value="0" disabled selected>Selecione</option>
        <option value="1">Basculante</option>
        <option value="2">Fixo</option>
        <option value="3">Janela</option>
        <option value="4">Porta</option>
        <option value="4">Stanley</option>
    </select>
    Produto

Comment: O que acontece?
Answer: O material_select faz o seu do select um display: none e o jQuery Validation ignora campos campos ocultos. Para ativar a validação de campos ocultos use:
$.validator.setDefaults({
  ignore: []
});

Ps.: Use no seu select o atributo required

$('select').material_select();

$.validator.setDefaults({
  ignore: []
});

$("form").validate({
  errorClass: "invalid form-error",
  errorElement: 'div',
  errorPlacement: function(error, element) {
    error.appendTo(element.parent());
  }
});
.form-error {
  color: #D8000C;
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.98.2/css/materialize.min.css" rel="stylesheet" />

<form>
  <select required>
    <option value="">- Selecione -</option>
    <option value="vanilla">Vanilla</option>
    <option value="chocolate">Chocolate</option>
  </select>

  <input type="submit" />
</form>
Answer: Tenta esse código. Eu acrescentei a tag requireddo html 5 e tirei o valor do placeholder.

<select id="comboBasculante" name="comboBasculante" required>
    <option value="" disabled selected>Selecione</option>
    <option value="1">Basculante</option>
    <option value="2">Fixo</option>
    <option value="3">Janela</option>
    <option value="4">Porta</option>
    <option value="4">Stanley</option>
</select>
Produto

Você pode checar nessa documentação: https://www.w3.org/TR/html5/forms.html#the-select-element
Answer: Adicione a instância do Materialize,como recomendado na documentação:
Documentação do Materialize.
    $(document).ready(function() {
        $('select').material_select();
    });

*{
background:#f1f1f1;
}
.mySelect{
margin:10px;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

        <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.5/css/materialize.min.css">

<select id="comboBasculante" name="comboBasculante" required>
<option value="" disabled selected>Selecione</option>
<option value="1">Basculante</option>
<option value="2">Fixo</option>
<option value="3">Janela</option>
<option value="4">Porta</option>
<option value="4">Stanley</option>
</select>
Produto

Answer: Solução Definitiva:
O MATCSS cria um <input> para substituir o <select>, mas não passa os parâmetros de validação para este input, como a classe validate e o span com helper-text.
$(document).ready(function(){
    $('select').formSelect();
    const _requiredSelects = $("select[required].validate");
    _requiredSelects.parent().find('input').addClass('validate').attr('required', true)
    .keydown(function($event) {
        return $event.keyCode == 9;
    });
    _requiredSelects.change(function($event) {
        const _select = $event.target;
        const _value = $(_select).val();
        const _input = $(_select).parent().find('input');
        _input.removeAttr('readonly', '');
        _input.val(_select.options[_select.options.selectedIndex].label);
        if (_value != '') {
            _input.addClass('valid');
            _input.removeClass('invalid');
        } else {
            _input.addClass('invalid');
            _input.removeClass('valid');
        }
    });
    _requiredSelects.each(function(){
        const _this = $(this);
        const _helper = _this.parent().parent().find('.helper-text');
        if (_helper !== undefined) {
            const _input = _this.parent().find('input');
            _helper.insertAfter(_input);
        }
    });
});


no disk io but iowait very high

Question: there is no disk io going results of iotop
Total DISK READ: 0.00 B/s | Total DISK WRITE: 0.00 B/s
  TID  PRIO  USER     DISK READ  DISK WRITE  SWAPIN     IO<    COMMAND
    1 be/4 root        0.00 B/s    0.00 B/s  0.00 %  0.00 % init [3]
 1930 be/4 named       0.00 B/s    0.00 B/s  0.00 %  0.00 % named -u ~d/run-root
 1931 be/4 named       0.00 B/s    0.00 B/s  0.00 %  0.00 % named -u ~d/run-root
 1932 be/4 named       0.00 B/s    0.00 B/s  0.00 %  0.00 % named -u ~d/run-root
 1933 be/4 named       0.00 B/s    0.00 B/s  0.00 %  0.00 % named -u ~d/run-root
 1810 be/4 root        0.00 B/s    0.00 B/s  0.00 %  0.00 % sh /usr/b~user=mysql
 9795 be/4 apache      0.00 B/s    0.00 B/s  0.00 %  0.00 % httpd
 8004 be/4 apache      0.00 B/s    0.00 B/s  0.00 %  0.00 % httpd
 3226 be/4 postfix     0.00 B/s    0.00 B/s  0.00 %  0.00 % tlsmgr -l -t unix -u
 8154 be/4 apache      0.00 B/s    0.00 B/s  0.00 %  0.00 % httpd
 9759 be/4 root        0.00 B/s    0.00 B/s  0.00 %  0.00 % find -name php.ini
 9249 be/4 apache      0.00 B/s    0.00 B/s  0.00 %  0.00 % httpd
 1756 be/4 postfix     0.00 B/s    0.00 B/s  0.00 %  0.00 % psa-pc-re~@localhost
 1863 be/4 mysql       0.00 B/s    0.00 B/s  0.00 %  0.00 % mysqld --~mysql.sock
 3123 be/4 root        0.00 B/s    0.00 B/s  0.00 %  0.00 % crond
 1758 be/4 postfix     0.00 B/s    0.00 B/s  0.00 %  0.00 % psa-pc-re~@localhost
 1865 be/4 mysql       0.00 B/s    0.00 B/s  0.00 %  0.00 % mysqld --~mysql.sock
 1592 be/4 sw-cp-se    0.00 B/s    0.00 B/s  0.00 %  0.00 % sw-cp-ser~ver/config
 7612 be/4 root        0.00 B/s    0.00 B/s  0.00 %  0.00 % sshd: root@pts/0
 7614 be/4 root        0.00 B/s    0.00 B/s  0.00 %  0.00 % sftp-server
 7615 be/4 root        0.00 B/s    0.00 B/s  0.00 %  0.00 % -bash
 1602 be/4 root        0.00 B/s    0.00 B/s  0.00 %  0.00 % sshd
 8003 be/4 root        0.00 B/s    0.00 B/s  0.00 %  0.00 % httpd

but iowait very high ?
iostat report
avg-cpu:  %user   %nice %system %iowait  %steal   %idle
           0.83    0.00    0.13   13.83    0.00   85.20

Device:            tps   Blk_read/s   Blk_wrtn/s   Blk_read   Blk_wrtn

server runs like a snail what could be wrong here ?
thanks
Answer: iowait can be waiting on anything io related. This includes network, USB, PCI and other devices. Try using iftop to see what your network is doing and consider removing devices from the system.
Comment: iotop too - http://guichaz.free.fr/iotop/
Comment: ty smarthall but i have no access to the box it self i rent it from a hosting company so i guess i have to put in a ticket
Comment: does not include program network access.  only file i/o.  https://serverfault.com/questions/37441/does-iowait-include-time-waiting-for-network-calls
Comment: Also monitor /proc/interrupts file for some time. It will show signs of any i/o in your system, because i/o usually is done asynchronously via interrupts. You'll see which hardware generates interrupts and then be able to debug it more thoroughly.

no disk io but iowait very high


If $\sin(\pi/3+t)+\sin (\pi/3-t)=p$, then evaluate $\sin(\pi/3+t)\cdot \sin(\pi/3-t)$

Question:
Knowing that
  $$\sin\left(\frac\pi3+t\right)+\sin\left(\frac\pi3-t\right)=p$$
  evaluate
  $$\sin\left(\frac\pi3+t\right)\cdot \sin\left(\frac\pi3-t\right)$$

I found that $\cos t = \dfrac{p}{\sqrt{3}}$.
Comment: Welcome! Please tell us what you know and what have you tried. Also, use LaTex to be more readable friendly :)
Comment: I found that the cost=p/sqrt 3
Comment: Gives us your full computation. Also, why is useful to compute the $\cos(t)$? Explaining helps you to understand what is going on.
Answer: It is $$\sin(\pi/3+t)+\sin(\pi/3-t)=\sqrt{3}\cos(t)=p$$ and $$\sin(\pi/3+t)\sin(\pi/3-t)=1/4(1+2\cos(2t))$$. Now use that $$\cos(2t)=2\cos^2(t)-1$$


How to use NUSOAP in my custom module?

Question: My users have to be guided to Bank Gate to pay the money After filling a Form in my custom module. the process of leading them has to be done through NUSOAP but it seems it is not functioaning inside module! it works find when i have the same code in a php file but in module ... I have no idea what is wrong with that! this is my submit function:
<code>function my_module_my_form_submit($form, &$form_state) {

  $nusoap_path = drupal_get_path('module', 'myblock') . '/nusoap.php';
  include_once($nusoap_path);

    $client = new nusoap_client('https://de.....com/pg/services/WebGate/wsdl', 'wsdl');
    $client->soap_defencoding = 'UTF-8';
    $result = $client->call('PaymentRequest', array(
                                                    array(
                                                            'MerchantID'    => 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX',
                                                            'Amount'        => 1000,
                                                            'Description'   => 'some texts',
                                                            'CallbackURL'   => 'http://......./verify.php'
                                                        )
                                                    )
    );
    //Redirect to URL
    if($result['Status'] == 100)
    {
        $form_state['redirect'] =('https://www.......com/pg/StartPay/'.$result['Authority']);
    } else {
        echo'ERR: '.$result['Status'];
    }

}
</code>
thanks in advanced for you help
Answer: I think I've had a similar issue in the past with a different payment gateway.
Inspect each variable (print_r or var_dump) one after another comparing the values between your stand alone php file and the drupal module.
When you find the point at which there is a difference you know what line it's going wrong.
Maybe shout at it a bit at this point, give it a prod, read some more API documentation and then you should almost be there ;)
Answer: my mistake was trying to do it on localhost! once i checked the same code on a real server everything was fine and it worked!

How to use NUSOAP in my custom module?


Deploying a windows machine with ansible and sysprep

Question: I was wondering if you could help me?  I'm trying to deploy a windows server 2012R2 base image using the vsphere ansible module.
I have created a Vsphere template where the guest machine has WinRM enabled, as per the powershell script on the ansible windows documentation website. Using the vsphere ansible module I then deploy a new VM from this template and pass in a powershell script to the guest to kick start my configuration. The problem is, when I try and domain join this new VM in a powershell script, I get errors with the SID of the new vm. The vsphere template hasn't run sysprep.
What I have then done is run sysprep.exe /generalize /oobe /reboot before turning the machine off to create the vsphere template. Ansible is now deploying this template instead. However, when this new template deploys, it is greeted with the windows welcome screen which blocks ansible provisioning it. When I click passed this manually, ansible still dosnt seem to be able to talk to it, I believe winRM has somehow been disabled during the sysprep.
Has anyone managed to overcome this problem before? My feeling is that this must be a solved problem?
Any pointers and support welcome :)
Thanks,
Answer: You probably want to use the /shutdown switch instead of /reboot before make it into template, and you should give an /unattend:unattend.xml with preseeded answers for making a silent installation.
Use setupcompleted.cmd to enable powershell and WinRM before first autologin/login.


nginx wont cache images when they are read through php files

Question: I have .php file which is loading images to hide their location. Every images are correctly caching through this directive:
location ^~ \.(jpg|jpeg|png|gif|ico|css|js)$ {
            expires max;
            valid_referers server_names blocked mysiteaddresishere;
            if ($invalid_referer) {
               return   403;
            }
}

by the way, valid referrers doesn't work, I don't know why.
I've added ^ before ~, someone told that this should look at the longest regex, maybe it do but not with php files.
I have in my vhost something like this:
location ~ \.php$ {
    try_files /a30bc49b5ff24bc50d55ba4306d73470.htm @php;
}

location @php {
    try_files $uri =404;
    include /etc/nginx/fastcgi_params;
    fastcgi_pass 127.0.0.1:9010;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_intercept_errors on;
}

Dunno if this is blocking caching on my php image reader, I can't figure out how to add into this expires for images.
I've found this site: en.dklab.ru /lib/HTTP_ImageResizer/, so I've tried like this:
location /imagehi.php {
        fastcgi_cache MYAPP;
        fastcgi_cache_valid 200 304 404 240h;
        fastcgi_cache_key "method=$request_method|ims=$http_if_modified_since|inm=$http_if_none_match|host=$host|uri=$request_uri";
        fastcgi_hide_header "Set-Cookie";
        fastcgi_ignore_headers "Cache-Control" "Expires";

    # or use proxy_* commands if you use Apache, not FastCGI PHP
}

But it still doesn't work. Any ideas what am I missing ?
Nginx conf
fastcgi_cache_key "$scheme$request_method$host$request_uri";

server {
    listen *:80;

    server_name mysite.com www.mysite.com;

    root   /var/www/mysite.com/web;

    index index.html index.htm index.php index.cgi index.pl index.xhtml;

    error_page 400 /error/400.html;
    error_page 401 /error/401.html;
    error_page 403 /error/403.html;
    error_page 404 /error/404.html;
    error_page 405 /error/405.html;
    error_page 500 /error/500.html;
    error_page 502 /error/502.html;
    error_page 503 /error/503.html;
    recursive_error_pages on;
    location = /error/400.html {

        internal;
    }
    location = /error/401.html {

        internal;
    }
    location = /error/403.html {

        internal;
    }
    location = /error/404.html {

        internal;
        }
    location = /error/405.html {

        internal;
    }
    location = /error/500.html {

        internal;
    }
    location = /error/502.html {

        internal;
    }
    location = /error/503.html {

        internal;
    }

    error_log /var/log/ispconfig/httpd/mysite.com/error.log;
    access_log /var/log/ispconfig/httpd/mysite.com/access.log combined;

    location ~ /\. {
        deny all;
        access_log off;
        log_not_found off;
    }

    location = /favicon.ico {
        log_not_found off;
        access_log off;
    }

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

    location /stats {

        index index.html index.php;
        auth_basic "Members Only";
        auth_basic_user_file /var/www/clients/client0/web1/web/stats/.htpasswd_stats;
    }

    location ^~ /awstats-icon {
        alias /usr/share/awstats/icon;
    }

    location ~ \.php$ {
        try_files /a30bc49b5ff24bc50d55ba4306d73470.htm @php;
    }

    location @php {
        try_files $uri =404;
        include /etc/nginx/fastcgi_params;
        fastcgi_pass 127.0.0.1:9010;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_intercept_errors on;
    }

    location /imagehi\.php\?=.+\.(jpg|jpeg|png|gif) {
        fastcgi_cache MYAPP;
        fastcgi_cache_valid 200 60m;
        # or use proxy_* commands if you use Apache, not FastCGI PHP
    }

    location /imagehi.php\?=([A-Z]|[0-9]|[a-z]|&)+\.(jpg|jpeg|png|gif)$ {
                 expires max;
    }
    location ~ (imagehi\.php\?=.+\.(jpg|jpeg|png|gif))${ {
                 expires max;
    }
    location ^~ \.(jpg|jpeg|png|gif|ico|css|js)$ {
                 expires max;
    }

Comment: `location ^~ \.(jpg|jpeg|png|gif|ico|css|js)$ {` is perfectly useless. `^~` modificator [**forbids**](http://nginx.org/en/docs/http/ngx_http_core_module.html#location) regexp matching so this location could only matches file with weird name `\.(jpg|jpeg|png|gif|ico|css|js)$`, but even this is impossible because every location starts with `/`.
Answer: Convert self answered question to CW
I solved it in php file image.php not in nginx. Solution was in headers i just followed this blog pages
// Return the requested graphic file to the browser
// or a 304 code to use the cached browser copy
function displayGraphicFile ($graphicFileName, $fileType='jpeg') {
    $fileModTime = filemtime($graphicFileName);
    // Getting headers sent by the client.
    $headers = getRequestHeaders();
    // Checking if the client is validating his cache and if it is current.
    if (isset($headers['If-Modified-Since']) && (strtotime($headers['If-Modified-Since']) == $fileModTime)) {

        // Client's cache IS current, so we just respond '304 Not Modified'.
        header('Last-Modified: '.gmdate('D, d M Y H:i:s', $fileModTime).' GMT', true, 304);
    } else {
        // Image not cached or cache outdated, we respond '200 OK' and output the image.
        header('Last-Modified: '.gmdate('D, d M Y H:i:s', $fileModTime).' GMT', true, 200);
        header('Content-type: image/'.$fileType);
        header('Content-transfer-encoding: binary');
        header('Content-length: '.filesize($graphicFileName));
        readfile($graphicFileName);
    }
}


What can a dominant seventh over a submediant chord resolve to?

Question: In this song from Family Guy, a barbershop quartet is singing a song in C major, and they end a phrase on a V7/vi (E7) chord, and proceed to drag that chord out for about one minute (until 1:52), at which point they restart the harmony with a tonal chord.
This has been bugging me for a while, and I've been wondering what that particular chord can resolve to that would make sense for the song if it hadn't been dragged out like that. So far I think it would be a IV (F) chord, but I'd like to know if there's anything else that it could be.
Comment: It's  a secondary dominant chord so you use the chord of what you are tonizing which in this case is A minor.
Answer: The resolution to vi (E7 => Am in the key of C) is the most obvious one. It represents a tonicization of the relative minor key (A minor in the key of C). A very common alternative would be the resolution to IV, as pointed out by you and in ttw's answer. This is a deceptive cadence, where a dominant seventh chord does not resolve to its related tonic chord, but to the superdominant. In this case the deceptive resolution must be interpreted in the key of A minor (E7 => F). A deceptive cadence in C major would be G7 => Am.
I do not doubt that other possibilities may exist, but these two are by far the most common resolutions.
Comment: The reason I think a deceptive cadence would work better than a perfect one is because of the song's tendency to avoid minor chords whenever possible — In every place where a ii (Dm) chord might go, a V/V (D) is used instead, and even the few chords that are based on an A (like the "pro" in "procedure" at 0:17 or so) have the C raised to a C#, so it's a V/ii or even V/V/V (A) rather than a vi (Am) outright.
Comment: A funnier progression would be VII(b3)(b7) second inversion (f, a flat, b, d flat) which could be interpreted as an inversion of German diminished (extra credit: resolving to iv second inversion instead of I!) or as the tritone substitute of V (in which case I should call the chord bII first inversion).
Answer: V7 of vi resolves nicely to vi or vi7 or VI or VI7 or your suggestion of iv or IV.


Isso é uma property, atributo de classe ou o quê?

Question: Tenho isso em meu código:
public ICommand ChangePositionCommand => new Command((obj) =>
        {
            _positionIndex++;
            if (_positionIndex >= Positions.Count)
                _positionIndex = 0;
            Position = Positions[_positionIndex];
            RaisePropertyChanged(nameof(Position));
        });

posso afirmar que isso é um atributo de classe, uma property ou o que?
Comment: Veja a edição da resposta.
Answer: A resposta original está abaixo e está errada porque a forma nova de escrever deu margem para entender errado (ninguém mais percebeu - curioso como coisas certas recebem negativos e as erradas não). A certa é:
Isso é uma propriedade. É bem óbvio, não tem parênteses, e todo método tem seu identificador seguido de parênteses. Como isto poderia ser um método?
Essa é uma propriedade que está sendo inicializada com um valor, no caso uma lambda e que você só pode pegar este valor já que não foi criado nem um getter nem um setter. Neste caso o compilador cria o getter para acessar este valor, caso contrário seria melhor eliminar tudo já que seria inacessível.
Veja como realmente é assim no SharpLab.
Não deixa de se transformar em um método get, mas no seu código é uma propriedade.
Eu ainda acho que poderia ser feito de forma mais simplificada, mas deve ser exigência de algum framework.

Isso é um método. O uso da notação => neste caso não é adequada já que existe mais de uma linha efetivamente, embora seja um único statement.
Tenho dúvidas se o código assim é necessário ou deveria ser desta forma, mas não é possível afirmar sem contexto.
Mais legível:
public ICommand ChangePositionCommand {
    return new Command((obj) => {
        _positionIndex++;
        if (_positionIndex >= Positions.Count)
            _positionIndex = 0;
        Position = Positions[_positionIndex];
        RaisePropertyChanged(nameof(Position));
    });
}

Coloquei no GitHub para referência futura.
Atributo garanto que não é.
Comment: Maniero, a minha dúvida surgiu devido ao "**;**" ao final com parêntesis após chaves.
Comment: É para finalizar o *statement* da declaração da *lambda*.
Comment: Marquei duas vezes a resposta e não foi. Essa será a terceira.
Answer: Isso é um método GET introduzido nas versões mais recente do C#:
public int X { get {return A + B;}}

Equivale a isso:
public int X => A + B;


Can't access added headers using NGINX auth_request_set

Question: I'm using auth_request along with a proxy cache. The caching itself seems to be working, but I wanted to add an extra layer of visibility by adding a header to the final request with the auth request cache status using $upstream_cache_status in the auth request.
However, I haven't been able to access any of the headers I added using auth_request_set. The $upstream_http_header_name variables always seems to stay empty even if I just add a static header, so this doesn't seem to be related to the $upstream_cache_status itself.
Below is a snippet of some of the relevant config. I'm still very new to NGINX so maybe I'm doing something wrong? Maybe there's another way to get the cache status from an auth_request?
Would appreciate any ideas from folks who are more experienced and knowledgeable. Thanks!
    location @request {
      auth_request /auth;

      auth_request_set $cache_status_auth $upstream_http_r_cache_status_auth;
      auth_request_set $test $upstream_http_test;
      ...
    }

    location /auth {
      internal;
      proxy_pass http://host.docker.internal:58090/$auth_query;
      proxy_pass_request_body off;
      proxy_cache auth_cache;
      proxy_cache_key "$auth_query";

      proxy_cache_use_stale error timeout updating http_502 http_503 http_504;
      proxy_cache_background_update on;
      proxy_cache_lock on;
      proxy_cache_lock_timeout 1s;
      proxy_http_version 1.1;
      proxy_set_header Connection "";

      # FIXME: this doesn't seem to actually work. $upstream_http_r_cache_status_auth doesn't end up getting populated?
      add_header r-cache-status-auth $upstream_cache_status;
      # FIXME: even this doesn't seem to work? nothing in $upstream_http_test either.
      add_header test "test";
    }

Comment: Take a look at this https://serverfault.com/questions/954333/nginx-upsteam-cache-status-custom-header-will-not-appear
Comment: Hmm would that explain why the $upstream_http_test variable also ends up being empty, even though it's just adding a static header?
Answer: auth_request_set variables are not accessible inside location blocks, but are available inside access_by_lua:
  access_by_lua_block {
    ngx.header["R-CACHE-STATUS-AUTH"] = ngx.var["upstream_cache_status"]
  }


How do I render a form?

Question: What is the alternative to drupal_get_form('user_login'). in Drupal 8?
I am using the following code in theme_name.theme, but it doesn't work.
// Include namespace for userLoginForm.
use \Drupal\Core\core\modules\user\src\Form;

function MYTHEMENAME_preprocess_page(&$variables) {
  $form = UserLoginForm::create();
}

Answer: drupal_get_form() has been replaced by the form builder service, e.g.:
$form = \Drupal::formBuilder()->getForm(\Drupal\user\Form\UserLoginForm::class);

See the Change Record for more details.
Actually, don't - that change record is incorrect. It'll tell you to pass the form ID, when in fact you need to pass the class string.
Answer: You can create a form under form folder . And then you can call your form anywhere and pass the paramater as shown.
Drupal 7 : $form = drupal_get_form('form_id',$parameter);
Drupal 8 : $form = \Drupal::formBuilder()->getForm('Drupal\custom_module\Form\CustomModuleForm',$parameter);
Comment: How to get a node add form, for eg: add article form (/node/add/article) ?
Comment: +1, you can pass it without $parameter in controller as well.
Answer: There are two options to return(D8) or render(D7) a form. These are \Drupal::formBuilder()->getForm and Drupal::formBuilder()->buildForm. I use \Drupal::formBuilder()->getForm as below.
Use this if you are not passing a parameter:
$form = \Drupal::formBuilder()->getForm('\Drupal\example\Form\ExampleForm');
return $form;

Use this if you are passing a parameter:
$parameter = "your_parameter";
$form = \Drupal::formBuilder()->getForm('\Drupal\example\Form\ExampleForm', $parameter);
return $form;
//pass to formbuild function
public function buildForm(array $form, FormStateInterface $form_state, $parameter = NULL){//form code}

Drupal 7 Equivalent of the above:
$parameter = 'your_parameter';
$form = drupal_get_form('form_id', $parameter);
print drupal_render($form);
//pass to form function
function form_id ($form, &$form_state, $parameter){//form code}

Cheers. Let me know if it helps.
Comment: Gosh, it took me ages again, although you even cover this in your answer, that the additional parameter passed to `buildForm` must always be initiated with `NULL`.
Answer: The documentation does allow an instance of the class as well. So
$formObj = new \Drupal\demo\Form\MyForm();
$form = \Drupal::formBuilder()->getForm($formObj);

is also correct.
Comment: Probably don't do this. In case the form class uses dependency injection, you've circumvented it here. Better off to let the form builder instantiate the class unless you have a good reason to do so.
Answer: Ok if all else fails here is a sneaky trick by setting a new form state object.
use Drupal\Core\Form\FormState;
...

$form_state = new FormState();
$form_state->set('name', $name);
$form_state->set('user', $user);
$render_array = \Drupal::formBuilder()->buildForm('\Drupal\mod\Form\MyForm', $form_state);
...
// Example render.
$response = new AjaxResponse();
// Show a dialog box.
$dialogText['#attached']['library'][] = 'core/drupal.dialog.ajax';
$response->addCommand(new OpenModalDialogCommand("Dialog Title", $render_array, ['width' => '300']));
return $response;

... then in your form method buildForm  you can then...
 // Get form state.
 $name = $form_state->get('name');
 if (!empty($name)) {
    $form['name'] = [
      '#type' => 'item',
      '#markup' => $name,
    ];
  }

Answer: Assuming the below is your form class
namespace Drupal\demo\Form;
use \Drupal\Core\Form\FormBase;
class MyForm extends FormBase {
}

You have to create a new instance from your form class first, and pass it to formBuilder's getForm.
$form_obj = new \Drupal\demo\Form\MyForm();
$form = \Drupal::formBuilder()->getForm($form_obj);

Comment: You don't "have to create a new instance" - this is wrong. You should be passing the class string.

How do I render a form?


The 'sine and cosine theorem' - formulas for the sum and difference

Question: I've read somewhere that the sine and cosine functions can be fully described by this theorem:

$\sin(0) = 0, \cos(0) = 1$
$\sin(a-b) = \sin(a)\cos(b) - \sin(b)\cos(a)$
$\cos(a-b) = \cos(a)\cos(b) + \sin(a)\sin(b)$
There is na $r>0$ such that:
$$0<\sin(x)<x<\tan(x), x \in(0, r), \tan(x) = \frac{\sin(x)}{\cos(x)} $$

With this theorem, we can prove things like:

$\sin^2(x) + \cos^2(x) = 1$ by doing $\cos(a-a) = \cos(a)\cos(a) + \sin(a)\sin(a)$
$\sin(-x) = -\sin(x)$ by doing $\sin(0-x) = \sin(0)\cos(x) - \sin(x)\cos(0)$
$\cos(a+b) = \cos(a)\cos(b) - \sin(a)\sin(b)$ by doing $\cos(a-(-b)) = \cos(a)\cos(-b) + \sin(a)\sin(-b)$
$\sin(a+b) = \sin(a)\cos(b)+\sin(b)\cos(a)$  by doing $\sin(a-(-b)) = \sin(a)\cos(-b) - \sin(-b)\cos(a)$

And other trigonometric identities that also follows from what I've already done.
The problem is that there are many definitions for the sine and cosine function. Let's begin by the classical definition:
Classical Definition
The sine function is defined as the ratio between the opposite side of the angle, and the hipotenuse of this right triangle.
The cosine function is defined as the ratio between the adjacent side of the angle, and the hipotenuse of this right triangle.
The tangent function is defined as the ratio between the sine function and the cosine function (with $\cos (x) \neq 0)$
The other trigonometric identities can be proven geometrically for an angle less than or equal $\frac{\pi}{2}rad$ because it's a right triangle. So, we can't prove $\sin(a-b)$ geometrically and then prove $\sin(a+b)$ analytically like I did, because we assumed a negative $b$, something that's not defined geometrically in the right triangle.
The identity $\sin^2(x) + \cos^2(x) = 1$ can be proven with a simple pythagorean theorem in a triangle with hypotenuse 1.
The formulas for the sum and difference of sines and cosines can be proven geometrically like in this images I found in this answer:

Unit circle definition
Imagine a circle centered at the origin of the cartesian plane, then:

The sine function for an $x \in R, x>0$ can be defined as the $y$ position of point of the circle where the angle stops if we travel anti-clockwise inside the circle's line.
The cosine for an $x \in R, x>0$ function can be defined as the $x$ position of point of the circle where the angle stops if we travel anti-clockwise inside the circle's line.
We can make the same definition for negative angles, so for an $x \in R, x<0$ the same holds, but we're know travelling clockwise.
The tangent function is defined as the ratio between the sine function and the cosine function (with $\cos (x) \neq 0)$
Then, we can define these functions for all real numbers, since when we travel $2\pi$ we get back to the initial point. So we defined sine and cosine as periodic functions.
Open question: How do I prove, with the unit circle periodic definition and without being circular, the $\sin(a-b)$ and $\cos(a-b)$ formulas? (same for $\sin(a+b)$ and $\cos(a+b)$.
Taylor Series definition
$$\sin x = \sum^{\infty}_{n=0} \frac{(-1)^n}{(2n+1)!} x^{2n+1}$$
$$\cos x = \sum^{\infty}_{n=0} \frac{(-1)^n}{(2n)!} x^{2n}$$
$$\tan x = \sum^{\infty}_{n=1} \frac{B_{2n} (-4)^n (1-4^n)}{(2n)!} x^{2n-1}$$
Here, in the same question, there's an analytic proof of the trigonometric identites, for these sums.
What's the best definition for calculus?
Well, in calculus we use trigonometric functions a LOT: in integral substitutions, in series, taylor series (like the ones I showed now), derivatives, convergence tests (like the Euler onde in the basel problem) and other things...
All the definitions I see, are kinda circular or not rigorous enough to make me feel good taking some derivatives or integral substitution, because I always care about the domain of these things. So I want to define it very nicely and be able to use all the trigonometric identities.
I've seen many geometrical proofs of $\sin(a-b)$, $\sin(a+b)$, $\cos(a-b)$, $\cos(a+b)$ using a right triangle and then suddenly the person starts using this formula for all real numbers. I need a complete definition of the trigonometric functions that works periodically and for all reals. The taylor series definition seems good but they're generated using trigonometric identities that are not yet proven (assuming this definition).
ps: I know that I used some primitive words in some definitions, like 'travel' so I let them in emphasis, but I hope you guys understand. And sorry by the long post, but I needed to do it, because I've never seen a complete definition in any book. Thanks.
Comment: Wow I've never noticed before that $\cos(x-x)=\cos^2 x+\sin^2 x$. How nice!
Comment: @NotNotLogical The beauty of it is that they don't need need to know. The function $f(x):=\int_{0}^{x}\frac{1}{u^2+1}du$ simply presents itself as an interesting function to define and study because its integrand is a basic rational function, yet this integrand's integral is *not* a rational function. It's a function that arisces out of necessity because without you cannot integrate all rational functions. That makes its properties worth studying. The recognition that it has properties of the familiar trig function comes later.
Comment: A derivation of the difference law for cosine using the unit circle can be found [here](http://chc.wrdsb.ca/sites/chc.wrdsb.ca/files/3U%20trig%20sum%20and%20difference.pdf).
Comment: @DavidH How do they know what integral to use if they haven't proved the derivative of sine and cosine yet? Starting by defining the _inverse_ trig functions in terms of _integrals_ would even be a little to abstract for me :)
Comment: What is the definition being applied to in calculus? Context is important.
Comment: The integral definitions of the inverse trig functions arise quite naturally in the development of beginning calculus, as is the integral definition of the logarithm.
Answer: The standard definition of the trig functions is in terms of a unit circle.  The classical definition in terms of right triangles is more limited in terms of scope.  For this reason in Calculus the more robust definition in terms of the unit circle is used.  From this 'standard' definition every identity about the trigonometric functions can be proven.
In your post above you gave the definition in terms of the unit circle, but you left what I think is an important point.  When defined in terms of the unit circle the trig functions are 'real valued'.  What we mean here is that they are defined in terms of a distance and not some constructed idea called an angle.  So let me begin with the definition in terms of the unit circle, then we will move to the sister proof to the one given above for the sine of a difference. From this we can establish the other three identities.

 Consider the unit circle
$$ \begin{equation}x^2+y^2 = 1 \end{equation} $$
Starting at the x-intercept (1,0) we travel a distance t around the circle in a counter-clockwise direction (a clockwise movement would be assigned a negative sign).  Once we travel a distance t around the circle we end at a point P(x,y) on the circle.  We then define
$$ \begin{eqnarray} \cos t = x \\ \sin t = y \end{eqnarray} $$

  It then turns out that we can return to angles by noting that on the unit circle the radian measure of the central angle subtended by the arc of length t is equal to t.  But we don't need to ever actually return to angles.  Our definition stands on its own.  Now an immediate consequence of our definition is the familiar Pythagorean identity for sine and cosine.
$$\begin{equation} \cos^2 t + \sin^2 t = 1 \end{equation} $$
(This is obtained by substituting sine and cosine into the unit circle equation for x and y.)
Before we move onto the identity you asked about first let us notice that the sine and cosine functions are periodic.  IE.
$$ \cos(a + 2k \pi) = \cos a $$.  I believe this is pretty clear because any trip around the circle will take you back to where you started.  Make that trip k times and you are still back where you started.  For this reason as mentioned above we can assume both angles are in$$ [0, 2 \pi)$$.
Also note that
$$\cos (-t) = \cos t $$ for all real numbers t.
  The last thing to address is that rotation is a rigid transformation.  In other words when we rotate the plane about a point, the distance between two points before rotation is the same after rotation.
Now we return to the problem.  Show that
$$\cos(a-b) = \cos a \cos b + \sin a \sin b $$
Without loss of generality assume $$0<b<a<2 \pi $$
(the case of b=0 is trivial, as is the case of a = 2 $\pi$, and the case a=b, you can verify these yourself)

We now consider the points (see diagrams) P($\cos a, \sin b)$ and Q($\cos b, \sin b)$ on the unit circle.  We can use the distance formula to find the length of segment PQ.  We then rotate the entire plane clockwise through a distance b along the circumference of the circle (or through an angle with radian measure b).  This will place point Q at Q`(1,0) and P will now be a distance b-a along the circle from (1,0) so it will be at P`($\cos(a-b), \sin(a-b))$.  We now proceed to use the distance formula.  Since distance is preserved through rotation segment PQ and segment P`Q` will have the same length.
$$\begin{eqnarray} \sqrt{(\cos a - \cos b)^2 + (\sin a - \sin b)^2} = \sqrt{(\cos(a-b)-1)^2 + (\sin(a-b) - 0)^2} \\ \cos^2 a - 2 \cos a \cos b + \cos^2 b + \sin^2 a - 2 \sin a \sin b + \sin^2 b = \cos^2(a-b) - 2 \cos(a-b) + 1 + \sin^2(a-b) \\ \cos^2 a + \sin^2 a +  \cos^2 b + \sin^2 b - 2 \cos a \cos b - 2 \sin a \sin b = \cos^2(a-b) + \sin^2(a-b) + 1 - 2 \cos(a-b) \\ - 2 \cos a \cos b - 2 \sin a \sin b = - 2 \cos(a-b) \\ \cos a \cos b  \sin a \sin b =  \cos(a-b) \end{eqnarray} $$
 Now I assumed $b<a$, is that ok?  The answer is yes but you might want to answer why.
 Armed with the cosine of the difference formula we can now prove the following.
$$ \begin{eqnarray} \cos(a+b) = \cos(a-(-b)) = \cos a \cos(-b) - \sin a \sin(-b) \\
= \cos a \cos b - \sin a \sin b \end{eqnarray} $$
The last step in the equality comes from our identity for $\cos(-t)$ above and the fact that $\sin(-t) = -\sin(t) $ as was mentioned in the previous post.
 Now we can show that $\cos(\frac{\pi}{2} - x) = \sin x$ and in a similar manner to the problem above that $\sin(\frac{\pi}{2} - x) = cos x$.  These are your familiar co-function identities.  Finally armed with these equations we can now demonstrate the sine of a difference which can then prove the sine of a sum formula.
$$ \begin{eqnarray} \sin(a-b) = \cos(\frac{\pi}{2} - (a-b)) \\ = \cos((\frac{\pi}{2} -a) + b) \\ = \cos(\frac{\pi}{2} -a) \cos b - \sin(\frac{\pi}{2} -a) \sin b \\ = \sin a \cos b - \cos a \sin b \end{eqnarray} $$
And so there we have it. I apologize if the formating is off a bit, still getting used to the system.  But now from this identities you can prove most any other basic identity involving the trig functions.  All of your double and half angle formulas and your sum-product and product-sum formulas.
Comment: Seems like I can't get the images to show up properly.  They do lend to understanding the proof.  So I will see if I can get them to work.
Comment: I read the definitions in the original problem statement, such as "point of the circle where the angle stops if we travel anti-clockwise inside the circle's line", as definitions in terms of distance (or more precisely, directed length of a path along the circle's circumference), so I didn't think this part of the definition was "left out." I suppose one _could_ read the phrase "inside the circle's line" differently.
Comment: @David I was commenting towards the OPs definition.  Since the definition he gave never mentioned distance explicitly, I chose to go with that definition first so that the remainder of my discussion and it generality would be clear.
Answer: I. I think that, at the point you're at, you'll be most satisfied at first with a development of the theory of trigonometric functions that starts with geometric considerations and builds up from there.  For this I know two approaches:
First, you can start with ratios of sides in right triangles, defining the functions first for acute angles and then extending them carefully to larger domains.  The only place I've seen this done in detail is the little book Trigonometry, by Gelfand and Saul, which I highly recommend (even though it's a textbook for children).  One very nice feature is that they give the right reasons for choosing the extensions they do — e.g., they justify the extension of sine from $[0^\circ,90^\circ]$ to $[0^\circ,180^\circ]$ by noting that it's the only way for the law of sines to be correct also for obtuse triangles.  The addition law is Ptolemy's theorem, for some range of angles, and then the extensions are chosen to make it valid everywhere.
Alternatively, you can derive an integral formula for the area of a circular sector, then use that function to define sine and cosine.  This is done carefully in chapter 15 of Spivak's Calculus.
II. Now, once you've got everything on a firm foundation like that, you can renovate: choose some proved property of sine and/or cosine which completely determine those functions, take it as a new definition of those functions, and rebuild the theory on that basis.  Of course, this only makes sense when you already know that the functions you're interested in have those properties (because you proved it from the old definition), since otherwise you're left wondering how we know that these newly defined functions are the same ones as the ones we already knew — but internally it holds up by its own logic.  Sometimes this kind of renovation can make the theory more elegant, sometimes it allows the use of the functions in a new context where the old definition is nonsensical, sometimes it's just neat.  Here are a few such properties:
First, sine is the only function $f$ satisfying

$f''=-f$
$f(0)=0$
$f'(0)=1$

(See Spivak's Theorem 4.  He proves the addition law not from his definition, but from these properties, quite tidily indeed.  You could view his definition as merely a technical matter of showing that some function having these properties exists, which could also be handled by the theory of differential equations.)
Second, you can define sine and cosine by their power series.  This is a very good approach if you're going to use them with complex numbers.
Third,
$$ \sin x = \frac{e^{ix} - e^{-ix}}{2i} $$
so if you've defined the complex exponential somehow, you can get the trig functions.  (Of course defining the complex exponential involves much the same types of considerations.)
Fourth, given a positive real number $p$, there is exactly one pair of functions $S,C$ satisfying

$C(x-y)=C(x)C(y)+S(x)S(y)$
$S(p)=1$
$S(x)\ge 0$ for all $x\in [0,p]$.

This is the main result of G. B. Robison, "A New Approach to Circular Functions, $\pi$ and $\lim (\sin x)/x$", Math. Mag. 41 (1968), 66–70 (jstor).  Taking $p=\frac\pi2$ yields the usual sine and cosine functions.  (Actually the author suggests first taking $S$ and $C$ to be the functions obtained with $p=1$, and then defining $\pi = 2\lim_{x\to 0} S(x)/x$.)  The paper proves all the usual basic trigonometric identities along the way — except, of course, for the identity for $\cos(x-y)$, since that's the definition!
Robison refers to a slightly earlier paper (W. F. Eberlein, "The Circular Function(s)", Math. Mag. 39 (1966), 197–201) which essentially defines arctan first (by an integral, as suggested in comments), then uses it to define the function which would usually be written $x\mapsto e^{ix}$, and thence sine and cosine.
III. You asked specifically how to prove the addition formulas from the unit circle definition.  My favourite (but not quite fully rigorous) method is this: the unit circle definition amounts to saying that if $R_\theta$ denotes counterclockwise rotation about the origin by $\theta$ radians then
$$ R_\theta\left[\begin{matrix} 1 \\ 0 \end{matrix}\right]
= \left[\begin{matrix} \cos\theta \\ \sin\theta \end{matrix}\right] $$
With a little geometry you can show also that
$$ R_\theta\left[\begin{matrix} 0 \\ 1 \end{matrix}\right]
= \left[\begin{matrix} -\sin\theta \\ \phantom-\cos\theta \end{matrix}\right] $$
You can prove that $R_\theta$ is linear (say, because it's an isometry that fixes the origin).  So it has a matrix, and the above two statements show that this matrix is
$$ \left[\begin{matrix} \cos\theta & -\sin\theta \\
\sin\theta & \phantom-\cos\theta \end{matrix}\right] $$
Now, it's intuitively obvious that $R_{a+b}=R_a\circ R_b$; therefore
$$
\left[\begin{matrix} \cos (a+b) & -\sin (a+b) \\
\sin (a+b) & \phantom-\cos (a+b) \end{matrix}\right]
=
\left[\begin{matrix} \cos a & -\sin a \\
\sin a & \phantom-\cos a \end{matrix}\right]
\left[\begin{matrix} \cos b & -\sin b \\
\sin b & \phantom-\cos b \end{matrix}\right]
$$
Multiplying the matrices on the RHS and identifying corresponding entries gives you the addition formulas.  [Edit: And, of course, this is in the linked question.]
Comment: Very neat, congratulations. Reference you suggests are indeed quite good too.
Answer: My recollection from high school math is that for calculus, we relied on the unit-circle definition, which agrees with the classical definition of sine and cosine for angles in the range $[0, \pi/2]$ as long as you accept that the measure of the angle is the same as the length of the intercepted arc.
On the unit circle, traveling a distance $2\pi$ brings you back to your starting point, so you can show that if $\sin \theta = y$, then  $\sin (\theta + 2n\pi) = y$ for any integer $n$. You can then show by means of congruent triangles (reflected across the $x$-axis) that $\sin(-x) = -\sin x$ for any real number $x$.
So without loss of generality, in evaluating $\sin(a - b)$
we can assume that $-\pi < a - b \le \pi$.
We can easily solve the cases $a - b = 0$ and $a - b = \pi$.
Moreover, whenever $-\pi < a - b < 0$,
we can use the fact that $\sin(a - b) = -\sin(b - a)$, so really we only need to
find the formula for $\sin(a - b)$ in the case where  $0 < a - b < \pi$.
Let $O$ be the center of the circle, let $A$ be the point you reach after traveling the distance $a$ counterclockwise on the circle, and let $B$ be the point reached after traveling distance $b$.  Then $\triangle AOB$ is a triangle whose angle at $O$ is $a - b$.
We now apply the following transformation to the $x$ and $y$ coordinates of $A$ and $B$:
\begin{eqnarray}
x \rightarrow  x \cos b + y \sin b, \\
y \rightarrow  y \cos b - x \sin b.
\end{eqnarray}
Let $A'$ and $B'$ be the points whose coordinates are produced by applying this transformation to the coordinates of $A$ and $B$, respectively.
Since the coordinates of $B$ are $(\cos b, \sin b)$, we can show that the coordinates of $B'$ are $(1, 0)$.
We can use the Pythagorean formula on pairs of coordinates to prove that the distance from $O = (0,0)$ to $A'$ is $1$, and that the distance from $A'$ to $B'$ equals the distance from $A$ to $B$, and now we know that the triangles $\triangle AOB$ and $\triangle A'OB'$ are congruent.  Therefore the angle at $O$ in $\triangle A'OB'$ has measure $a - b$.
Meanwhile, we can find that the $y$-coordinate of $A'$ is $\sin a \cos b - \cos a \sin b$.
It just remains to show that  $\triangle AOB$ and $\triangle A'OB'$ have the same orientation (so that $A'$ is above the $x$-axis), which you can do by applying a formula on the coordinates of the vertices of a triangle that gives the triangle's orientation (that is, the outcome is multiplied by $-1$ if you reflect the triangle), or by other knowledge of isometries.  Once we know this, we have shown that
\begin{equation}
\sin(a - b) = \sin a \cos b - \cos a \sin b.
\end{equation}
A similar procedure works for the cosine difference formula, though in this case we don't have to show that $A'$ is above the axis:
\begin{equation}
\cos(a - b) = \cos a \cos b - \sin a \sin b.
\end{equation}
For $\sin(a + b)$ and  $\cos(a + b)$, just substitute $-b$ for $b$ in the formulas already known.
Answer: I created this shortcut proof for the cos addition formula, it uses the cosine and sine formula
The proof I know usually involves complex triangle shapes, so I'll be working with a basic triangle here

$a+b+c = \pi$, and $c = \pi -(a+b)$
$$ C^2 = A^2+B^2-2AB\cos{c}$$
$$ C^2 = A^2+B^2-2AB\cos{(\pi-(a+b))}$$
$$\frac{C^2}{A^2} = \frac{A^2}{A^2}+\frac{B^2}{A^2}-2\frac{AB}{A^2}\cos{(\pi-(a+b))}$$
$${\frac{C}{A}}^2 = 1+{\frac{B}{A}}^2-2\frac{B}{A}\cos{(\pi-(a+b))}$$
$$\frac{\sin{a}}{A} = \frac{\sin{b}}{B} = \frac{\sin{c}}{C} $$
$$\frac{\sin^2{c}}{\sin^2{a}} = 1+\frac{\sin^2{b}}{\sin^2{a}}-2\frac{\sin{b}}{\sin{a}}\cos{(\pi-(a+b))}$$
$$\sin^2{c} = \sin^2{a} \cdot ( 1+\frac{\sin^2{b}}{\sin^2{a}}-2\frac{\sin{b}}{\sin{a}}\cos{(\pi-(a+b))} )$$
$$1-\sin^2{c} = 1-\sin^2{a} \cdot ( 1+\frac{\sin^2{b}}{\sin^2{a}}-2\frac{\sin{b}}{\sin{a}}\cos{(\pi-(a+b))} )$$
$$\cos^2{c} = 1-\sin^2{a} \cdot ( 1+\frac{\sin^2{b}}{\sin^2{a}}-2\frac{\sin{b}}{\sin{a}}\cos{(\pi-(a+b))} )$$
$$\cos^2{c} = 1-\sin^2{a}-\sin^2{b}+2\sin{a}\sin{b}\cos{c}$$
$$\cos^2{c} - 2\sin{a}\sin{b}\cos{c}+\sin^2{a}+\sin^2{b}-1 = 0$$
$$\cos{c} = \frac{ 2\sin{a}\sin{b} \pm \sqrt{ (2\sin{a}\sin{b})^2-4(\sin^2{a}+\sin^2{b}-1) } }{2}$$
$$\cos{c} = \frac{ 2\sin{a}\sin{b} \pm \sqrt{ 4\sin^2{a}\sin^2{b}-4\sin^2{a}-4\sin^2{b}+4 } }{2}$$
$$\cos{c} = \frac{ 2\sin{a}\sin{b} \pm 2\sqrt{ \sin^2{a}\sin^2{b}-\sin^2{a}-\sin^2{b}+1 } }{2}$$
$$\cos{c} = \frac{ 2\sin{a}\sin{b} \pm 2\sqrt{ (1-\sin^2{a})(1-\sin^2{b}) } }{2}$$
$$\cos{c} = \frac{ 2\sin{a}\sin{b} \pm 2\sqrt{ \cos^2{a}\cos^2{b} } }{2}$$
$$\cos{c} = \sin{a}\sin{b} \pm \cos{a}\cos{b}$$
$$\cos{(\pi-(a+b))} = \sin{a}\sin{b} - \cos{a}\cos{b}$$
$$-\cos{(a+b)} = \sin{a}\sin{b} - \cos{a}\cos{b}$$
$$\cos{(a+b)} = \cos{a}\cos{b}- \sin{a}\sin{b}$$
Comment: You and I have very different definitions of the term "shortcut". ;)   (Admittedly, I'm biased. The geometric proof quoted by OP [is mine](https://math.stackexchange.com/a/1342/409).) ... Style quibbles aside,  you need to justify changing "$\pm$" to "$-$" towards the end.
Comment: @Blue that is very brilliant, I've seen the image on Wikipedia before.. didn't know it was create by you,
Comment: I think you should see [this](https://math.stackexchange.com/questions/2387711/circle-and-rectangle-solving-systems-of-nonlinear-equation\)
Answer: The most straightforward definition is from $e^z$.
First define $e^z = \sum_{k=0}^\infty \frac{z^n}{n!}$, and prove that $e^{z+z'}=e^ze^{z'}$ using a Cauchy product. You also get at once that the derivative of $e^z$ is $e^z$.
Define $\cos z = \frac{e^{iz}+e^{-iz}}{2}$, $\sin z = \frac{e^{iz}-e^{-iz}}{2i}$, and similarly $\cosh z = \frac{e^{z}+e^{-z}}{2}$, $\sinh z = \frac{e^{z}-e^{-z}}{2}$. You will have trivially the derivatives of these functions. As a side remark, this eliminates the usual problem with $\lim_{x\rightarrow 0} \frac{\sin x}{x}=1$, when defining trig functions geometrically.
From the formula $e^{z+z'}=e^ze^{z'}$, you can derive most usual trigonometric formulas (except those involving $\pi$, which is yet to be defined). You will get almost the same formulas for hyperbolic trigonometry.
Notice $\cos z$ and $\sin z$ are real valued for real $z$. From series definition you know they are $C^\infty$ on $\Bbb R$, and especially, they are continuous. You have $\cos 0 = 1$ and it's easy to prove that $\cos 2<0$, thus $\cos$ has a root in $]0, 2[$. Similarly you can prove that $\sin x > 0$ in this interval, and from $\cos'=-\sin$, you know $\cos$ has only one root. Call it $\frac{\pi}{2}$ (that is, define $\pi$ to be twice the root). Then from addition formulas, it's easy to prove $\cos$ and $\sin$ are $2\pi$-periodic.
Then you are done with the main properties of these functions. If you like, you can also define $\tan x$ and all other lesser known function (secant, cosecant, cotangent), and derive formulas for $\tan (x+y)$ and alike. And define inverse trig functions (well, strictly speaking, they are inverses of restrictions of trig functions to carefully chosen intervals, so that they are bijective on them), etc.


Split the first and second part of list of list into two sublists

Question: I am facing an issue given below and I want to separate the 0th element and the 1st element in two separate lists. for eg I have a list
a = [[1, 2], [3,4], [5,6], [7,8]]

I want two lists like:
a0 = [1,3,5,7]
a2 = [2,4,6,8]

Can anyone help me with this please?
Comment: Can you show us your attempt and what result you got with your attempt?
Answer: You can use zip
a = [[1, 2], [3, 4], [5, 6], [7, 8]]
a = [[*x] for x in zip(*a)]
print(a[0], a[1]) # [1, 3, 5, 7] [2, 4, 6, 8]

Answer: You can do this -
a = [[1, 2],[3,4],[5,6],[7,8]]
a0 = []
a2 = []
for i in a:
    a0.append(i[0])
    a2.append(i[1])

print(a0)
print(a2)

Answer: Using a list comprehension:
a = [[1, 2],[3,4],[5,6],[7,8]]
a0 = [x[0] for x in a]
a2 = [x[1] for x in a]
print(a0)  # [1, 3, 5, 7]
print(a2)  # [2, 4, 6, 8]

Answer: a = [[1, 2],[3,4],[5,6],[7,8]]
a0 = []
a1 = []

for x in a:
    a0.append(x[0])
    a1.append(x[1])

Answer: use chain to flatten the list, then calculate the middle index, then split it into two lists from the middle index
In [1]: from itertools import chain

In [2]: a = [[1, 2],[3,4],[5,6],[7,8]]

In [3]: flat = list(chain.from_iterable(a))

In [4]: flat
Out[4]: [1, 2, 3, 4, 5, 6, 7, 8]

In [5]: middle = len(flat) // 2

In [6]: first_half = flat[:middle]

In [7]: second_half = flat[middle:]

In [10]: first_half
Out[10]: [1, 2, 3, 4]

In [11]: second_half
Out[11]: [5, 6, 7, 8]

Answer: You can try below code
import numpy as np
a = [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]]
np.array(a).T.tolist()

gives as
[[1, 3, 5, 7, 9], [2, 4, 6, 8, 10]]


openGL ES 2.0. image fit screen in landscape and portrait orientation Android

Question: I start learning openGL ES 2.0. Now i can add texture to objects and create elementary figures(sphere, triangle, cube etc).
But now I have some problem. I have rectangle with texture. It is my target image. And now I want make this image fitted the drawing region in landscape and portrait orientation. Basically images are landscape oriented.
For exaple:

Screen must be without black lines near the borders of screen. When screen change they orientation - image must change size and fit screeen again.
I don't know how implement it on OpenGl on Android. what should I change? parameters of viewport or other parameters? and how i do this?
Answer: You'll want a projection that takes the screen size and orientation into account. For example:
<code>float aspectRatio = width / (float) height;
orthoM(projectionMatrix, 0, -aspectRatio, aspectRatio, -1f, 1f, -1f, 1f);
</code>


A few questions about working with PHP 5.4

Question: I installed PHP 5.4 on Debian from source and I run php scripts on the PHP Built-in web server with new php features without any error but php scripts do not run with apache2 with new php features.
I did not understand the relationship between php and apache2 completely.  So I have a few questions:

I can run php scripts with the built-in php server, so is the built-in web server enough to serve php script without any web server such as apache or nginx ? (If you say no, please explain why. )
How can I use PHP 5.4 with apache2 ?
Why does apache2 not interpret new PHP features even though I installed PHP 5.4 ?
Must I compile apache2 again?  If so, why ?
What is the relationship betwen apache2, mod_php module and php ?
Comment: remaining questions belong on ServerFault IMO.
Comment: *(reference)* [The internal web server is designed for developmental purposes only, and should not be used in production.](http://de2.php.net/manual/en/features.commandline.webserver.php)
Comment: *(reference)* http://php.net/migration54
Answer: I can run php script with built-in php server, so Does built-in web server enough to serve php script without any web server such as apache or nginx ? (If you say no, why? )

Yes, but ONLY for development. The built in server is very primitive and not meant for production in any shape or form.

How can I use php 5.4 with apache2?

Install via your distro package manager (if available in a repo) - or compile it; I'd highly suggest you install the Apache devel headers for your mpm. Look into the configure option '--with-apxs2' in the documentation which takes an extra step out of configuration for apache.

Why apache2 does not interpret new PHP features although that I installed PHP 5.4 ?

If you restarted Apache and it's still running say, 5.3 - then You didn't install or configure it correctly when compiled.

Do I must compile apache2 again , why ?

Not enough information to help you out on this

How does process relation among apache2,mod_php module and php ?

Without being too winded: Apache configuration loads the php module (a mere 'key' mapped to the module) which is a .so file. Then it associates files of the PHP filetype to be processed with that SAPI.


Best service on AWS for collecting user action data

Question: What is the best service on AWS for gathering user action data? Metrics like the number of sessions, unique sessions, duration of sessions, user's search, how are they responding to the value of real-time recommendations, and where do they land.
I'm using Amplify for deploying my application.
So far I thought about extracting these metrics from CloudWatch but I was wondering if maybe there is a service that will help with this. I also looked into AWS pinpoint but I don't think that also is the right tool for what I want to achieve.
Answer: AWS Cloudwatch is most likely the best service for this, since it either has the information already or you can push custom metrics in.
Comment: Do you have any suggestion on how I can extract data I need from Cloudwatch logs?
I read this one articel  but I wa wondering if you know any better way.
https://praveshchhabra.medium.com/data-analysis-on-aws-using-quicksight-8ca033dd3563
Comment: I have not tried to do that so I can't recommend anything. Cloudwatch is the best source for the data, analysis someone else will have to help with.
Answer: Here is AWS support answer to this question:

I would like to inform you that you can Amazon Cloudwatch logs to log
user activity on your application, you can refer to the following
documentation for the same.
[+]
https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/WhatIsCloudWatchLogs.html
CloudWatch Logs enables you to centralize the logs from all of your
systems, applications, and AWS services that you use, in a single,
highly scalable service. You can then easily view them, search them
for specific error codes or patterns, filter them based on specific
fields, or archive them securely for future analysis. CloudWatch Logs
enables you to see all of your logs, regardless of their source, as a
single and consistent flow of events ordered by time, and you can
query them and sort them based on other dimensions, group them by
specific fields, create custom computations with a powerful query
language, and visualize log data in dashboards.
You can also consider using Amazon Timestream to store and analyze
events on your application. You can then ingest this data in
Quicksight to visualize and build dashboard.
[+]
https://docs.aws.amazon.com/timestream/latest/developerguide/what-is-timestream.html#what-is.use-cases
Amazon TimeStream is a fast, scalable, and serverless time series
database service for IoT and operational applications that makes it
easy to store and analyze trillions of events per day up to 1,000
times faster and at as little as 1/10th the cost of relational
databases.


Which tests should I run with one control group and 2 treatment groups?

Question: I'm really bad at stats and am running an experiment looking at growth rate or individuals over the period of 28 days. I collected data on Day 0, 7, 14, 21, and 28 so I have 5 data points. I would like to compare the two to the control group to see if they are statistically different and then compare the two different treatment groups to see if those are statistically different. To clarify, I would really like to look at the rate of growth. What is the best way to organize my data (do I need to subtract subsequent weeks?) and which type of stats tests should I run (one-way ANOVA or two-way i literally have no clue)? Any specifics would be great.
PS-I have access to and some familiarity with JMP and I have StatPlus for XCEL
Comment: The methods that are appropriate here are fairly advanced. Given your evident level of statistical sophistication, you should probably work with a statistical consultant. Such services are often available through your university.
Answer: When you collect data on the same subjects repeatedly you violate the assumption of independent errors that is part of both one-way and two-way ANOVA.  There are various methods for dealing with this including
1) Repeated measures ANOVA (but this makes assumptions that are usually not tenable)
2) Multilevel models
3) Generalized estimating equations.
As @gung notes, these methods are fairly advanced and you probably will need help.
Also ... for the future: The time to figure out how you  will analyze your data (or, at least, how you plan to analyze your data) is before you start collecting it.


DNS update not visible for http?

Question: My website is hosted by provider A. Due to contractual issues I was forced to move the domain to hoster B. B is the new registrar as well.
According to the whois entry the domain was successfully moved to B. Apparently, the DNS server have not updated yet, becasue the old servers are still accessible when typing www.mydomain.com in my browser.
However, when using services such as http://get-site-ip.com/ the retrieved IP points to hoster B. How is this possible? This would mean that the DNS server did update. But why can I still access the old servers with http?
Why are the servers of hoster A still accessible though the website's IP points to my new hoster.
Comment: You use the definite article 'the' as if there was one DNS server; there are millions, although there _should_ be only two (or a handful) that are authoritative and those should update almost instantly, and the (many) others that have cached old data _should_ refresh at or before TTL as discussed in the answer.
Comment: What OS are you using? What DNS is configured?
Answer:
How is this possible?

Caching - (nearly) always caching.
When a DNS request is made, part of the response is the Time To Live(TTL) of the record. The upstream caching DNS server that serviced your request will have looking in it's cache to see if it had a record for example.com. It will have determined that the TTL had not expired and it will have served your request from it's cache.
When you went to get-site-ip.com there are 2 possibilities

it did not have had a record for example.com so it had to look it up.
it does not cache records and looked it up.

In both scenarios, it has to go to the DNS and request the records which are for your new server.
Comment: I refuse to propagate that apocrypha.
Comment: You should probably add that it can take up to 48 hours for DNS to propagate after a change. It all depends on where the server is and how often the cached records are flushed on all the devices between wherever you are and wherever it is. The best thing you can do is on the old Pages put in a forward to the new one based on IP.
Comment: Do you have an external source for that opinion? Every external dns provider I have worked with mentions the delay. I have seen it operationally by checking from geographically separated independent hosts.
Comment: My own testing when I recently moved some systems about. Everything either worked straight away because they had not recently looked up the relevant records or soon after the TTL expired the new addresses were picked up. That's the way the system is designed to work. Granted TTLs can be and are ignored but that's incorrect behaviour. The mantra of 48 hours is just that.
Comment: And my comment is that those hosts that you're checking from are all geographically located in the same place. When I was checking this a few years ago I was checking from places in different countries across oceans.
Comment: No, the testing points were located all over the globe specifically .au, .hk, us California, and New York, .de and .fr for services in .gb and .ca. Can I suggest you go and refresh your understanding of DNS 'propagation'. It's not like ripples from a stone in a pond, it's entirely dependent on TTL and caching.
Comment: I do agree with you that it should not take that long. The part of that is setting the correct customer expectation during the move. That is why I still use that "up to" delay figure.

DNS update not visible for http?


SQL 3 NF normalization

Question: I have a table with 4 columns to display the bill of buying an item, column 1 is the primary key, column 2 and 3 are the price and the amount of the item, column 4 is the sum of the price, which is calculated by multiply the value in column 2 and 3. Do i need to delete column 4 to make sure that there is no transitive functional dependency in the table.
<code>+---------+-------+--------+------+
| bill_id | price | amount | sum  |
+---------+-------+--------+------+
|       1 |     2 |      5 |   10 |
|       2 |     3 |      5 |   15 |
+---------+-------+--------+------+
</code>
Comment: Why would you, or wouldn't you? Where are you stuck in what process? PS The result of a multiplication is a product, not a sum.
Comment: Column 4 is dependent on column 2 and 3, which creates transitive dependency. I don't know if i should delete it or not to satisfy 3NF.
Comment: Please clarify via edits, not comments. And that is no explanation, it isn't reasoned by clear small steps back defintions. And it isn't transitive FDs that are a problem but certain transitive FDs. And you haven't said how you are stuck. Why don't you know? What step of reasoning are you stuck on? Otherwise we don't know what you do or don't understand or misunderstand & what are we supposed to answer? You would be just asking for a tutorial while pretending to have actually tried to answer by giving a guess at something you noticed.
Answer: No, you don't need to. NFs are guidelines - very important and recommended, but just guidelines. While violation of 1NF is almost always a bad design decision, you may choose to violate 3NF and even 2NF provided you know what you are doing.
In this case, depending on the context, you may choose not to have a physycal "sum" column, and have the value calculated on the fly, although this could easily raise performance issues. But please don't even think of creating a new table which would have all possible combinations of quantity and unit price as a compound PK!
If you look at any ERP on the market you will see they store quantity, unit price, and total amount (and much more!) for every line of the quotes, orders, and invoices they handle.

SQL 3 NF normalization


Best practice to handle default_server and public ip in nginx

Question: I have recently created a nginx server on debian 8. It came up with a default config on /etc/nginx/sites-available/default which redirects to an nginx welcome page.
server {
listen 80 default_server;
listen [::]:80 default_server;

root /var/www/html;
index index.php index.html index.htm index.nginx-debian.html;

server_name your_server_ip;

location / {
    try_files $uri $uri/ =404;
}

location ~ \.php$ {
    include snippets/fastcgi-php.conf;
    fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
}

location ~ /\.ht {
    deny all;
}
}

I had added a new production page, say 'example.com' with ssl on it.
In the config for ../example.com, it is not set as the default server.
server {
listen 80;
listen [::]:80;
server_name example.com www.example.com;
return 301 https://$server_name$request_uri;
}

server {

# SSL configuration

listen 443 ssl;
listen [::]:443 ssl;
include snippets/ssl-example.com.conf;
include snippets/ssl-params.conf;
....

Now when I ssl security tested it on https://www.ssllabs.com/ssltest/analyze.html?d=example.com, it got a A+. But it had commented 'Inconsistent server configuration'.
And when I load the ip address, say x.x.x.x on browser as https:// x.x.x.x it loads the same page as of https://example.com but without ssl (green address bar) on it. If i load http:// x.x.x.x it loads the default nginx welcome page.
I tried to set the default config (for ip) to get a forbidden message, I have added the following code
location / {
deny all;
}

Now when I ssl security test the example.com, it says "No secure protocols supported" and no test results appeared.
So my questions are,
What should be done with the default config that comes with nginx which loads for the ip address?
which server_name (config file) should be set as the default_server on 'listen' command?
what should be done with the ip which is currently forwarding https requests to the example domain?
Intended results:-
https:// example.com only should be used to connect to the server and loading ip address can show 'page not found' or 'forbidden', since the example.com will be used for php scripts on it.
SSL tests should give atleast a A rating after the set configuration.
ip address should not accept any connections directly and process it.
Answer: You can have this as your default server block:
server {
    listen 80 default_server;
    listen 443 ssl default_server;

    server_name _;

    ... SSL keys for default server ...

    return 403;
}

This will cause any HTTP connection of which Host: header does not match any other virtual host on the server to return 403 Forbidden error message to the client.
If you use valid SSL keys here for the hostname that does not match any existing hostname, the client will get 403 error page directly. If you use self-signed certificate here, then the user will get an untrusted certificate error message.
Comment: Thank you for the answer. I don't understand the second part, regarding ssl keys. I have ssl certificates for example.com (non self-signed). But no certificates have been setup for ip and else. So should I use the keys for example.com or create (non self-signed) keys for ip?
Comment: Yes, that is what you need, just like in the answer you provided.
Comment: The answer didn't work as expected. ssllabs.com gave a "T" rating for misconfiguration (previously A+) and when loading the production site, its somehow checking ip's self signed with sites' ca signed certificate and throwing a mismatch error. Still unsolved hence.
Comment: Please edit your complete nginx configuration into your question.
Answer: You can use "ssl_reject_handshake on" to reject SSL connection. It's like "return 444" to close connection.
# HTTP:80 = catch-all server block, resulting in a 444 response for unknown domains.
# HTTPS:443 = catch-all server block, resulting in reject SSL connection for unknown domains.

server {
    listen 80 default_server;
    listen [::]:80 ipv6only=on default_server;
    server_name "_";
    return 444; # Connection closed without response
}

server {
    listen 443 default_server;
    listen [::]:443 ipv6only=on default_server;
    server_name "_";
    ssl_reject_handshake on; # Reject SSL connection
}

Answer: Found a usable solution finally. Quora does something like this. To redirect the default to 404.
Source : Properly setting up a "default" nginx server for https
By setting the default config to this.
server {
server_name _;
listen       80  default_server;
return       404;
}

server {
listen 443 ssl;
server_name _;
ssl_certificate /etc/nginx/ssl/nginx.crt;
ssl_certificate_key /etc/nginx/ssl/nginx.key;
return       404;
}

Then make directory for ssl if it doesn't exist
sudo mkdir -p /etc/nginx/ssl

Then create a self signed ssl for the same
sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /etc/nginx/ssl/nginx.key -out /etc/nginx/ssl/nginx.crt

Check for errors and reload nginx to get the 404
nginx -t

sudo sytemctl reload nginx


return only a single of multiple return values in Go

Question: Is there a better way to return only a single of multiple return values?
<code>func makeRune(s string) (r rune) {
    r, _ = utf8.DecodeRuneInString(s)
    return
}
</code>
Comment: If you don't think there could be an error there, I'd recommend capturing it and panicking if you're wrong.  You will otherwise just have confusion when an actual error occurs and you've covered it up because you're sure it can't happen.
Comment: Nope. Why are you ignoring errors?
Comment: The second return value of utf.DecodeRuneInString is the rune length, not an error.  An error condition is actually returned in the first value as the constant utf8.RuneError.  Throwing away the length is fine if you want only a single rune.  If you wish to then obtain the next rune though, the length could come in handy for the expression s[length:].
Comment: This (internal) function exists only to make my code shorter. It is very unlikely to ignore an error in my case. But this should be a general example and not a "how to ignore errors with concise syntax" example ;-)
Comment: What are you looking for as a "better way"? What is it that you don't like here?
Answer: Yes.  You should add a comment for why you are doing this.  Because motives for doing this are often misguided, people will question it, as they have in the comments to your OP.  If you have good reason for writing a function to toss a return value, justify it in a comment.  Perhaps you could write,
<code>// makeRune helper function allows function chaining.
func makeRune(s string) (r rune) {
    // toss length return value.  for all use cases in this program
    // only the first rune needs to be decoded.
    r, _ = utf8.DecodeRuneInString(s)
    return
}
</code>
This also helps code review by following the rule of thumb, "if the comments and the code disagree, both are probably wrong."  If function chaining was not required, the function's whole purpose is questionable.  If your comments suggested you thought you were tossing an error value, that would be a red flag.  If your comments suggested you thought that s could only contain a single rune, that would be a red flag as well.  Given my example comments above, I might read what I had written and decide the function would be better named firstRune.  That carries more specific meaning and avoids suggesting semantics similar to that of the Go make function.


Update field data added in user form using a hook?

Question: I've added three fields in user form.

User code
User name
User ID.

I want to add this field data into the database. My question is, in which hook, i should write the logic of manipulating and saving data.
Comment: How did you add fields to user form? If you used admin interface (admin/config/people/accounts/fields) all information will be automatically stored in the database
Comment: Ya. absolutely correct. But it can be done by new user at time of registration. What i want is, Those accounts which is already their since long, I want to update that one.
Comment: I found solution using user_import module. It worked very well.
Answer: Hook implementation depends on when you want to manipulate the user account data.

Before creation of a new user account, hook_user_insert().
Before updating any user account, hook_user_update().

If you need to update existing users with new data you need your own custom function that makes user of user_load() (to load a user object) & user_save() (to save your manipulated user object with new data).


Drupal Commerce Stock Availability or Out of Stock

Question: I am working on Drupal Commerce website. Using Commerce Stock I am able to manage the inventory but on product details page I want to print the following.
Availability: In Stock
or
Availability: Out of Stock
Also if possible
Availability: Limited Stock
If I am displaying stock filed its showing number of items available in stock, which I don't want to display.
Is there any way in Drupal I can acheive this task?
Comment: how are you displaying your products? Views, node view modes, other?
Comment: Are you working with Drupal 7 Commerce or Drupal 8 Commerce. If you know, please then tag your question with 7 or 8. Thank you.
Answer: On Drupal 7.61 & Commerce Stock 7.x-2.3 I've solved it with hook_commerce_product_reference_default_delta_alter:
<code>/**
 * Implements hook_commerce_product_reference_default_delta_alter().
*/
function test_module_commerce_product_reference_default_delta_alter(&$delta, $products) {

foreach ($products as $product) {
  if ($product->commerce_stock['und'][0]['value'] > 0){
    $product->commerce_stock['und'][0]['value'] = "On stock";
  }else {
    $product->commerce_stock['und'][0]['value'] = "Out of stock";
  }
 }
}
</code>
Answer: You can set these message in STOCK manage display of every product variation type. Store->Configuration->Product variation types->YOUR PRODUCT VARIATION TYPE->Manage display. Change label as above and change format as Show stock display as message .Finally change the message on settings on right side of field.