SEM: How to report latent factor relationships (covariance vs. correlation)?

Question: I would like to report results from SEM I did in R using the lavaan package. I have gotten increasingly confused about how papers use different terms and units to describe latent factor relationships seemingly interchangeably.
Here is a picture of one of the models with a number for each relationship I would like to describe. I know they are not all latent, but I want to make sure I understand all concepts properly. The depicted coefficients are all standardized. I know I will need to report their significance levels in the final report.

I think that number...

1 with the double-headed arrow is a latent covariance. However, I have read that correlation is standardized covariance, which makes me think that this would have to be reported as correlation with the unit r (e.g., r = .30) because it is standardized. But I have also read that standardized values are reported without unit. Which of the options is correct?
2 with the single-headed arrow is a latent correlation and should be reported as r = .86. However, I have seen many papers reporting this as regression instead and call it a beta coefficient (e.g., beta = .86). Is this the same thing?
3 and all other coefficients on this level are factor loadings and should be reported as that without a unit (e.g., "the standardized factor loading of mz was .82").
4 with the double-headed arrow is a covariance, but on a manifest level. I have the same question about this one as for 1, as this is also a standardized value and I might have to report it as correlation instead.

Can someone help me untangle this theoretical mess?
Answer:
Doesn't really matter. A correlation is a covariance. It's more interpretable if you use the correlation. If you want to report the confidence intervan, you should use the covariance though.
It's single headed, it's regression. I don't recall seeign a paper that says that. Your model is drawn strangely - WM is a mediator of the relationship between age and Gf, but that's not clear from the way it's drawn. Typically if it's later in the causal flow it should mov one level.
Yes, but a factor loading is a regression coefficient.
Same answer.

Also, why is age latent?
Comment: Also, why is age **both** latent and observed!?
Comment: Thank you so much! Regarding your answer for 2: You don't recall a paper saying it's regression? Or you don't recall a paper using beta coefficients? Here's an example for the latter: https://doi.org/10.1016/j.intell.2014.05.007
Regarding the latent age variable - yeah, that's wrong and I just changed it. Thanks! I did it because semPaths gave me really messy plots when age was observed, so it's merely a cosmetic thing. Same reason for the not-so-visible mediation.
Comment: ...more specifically: Could you clarify if I should report the regression in (2) with r or with betas or if those two measures are the same thing as long as they are standardized and thus I can choose freely?
Comment: Sorry, don't recall a paper saying a single headed arrow is a correlation. Generally software that draws a plot for you doesn't do a good job.


Variable selection for time covariate

Question: I'm fitting a linear model where the response is a function both of time and of static covariates (i.e. ones that are independent of time). The ultimate goal is to identify significant effects of the static covariates.
Is this the best general strategy for selecting variables (in R, using the nlme package)? Anything I can do better?

Break the data up by groups and plot it against time. For continuous covariates, bin it and plot the data in each bin against time. Use the group-specific trends to make an initial guess at what time terms to include-- time, time^n, sin(2*pi*time)+cos(2*pi*time), log(time), exp(time), etc.
Add one term at a time, comparing each model to its predecessor, never adding a higher order in the absence of lower order terms. Sin and cos are never added separately. Is it acceptable to pass over a term that significantly improves the fit of the model if there is no physical interpretation of that term?.
With the full dataset, use forward selection to add static variables to the model and then relevant interaction terms with each other and with the time terms. I've seen some strong criticism of stepwise regression, but doesn't forward selection ignore significant higher order terms if the lower order terms they depend on are not significant? And I've noticed that it's hard to pick a starting model for backward elimination that isn't saturated, or singular, or fails to converge. How do you decide between variable selection algorithms?
Add random effects to the model. Is this as simple as doing the variable selection using lm() and then putting the final formula into lme() and specifying the random effects? Or should I include random effects from the very start?. Compare the fits of models using a random intercept only, a random interaction with the linear time term, and random interaction with each successive time term.
Plot a semivariogram to see if an autoregressive error term is needed. What should a semivariogram look like if the answer is 'no'? A horizontal line? How straight, how horizontal? Does including autoregression in the model again require checking potential variables and interactions to make sure they're still relevant?
Plot the residuals to see if the variance changes as a function of fitted value, time, or any of the other terms. If it does, weigh the variances appropriately (for lme(), use the weights argument to specify a varFunc()) and compare to the unweighted model to see if this improves the fit. Is this the right sequence in which to do this step, or should it be done before autocorrelation?.
Do summary() of the fitted model to identify significant coefficients for numeric covariates. Do Anova() of the fitted model to identify significant effects for qualitative covariates.
Answer: Fully data-driven model selection will result in standard errors and P-values that are too small, confidence intervals that are too narrow, and overstated effects of remaining terms in the model.
For time effects I usually model using restricted cubic splines.  A detailed case study in the context of generalized least squares for correlated serial data may be found at http://biostat.mc.vanderbilt.edu/RmS - see the two attachments at the bottom named course2.pdf and rms.pdf.  This uses the R rms package.  The case study contains information about the choice of basis functions for the time component.
Comment: @Frank H: In the presence of static covariates you are suggesting that we condition their coefficients on a deterministic impact of "memory" or "time".There are two diametrically different ways of conditioning or adjusting for "memory" or "time". The second approach would be to use a suitable lag structure for the Y variate as causative/support variables. I have found that trying both ways i.e. conditioning upon dummy time trends/level shifts vs lagged memory,one can determine an optimal strategy to evaluate the significance of the static covariates.
Comment: That is one time series approach to the problem.  For many (but not all) problems it is simpler and just as well-fitting to use a "forward look" approach where between-time correlations are described in the covariance/correlation matrix for a vector of y values across time.  What I've described is the basis for mixed effects models, generalized least squares, and GEE.
Comment: Yes I think you are right if there are time-varying covariates.  But the statement of the problem explicitly used the phrase "static covariates".  In that setting there are two ways to model the dynamic response variable y - the way you've suggested and by specifying the mean profile function and correlation functions.
Comment: I may be not understanding where you're coming from, but a serial data model handles the correlation structure through a specific correlation function (usually) of the absolute difference between two times.  For example it is common to use the continuous time AR1 correlation structure.  You don't actually need to form lags to carry out the analysis using generalized least squares or mixed effects models.  I specify the mean time profile through fixed effects of time (e.g., quadratic, cubic spline, etc.).
Comment: @Frank H: I apologize if I wasn't clear but if your forge a model as y(t)= constant+phi1*y(t-1)+phi2*y(t-2)+....phik*y(t-k) PLUS the covariates where the number and the nature of the "phis" have been analytically determined to be suffcient you are then controlling for "time dependency" . THis model might also actually include "level shifts and or time trends and/or pulses/seasonal pulses as necessary. By comparing the resultant adequacy of this approach vs your assumed approach one might be able to conclude about the best way "to condition for time" so that the covariates can be evaluated.
Comment: @Frank H. Am I right to confirm that my suggested approach generalizes to dynamic covariates whereas your approach does not.  If this is so why bother with the inferior approach as interpretation of the time effects is also NOT available as dummy time trends yields apparently no such interpretation. Perhaps the available free software is too restrictive and not general enough in this regard.
Comment: The truth is, I took a look at some of the dynamic regression R packages, and realized that there will be a huge learning curve with them because I not only know nothing about this, I don't even know what prerequisite topics I need to read up on in order to understand them. The linear model approach I at least kind of understand, and @frank-harrell is absolutely correct about the covariates other than time being static. While I get up to speed on what the ideal approach might be, I desperately need to know what I need to change about my proposed approach to at least make it a valid one.
Comment: _Fully data-driven model selection will result in standard errors and P-values that are too small, confidence intervals that are too narrow, and overstated effects of remaining terms in the model._  To be clear, though I'm being deliberately general about the shape of the time dependence, it's not fully data-driven. I.e. we have growth curves that we would not consider fitting with trig functions and we have circadian patterns that we wouldn't fit with log functions. To the extent that I would use the data for fitting the curve it would be to decide if there should be a linear term added, e.g.
Comment: ...and thank you so much for the link to the online book, @frank-harrell. I hadn't seen this particular one before and am reading the longitudinal data example and the model selection/validation chapters now.
Answer: Fitting models that include time, time-squared, time-cubed , sines , cosines et all are not very useful in my opinion as they assume deterministic structure that often is inappropriate. Using historical values that are lagged values of the output and possibly covariate series is the approach to take. When constructing these models one needs to verify a few things ( the Gaussian Assumptions ) before declaring victory :
1. that the mean of the errors is "near zero" for all time intervals otherwise empirically identifiable structure like Pulses, Level Shifts, local time trends and/or seasonal pulses might be needed (N.B. This is not guaranteed by simply including a constant in the model ) ; 2. that there is no provable auto-correlative structure in the residuals for ALL LAGS ; 3. that the parameters of your model are stable/constant over time ; 4. that the variance of the errors is constant over time thusly no structural breaks in variance requiring weighted estimation and no dependence of the error variablility on the level of the series and no stochastic variance adaptation in effect. The suggested approach is called a Transfer Function and is a super-set of Regression and ARIMA modelling in conjunction with Intervention Detection

Variable selection for time covariate


Plone 3.2.1 on Fedora 10 with Active Directory Authentication

Question: I have gone through tons of documents over the internet in enabling Active Directory Authentication for Plone 3 using LDAPMultiplugins, PlonePAS etc., but none of them are working for me.
Is there any one who has successfully done this? Even if this has accomplished on Windows, it is ok!
Answer: The current best-practice is plone.app.ldap:
http://pypi.python.org/pypi/plone.app.ldap
Answer: I've had a few experiences with Plone 3 + LDAP + Active Directory in Windows.
The worst problems I've had were related to installing the Python LDAP libraries, and configuring them (specially configuring the library to recognize the CA certificate for the SSL server certificate in a LDAP over SSL connection).
What exactly is the problem you are facing?


git on HTTP with gitolite and nginx

Question: I am trying to setup a server where my git repo would be accessible with HTTP(S).
I am using gitolite and nginx (and gitlab for web interface but I doubt it makes any difference).
I have searched the whole afternoon and I think I'm stuck.
I have think I have understood that nginx needs fcgiwrap to work with gitolite, so I tried several configurations, but none of them work.
My repositories are at /home/git/repositories.
Here's the three nginx configurations I have tried.
1:
   location ~ /git(/.*) {
       gzip off;
       root /usr/lib/git-core;

       fastcgi_pass  unix:/var/run/fcgiwrap.socket;
       include /etc/nginx/fcgiwrap.conf;

       fastcgi_param SCRIPT_FILENAME /usr/lib/git-core/git-http-backend;
       fastcgi_param DOCUMENT_ROOT /usr/lib/git-core/;
       fastcgi_param SCRIPT_NAME git-http-backend;

       fastcgi_param GIT_HTTP_EXPORT_ALL "";
       fastcgi_param GIT_PROJECT_ROOT /home/git/repositories;
       fastcgi_param PATH_INFO $1;
       #fastcgi_param PATH_TRANSLATED $document_root$fastcgi_path_info;
    }

Result:
> git clone http://myservername/projectname.git test/
Cloning into test...
fatal: http://myservername/projectname.git/info/refs not found: did you run git update-server-info on the server?

and
> git clone http://myservername/git/projectname.git test/
Cloning into test...
error: The requested URL returned error: 502 while accessing http://myservername/git/projectname.git/info/refs
fatal: HTTP request failed

2:
   location ~ /git(/.*) {
        fastcgi_pass  localhost:9001;
        include       /etc/nginx/fcgiwrap.conf;
        fastcgi_param SCRIPT_FILENAME     /usr/lib/git-core/git-http-backend;
        fastcgi_param GIT_HTTP_EXPORT_ALL "";
        fastcgi_param GIT_PROJECT_ROOT    /home/git/repositories;
        fastcgi_param PATH_INFO           $1;
    }

Result:
> git clone http://myservername/projectname.git test/
Cloning into test...
fatal: http://myservername/projectname.git/info/refs not found: did you run git update-server-info on the server?

and
> git clone http://myservername/git/projectname.git test/
Cloning into test...
error: The requested URL returned error: 502 while accessing http://myservername/git/projectname.git/info/refs
fatal: HTTP request failed

3:
location ~ ^.*\.git/objects/([0-9a-f]+/[0-9a-f]+|pack/pack-[0-9a-f]+.(pack|idx))$ {
    root /home/git/repositories/;
  }

  location ~ ^.*\.git/(HEAD|info/refs|objects/info/.*|git-(upload|receive)-pack)$ {
    root /home/git/repositories;

    fastcgi_pass unix:/var/run/fcgiwrap.socket;
    fastcgi_param SCRIPT_FILENAME   /usr/lib/git-core/git-http-backend;
    fastcgi_param PATH_INFO         $uri;
    fastcgi_param GIT_PROJECT_ROOT  /home/git/repositories;
    include /etc/nginx/fcgiwrap.conf;
  }

Result:
> git clone http://myservername/projectname.git test/
Cloning into test...
error: The requested URL returned error: 502 while accessing http://myservername/projectname.git/info/refs
fatal: HTTP request failed

and
> git clone http://myservername/git/projectname.git test/
Cloning into test...
error: The requested URL returned error: 502 while accessing http://myservername/git/projectname.git/info/refs
fatal: HTTP request failed

Also note that with any of those configurations, when I try to clone with a project name that actually doesn't exist, I get a 502 error.
Does anyone already succeeded in doing this? What am I doing wrong?
Thanks.
UPDATE:
nginx error log file said:
2012/04/05 17:34:50 [crit] 21335#0: *50 connect() to unix:/var/run/fcgiwrap.socket failed (13: Permission denied) while connecting to upstream, client: 192.168.12.201, server: myservername, request: "GET /git/oct_editor.git/info/refs HTTP/1.1", upstream: "fastcgi://unix:/var/run/fcgiwrap.socket:", host: "myservername"

So I changed permissions for /var/run/fcgiwrap.socket, and now I have :
> git clone http://myservername/git/projectname.git test/
Cloning into test...
error: The requested URL returned error: 403 while accessing     http://myservername/git/projectname.git/info/refs
fatal: HTTP request failed

Here is the error.log file I have now:
2012/04/05 17:36:52 [error] 21335#0: *78 FastCGI sent in stderr: "Cannot chdir to script directory (/usr/lib/git-core/git/projectname.git/info)" while reading response header from upstream, client: 192.168.12.201, server: myservername, request: "GET /git/projectname.git/info/refs HTTP/1.1", upstream: "fastcgi://unix:/var/run/fcgiwrap.socket:", host: "myservername"

I keep on investigating.
Comment: Have user, under is running fastcgi process, rights to enter directory `/usr/lib/git-core/git/projectname.git/info`?
Comment: {ln -s /home/git /usr/lib/git-core/git}
or set {{root /home;}} -but second could be security problem
Answer: Here is what I set in my Apache config (I know: not nginx, but still can help you):
SetEnv GIT_PROJECT_ROOT @H@/repositories
SetEnv GIT_HTTP_EXPORT_ALL
SetEnv GITOLITE_HTTP_HOME @H@
ScriptAlias /hgit/ @H@/gitolite/bin/gl-auth-command/
SetEnv GIT_HTTP_BACKEND "@H@/usr/local/apps/git/libexec/git-core/git-http-backend"

(with @H@ the path where .gitolite.rc and, in my case, the repositories are stored)
I don't see GITOLITE_HTTP_HOME and GIT_HTTP_BACKEND defined in your config.
See the full config here.
Answer: Old question, but it popped up first when I was looking for this, so thought I'd post an answer to at least part of the problem.
I'll just refer to your attempt #1 for ease.
I think the main problem you're having here is this line:
fastcgi_param SCRIPT_FILENAME /usr/lib/git-core/git-http-backend;

What you're doing here is passing the request to the git backend, but I think you want to be passing it to the gitolite backend:
fastcgi_param SCRIPT_FILENAME /path/to/gitolite/base/gitolite/src/gitolite-shell;

So I think when you tried:
git clone http://myservername/projectname.git

Git happily looked for something, and couldn't find it (because you set git to the wrong location based on your server mappings). But when you tried:
git clone http://myservername/git/projectname.git

Git wasn't able to do anything, because gitolite owns the GIT_PROJECT_ROOT at that location in your nginx config.
You may also want to make the script available in the gitolite bin and direct nginx to it there---seems to be convention:
/path/to/gitolite/base/bin/gitolite-shell

Directing nginx to the gitolite backend will address your server error issue.
I'm now having a 'can't find the repository' error, but I think that's because my http basic auth users don't match up to my gitolite user permissions. If I can be bothered trying to address that, I'll update.
On that note, there is a potential second problem with your script if you're using basic authentication for this server (since you've just posted the config for the location and not the whole server). In that case, you need to pass the authenticated user to gitolite. You'd actually need to do this for a normal git setup too:
fastcgi_param REMOTE_USER $remote_user;

I should point out that this may also be related to my 'can't find the repository' issue, if gitolite requires something different in this respect than normal git. I suspect that gitolite might require this regardless of whether authentication is enabled or not, unless you can get anonymous access working for gitolite with nginx.
NB: I think there are multiple ways of passing the request to git or gitolite. So if you set http up for git, the following (that you've used) is often recommended and works:
fastcgi_param PATH_INFO $1;

But for gitolite, you see alternatives that are different. The most common is:
fastcgi_param PATH_INFO $fastcgi_path_info;

I am using the former, and as I said, it seems to work. But my problem might be that nginx is not passing the path properly (as opposed to a 'user' problem). Worth noting.

git on HTTP with gitolite and nginx


Is Ajax the first team not to qualify for the next stage (because they ended up 3rd) with as much as 10 points?

Question: Last Tuesday, group H of the Champions League 2019/20 was decided, and the Dutch football (soccer) club Ajax ended up third place with as many as 10 points, failing to qualify for the next round since both Valencia and Chelsea have 11.
It's rather unlikely not to qualify with 11 points; that means two other teams need to have at least 11 points, for a total of 33 points. There are 12 matches in the group stage, for a total of 36 points, so there are at most three draws; this can only happen if the three teams beat the fourth team twice, and their six head-to-head matches end up in one win, one loss and two draws for each team; each team ends up with 11 points, but goals fore/against may make a distinction here.
Similarly, there's only one scenario where a team with 12 points doesn't qualify: if two other teams have 12 points, when all matches are decisive, they all beat the fourth team and they all win exactly two out of four head-to-head matches.
In the history of the Champions League, have any other teams failed to qualify for the next round (in a group of 4, where the top 2 qualify) with as much as 10 points? What about other (high level) football competitions?
Comment: Wikipedia article [European Cup and UEFA Champions League records and statistics](https://en.wikipedia.org/wiki/European_Cup_and_UEFA_Champions_League_records_and_statistics) has a section "[Most points achieved, yet knocked out](https://en.wikipedia.org/wiki/European_Cup_and_UEFA_Champions_League_records_and_statistics#Most_points_achieved.2C_yet_knocked_out)" ([current revision](https://en.wikipedia.org/w/index.php?title=European_Cup_and_UEFA_Champions_League_records_and_statistics&oldid=930434920#Most_points_achieved,_yet_knocked_out)).
Comment: It's worth to keep in mind that the format wasn't always the same it is now. For example, at some point there was [first and second group stage](https://en.wikipedia.org/wiki/2001%E2%80%9302_UEFA_Champions_League). Also in some editions [no all runner-ups advanced](https://en.wikipedia.org/wiki/1997%E2%80%9398_UEFA_Champions_League).
Comment: I have added ([tag:champions-league]) tag - to me it seems suitable for the question. However, you mention that you're interested also in other competitions. Perhaps ([tag:europa-league]) could be added too?
Comment: @Martin yes, those are the most common situations I could think of. World Cups etc. have groups of 4 but they're single-rounded; I could imagine one of the countries has a competition with a playoff structure similar to this one.
Answer:
It's mathematically impossible not to qualify with 11 points

That is not correct.

Is Ajax the first team not to qualify for the next stage with as much
  as 10 points?

No.
During the 2013-2014 UEFA Champions League, in the Group F, Napoli finished 3rd of its group and didn't qualify.

Dortmund  12 (+5)
Arsenal   12 (+3)
Napoli     12 (+1)
Marseille   0 (-9)

It also happened in old format during the 1997-1998 UEFA Champions League for the PSG, eliminated with 12 Pts in the group E and ranked third of "runners-up" (only the two first qualify).
Source : https://www.uefa.com/uefachampionsleague/news/newsid=2568008.html
Also see : Highest Points to finish Runner-Up in Champions League Group? Lowest points to win Champions League Group?
Comment: Ah, right (so +1), and 11 points is possible too (but I guess it never happened before)?
Comment: If all of the top three teams in a group have 11 points, they necessarily all beat the last team twice, drew once with each of the others, and then beat one but lost to the other. One of these three teams will be eliminated by other tiebreakers.
Comment: If the third team has 11 points, it is impossible for the second team to have 12 points (though the first team could have 12 points, and only by winning four, losing two).


Carregar ComboBox a partir de uma tabela MySQL - Manipular chave e outro campo

Question: Tenho uma tabela com a seguinte estrutura:
<code>+----------------+-------------+------+-----+---------+-------+
| Field          | Type        | Null | Key | Default | Extra |
+----------------+-------------+------+-----+---------+-------+
| idLocalidade   | int(11)     | NO   | PRI | NULL    |       |
| localidadeNome | varchar(45) | NO   |     | NULL    |       |
+----------------+-------------+------+-----+---------+-------+
</code>
No XAML uma ComboBox;
<code><ComboBox x:Name="selecaoComboBox"  Grid.Row="2" Grid.Column="1" Margin="5" SelectionChanged="selecaoComboBox_SelectionChanged"  />
</code>
Carrego os dados da tabela para a ComboBox desta forma:
<code>    private void carregarComboBox()
    {
        MySqlConnection ligacaoBD = new MySqlConnection(ConfigurationManager.ConnectionStrings["stringDeLigacaoDB"].ConnectionString);
        try
        {
            ligacaoBD.Open();
            var dataAdapter = new MySqlDataAdapter("SELECT idLocalidade, localidadeNome FROM localidade", ligacaoBD);
            DataSet ds = new DataSet();
            dataAdapter.Fill(ds, "localidade");
            DataTable dt = ds.Tables[0];
            selecaoComboBox.ItemsSource = ((IListSource)dt).GetList();
            selecaoComboBox.DisplayMemberPath = "localidadeNome";
            selecaoComboBox.SelectedValuePath = "idLocalidade";
        }
        catch (MySqlException ex)
        {
            MessageBox.Show(ex.ToString());
        }
        finally
        {
            ligacaoBD.Close();
        }
    }
</code>
De seguida pretendo preencher duas TextBox com os dados de cada registo, sempre que é selecionado um valor na ComboBox.
A versão incompleta é esta:
<code>    private void selecaoComboBox_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
    {
        idLocalidadeTextBox.Text = selecaoComboBox.SelectedValue.ToString();
        localidadeNomeTextBox.Text = selecaoComboBox.Text;
    }
</code>
O campo idLocalidade consigo obter, mas o mesmo já não se aplica ao campo localidadeNome, que é uma string vazia!
O que falha nesta abordagem?
Comment: Estranho! Ao selecionar um item pela segunda vez, aparece-me o texto do anterior.
Answer: Das soluções que encontrei esta pareceu-me a mais simples.
Bastou alterar o manipulador de evento:
<code>    private void selecaoComboBox_DropDownClosed(object sender, System.EventArgs e)
    {
        if (selecaoComboBox.SelectedIndex > -1)
        {
            idLocalidadeTextBox.Text = selecaoComboBox.SelectedValue.ToString();
            localidadeNomeTextBox.Text = selecaoComboBox.Text;
        }
    }
</code>
Só ainda não percebi porque razão o selecaoComboBox.Text me ia sempre buscar o valor anterior no exemplo inicial!


file_get_contents("php://input") is empty

Question: I'm using file_get_contents("php://input") to get the body of a post request. However, it's coming back as an empty string when I call var_dump(). I checked php.ini config and allow_url_fopen is set to On.
I'm using postman to test the request. Nothing special, no multipart/form, just a plain post with a few params. Because I'm using php://input always_populate_raw_post_data can be configured off, right?
Comment: yes, `always_populate_raw_post_data` can configured off. You have to post more code or/and details. As per your description, your code has not problem.
Comment: Try enabling `error_reporting` and `dispaly_errors` and check if it's throwing any errors
Comment: There is no more code that really matters. At the very top of my php script there's var_dump(file_get_contents("php://input")) Then I just make a request using postman. The script is definitely getting hit and producing 200 ok it's just there's an empty string even though I'm passing params in url param key : value
Comment: show how do you posting your data (headers, params)
Comment: sending this post request in postman: http://www.beanbagapp.com/beanbag/flagContent.php?name=Bill&userName=bpp123
Comment: the code looks like: $JSONArray  = json_decode(file_get_contents("php://input"), true); var_dump($JSONArray)
Comment: Content-Type → text/html; charset=utf-8
Answer: if you already asigned the value, eg $str = file_get_contents("php://input"); then when you var_dump it would go for empty.
Using postman (Chrome Extension) to check your post value.
Answer: Yes, you need enable always_populate_raw_post_data
Reference here
Comment: No. `always_populate_raw_post_data` refer to `$HTTP_RAW_POST_DATA`. Read careful your own link.


Exibir resultados separados por vírgulas com MySQL

Question: administrador  | regiao
bruno          | 2,3,4
pedro          | 1
jose           | 5,7

Tenho uma tabela administrador e uma tabela região, onde 1 administrador pode administrar uma região ou várias. Quero fazer uma consulta que me traga o nome das regiões que cada administrador é responsavel separando por vírgulas. Ex:
administrador  | regiao
bruno          | São Paulo, Belo Horizonte, Sorocaba
pedro          | Boituva
jose           | Rio de Janeiro, Resende

Como fazer essa consulta?
Answer: Fiz um fiddle para validar, aproveitando a ideia do group_concat da resposta do @fernandosavio:
select a.nomeAdm as nome,
       GROUP_CONCAT(DISTINCT r.nomeREg SEPARATOR ", ") as regiao
  from regiao r
 inner join administrador a on r.idAdm = a.idAdm
 group by r.idAdm, a.nomeAdm

Aqui o fiddle: http://sqlfiddle.com/#!9/06be20/8
Answer: Depois entender melhor o problema eis meus pensamentos e possíveis soluções.
Solução 1:
A melhor ideia seria reestruturar as tabelas com foreign keys. N-1 caso as áreas só possam ter apenas um administrador. N-N caso uma área possa ter vários administradores e cada administrador possa administrar várias áreas.
Se for escolhida a opção N-1, a resposta do @ricardo-pontual é exatamente o que tu precisa. Desde que a tabela regions tenha uma chave estrangeira para a tabela administrators.
Resposta do @ricardo-pontual para referência:
SELECT
    a.nomeAdm as nome,
    GROUP_CONCAT(DISTINCT r.nomeREg SEPARATOR ", ") as regiao
FROM regiao r
INNER JOIN administrador a ON r.idAdm = a.idAdm
GROUP BY r.idAdm;

Caso N-N seja a necessidade, mantenho a resposta anterior que é ter um tabela pivô com chaves estrangeiras para regions e administrators.
SELECT
    a.nome as administrador,
    GROUP_CONCAT(DISTINCT r.nome SEPARATOR ", ") as regioes
FROM administradores as a
INNER JOIN adm_regioes AS ar ON ar.adm_id = a.id
INNER JOIN regioes AS r ON ar.regiao_id = r.id
GROUP BY a.id;

Solução 2:
Se não for possível reestruturar as tabelas, é possível fazer um join usando REGEXP para que o SGBD reconheça o campo regions e consiga fazer a referência à tabela regions.
Um exemplo seria:
SELECT
    a.nome as nome,
    a.regions as regions,
    GROUP_CONCAT(DISTINCT r.nome SEPARATOR ', ') as regions_concat
FROM administrators as a
INNER JOIN regions as r
    ON a.regions REGEXP CONCAT("[[:<:]]", r.id, "[[:>:]]")
GROUP BY a.id;

Resultado:
+-------+---------+----------------------+
| nome  | regions |    regions_concat    |
+-------+---------+----------------------+
| Pedro |       1 | Sao paulo            |
| João  |     2,3 | Campinas, Manaus     |
| José  |     4,5 | Campo Grande, Santos |
+-------+---------+----------------------+

O INNER JOIN seria feito aplicando a REGEXP na coluna onde os símbolos [[:<:]] e [[:>:]] são os word boundaries (equivalente ao \b em outras engines de REGEXP).
Dessa maneira teu problema é resolvido, porém deve-se salientar que não é o ideal e também nem um pouco performático.
Veja em funcionamento no DBFiddle
PS: É preciso testar se funciona normalmente com números de dois ou mais dígitos também.

Estas são as opções que vejo sem precisar tratar a nível de aplicação. Espero que ajude.
Comment: acho que se rodar no mesmo select, vai duplicar o nome do administrador...
Comment: Vou atualizar com o DISTINCT então.
Comment: Não é um N-N, só tenho duas tabelas, a de Administrador e a de Região...a tabela de administrador guarda os ids da região separados por virgulas, como descrito na pergunta.
Comment: Desculpa @DaywisonFerreiraLeal... vou melhor a resposta.
Answer: select admin.name,
       GROUP_CONCAT(DISTINCT r.name SEPARATOR ", ") as regiao
  from regions r
 inner join administrator admin on r.id = admin.regions
 group by r.id, admin.name order by admin.id desc

O resultado da Query acima foi:
name | regiao
pedro| sao paulo
joao | manaus
jose | campo grande

Quando na verdade deveria ser:
name | regiao
pedro| sao paulo
joao | manaus, campinas
jose | campo grande, santos

A query não está fazendo as concatenações, só esta considerando a primeira região.
Lembrando que as tabelas estão assim :
Regions
id | name
1  | Sao paulo
2  | Manaus
3  | Campinas
4  | Campo Grande
5  | Santos

Administrator
id | name | regions
1  | pedro| 1
2  | joao | 2,3
3  | jose | 4,5

Comment: Na tua query tu está agrupando por região e por administrador, quando aparentemente tu quer que agrupe apenas por administrador.
Se tu tirar o `r.id,` do `GROUP BY` tua query vai fazer mais sentido, logicamente falando.
O realmente problema e quebrar o campo `regions` dentro do `SELECT` pra usar no `WHERE`
Comment: Já removi o **r.id** do GROUP BY mas ele continua não concatenando as regiões de cada administrador..
Comment: Suponho que o campo `administrator.regions` é `VARCHAR`. Se for o caso, o MySQL está convertendo o campo para inteiro e por isso não enxerga as outras regiões. Pois quando ele converte "1,2,3" pra INTEGER o valor convertido é `1`.
Comment: A resposta do @ricardo-pontual seria a forma correta de fazer essa relação 1-N.
Comment: @fernandosavio o campo regions é varchar mesmo, acabei de ver aqui na tabela.
Comment: Alguma solução?
Comment: Atualizei minha resposta. Se não tiver como alterar a estrutura do campo vai ter que usar REGEXP no JOIN mesmo.
Comment: Meu problema foi resolvido usando REGEXP, como mencionado na sua soluçāo


Windows 2008 server multihome issue

Question: I have moved from Windows 2003 server to Windows 2008 and have some issues related to IIS or networking I would rather say.
I have two NIC's in the server. One is with a fast IP address given by the ISP XX.XX.XXX.XXX which is connected to the internet and the other one is a local one with and address looking like 192.168.0.1
In the RRAS the first NIC is configured as the public interface going on the internet and the services provided by the server such as Web server and mail server are added as offered services on that interface meaning that the RRAS sees that as a Proxy.
The other one, the internal one, is meant to be the router for the local network to access the internet.
Everything works fine meaning that I can get on the internet without any problems from the internal network and my websites on the server are accessible from the Internet.
THE HUGE problem is when I try to access my websites from within the local network - nothing happens. I don't get a 404 page, it just hangs on there and nothing happens. The web server is configured correctly and is accessible from internet.
Any idea why or what kind of configuration problems I might have?
Comment: As an aside I would `HIGHLY` recommend you use a stand alone router for all of this. While Windows can act as a router I have never seen the point, especially since a small Linksys or NetGear can easily do the job of Windows. Any particular reason you are using the server as a router?
Comment: I second the notion. Also I'd just as strongly recommend to separate publicly accessible services from your LAN. A public-facing web server should be placed in a DMZ.
Comment: Thank you for your answers. The strange thing is that while from the local network I can navigate on the Internet and from the server itself I can see my sites, I can not do that from any machine on the network. Why I use the Windows as a router is quite simple.. I don't know how to do something different. The server have two NIC one facing the internet and one facing the internal network. So how should I proceed as I have no clue on this? Thank you!
Answer: I think you may be running into a hairpin issue, where you are sending traffic into your local lan segments interface, it should then be hair pined on the outbound interface but isnt.
The easiest solution would be to connect to the webserver on its internal IP (192.x) address. You may need to have IIS set to bind against both the external and internal IP.
That would be the easiest, (read not the best) way of fixing it.
Answer: Adding on to Steve's answer...
Manually entering the web server's address into your local hosts file for the internal IP should do the trick as well.

Windows 2008 server multihome issue


Proof: Derivative of $(-1)^{x}$

Question: The derivative for $(-1)^{x}$ is
\begin{equation}
\frac d{dx}\left[(-1)^x\right]=i\pi(-1)^{x}
\end{equation}
But why?
What happens with higher order derivatives?
Thanks in advance.
Comment: The expression $(-1)^x$ is not defined in general.  You can interpret it to mean $e^{ \pi x i}$, and the formula follows from that.  But you could just as easily assume that it means $e^{3 \pi  x i}$ which has the derivative $3 \pi ie^{3 \pi  x i}$.
Comment: $i\pi$ is constant, correct?
Comment: Do you have a reference for your formula? Is the function you are considering a function from the real numbers to the real numbers? What is your definition of $\frac{d}{dx}$?
Answer: Since
$$(-1)^{x}=(e^{i\pi})^x=e^{i\pi x}$$
We have
$$
\dfrac{d}{dx}\left((-1)^{x}\right)=\dfrac{d}{dx}\left(e^{i\pi x}\right)=i\pi e^{i\pi x}=i\pi(-1)^{x}
$$
For higher order derivatives
$$
\dfrac{d^{n}}{dx^{n}}\left((-1)^{x}\right)=(i\pi)^n(-1)^{x}
$$
Comment: @AkshatTripathi It's not that $e^{i \pi x} = -1$ but that $e^{i \pi} = -1$. By [Euler formula](https://en.wikipedia.org/wiki/Euler%27s_formula), we have: $$e^{\theta i} = \cos \theta + i \sin \theta,$$ plugging in $\theta = \pi$ we get the desired result.
Comment: @AkshatTripathi That's a pretty famous result in calculus, actually. Though I see why you're confused — How do you multiply something by itself an imaginary amount of times? The proof is too long to write in a comment, but trust us that the equation makes sense and is true.
Comment: I don't get it. How is eiπx = -1?
Comment: All right, thanks.
Answer: Mistake 1: The function $(-1)^x$ is not well-defined, even if $x$ is a complex number.
Mistake 2: You cannot say $\left( e^{\pi i} \right)^x = e^{\pi i x}$. The multiplication of exponent rule does not extend to complex numbers. Indeed, otherwise you have problems like $1^{\pi} = e^{2\pi^2 i}$, which is clearly false.
Comment: Possibly relevant: Wolfram Alpha interprets $(-1)^x$ to mean $e^{\pi ix}$.
Answer: We have that $e^{i\pi}=-1$, so $(-1)^x=e^{i\pi x}$, therefore $\frac{d}{dx}e^{i\pi x}=i\pi e^{i\pi x}=i\pi (-1)^x$.
It's easy to see that $\frac{d^n}{dx^n}(-1)^x=(i\pi)^n(-1)^x$.
Answer: Observe the function $w=(-1)^z$ This is equivalent to $w=e^{z\ln(-1)}$ Now, recalling that the logarithm is a multivalued function, $$\ln(-1)=\ln\vert(-1)\vert +i\arg(-1)=i(\pi+2\pi n)$$We see that $(-1)^z$ Is equivalent to $w=e^{i\pi (2n+1)z}$ For all integers $n$. This means, except in special cases, that $(-1)^z$ has an infinite number of complex values. If we choose to let n be constant, and define $(-1)^z$ as the resulting single valued function, the complex derivative is equal to$$ i\pi (2n+1)e^{i\pi (2n+1)z}$$

Proof: Derivative of $(-1)^{x}$


how do I pull out a random record from an SQL table?

Question: I have an SQL table which has two integers. Let these integers be a and b.
I want to SELECT out a random record, such that the record is selected with probability proportional to C + a/b for some constant C which I will choose.
So for example, if C = 0, and there are two records with a=1,b=2 and a=2,b=3, then we have that for the first record C+a/b = 1/2 and for the second record C+a/b = 2/3, and therefore with probability 0.3 I will choose the first record, and probability 0.7 I will choose the second record from that SELECT query.
I know SQL well (I thought), but I am not even sure where to begin here. I thought of doing a select for the "SUM(a/b)" first, and then doing a select for the first record the sum of C+a/b up to it exceeds a random number between C*number_of_records + SUM(a/b) for the first time. But, I don't really know how to do that.
Comment: I'd say this is a duplicate:  http://stackoverflow.com/q/19412/341547   Unless you have something that's specifically different from that general discussion.
Comment: @MikeRyan I would say this is a different question, as the probability aspect brings a new factor into the question
Comment: @ewok -- ok, on a more thorough read, I think you're right -- though ultimately it will be extending those techniques.
Comment: How many rows might there be in the table? One possible tactic could get very slow if there are lots of rows (for arbitrary values of lots), while another option is awkward as heck to write, but would (?) only scan the table once.
Comment: ewok, no, this is not for homework. @Philip I think there would be a few hundreds of thousands rows in the database.
Answer: You could do something like sorting by a random number multiplied by your other stuff, and just select top 1 from that query - something like:
<code>SELECT TOP 1 (your column names)
FROM (your table)
ORDER BY Rand() * (your calculation)
</code>


Mismatch version between installed package and executable version printing

Question: I am facing an issue about mismatch between last updated package of PHP and what is actually run.
Recently I have updated my Ubuntu server by running:
apt-get update && apt-get upgrade

On the output I have noticed the right package version was installed:
Unpacking php7.1-fpm (7.1.33-1+ubuntu18.04.1+deb.sury.org+1) over (PHP Version 7.1.25-1+ubuntu18.04.1+deb.sury.org+1) ...

I have controlled the installed version by running following command:
apt-cache madison php7.1-fpm
php7.1-fpm | 7.1.33-1+ubuntu18.04.1+deb.sury.org+1 | http://ppa.launchpad.net/ondrej/php/ubuntu bionic/main amd64 Packages

But when I run phpinfo() from php-fpm socket, I still see the previous installed version:
PHP Version 7.1.25-1+ubuntu18.04.1+deb.sury.org+1

What I have tried?

To restart php7.1-fpm.
To restart Nginx (which is in top of PHP fpm).

EDIT 1
$ which php
/usr/bin/php

$ ls -al /usr/bin | grep php
php -> /etc/alternatives/php
php7.1

$ ls -al /etc/alternatives | grep php
php -> /usr/bin/php7.1
php.1.gz -> /usr/share/man/man1/php7.1.1.gz

$ /usr/bin/php7.1 -v
PHP 7.1.25-1+ubuntu18.04.1+deb.sury.org+1 (cli) (built: Dec  7 2018 08:15:52) ( NTS )

EDIT 2
$ dpkg -l 'php*'|grep ^ii
ii  php-common         2:69+ubuntu18.04.1+deb.sury.org+2+php7.3   all          Common files for PHP packages
ii  php-geoip          1.1.1-2+ubuntu18.04.1+deb.sury.org+10      amd64        GeoIP module for PHP
ii  php-igbinary       3.0.1+2.0.8-1+ubuntu18.04.1+deb.sury.org+1 amd64        igbinary PHP serializer
ii  php-memcached      3.1.3+2.2.0-1+ubuntu18.04.1+deb.sury.org+1 amd64        memcached extension module for PHP, uses libmemcached
ii  php-msgpack        2.0.3+0.5.7-1+ubuntu18.04.1+deb.sury.org+1 amd64        PHP extension for interfacing with MessagePack
ii  php-redis          5.0.2+4.3.0-2+ubuntu18.04.1+deb.sury.org+1 amd64        PHP extension for interfacing with Redis
ii  php7.1             7.1.33-1+ubuntu18.04.1+deb.sury.org+1      all          server-side, HTML-embedded scripting language (metapackage)
ii  php7.1-cli         7.1.25-1+ubuntu18.04.1+deb.sury.org+1      amd64        command-line interpreter for the PHP scripting language
ii  php7.1-common      7.1.25-1+ubuntu18.04.1+deb.sury.org+1      amd64        documentation, examples and common module for PHP
ii  php7.1-curl        7.1.25-1+ubuntu18.04.1+deb.sury.org+1      amd64        CURL module for PHP
ii  php7.1-fpm         7.1.25-1+ubuntu18.04.1+deb.sury.org+1      amd64        server-side, HTML-embedded scripting language (FPM-CGI binary)
ii  php7.1-gd          7.1.25-1+ubuntu18.04.1+deb.sury.org+1      amd64        GD module for PHP
ii  php7.1-gmp         7.1.25-1+ubuntu18.04.1+deb.sury.org+1      amd64        GMP module for PHP
ii  php7.1-intl        7.1.25-1+ubuntu18.04.1+deb.sury.org+1      amd64        Internationalisation module for PHP
ii  php7.1-json        7.1.25-1+ubuntu18.04.1+deb.sury.org+1      amd64        JSON module for PHP
ii  php7.1-mbstring    7.1.25-1+ubuntu18.04.1+deb.sury.org+1      amd64        MBSTRING module for PHP
ii  php7.1-mcrypt      7.1.25-1+ubuntu18.04.1+deb.sury.org+1      amd64        libmcrypt module for PHP
ii  php7.1-mysql       7.1.25-1+ubuntu18.04.1+deb.sury.org+1      amd64        MySQL module for PHP
ii  php7.1-opcache     7.1.25-1+ubuntu18.04.1+deb.sury.org+1      amd64        Zend OpCache module for PHP
ii  php7.1-readline    7.1.25-1+ubuntu18.04.1+deb.sury.org+1      amd64        readline module for PHP
ii  php7.1-sqlite3     7.1.25-1+ubuntu18.04.1+deb.sury.org+1      amd64        SQLite3 module for PHP
ii  php7.1-xml         7.1.25-1+ubuntu18.04.1+deb.sury.org+1      amd64        DOM, SimpleXML, WDDX, XML, and XSL module for PHP
ii  php7.1-zip         7.1.25-1+ubuntu18.04.1+deb.sury.org+1      amd64        Zip module for PHP

Comment: Can you post the output of `which php`?
Comment: i have updated my post, it is for `php cli` which have the same original issue than `php7.1-fpm`
Comment: Could you please show the output of `dpkg -l 'php*'|grep ^ii` ?
Comment: I have updated my post, i have may find someting.
Comment: @jollyroger thx for your help, after forcing upgrade of all sub package, all was good.
Answer: The list of installed packages shows only php7.1 to be of version 7.1.33 but all subpackages aren't upgraded to the 7.1.33. You might want to upgrade php7.1-cli and php7.1-fpm to upgrade all dependant packages at once as they have more strict version dependency.
You might want to use apt-cache policy in future since apt-cache madison shows available packages and not installed on a system:
[jollyroger@desktop:~]% apt-cache policy vim-tiny
vim-tiny:
  Installed: 2:8.1.0875-5+b1
  Candidate: 2:8.1.2136-1
  Version table:
     2:8.1.2136-1 990
        990 http://deb.debian.org/debian sid/main amd64 Packages
 *** 2:8.1.0875-5+b1 100
        100 /var/lib/dpkg/status
     2:8.1.0875-5 500
        500 http://deb.debian.org/debian buster/main amd64 Packages

Please note the Installed line as well as the line marked with ***.
Comment: What is confusing for me is why simple `apt-get upgrade` doesn't update all my previously installed package ? on my case i was forcing to do `apt-get upgrade php7.1-cli`
Comment: This is because `php7.1` depends on `(libapache2-mod-php7.1 | php7.1-cgi | php7.1-fpm)` with no exact version specified (e.g. `(php7.1-fpm = 7.1.33-1+ubuntu18.04.1+deb.sury.org+1)`) and thus the dependency relies on the package name only. This is most probably not intended behavior and bug should be filed to Debian/Ubuntu BTS.
Answer: base on the recommandation from @jollyroger in comment, i have force apt-get to upgrade all sub package for PHP.
apt-get upgrade php7.1-cli php7.1-common php7.1-curl php7.1-fpm php7.1-gd php7.1-gmp php7.1-intl php7.1-json php7.1-mbstring php7.1-mcrypt php7.1-mysql php7.1-opcache php7.1-readline php7.1-sqlite3 php7.1-xml php7.1-zip

Then all package was updated like charm :
$ dpkg -l 'php*'|grep ^ii
ii  php-common         2:69+ubuntu18.04.1+deb.sury.org+2+php7.3   all          Common files for PHP packages
ii  php-geoip          1.1.1-2+ubuntu18.04.1+deb.sury.org+10      amd64        GeoIP module for PHP
ii  php-igbinary       3.0.1+2.0.8-1+ubuntu18.04.1+deb.sury.org+1 amd64        igbinary PHP serializer
ii  php-memcached      3.1.3+2.2.0-1+ubuntu18.04.1+deb.sury.org+1 amd64        memcached extension module for PHP, uses libmemcached
ii  php-msgpack        2.0.3+0.5.7-1+ubuntu18.04.1+deb.sury.org+1 amd64        PHP extension for interfacing with MessagePack
ii  php-redis          5.0.2+4.3.0-2+ubuntu18.04.1+deb.sury.org+1 amd64        PHP extension for interfacing with Redis
ii  php7.1             7.1.33-1+ubuntu18.04.1+deb.sury.org+1      all          server-side, HTML-embedded scripting language (metapackage)
ii  php7.1-cli         7.1.33-1+ubuntu18.04.1+deb.sury.org+1      amd64        command-line interpreter for the PHP scripting language
ii  php7.1-common      7.1.33-1+ubuntu18.04.1+deb.sury.org+1      amd64        documentation, examples and common module for PHP
ii  php7.1-curl        7.1.33-1+ubuntu18.04.1+deb.sury.org+1      amd64        CURL module for PHP
ii  php7.1-fpm         7.1.33-1+ubuntu18.04.1+deb.sury.org+1      amd64        server-side, HTML-embedded scripting language (FPM-CGI binary)
ii  php7.1-gd          7.1.33-1+ubuntu18.04.1+deb.sury.org+1      amd64        GD module for PHP
ii  php7.1-gmp         7.1.33-1+ubuntu18.04.1+deb.sury.org+1      amd64        GMP module for PHP
ii  php7.1-intl        7.1.33-1+ubuntu18.04.1+deb.sury.org+1      amd64        Internationalisation module for PHP
ii  php7.1-json        7.1.33-1+ubuntu18.04.1+deb.sury.org+1      amd64        JSON module for PHP
ii  php7.1-mbstring    7.1.33-1+ubuntu18.04.1+deb.sury.org+1      amd64        MBSTRING module for PHP
ii  php7.1-mcrypt      7.1.33-1+ubuntu18.04.1+deb.sury.org+1      amd64        libmcrypt module for PHP
ii  php7.1-mysql       7.1.33-1+ubuntu18.04.1+deb.sury.org+1      amd64        MySQL module for PHP
ii  php7.1-opcache     7.1.33-1+ubuntu18.04.1+deb.sury.org+1      amd64        Zend OpCache module for PHP
ii  php7.1-readline    7.1.33-1+ubuntu18.04.1+deb.sury.org+1      amd64        readline module for PHP
ii  php7.1-sqlite3     7.1.33-1+ubuntu18.04.1+deb.sury.org+1      amd64        SQLite3 module for PHP
ii  php7.1-xml         7.1.33-1+ubuntu18.04.1+deb.sury.org+1      amd64        DOM, SimpleXML, WDDX, XML, and XSL module for PHP
ii  php7.1-zip         7.1.33-1+ubuntu18.04.1+deb.sury.org+1      amd64        Zip module for PHP

$ php -v
PHP 7.1.33-1+ubuntu18.04.1+deb.sury.org+1 (cli) (built: Oct 26 2019 19:29:18) ( NTS )


Firebase Custom Messages iOS

Question: I'm referring to the interpreting messages portion in https://firebase.google.com/docs/cloud-messaging/ios/receive .
Where in my code can I change the text for notifications in Firebase?
Comment: Please first have a look at https://stackoverflow.com/help/how-to-ask and then provide more details and code that show what you have already tried.
Answer: In order to send a push notification to a device, You need to have a script (or a piece of code) ideally hosted on a server that would send a push notification on your behalf.
There you can customize the message and even play an audio upon receiving a notification.
Here is a code snippet in java that can be used to send a push notification to a device (or a group of devices).
private Map sendPush(String to, String from, String title, String message,
            String sound) throws IOException {
    sound = (sound != null) ? sound : "default";  // set default audio file name
    // Creating the URL and connection
    URL url = new URL(FCM_URL); // your firebase URL
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setDoOutput(true);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/json");
    conn.setRequestProperty("Authorization", "key=" + FCM_KEY); // the firebase project key

    conn.setDoOutput(true);

    // set the notification body
    Map<String, String> notificationBody = new HashMap();
    notificationBody.put("title", title); // notification title
    notificationBody.put("body", message); // notification message
    notificationBody.put("sound", sound);
    notificationBody.put("badge", "1");

    Map<String, String> dataBody = new HashMap();
    dataBody.put("sender", from); // sender id

    Map<String, Object> pushBody = new HashMap();
    pushBody.put("notification", notificationBody);
    pushBody.put("data", dataBody);
    pushBody.put("to", to); // receiver(s) id
    pushBody.put("priority", "high");

    // convert your dictionary to json string using Google Gson library (similar to JsonSerialization class in swift)
    String input = new Gson().toJson(pushBody);

    // write input bytes in request body
    try (OutputStream os = conn.getOutputStream()) {
        os.write(input.getBytes());
        os.flush();
    }

    StringBuilder responseString;
    Reader reader = new InputStreamReader(conn.getInputStream()); // send request and receive response

    // parse response
    try (BufferedReader in = new BufferedReader(reader)) {
        String inputLine;
        responseString = new StringBuilder();
        while ((inputLine = in.readLine()) != null) {
            responseString.append(inputLine);
        }
    }

    // using Google Gson to convert json string into Map (similar to JsonSerialization class in swift)
    Map<String, Object> responseObject = new Gson().fromJson(responseString.toString(),
                Map.class);

    return responseObject;
}

Since this is a java code, so i have hosted it in a java application deployed on Apache Tomcat Server.
You can find several similar implementations in various languages like php or node.js etc.
Hope this helps
Comment: This is what I'm looking for! D you have any idea what I should do to put this into Swift?
Comment: AFAIK you can't send a push directly from your app. You can either send an `http` request to a server API that would send yhe request on your behalf. or you may explore the Google Cloud Functions. https://firebase.google.com/docs/functions/
Answer: first create p.12 certificate and upload in firebase ->project settings ->cloud messaging tab ->select your iOS app ->add APNS certificate.
A. Create a (.certSigningRequest) CSR file
Open Keychain Access from Utilities
From Keychain Access toolbar select Keychain Access -> Preference
In the pop up window select Certificates tab
Set both "Online Certificate Status Protocol" and "Certificate Revocation List" to "Off"
Close this window
Now from toolbar, open Keychain Access > Certificate Assistant > Request a Certificate From a Certificate Authority
Enter email address and common name that you used to register in the iOS Developer Program
Keep CA Email blank and select "Saved to disk" and "Let me specify key pair information"
Click Continue
Choose a filename & destination on your hard drive
Click Save
In the next window, set "Key Size" value to "2048 bits"
Set "Algorithm" to "RSA"
Click Continue
This will create and save your certSigningRequest file (CSR) to your hard drive. A public and private key will also be created in Keychain Access with the Common Name entered.
B. Create ".cer" file in iOS developer account
Login to apple developer account Click "Certificates, Identifiers & Profiles"
Click "Provisioning Profiles"
In the "Certificates" section click "Production"
Click the "Add" (+) button at the top-right of the main panel
Now, choose "App Store and Ad Hoc"
Click Continue
Click "Choose File" & find CSR file you've made from your hard drive
Click Generate
Click Download to get the file
C. Install .cer and generate .p12 certificate
Find .cer file you've downloaded and double-click
Set Login drop-down to "login" and Click Add
Open up KeyChain Access and you'll find profile created in Step A
You can expand "private key" profile (shows certificate you added)
Select only these two items (not the public key)
Right click and click "Export 2 items…" from popup
Now make sure file format is ".p12" and choose filename and destination on your hard drive
Click Save. Now, you'll be prompted to set a password but keep these both blank
Click OK. Now, you have a .p12 file on your hard drive
and open your Xcode project and select target->capabilities->pusnotification->on
next do this stuff https://firebase.google.com/docs/cloud-messaging/ios/receive
next push message from firebase cloud messaging console with message and title and select your app target->user segment->your app.
then your app will able

Firebase Custom Messages iOS


Proving a limit by definition in the multivariable case

Question: I am doing my first steps in this subject and I am trying to understand the following:
So we use the same definition as the single variable case, just that the distance (absolute value) is now replaced with norm.
For all $\epsilon>0$ there is $\delta>0$ such that if $||(x_1,x_2,...,x_n)-(p_1,p_2,...,p_n)||<\delta$ then $||f(x_1,x_2,...,x_n)-f(l_{1},l_2,...l_n)||<\epsilon$
But because we are in the euclidean space and we have a scalar function, can we always assume that $||f(x_1,x_2,...,x_n)-f(l_{1},l_2,...l_n)||<\epsilon\iff |f(x_1,x_2,...,x_n)-f(l_{1},l_2,...l_n)|<\epsilon$
Or in other words, we can always look at the morm of between function and the limit point as an absolute value?
And if for example we have to prove by definition: $$lim_{(x,y)\to (0,0)}\frac{xy}{\sqrt{x^2+y^2}}=0$$
We can immediately with $|\frac{xy}{\sqrt{x^2+y^2}}-0|$?
And then:
$|\frac{xy}{\sqrt{x^2+y^2}}-0|\leq \frac{|x||y|}{\sqrt{x^2+y^2}}\leq \frac{|x||y|}{\sqrt{x^2}}=\frac{|x||y|}{|x|}=|y|=\sqrt{y^2}<\sqrt{x^2+y^2}<\epsilon$
So it is sufficient to  take $\delta=\epsilon$
Comment: Indeed; which is why I already deleted my comment.
Comment: @StackTD maybe in a case the we are not in the euclidean space with the euclidean norm?
Comment: @StackTD sorry you were fast
Answer: If you're using the Euclidean distance for the norm, then it doesn't matter, since for $\vec x = (x)$ with $x \in \mathbb{R}$, you have $\| \vec x \| = \| (x) \| = \sqrt{x^2} = |x|$. In that case, the norm usually isn't used in the definition but simply the absolute value (see here for example).


Can the marginal distributions of A,C and B,C be used to build joint distribution of A and B?

Question: There are three random variables $A$, $B$ and $C$. If the variables $A$ and $B$ were independent, their marginal joint distribution would be given by
$$
P(A,B) = P(A)P(B)
$$
For example, given the discrete probability distributions of $A = \{ A_1, A_2 \}$:
A1 0.6
A2 0.4

and of $B = \{B_1, B_2 \}$:
B1 0.4
B2 0.6

The joint probability distribution would then be $P(A,B)=P(A)P(B)$:
A1 B1 0.24
A1 B2 0.36
A2 B1 0.16
A2 B2 0.24

However, If the variables are not independent, and we know the marginal joint distributions of $P(A,C)$ and $P(B,C)$, e.g.
A1 C1  0.4       B1 C1  0.1
A1 C2  0.2       B1 C2  0.3
A2 C1  0.2       B2 C1  0.5
A2 C2  0.2       B2 C2  0.1

Is that enough to build the joint distribution of $P(A,B,C)$? And, additionally, the marginal joint distribution of $P(A,B)$?
Comment: You already have the joint distribution of P(AB)=P(A)P(B).  I don't understand why are you trying to use C to obtain P(AB) when you already have that from your first step?  Also, P(AB) is not equal to P(A)P(B|A).
Comment: I reopened the question despite the fact the criteria in your example are inconsistent.  For instance, you are asserting that the probability of `C1` is $0.4+0.1=0.5$ while also asserting it equals $0.1+0.5=0.6.$  The question might be clearer to some readers if the example actually had a solution.  That might help everyone see that in general there are many solutions.
Comment: Please explain to us *how* $C$ "gives us more information:" what does it represent?  What do the entries in your last table mean?
Comment: The P(AB)=P(A)P(B) only in the case of the events being independent. Their respective joint distributions with C show this not to be the case.
Comment: Thanks, I updated the probabilities so they should be consistent.
Answer: In the general case, no. The marginals of $P(A,C)$ and $P(B,C)$ are enough to determine the full joint distribution of $P(A,B,C)$ only in the case of conditional independence:
$$
P(A \mid B,C) = P(A\mid C)
$$
and equivalently:
$$
P(B \mid A,C) = P(B\mid C).
$$

Starting with the full joint probability $P(A,B,C)$. Given the formula for joint probability
$$P(X,Y)=P(X\mid Y)P(Y),$$ we get:
$$
P(A,B,C)=P(A,C)P(B\mid A,C).
$$
If the events $A$ and $B$ are not conditionally independent given $C$, now we would need to know the distribution of $P(B \mid A,C)$, which would be enough to form the full joint distribution.
If we assume the probability of B given C be independent of A, the formula simplifies to:
$$
P(A,B,C)=P(A,C)P(B\mid C).
$$
Using the example probabilities,
e.g.
$$
P(A_1,B_1,C_1) = P(A_1,C_1)P(B_1\mid C_1) = 0.4 \cdot \frac{0.1}{0.1+0.5} = \frac{2}{30},
$$
where $P(B_1 \mid C_1)$ is the conditional probability of observing $B_1$ after observing $C_1$.
The full table of probabilities is then:
A1 B1 C1    4/60
A1 B1 C2    9/60
A1 B2 C1   20/60
A1 B2 C2    3/60
A2 B1 C1    2/60
A2 B1 C2    9/60
A2 B2 C1   10/60
A2 B2 C2    3/60

And the joint distribution of A, B (summing over C):
A1 B1   13/60   0.2166...
A1 B2   23/60   0.3833...
A2 B1   11/60   0.1833...
A2 B2   13/60   0.2166...

We can see that $A$ and $B$ are not independent -- but they are still conditionally independent given $C$! If this is not true, the full joint distribution cannot be built from marginal joint distributions like this.
Comment: So that readers don't leave with the wrong impression that this kind of information determines the joint distribution, you really ought to point out how unusual your set of conditions is: it permits a unique answer, whereas in general there will be a two-parameter family of solutions.
Comment: The number of solutions is infinite generally.  That is because as soon as you have two distinct solutions, any mixture of them will be a solution, too, and all those mixtures will be different.
Comment: @Apprentice I edited my answer to take into account his comment -- specifically the first part, that they need to be (conditionally) independent. Only then you can get the joint probability by multiplication. There are not infinite number of joint distributions, but you would need the extra info about their relationship to get to the single joint distribution.
Comment: Hi @Huber, so are you suggesting that for any two marginals P(A,B) and P(B,C) there are an infinite number of joint distributions P(A,B,C)? Do you have a reference for this fact?
Comment: @whuber how do you prove that exist two distinct solutions then?
Comment: You exhibit them.  It's not at all difficult to construct circumstances with multiple solutions.  Look at trivariate Normal distributions, for instance.
Answer: For the 2x2x2 example case we can have the same joint distribution for
$$P'(000) = P(000) + x \\
P'(001) = P(001) - x \\
P'(010) = P(010) - x \\
P'(011) = P(011) + x \\
P'(100) = P(100) - x \\
P'(101) = P(101) + x \\
P'(110) = P(110) + x \\
P'(111) = P(111) - x$$
In this case for any marginal, it will be a sum of two of the cases where one has -x and the other +x, leaving everything unchanged.

Alternative reasoning: You can consider the number of parameters.
In your example:

The marginal conditions involve two times three independent parameters
The joint distribution has seven independent parameters.

This indicates that the marginal distributions does not fix the joint distribution.


How far does Excel look into failed If statement?

Question: I am working with VBA and I am asking this question in order to optimize my code. I have something like this
If reallySmallMethod() And reallyBigMethod() then
    'Do some awesome code
End If

So I put the reallySmallMethod() before the reallyBigMethod(), because I figured that Excel would skip the big one if the small one failed. But when I place a break point and step through this if statement, it appears that Excel runs the big method anyways, even if the small method failed. Is it looking for an Or perhaps?
So now I've done this to optimize it
If reallySmallMethod() then
    If reallyBigMethod() then
        'do some awesome code
    End If
End If

It actually seemed like this code was faster when I was working in 'Break mode', but I'm not sure.
Thanks!
Answer: What your asking about is commonly called short circuit (Boolean) evaluation (vs. eager evaluation).  See https://en.wikipedia.org/wiki/Short-circuit_evaluation.  FYI, this property is usually defined in the language (as short circuit or eager) rather than being an optimization the compiler is allowed to do.  VBA doesn't have it, or in other words it's boolean operators are defined as eager.  You have to write two nested If statements to achieve the desired effect.
It can be noted that short circuit Boolean operators often produces results more expected by programmers than eager. For example, a conditional expression of i < array.length && array [i] ... will work nicely when the intent is to bypass the array indexing of the right hand of the && operator when i is out of array bounds using a short circuit operator. However, a language with an eager boolean operations will still evaluate the right hand expression even though the apparent bounds check has failed.
As Wikipedia notes, some languages define both a short circuit and an eager version of boolean operators, e.g. Visual Basic .NET -- not to be confused with VBA, of course.


Is it possible to get a RAID array to rebuild on disks in different bays?

Question: I have a RAID-6 Sata SSD array running on a new HPE Smart Array P408i-a SR Gen10.
Unfortunately, two of the bays in the new server have failed, leaving us in a very precarious situation.
We have moved the SSDs into two spare bays, and they are showing up fine in the server, but the array is not rebuilding on them.
Is it possible to get the array to rebuild on the SSDs when they are in diffent bays?
EDIT: it may be important to note that one of the SSDs has been replaced with a new one, and the original was returned to the manufacturer, so was never part of the array.
Here is the disk info from ssacli:
/opt/smartstorageadmin/ssacli/bin/ssacli ctrl slot=0 pd all show

HPE Smart Array P408i-a SR Gen10 in Slot 0 (Embedded)

   Array A

      physicaldrive 1I:1:1 (port 1I:box 1:bay 1, SATA SSD, 1.9 TB, OK)
      physicaldrive 1I:1:2 (port 1I:box 1:bay 2, SATA SSD, 1.9 TB, OK)
      physicaldrive 1I:1:3 (port 1I:box 1:bay 3, SATA, 0 GB, Failed)
      physicaldrive 2I:1:5 (port 2I:box 1:bay 5, SATA SSD, 1.9 TB, OK)
      physicaldrive 2I:1:6 (port 2I:box 1:bay 6, SATA SSD, 1.9 TB, OK)

   Unassigned

      physicaldrive 2I:1:7 (port 2I:box 1:bay 7, SATA SSD, 1.9 TB, OK)
      physicaldrive 2I:1:8 (port 2I:box 1:bay 8, SATA SSD, 1.9 TB, OK)

   Array A

      physicaldrive 1I:1:4 (port 1I:box 1:bay 4,, 0 GB, Failed)

Bays 3 and 4 are the failed ones (4 failed before 3).  Bay 7 contains the old disk from bay 3, bay 8 contains a new disk.
Answer: You should be able to add the drives in the spare bays as "hot spare" to the array. That should then also immediately trigger a rebuild onto these drives.
Comment: Thanks for the suggestion.  Unfortunately, `ssacli ctrl slot=0 array A add spares=2i:1:7,2i:1:8` is telling me: *Error: The array status is NOT okay. Cannot perform operation. Spare is not allowed*
Comment: Then you should probably try to `ssacli ctrl slot=0 array A remove drive=1I:1:3,1I:1:4` to remove the failed drives from the array and then `ssacli ctrl slot=0 array A add drives=2i:1:7,2i:1:8`.
Comment: Hmm. `remove drives=1I:1:3,1I:1:4` complains that it's not supported with the current configuration.  *Reason: Array is transforming*.  Not sure what that means.  `ld all show detail` says the Status is *Interim Recovery Mode*.


$\sum_{n = 0}^\infty (-1)^n = \frac{1}{2}$ - Where have I gone wrong?

Question: Not sure where I've gone wrong in the following:
Consider the integral
$$
\int_0^\infty e^{-2x}\:dx = \frac{1}{2}
$$
Via some simple manipulation we find:
\begin{align}
\int_0^\infty e^{-2x}\:dx &= \int_0^\infty e^{-x} e^{-x} \:dx = \int_0^\infty e^{-x} \left[ \sum_{n = 0}^\infty (-1)^n\frac{x^n}{n!} \right] \:dx \\
&= \int_0^\infty \sum_{n = 0}^\infty \frac{(-1)^n}{n!} x^ne^{-x} = \sum_{n = 0}^\infty \frac{(-1)^n}{n!} \int_0^\infty x^ne^{-x}  \:dx \\
&= \sum_{n = 0}^\infty \frac{(-1)^n}{n!} \Gamma(n + 1) = \sum_{n = 0}^\infty \frac{(-1)^n}{n!} n! = \sum_{n = 0}^\infty (-1)^n
\end{align}
And so,
$$
 \sum_{n = 0}^\infty (-1)^n = \frac{1}{2}
$$
This is the famous Grandi's Series which is divergent.
My question: Where have I gone wrong here? What rule/axiom/etc have I violated in my work in achieving this 'result'?
Comment: @DavidGalea which is fine for a finite sum.  Interchanging an *infinite* sum on the other hand requires more justification, just like how interchanging integrals with one another would have required justification, or exchanging a limit inside an integral with outside.
Comment: Well, you swapped a sum and an integral. Do you have a theorem to justify that?
Comment: @DavidGalea Linearity is for finite sums. Using some kind of additional structure, you can extend this to infinite sums in **certain circumstances**. You have found one of the circumstances where it fails.
Comment: You can't interchange the sum and the integral.
Comment: @JohnHughes - The Linearity of continuous integrals
Comment: @JMoravitz - Okay great - what theorems should I explore for this type of situation?
Answer: This is a great question and illustrates the subtleties in manipulating infinite sums. This interchange of limit and integration has violated Fubini's/Tonelli's theorem  [Link] . In particular
$$
\sum_{n=0}^\infty |(-1)^n| = \sum_{n=0}^\infty 1
$$
is divergent, as is
$$
\int_0^\infty \sum_{n=0}^\infty\left|\frac{1}{n!}x^ne^{-x}\right|\,dx = \int_0^\infty \sum_{n=0}^\infty\frac{1}{n!}x^ne^{-x}\,dx
$$
Therefore we cannot apply Fubini's/Tonelli's and would need to find some other justification of the interchange. Since we have proved that a divergent series converges, we will not be able to find a theorem justifiying the interchange.
Comment: Yes but that shows we can't apply Fubini's theorem. And Fubini's theorem doesn't give us a necessary condition.
Comment: @bjorn93 Sorry, you are correct. Although the fact that we have proved a divergent series converges implies that no such interchange is justified. I have modified my answer to reflect this subtly.
Comment: @KyleC The first answer in that link provides an example where the conditions for Fubini's theorem are violated yet the interchange is possible.
Comment: Thank you Kyle.
Comment: @bjorn93 See the link. Fubini's is an if and only if statement.


iPhone Shake event not properly working

Question: I have this inside my viewController:
<code>- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event {

    if (event.type == UIEventSubtypeMotionShake) {

        NSLog(@"I have shaked");

    }
}
</code>
Why is this not working?
Edit:

I do infact have this:
<code>- (void) viewWillAppear:(BOOL)animated
{
    [shakeView becomeFirstResponder];
    [super viewWillAppear:animated];
}
- (void) viewWillDisappear:(BOOL)animated
{
    [shakeView resignFirstResponder];
    [super viewWillDisappear:animated];
}
</code>
Answer: If the UIViewController is loaded at the very start of the application, I've seen an odd glitch in OS 3.0 where it would not become the first responder unless you delayed the appropriate message a bit.  Try placing
<code>[self performSelector:@selector(becomeFirstResponder) withObject:nil afterDelay:0.3];
</code>
within -loadView or something else that is called when the controller is first set up.
There may be a more elegant way to work around this, but this approach has worked for me.
Answer: The viewController must be the first responder during the shake to receive this event.
This could be one reason it's not working.

iPhone Shake event not properly working


inconsistent hoverIntent behavior in chrome, works fine in FF and on other page elements

Question: I'm working on a simple hoverIntent bit on two page elements (hovering over "search_over" makes "search" visible, and hovering over "subscribe_over" makes "subscribe" visible), and I can't figure out why it's working on "subscribe_over" and not "search_over". I'm testing now in Chrome and FF, and it works fine on both divs in FF and only on "subscribe_over" in chrome. can you help me figure out why? Maybe also relevant: I was working on this as a stand-alone page, and I'm now in the process of wordpress-ifying it. It might be a product of clashing with functions in wp_head, though I'm not knowledgeable enough about what goes on under the hood there to make an educated guess at the moment.
here's the jquery code:
var mouseOver = false;
var mouseOver_search = false;

    $('#subscribe').hide();
    $('#subscribe').hover(
        function(){ mouseOver = true; },
        function(){
            mouseOver = false;
            $(this).fadeOut(300);
        }
    );
    $("#subscribe_over").hoverIntent({
        over: appear, // Function to call when mouseover is called
        timeout: 500, // How often in milliseconds the onmouseout should be checked
        out: disappear // Function to call when mouseout is called
    });

    function appear() {
        $('#search').hide();
        $("#subscribe").fadeIn(50);
    }

    function disappear() {
        if (mouseOver == false) $("#subscribe").fadeOut(300);
    }

    $('#search').hide();
    $('#search').hover(
        function(){ mouseOver_search = true; },
        function(){
            mouseOver_search = false;
            $(this).fadeOut(300);
        }
    );
    $("#search_over").hoverIntent({
        over: appear_s, // Function to call when mouseover is called
        timeout: 500, // How often in milliseconds the onmouseout should be checked
        out: disappear_s // Function to call when mouseout is called
    });

    function appear_s() {
        $('#subscribe').hide();
        $("#search").fadeIn(50);
    }

    function disappear_s() {
        if (mouseOver_search == false) $("#search").fadeOut(300);
    }

so, it's literally the same code copied and pasted for the two separate elements with separate function names. it's twice as long as it needs to be, but it's clear that the two elements are governed identically. if it helps, it's at http://yummrs.com/blog (and is very much still under construction!).
last time i had a question answered here, i had the trailing comma of death and it was a simple fix, but i don't see any lingering commas here... thanks in advance for your help.
Comment: I had to "lol" pretty hard seeing the 'comma of death' picture :p
Comment: haha... word. i won't be forgetting that one any time soon.
Answer: looks like it's a known bug already for chrome: http://plugins.jquery.com/content/google-chrome-bug-hoverintent
Comment: odd. but why was it working before i put it in wordpress? it never gave me any problems until i brought all the code into wp.
Comment: hmm, did your xhtml declaration change?
Answer: In your code, you have defined:

subscribe ↓

search

Aren't you missing a href for your search  tag?
Comment: I just validated your HTML in FireFox and it had errors.  This might be the cause of your problem.  Chrome will break things when validation is incorrect.
Comment: damn, it validates now and i still have the problem. any other ideas? like i said, it worked fine before wordpress entered the picture. that code is available at http://yummrs.com/blog/blog files/
Comment: ok, new piece of info: commenting out `subscribe ↓` doesn't fix anything.
Comment: SOLVED. it had to do with some code that changed the position of the background image. chrome doesn't like it when you call hover and hoverIntent on the same element. i combined the hover function with the hoverIntent functions and voila, no more problem. thanks for all your help!! now my html validates, too :)


Why is $\arcsin(\sin(x))$ equal to $x$?

Question:
Why is $\arcsin(\sin(x))$ equal to $x$?

Most videos only state this but give no explanation other than: "They cancel." As these are not reciprocals, how do they "cancel"?
Comment: because this is the inverse function and we get $$f^{-1}(f(x))=x$$
Comment: You'd better say that "their effects cancel out" or compensate each other. $\arcsin(\sin x)=x$, so that the composition of the two functions is neutral (at least in some range). This is true for all inverse functions, both ways: $f(f^{-1}(x))=f^{-1}(f(x))=x$.
Answer: By definition, $\arcsin\colon[-1,1]\longrightarrow\left[-\frac\pi2,\frac\pi2\right]$ is the inverse of the restriction to $\left[-\frac\pi2,\frac\pi2\right]$ of the sine function. Therefore, for each $x\in\left[-\frac\pi2,\frac\pi2\right]$ we have $\arcsin\bigl(\sin(x)\bigr)=x$ because that's part of the definition of inverse functions. The other part of the definition says that, if $x\in[-1,1]$, then $\sin\bigl(\arcsin(x)\bigr)=x$.
Comment: good to point out it is only valid on these intervals.
Answer: It is not valid for all $x$! E.g. $\arcsin(\sin(10 \tfrac{\pi}{4})) = \arcsin(1) =  \tfrac{\pi}{2}.$
Since $\sin(x)$ is periodic, you have to restrict $x$ to $[- \tfrac{\pi}{2}, \tfrac{\pi}{2}].$ For other $x$ you get a saw-tooth function for $\arcsin(\sin(x))$
Comment: Note that this is a triangle wave, at least in audio engineering. Sawtooth vs triangle and other forms can be seen here: https://en.wikipedia.org/wiki/Triangle_wave
Answer: If $f:A \to B$ is a bijective map, then $f^{-1}(f(x))=x$ for all $x \in A$.
This is meant by "cancel".
Comment: i think cancel is the wrong for this, i would say sich gegenseitig aufheben, but i don't know what it is in english
Comment: But isn't this statement false for arcsin and sin? It's true only for x ∈ [−π/2,π/2].
Dr. G: I agree "cancel out" doesn't feel quite right, perhaps  "invert?" "Undoes?" But I used Google translate on your German and got "cancel each other out." :)
Answer: Perhaps seeing this graphically will help.
Restricting $x \in [-\pi/2, \pi/2]$ in order that a unique value for $\arcsin(x)$ exists the black arrows on the plot below show the effect of $x\to \sin(x) = y$. The the red arrows then show the effect of $y \to \arcsin(y)=\arcsin(\sin(x)) = x$ and you end up back where you started.
You might imagine extending the graph beyond $x \in [-\pi/2, \pi/2]$ to see why a unique value of $\arcsin(x)$ would not exist.

Why is $\arcsin(\sin(x))$ equal to $x$?


How do you convert from vector equation of a plane to general equation?

Question: Is there a way to go from a vector equation for example :
$$
[x, y, z] = [1, 6, 2] + s[3, -2, 5] + t[5, 1, -6]
$$
to general equation which is the form:
$$
ax+by+cz+d=0\ ?
$$
Comment: Do you know about normal vectors? If so, take the cross product of two (independent) vectors in the plane to get a normal vector to the plane.
Answer: Okay, so we are given the two direction vectors.  The equation of a plane is stated based on its normal.  so we take the cross product of the two direction vectors to get a vector perpendicular to both.
\begin{array}{l}
\left[ {\begin{array}{*{20}{c}}
3\\
{ - 2}\\
5
\end{array}} \right] \times \left[ {\begin{array}{*{20}{c}}
5\\
1\\
{ - 6}
\end{array}} \right]\\
 = \left| {\begin{array}{*{20}{c}}
{\left[ {\begin{array}{*{20}{c}}
1\\
0\\
0
\end{array}} \right]}&{\left[ {\begin{array}{*{20}{c}}
0\\
1\\
0
\end{array}} \right]}&{\left[ {\begin{array}{*{20}{c}}
0\\
0\\
1
\end{array}} \right]}\\
3&{ - 2}&5\\
5&1&{ - 6}
\end{array}} \right|\\
 = \left[ {\begin{array}{*{20}{c}}
1\\
0\\
0
\end{array}} \right]\;\cdot\left( { - 2\;\cdot\;\left( { - 6} \right) - 1\;\cdot\;5} \right) - \left[ {\begin{array}{*{20}{c}}
0\\
1\\
0
\end{array}} \right]\;\cdot\left( { - 6\;\cdot\;3 - 5\;\cdot\;5} \right)\; + \left[ {\begin{array}{*{20}{c}}
0\\
0\\
1
\end{array}} \right]\;\cdot\;\left( {1\;\cdot\;3 - 5\;\cdot\;\left( { - 2} \right)} \right)\\
 = \left[ {\begin{array}{*{20}{c}}
7\\
{43}\\
{13}
\end{array}} \right]
\end{array}
now that we have the normal [a,b,c] we can create the scalar equation for a plane from it:  Ax+By+Xz+D=0
Now we know A,B,and C.  We don't know D, but we can sub in the given point [1,6,2] to find D.
\begin{array}{l}
7x + 43y + 13z + D = 0\\
7\;\cdot\;\left( 1 \right) + 43\;\cdot\;\left( 6 \right) + 13\;\cdot\;\left( 2 \right)\; + D = 0\\
D =  - 291\\
\\
so:\\
7x + 43y + 13z - 291 = 0
\end{array}


Is it possible to let a superclass to have all subclass as a class variable

Question: Is it possible to let a superclass to have all subclass's type (Type) as a class variable (ClassVar)?
For example, if we have
class A:
    sub_types: ClassVar[List[Type["A"]]]

class B(A): pass
class C(A): pass
class D(A): pass

What I want is A.sub_types = [A, B, C, D] and B.sub_type = [A, B, C, D] and the same for both C and D.
Answer: Yes, we may leverage __init_subclass_ for this behavior and then have a list modified for each subclass. Like this :
class SubTypeWatch:
    sub_types = []

    def __init_subclass__(cls, **kwargs) -> None:
        cls.sub_types.append(cls)
        super().__init_subclass__(**kwargs)

Then let your first child (root) class Inherit this
class A(SubTypeWatch):
    pass

class B(A):
    pass

class C(B):
    pass

class D(C):
    pass

This would result in a shared common sub_type between children.
And it's the same for A, B, C, and D as you specified (it's the same list instance even).
>>> A.sub_types
[<class '__main__.A'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.D'>]
>>> B.sub_types
[<class '__main__.A'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.D'>]
>>> C.sub_types
[<class '__main__.A'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.D'>]
>>> D.sub_types
[<class '__main__.A'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.D'>]
>>>


Displaying translated taxonomy terms

Question: I am trying to achieve a multilingual site that shares its content across all the (currently two) languages, so the same content resides under the same term no matter what language is currently active.
I've been told that I should use the i18n module, which I did. So right now I have all the names of the terms translated in both languages, so that is all working as it should.
The problem is that when I change the language to, for example, Arabic, all the term titles are still in English, even though I have a nice list of translated Arabic counterparts.
So the question I would like to ask is: is there a way to get Drupal to replace all the English terms with the Arabic ones wherever a term's name is displayed? (so make it behave as if every term name has been run through Drupal's t() function)
Most people who tried to answer this question just suggested I use the i18n module. So yeah, I already did that. I have the translations for the term names, but when changing the language, the term names are still in English
Any help would be greatly appreciated
Edit: Please note that I am not talking about a specific module here. For example, when I go to the admin panel's "Add Node" page, I have a drop-down box filled with terms that I have translated, with the language set to Arabic, and yet they still show up as English. This goes to show that it does not work with Drupal Core modules, so it is not likely to be caused by a poorly coded module per se.
Comment: I would expect this to "just work". You probably have a simple configuration error, or possibly a badly coded module/template. You need to "divide and conquer" the problem, as we can't do the debugging for you.
Comment: So would I. But it doesn't seem to work, and I just wanted to find out whether this was the default behaviour, i.e. whether more steps are needed to actually get the translations to show. I'm not asking anyone to solve the problem as a whole, but just to shed some light on the whole process of getting the term names to show up as translated (a task that shouldn't be hard to begin with). I don't think it's a module's fault, as the default Drupal dropdown boxes don't translate it either.
Answer: Fixed, the problem was that the translations did not have the correct context linked to the translation.
Comment: Is there any chance you could summarise your solution  and mark your own answer accepted?

Displaying translated taxonomy terms


Anylogic: Running a model but stuck suddenly without any error

Question: I'm new to Anylogic and created a simple traffic model. Only use 'carSource', 'CarMoveTo', 'Car Dispose' blocks to set the car routes. But After I ran the model, it worked for a while, then all the cars froze without any error occurring. 'Events' panel also stopped. How to solve it?
Answer: Most likely your model is running into an infinite loop somewhere in the logic. The first place to check would be all your loops that might become infinite,e.g Do loops, Do-while loops, iterator for loops where you perhaps change the counter variable manually...
If you have the professional version of AnyLogic the best option is to run the model in debug mode until you get this to the point where it freezes and then press pause. You will then see where in the code the model is getting stuck.

If this does not work you might need to start putting traceln in major functions and see ing you can spot the last traceln that gets printed and keep on adding more and more until you can find the point between two traceln where the model freezes
Answer: I had the same problem, that after a certain time, all cars froze and there wasn't a signle error.
The problem on my side was that the stop line was too close to the intersection, so I moved it a little bit farther.


how to call on('keyup') inside ajax success

Question: i'm trying to make live search based on returned json data via ajax call , this is what i tried , but unfortunately it doesnt work

function returnVistors(){

    k = '';
    $.ajax({
        type:'GET',
        url:'/vistors/list',
        success:function(data){
            const visitors = data.visitors
            const searchInput = document.getElementById('search_visitors').value;
            if(searchInput.length > 0){
                $('#search_visitors').on('keyup',function(){
                for(i = 0;i < visitors.length; i++){
                    const full_name = visitors[i]['full_name'].toLowerCase();
                    if(full_name.incudes(searchInput)){
                        k+='
'+visitors[i]['full_name'] + ' - '+ visitors[i]['city']+'
'
                    }

                    k+='
'+visitors[i]['full_name'] + ' - '+ visitors[i]['city']+'
'
                }
            });
            }
            else{

          for(i = 0;i < visitors.length; i++){
            const id = visitors[i]['id']
            const detail_url = '{% url "vistors:vistor_obj" id=1111 %}'.replace(/1111/,parseInt(id));
            k+='';
            k+='
'+visitors[i]['full_name'] + ' - '+ visitors[i]['city']+'
'
          }

          document.getElementById('visitors_results').innerHTML = k
        }

        },

      });

}

                <button class="text-lg focus:outline-none"></button>
                <input type="text" class="w-11/12 focus:outline-none" name="search_visitors" id="search_visitors" placeholder="search here">

is it possible creating a new function inside ajax success !? thank you for letting me know
Comment: this code has a lots of problem! like
val() is not member of getElementById and visitors variable is not defined etc..
Comment: @CyC0der fixed the issues , sorry
Comment: but still not work
Comment: still has problem,  returnVistors() never called any where
Comment: @freedomn-m its different , you can check it again
Comment: @freedomn-m , anyway is there any solution or not ? thank you
Comment: why your key up under function ? Also , what exactly doesn't work here ?
Answer: You should do the ajax call inside a keyup event handler and not the other way around, it just causes confusion.
You can refer to this code below and see how you can do it.
$('#search_visitors').on('keyup',function(){

    const searchInput = document.getElementById('search_visitors').val();

    if(searchInput.length > 0){
        $.ajax({
            type:'GET',
            url:'/vistors/list',
            success:function(visitors){

                if(visitors.length>0){
                    for(i = 0;i < visitors.length; i++){
                        const full_name = visitors[i]['full_name'].toLowerCase();
                        if(full_name.incudes(searchInput)){
                            k+='
'+visitors[i]['full_name'] + ' - '+ visitors[i]['city']+'
'
                        }

                        k+='
'+visitors[i]['full_name'] + ' - '+ visitors[i]['city']+'
'
                    }
                }
                else
                {
                    for(i = 0;i < visitors.length; i++){
                        const id = visitors[i]['id']
                        const detail_url = '{% url "vistors:vistor_obj" id=1111 %}'.replace(/1111/,parseInt(id));
                        k+='';
                        k+='
'+visitors[i]['full_name'] + ' - '+ visitors[i]['city']+'
'
                    }

                    document.getElementById('visitors_results').innerHTML = k
                }

            },
        })
    }

});

Also, you are referring to the visitors variable inside your success function callback when you are naming the incoming data as data


Why do I need double parentheses  in constructor calls like: foo x( (bar()) );

Question:
Possible Duplicate:
Why is it an error to use an empty set of brackets to call a constructor with no arguments?

I have seen the C++ FQA entries about nested constructor calls and bracing and always wondered how C++ parsers resolve two and why it isn't possible for parsers to resolve it.
So I get why foo xxx(); is ambiguous. but what makes then foo x(bar()); ambiguous, as it is clearly no forward-declaration. (i.e.: there should be a grammar that can successfully detect this).
Could someone explain the limitations and ambiguity in that part of the C++ grammar?
Comment: google "most vexing parse"
Comment: These are braces: `{}`. These are parentheses: `()`.
Comment: The FAQ entry you linked explains that. Third paragraph from bottom.
Answer: foo x(bar());

This could be either:
1) A declaration for a variable called x whose value is a default-constructed bar. This is the same as foo x = bar();.
2) A declaration for a function called x that returns foo and takes a single parameter -- a function that returns a bar and takes no parameters. This is the same as foo x(bar (void));
Comment: No, 2 isn't an invalid declaration. `foo x(bar (void))` means that `x` is a function that returns `foo` and takes `bar (*)(void)`. The reason the `(*)` doesn't have to be explicit is that there's a rule for function declarations that if a parameter type is a function type then the parameter is 'adjusted' to be a pointer to that function type. This is exactly like the rule where if a parameter is an array it is 'adjusted' to be a pointer type; `void a(int x[])` is exactly equivalent to `void a(int *x)`, and `foo x(bar())` is equivalent to `foo x(bar(*)())`.
Comment: that is my point here isn't 2 an invalid declaration? or what does it mean? does it mean then that bar is a function prototype and foo takes a function pointer as first argument? shouldn't that be bar (*)() then?
Answer: The C++ FQA is a pile of garbage. Ignore it.
As for foo x(bar()), it is as ambiguous as foo x(), except the type of x also takes an argument, which is a function. Add a pointer here and you'll see what I mean.
foo (*x)();
foo (*x)(bar(*)());

Even the idea of allowing this is beyond silly, but nobody can change it now.
(I have a sneaking suspicion that this grammar is a tad off, but I'm sure someone will correct me).
Comment: I don't think `x` is a function pointer here, just a function declaration that decays to a pointer when used.
Comment: It isn't, I'm just adding the pointer to make it more obvious how it's equivalent.


How to parse multiple values from a JSON in Android?

Question: I have tried parsing JSON for the first time. In my JSON data there are multiple JSON objects in a single JSON array. The data sample:

{ "root":[ {"Sc_we":[ ]}, {"Sc_wesam":[ {"head":"Welcome page"}, {"color":"Black"} ]} ] }

This is my code:
 public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    try {
        website = new URL(
                    "http://xxxxxxx");
        InputStream in = website.openStream();
        parseMovie(in);
    }
    catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

protected void parseMovie(InputStream json) throws IOException,
JSONException {
    // TODO Auto-generated method stub

    BufferedReader reader = new BufferedReader(new InputStreamReader(json));
    StringBuilder sb = new StringBuilder();
    String line = reader.readLine();
    while (line != null) {
        sb.append(line);
        line = reader.readLine();
    }
    reader.close();
    System.out.println(sb);
    JSONObject jobj = new JSONObject(sb.toString());
    System.out.println("jsonobj:" + jobj);

    JSONArray array = jobj.getJSONArray("root");

    System.out
        .println("jsonobject   :+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"
                + array);
}

I get the above JSON data, but I need the S_we value and Sc_wesam data.
How do I do this?
Answer: You can iterate over individual elements using your JSONArray, and make some assumptions about your data:
JSONArray array = jobj.getJSONArray("root");
JSONObject subObj;
JSONArray subArray;

for (int i = 0; i < array.length(); i++)
{
    subObj = array.getJSONObject(i);

    if (subObj.has("Sc_wesam")) // handle Se_wesam
    {
        subArray = subObj.getJSONArray("Sc_wesam");

        for (int j = 0; j < subArray.length(); j++)
        {
            subObj = subArray.getJSONObject(j);
            if (subObj.has("head"))
                System.out.println("Sc_wesam head value: " +
                                   subObj.getString("head"));
            else if (subObj.has("color"))
                System.out.println("Sc_wesam color value: " +
                                   subObj.getString("color"));
        }
    }
    else if (subObj.has("Sc_we")) // handle Se_we
    {
        subArray = subObj.getJSONArray("Sc_wesam");

        // ... etc.
    }
}

Comment: @Ramz the code will loop over all the sub-objects in the array, but you may need to make more assumptions about the data, i.e. look for more names beside just _Sc_we_ and _Sc_wesam_. It also depends on what you want your results to look like: do you want to completely parse the JSON structure, or just pull out parts of it?
Comment: got the answer but what if i have more than two in my json arraor the are more that two obj for my link what should i do for that.any way thankx for helping


Erro ORA-01461 ao tentar salvar um campo de texto CLOB gerado por um template. O que faço para corrigir isto?

Question: Ocorre erro ao tentar salvar um registro na classe Lotemail.
tabela:
lotemail
LOTEMAILID            NOT NULL NUMBER(18)
LOTEMAILCORPO                  CLOB

Classe:
class Lotemail(models.Model):
    lotemailid             = models.BigIntegerField( primary_key=True)
    lotemailcorpo          =  models.TextField()

    class Meta:
        db_table = 'lotemail'

Trecho da Rotina:
lotemail = Lotemail()
lotemail.lotemailcorpo         = content
lotemail.save()
Na rotina acima a variável "content" é uma String, gerada a partir de uma lista de objetos que vai para um template em layout HTML.
O que é estranho que em uma rotina funciona e na outra não.
Verifiquei tamanho de String e a que dá erro o length é menor que ao que dá certo, e o template tem o mesmo charset (do que dá certo e o que dá errado).
Erro:
DatabaseError at /procedimentos/previsao/notas/preview

ORA-01461: can bind a LONG value only for insert into a LONG column

Request Method:     POST
Request URL:    http://127.0.0.1:8000/procedimentos/previsao/notas/preview
Django Version:     1.6.5
Exception Type:     DatabaseError
Exception Value:

ORA-01461: can bind a LONG value only for insert into a LONG column

Exception Location:     /usr/lib64/python2.7/multiprocessing/pool.py in get, line 554
Python Executable:  /root/Documentos/desenvolvimento/intranet-master/venv/bin/python
Python Version:     2.7.5

Peço alguma sugestão para ajudar-me a corrigir isto.
Answer: O erro "ORA-01461: can bind a LONG value only for insert into a LONG column" se refere a algumas restrições que o tipo LONG tem.
Como sugestão, conforme esta resposta no SOEN, você pode:

criar a coluna como sendo varchar2, determinando o tamanho de acordo com o máximo de dígitos, ou
inserir no campo um valor tipo contador com até 20 caracteres.

creating a table with a column of varchar2 (20 or any arbitrary length) and
inserting into the above table with a row containing more than 20 characters

OBS: na própria resposta do SOEN lincada existem algumas outras alternativas que talvez até resolvam melhor o seu problema, vale dar uma olhada.


JS GetElementByClassName[0] return undefined

Question: I am following a tutorial on W3Schools to make a JS slideshow. While this seems simple enough, even after directly copying their code, my JavaScript is having some VERY nonsensical and frustrating errors. The issue seems to be that, when my function accesses document.getElementsByClassName("slides")[some_index_here], it returns undefined, despite that, when I access the SAME element in the exact same way through inspect element console, what I am looking for shows up. What is going on?
Comment: Are you declaring your script after the DOM or before it? My assumption is your script is loading before it has time to parse over the DOM.
Comment: Your code is being executed before those elements exist on the page
Comment: We need your markup
Comment: "I am following a tutorial on W3Schools" Thank You for not linking to *that* site.  ;)
Comment: this is nonsensical and silly :-) we should write a letter to w3 schools
Comment: If figured out that I was not wrapping anything in window.onload.
Answer: I found that I needed to wrap what I did in a window.onload function, because the code was executing before elements existed.