Non-algebraic flops

Question: I am looking at Exercise 84 on Kollár's Exercises in the birational geometry of algebraic varieties about non-algebraic flops:

Let $X \subset \mathbb{P}^4$ be a general smooth quintic hypersurface. It is know that for every $d \geq 1$, $X$ contains a smooth rational curve $\mathbb{P}^1 \cong C_{d} \subset X$ of degree $d$ with normal bundle $\mathcal{O}(-1)^{\oplus 2}$. Prove that the flop of $C_{d}$ exists if we work with compact complex manifolds. Denote the flop by $\phi_{d}: X \dashrightarrow X_{d}$ and let $H_d$ be the image of the hyperplane class. Compute the self intersection $(H_{d})^{3}$ and conclude that the $X_{d}$ are not homeomorphic to each other and not projective.

If I'm correct the intersection number $(H_{d})^{3} = 5 - 5d^3$ and the picard number $\rho(X_{d}) = 1$ so $X_{d}$ is not projective. However, I think the variety $X_{d}$ is constructed by first blowing up the curve $C_d$ with exceptional divisor $E \cong \mathbb{P}^1 \times \mathbb{P}^1$, and then contract the other negative extremal ray by the minimal model program. Doesn't this construction always give projective varieties? I feel like I messed up with something in this contradiction.
Any help is appreciated!
Comment: Actually, my computation shows that $(H_d)^3=5-d^3$.
Comment: Another comment: There is a misquote in Kollar's statement. In the original Clemens' paper, the degree of $C_d$ is something like a quadric polynomial dependent on $d$ (computed in Voisin's _Variations of Hodges structure of Calabi-Yau threefolds_, Chapter 4). It's not the case that for each degree there is such a rational curve, at least not from the Clemens' construction.
Answer: After reading some analytic theory on contractions, it turns out the point here is that the other fibre of the exceptional divisor $E$ is not extremal, so one cannot use the Minimal Model Program here. Instead one should use the following analytic contraction theorem of Nakano (Main Theorem, On the Inverse of Monoidal Transformation, Shigeo Nakano):

Let $\tilde{X}$ be a complex analytic manifold of complex dimension $n \geq 3$ and $S$ an analytic submanifold of $\tilde{X}$ of codimension 1. Suppose that $S$ has a structure of an analytic fibre bundle over an analytic manifold $M$ with a projective $(r-1)$-space as the standard fibre and that $r > 1$. Denote $L_a$ the fibre over $a \in M$ in the bundle $S \rightarrow M$. Then, in order that there exists an $n$-dimensional analytic manifold $X$ containing $M$ and a holomorphic map $\pi: \tilde{X} \rightarrow X$ in such a way that $(\tilde{X},\pi)$ is the monoidal transformation of $X$ with center $M$ and $S = \pi^{-1}(M)$, it is necessary and sufficient that the following conditions are satisfied:(1) for any $a \in M$, $\mathcal{O}(S)|_{L_a} \cong \mathcal{O}_{L_a}(-1)$; (2) each $L_a$ has a neighbourhood $V$ in $\tilde{X}$ such that $\mathcal{O}(K_V) = \mathcal{O}(S)^{k}$, where $k$ is a non-negative integer.

One can verify condition (1) by computing the normal bundle of $S$, and condition (2) from the fact that $X$ is smooth Calabi-Yau variety.
Answer: This is a very interesting question. I was also puzzled by this for a while. Here is a proof of why the fiber $F_2$ of the other contraction is not an extremal curve.
Let $\tilde{X}$ denote the blowup of $X$ at one rational curve $C$ of degree $d$. The exceptional divisor $E\cong \mathbb P^1\times \mathbb P^1$ has two rulings $F_1$ and $F_2$. $F_1$ is a fiber of $\tilde{X}\to X$ and $F_2$ is the fiber of the other contraction.
Since $X$ contains 2875 lines, one can take one of the lines $L$ disjoint from $C$. Now we have three curve classes $[L], [F_1]$ and $[F_2]$ for $\tilde{X}$. Since $H^4(X,\mathbb Z)$ has rank 1 (generated by $[L]$),  $H^4(\tilde{X},\mathbb Z)$ has rank 2 according to the blowup formula for cohomology, so there has to be a relation between three classes.
We claim that
$$[F_2]=d[L]+[F_1]. \label{1}\tag{1}$$
This shows $[F_2]$ is indeed not extremal in the cone of curves.
It suffices to show the intersection number with all the surface classes on the both sides of equation coincide. The Picard group $\text{Pic}(\tilde{X})$ is generated by $E$ and the strict transform $\tilde{H}$ of a general hyperplane section $H$. A direct computation shows:
$$\tilde{H}\cdot L= 1, ~E\cdot L= 0,$$
$$\tilde{H}\cdot F_1= 0, ~E\cdot F_1= -1,$$
$$\tilde{H}\cdot F_2= d, ~E\cdot F_2= -1.$$
Therefore the equation $\eqref{1}$ is established.
(p.s., I still can't see homologically why the relation $\eqref{1}$ holds, i.e., how to find a 3-chain bounding the three curves.)

Non-algebraic flops


GWT project changes after compile

Question: I have big maven GWT project. I have added one column to my grid in one module. When I check it through debug from Development mode everything is OK(the column is full of data). But when I create war file and deploy it on Tomcat7 the column appears but its empty(without any data). After creating war file if I try debug mode I cant see any data too. But if I add any changes to file , save it and run debug again its ok again, full of data.
Why after making war package I cant see any data? What happens after compile?
Comment: Do you `mvn clean` before you `mvn package` for deployment?
Answer: There could be many reason for this kind of bug.
1st of all debug mode and real deployment doesn't run the same way. Debug mode is a full java execution associated with a browser plugins which manage the display whereas the war will be deployed as a full html / js client that asynchronously calls your server services, rendering could so be different.
Otherwise it could be a synchronization problem due to difference of execution speed between the 2 modes, your view could be generated before the data are available in a way and after in other one, assuming no refresh mechanism is implemented.
Otherwise it' may be a js compilation problem, check compilation output.
Comment: The data is been taken from my DataBase
Comment: When everything is OK grid column shows current values from DB

GWT project changes after compile


How do I solve This Error? 'Unable connect '

Question: It's selenium. and the development environment pycharm
What does the yellow line in import os mean? and Hod do I solve This error??
And I want to save images crawled by Google using Selenium to my desktop file.
desktop file name 'Image'.
file address is '/Users/jun/Desktop/PyCham/selenium image folder
help me . I'm english pool sorry.
Answer: You have to mention from where to import the os.
Similarly to
from selenium import webdriver

You have to mention from where os will be imported.
BTW, also, path need to contain the hromedriver with the extension.
Like this:
path = 'C:\webdrivers\chromedriver.exe'

Answer: import os is highlighted because before it you have an infinite loop. This code
while True:
    browser.find_element_by_tag_name('body').send_keys(Keys.PAGE_DOWN)
    time.sleep(1)

will never end because there are no conditions to stop this while loop and no breaks implemented.
So all the code under this while is unreachable, including the import os
Also I see that the path to the folder is too long and it looks like you pasted it two times. Since you are using MacOS (according to the file system structure), the path should start with /Users/


Is this Bayes Theorem?

Question: Is this Bayes Theorem?
I'm reading this blog and it says this is Bayes Theorem. I thought Bayes Theorem just had two probabilities divided by one probability.
Answer: Yes, it's just Bayes theorem with some additional probability rules applied (and then some additional manipulations).
e.g. one such rule being used is $p(z,\theta) = p(z|\theta)\, p(\theta)$, which follows from the definition of conditional probability. See
https://en.wikipedia.org/wiki/Conditional_probability#As_an_axiom_of_probability
You might start with $p(z|y,\theta)=p(y|z,\theta)\, p(z,\theta)/p(y,\theta)$ and then apply common probability rules.
If it is not immediately clear that this expression is just Bayes, begin with:
$p(z|y,\theta)\, p(y,\theta) = p(z,y,\theta) = p(y|z,\theta)\, p(z,\theta)$ (which follows from conditional probability axioms) and divide through by $p(y,\theta)$, in similar fashion to deriving the most basic form of Bayes' theorem.
Then proceed to apply simple manipulations using basic facts as needed.
Comment: Thank you. I know I can infer it from the equations, but what does the comma mean here exactly? How is it different from the | symbol? $p(z|y,\theta)$
Comment: When you're dealing with the joint distribution of more than one variable you put commas between the variables -- see https://en.wikipedia.org/wiki/Probability_density_function#Densities_associated_with_multiple_variables  and https://en.wikipedia.org/wiki/Joint_probability_distribution#Continuous_case, compare that with the use of the vertical bar in conditional distributions, with the thing after $|$ being what is conditioned on -- see https://en.wikipedia.org/wiki/Conditional_probability_distribution#Conditional_continuous_distributions

Is this Bayes Theorem?


Como limitar o número de casas antes da vírgula em uma expressão regular?

Question: Estou usando esta expressão para não deixar o usuário digitar ponto antes de qualquer número e limitando 2 casas depois da vírgula, mas eu precisava também limitar 5 casas antes da vírgula, do jeito que está eu posso inserir quantos números quiser antes da vírgula. Alguém sabe como posso fazer isso? estou apanhando aqui.
Minha expressão: "([0-9]+(\\.)?([0-9]?[0-9]?))"
Comment: Tipo assim? `\d{1,5}(\.\d{1,2})?` (1 a 5 dígitos, e opcionalmente o ponto seguido de 1 ou 2 dígitos) P.S. Esses grupos são de captura? Ou tanto faz?
Answer: Da mesma forma que você fez pra limitar depois:
"([0-9][0-9]?[0-9]?[0-9]?[0-9]?(\\.)?([0-9]?[0-9]?))"

Ou seja, o primeiro é obrigatório, e os 4 seguintes são opcionais. No entanto, eu tenho algumas sugestões pra melhorar essa regex:

Use as chaves para escolher o número de vezes que um elemento vai se repetir. exp{n} significa que a expressão precisa ocorrer exatamente n vezes. exp{a,b} significa que ela precisa ocorrer no mínimo a e no máximo b vezes:
"([0-9]{1,5}(\\.)?([0-9]{0,2}))"

Se esses grupos não forem de captura, eu sugiro removê-los, pois isso complica desnecessariamente a regex:
"[0-9]{1,5}\\.?[0-9]{0,2}"

Desse jeito ainda é possível se ter um ponto sem nenhum dígito na frente, ou nenhum ponto e dois dígitos a mais. Ligue o ponto aos dígitos, e exija ao menos 1 dígito se o ponto estiver presente:
"[0-9]{1,5}(\\.[0-9]{1,2})?"

Você pode usar \d (escapado, \\d) para representar um dígito, em vez do intervalo [0-9]:
"\\d{1,5}(\\.\\d{1,2})?"

Se você quiser evitar zeros à esquerda, separe o caso do 0 com o caso de [1-9] seguido de 0 a 4 dígitos:
"(0|([1-9]\\d{0,4}))(\\.\\d{1,2})?"

Comment: vlw pela resposta, mas nenhum funcionou. O que acontece é que estas expressões deixam eu colocar se eu tiver digitado até 5 números. Elas aceitam mais de 5 números, e depois do 6° número não deixa mais eu digitar ponto.
Comment: @daniel12345smith O problema deve estar na forma como você está usando então, e não na expressão em si. Pois as expressões estão corretas, veja [esse exemplo](http://rubular.com/r/9ssoaGRUwt). Se precisar de mais ajuda, mostre o código Java onde você usa essa expressão.
Answer: Imagino que esta possa lhe satisfazer:
/^(\d{1,5})?(\.\d{1,2})?$/
Aqui seque um exemplo em HTML da validação:

$('input').keyup(function(e){
  var val = this.value;
  var test = /^(\d{1,5})?(\.\d{1,2})?$/

  if(test.test(val)){
    $("p").html("Válido.")
  }else{
    $("p").html("Inválido.")
  }
});

<input type="text" value="12345.67"/>


Erro ao listar dados do banco - JPA2 e Hibernate / JSF

Question: Erro do console no eclipse

mar 27, 2018 2:05:24 PM com.sun.faces.application.view.FaceletViewHandlingStrategy handleRenderException
GRAVE: Error Rendering View[/Fornecedor.xhtml]
javax.el.ELException: /Fornecedor.xhtml @29,86 value="#{fornecedorBean.listaFornecedor}": Error reading [listaFornecedor] on type [bean.FornecedorBean]
    at com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:114)
    at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:194)
    at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:182)
    at javax.faces.component.UIData.getValue(UIData.java:730)
    at javax.faces.component.UIData.getDataModel(UIData.java:1809)
    at javax.faces.component.UIData.setRowIndexWithoutRowStatePreserved(UIData.java:483)
    at javax.faces.component.UIData.setRowIndex(UIData.java:472)
    at com.sun.faces.renderkit.html_basic.TableRenderer.encodeBegin(TableRenderer.java:82)
    at javax.faces.component.UIComponentBase.encodeBegin(UIComponentBase.java:826)
    at javax.faces.component.UIData.encodeBegin(UIData.java:1131)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1777)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1782)
    at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:439)
    at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:124)
    at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:120)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:594)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:494)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:137)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:651)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:407)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:754)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1376)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.NoSuchFieldError: NONE
    at org.hibernate.ejb.QueryImpl.<init>(QueryImpl.java:620)
    at org.hibernate.ejb.QueryImpl.<init>(QueryImpl.java:81)
    at org.hibernate.ejb.AbstractEntityManagerImpl.createQuery(AbstractEntityManagerImpl.java:291)
    at repository.FornecedorRepository.buscaTodas(FornecedorRepository.java:28)
    at bean.FornecedorBean.getListaFornecedor(FornecedorBean.java:94)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at javax.el.BeanELResolver.getValue(BeanELResolver.java:94)
    at com.sun.faces.el.DemuxCompositeELResolver._getValue(DemuxCompositeELResolver.java:176)
    at com.sun.faces.el.DemuxCompositeELResolver.getValue(DemuxCompositeELResolver.java:203)
    at org.apache.el.parser.AstValue.getValue(AstValue.java:169)
    at org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:184)
    at com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:109)
    ... 39 more

mar 27, 2018 2:05:24 PM org.apache.catalina.core.StandardWrapperValve invoke
GRAVE: Servlet.service() for servlet [Faces Servlet] in context with path [/Venda_Estoque] threw exception [NONE] with root cause
java.lang.NoSuchFieldError: NONE
    at org.hibernate.ejb.QueryImpl.<init>(QueryImpl.java:620)
    at org.hibernate.ejb.QueryImpl.<init>(QueryImpl.java:81)
    at org.hibernate.ejb.AbstractEntityManagerImpl.createQuery(AbstractEntityManagerImpl.java:291)
    at repository.FornecedorRepository.buscaTodas(FornecedorRepository.java:28)
    at bean.FornecedorBean.getListaFornecedor(FornecedorBean.java:94)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at javax.el.BeanELResolver.getValue(BeanELResolver.java:94)
    at com.sun.faces.el.DemuxCompositeELResolver._getValue(DemuxCompositeELResolver.java:176)
    at com.sun.faces.el.DemuxCompositeELResolver.getValue(DemuxCompositeELResolver.java:203)
    at org.apache.el.parser.AstValue.getValue(AstValue.java:169)
    at org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:184)
    at com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:109)
    at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:194)
    at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:182)
    at javax.faces.component.UIData.getValue(UIData.java:730)
    at javax.faces.component.UIData.getDataModel(UIData.java:1809)
    at javax.faces.component.UIData.setRowIndexWithoutRowStatePreserved(UIData.java:483)
    at javax.faces.component.UIData.setRowIndex(UIData.java:472)
    at com.sun.faces.renderkit.html_basic.TableRenderer.encodeBegin(TableRenderer.java:82)
    at javax.faces.component.UIComponentBase.encodeBegin(UIComponentBase.java:826)
    at javax.faces.component.UIData.encodeBegin(UIData.java:1131)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1777)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1782)
    at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:439)
    at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:124)
    at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:120)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:594)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:494)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:137)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:651)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:407)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:754)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1376)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Unknown Source)

FornecedorRepository
public class FornecedorRepository {

    private EntityManager manager ;

    public FornecedorRepository (EntityManager manager ) {
        this.manager = manager ;
    }

    @SuppressWarnings("unchecked")
    public List <Fornecedor> buscaTodas() {
        Query query = this.manager.createQuery(" SELECT e FROM Fornecedor e");
        return query.getResultList();
    }
}

FornecedorBean
@ManagedBean
public class FornecedorBean {

    private List<Fornecedor> listaFornecedor;

    public List<Fornecedor> getListaFornecedor() {
        try {
            EntityManagerFactory factory = Persistence.createEntityManagerFactory("venda_estoque");
            EntityManager manager = factory.createEntityManager();

            FornecedorRepository fr = new FornecedorRepository(manager);
            fr.buscaTodas();
        }catch(Exception e) {
            e.printStackTrace();
        }
        return listaFornecedor;
    }

    public void setListaFornecedor(List<Fornecedor> listaFornecedor) {
        this.listaFornecedor = listaFornecedor;
    }

}

Comment: Pode nos passar o resultado do `mvn dependency:tree` e o conteúdo do pom.xml? (assumindo que esteja usando maven). Este problema costuma aparecer quando tem algo errado no classpath
Comment: não estou utilizando maven
Comment: Está com as libs do hibernate direto no projeto? Mostra todos os JARs que estão no projeto então.
Comment: sim eu coloquei as libs do hibernate. Coloquei as um print dos jars utilizado
Answer: Verifique a versão da biblioteca hibernate-commons-annotations que está 4.0.1 enquanto as outras estão 4.1.6.
Uma outra coisa a linha:
fr.buscaTodas();

Deveria ser:
listaFornecedor = fr.buscaTodas();


Obtaining angle of rotation from eigenvalues of the rotation matrix

Question: Suppose we have a 2D rotation matrix. If we plot eigenvalues on the complex plane, angle of rotation is connected to eigenvalues -- larger rotations have eigenvalues further away from 1.

To extend this to higher dimensions, I want to know the following:
Given a fixed generic orthogonal matrix $A$, and a random Gaussian vector $x$, can we get $z$, the expected value of cosine of the angle between $x$ and $Ax$, from eigenvalues of $A$?
There appears to be square-root-like relationship, if rotation is small, all eigenvalues are close to $1$, as we increase $z$, eigenvalues get further away from $1$.

This plot is made by taking orthogonal component of QR decomposition of $I+\epsilon G$ for random Gaussian matrix $G$ and varying values of $\epsilon$. Estimating angle of rotation by trying it on random Gaussian vectors, and plotting against arg of the eigenvalues.
Notebook
Answer: Yes, the expected value of the cosine is uniquely determined by the eigenvalues, being the average of the real parts.
We can decompose $A$ as rotations $R_i$ of mutually orthogonal 2D subspaces $V_i$ (and the identity or reflection along a 1D space if the dimension is odd).
Let $\lambda_i, \overline{\lambda_i}$ be the eigenvalues of $A$ corresponding to $R_i$ and let $x_i$ be the projection of $x$ onto $V_i$.
Then $x^TAx = \sum_i x_i^T R_i x_i$.
For $v_i$ uniformly distributed on $\{v\in\mathbb{R}^2: \|v\|_2 = 1\}$, we have $\mathbb{E}[v_i^T R_i v_i] = \Re(\lambda_i)$, so with $x$ uniformly distributed on the sphere, $$\mathbb{E}[x^TAx] = \frac{2}{n}\sum_i \Re(\lambda_i),$$ where $n$ is the dimension.
Comment: Oh that's great, so simple!


Let 'web-view' mobile iOS/Android app talk consume/feed site

Question: I have a Drupal 8 site with the following modules:

HAL.
HTTP Basic Authentication.
REST UI.
RESTful Web Services.
Serialization.

Using the REST UI module, I configured it as follows.
Settings for resource User
Granularity
 - Resource
Methods
 - GET
 - POST
 - PATCH
Accepted request formats
 - json
Authentication providers
 - basic_auth
 - cookie
I created an IOS & Android web-view app. I am using the Firebase module to send 'Push Notifications' to registered users on the website on specific events, such as Send a push notification to the 'node author' whenever his node is updated.
I know I have to pass a unique token of the mobile device used by the logged in user and store it on my Drupal site. for that, I have created the  field_user_push_token text field on the user profile page in order to store the token received from the mobile device of the user.
How can I transfer the token from the mobile device to the field_user_push_token field?
I believe I should use the PATCH method, but I don't know how.
Am I on the right track by using the RESTful Web Services, or is there a better method?
UPDATE #1:
I am the web developer of the website but not the mobile developer, so I asked a mobile developer (Not familiar with Drupal) to create the 'web-view' apps for me... He told me to setup an API for him so he can access the website and he will generate the token and send it to my Drupal website through the provided API...
My skills towards Restful API are very limited so by following some tutorial I have setup the Restful web service API on my website but:
What information I have to give him in order to access my website from the created 'web-view' app ?
is it only https://example.com/user/{user}?_format=json or I am missing something here ?
I am a bit confused...
Answer: Elie Masaad, You can use PATCH method like this Drupal 8 Android app at https://github.com/onedrupal/One-Drupal-Android.
PATCH related android source code using OkHttpClient https://github.com/onedrupal/One-Drupal-Android/blob/master/app/src/main/java/com/technikh/onedrupal/activities/ActivityPost.java#L637
request = new Request.Builder()
                        .header("Content-Type", "application/json")
                        .url(url)
                        .patch(api_body)
                        .build();
OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(20, TimeUnit.SECONDS)
                .writeTimeout(20, TimeUnit.SECONDS)
                .readTimeout(20, TimeUnit.SECONDS)
                .addInterceptor(new AddCookiesInterceptor())
                .build();

AddCookiesInterceptor at https://github.com/onedrupal/One-Drupal-Android/blob/master/app/src/main/java/com/technikh/onedrupal/network/AddCookiesInterceptor.java
You can define your REST endpoint for Android Retrofit at https://github.com/onedrupal/One-Drupal-Android/blob/master/app/src/main/java/com/technikh/onedrupal/network/GetSiteDataService.java#L31 like
@GET("/node/{editNid}?_format=json")
    Call<ModelNodeType> getNode(@Path("editNid") String nid);

Comment: Elie Masaad, one_api module is just a configuration around core REST APIs. Download & enable Rest UI module at https://www.drupal.org/project/restui. Then you will be able to enable user PATCH endpoint. Use something like POSTMAN https://www.getpostman.com/ to update user field_user_push_token field using PATCH endpoint. If you are able to successfully use POSTMAN to update the field_user_push_token field then you can do it from iOs or Android(OkHttpClient) code.
Comment: thank you for the answer, your app looks promising and sure will use it on a different project currently under development! However, my case here is different since my current project requires app for both IOS and android which they are already built and ready to use (web-view apps)... I need to find the solution for **How can I transfer the token from the mobile device to the field_user_push_token field available on user profile page ?** using Restful web service API module and not One_API module... Correct me please if I am wrong !


Matplotlib Pyplot logo/image in Plot

Question: I'm struggling to achieve a simple goal in matplotlib... I want to put a small logo or indicator in the bottom right of my graph, without altering the axis or the real data that is being displayed. Here is my code now:
fig = plt.figure()
plt.rcParams.update({'font.size': 15})

img = plt.imread('./path/to/image.png')
ax1 = fig.add_subplot(111)
ax1.yaxis.tick_left()
ax1.tick_params(axis='y', colors='black', labelsize=15)
ax1.tick_params(axis='x', colors='black', labelsize=15)

plt.grid(b=True, which='major', color='#D3D3D3', linestyle='-')

plt.scatter([1,2,3,4,5],[5,4,3,2,1], alpha=1.0)

plt.autoscale(enable=True, axis=u'both')

fig.savefig('figure.png')

My output from this is below.
This is now laying the photo over the whole graph -- I'd like it scaled to 20% of width & height (if possible) and anchored to the bottom right. This also ruins my axis, because in this output I should be in the 0-100 range on both x & y. Any ideas to solve this, the scaling is the big issue.
Edit1: I've tried the solution below and linked questions here on SO. The problem is relying on the extent variable being passed to imshow() then doesn't work well when introducing new data. For example plotting a scatter plot coming from a data frame, could be from 0..1000 and 50..100 but using extent won't show the label or the position will be off.
Edit2: There seems to be some progress with getting the figure length with fig.get_size_inches() and passing the variable to extent. Apparently all of matplotlib graph calculations are done through inches, so this may be a promising lead.
Answer: import matplotlib.image as image
import matplotlib.pyplot as plt

im = image.imread('debian-swirl.png')
fig, ax = plt.subplots()
ax.imshow(im, aspect='auto', extent=(0.4, 0.6, .5, .7), zorder=-1)
ax.yaxis.tick_left()
ax.tick_params(axis='y', colors='black', labelsize=15)
ax.tick_params(axis='x', colors='black', labelsize=15)
ax.grid(b=True, which='major', color='#D3D3D3', linestyle='-')
ax.scatter([1,2,3,4,5],[5,4,3,2,1], alpha=1.0)
plt.show()

I added a png file to bottom left. Adjust the extent parameter to set the logo position.
Similar to : Scale image in matplotlib without changing the axis
Comment: Is it not possible to contain the image to 20% width and height of the plot, not depending on the data? I'd like to be able to constantly put this image on any plot that I create, and with this code I have to adjust the "extent" factor depending on how my axis scales with new data
Comment: Eg. If I change the data being passed in to [100,90,89,70], [55, 23,76,29] this no longer displays an image
Comment: I'm also interested in an answer that utilizes fractional coordinates of the axis (not the entire figure).
Answer: The following is an adaptation of the answer by Kirubaharan J, but adapting the position of the logo to the extent of the graph (but the aspect ratio of the logo itself is not preserved)
import matplotlib.image as image
import matplotlib.pyplot as plt

im =image.imread('debian-swirl.png')
fig, ax = plt.subplots()
ax.yaxis.tick_left()
ax.tick_params(axis='y', colors='black', labelsize=15)
ax.tick_params(axis='x', colors='black', labelsize=15)
ax.grid(b=True, which='major', color='#D3D3D3', linestyle='-')
ax.scatter( [100,90,89,70], [55, 23,76,29], alpha=1.0)

plt.autoscale(enable=True, axis=u'both')

xrng=plt.xlim()
yrng=plt.ylim()
scale=.2 #the image takes this fraction of the graph
ax.imshow(im,aspect='auto',extent=(xrng[0],xrng[0] + scale*(xrng[1]-xrng[0]), yrng[0], yrng[0] + scale*(yrng[1]-yrng[0]) ), zorder=-1)
plt.xlim(xrng)
plt.ylim(yrng)

plt.show()

Answer: I've worked on a similar problem to print several pdf with a fix logo on every pages independant of the graph size. The best solution I found was using GridSpec.
fig = plt.figure(figsize = (11,8.5)) # 8.5" x 11" : letter format
G = plt.GridSpec(14,21)

I my case I'v build a grid of 14 square by 21 over an 8.5 x 11 inch template.
Then I just have to allocate a section of the grid for the logo and import it using matplotlib.image
ax = fig.add_subplot(G[2:5,5:14])
logo = mpimg.imread("logo.png")
imagebox = OffsetImage(logo, zoom=0.08)
ab = AnnotationBbox(imagebox, (0.4, 0.6), frameon = False)
ax.add_artist(ab)

You can control the scale using the zoom arg in OffsetImage
You can find the detail at the following link :
https://www.science-emergence.com/Articles/How-to-insert-an-image-a-picture-or-a-photo-in-a-matplotlib-figure/
Comment: I just encountered this problem and using AnnotationBbox as in your link was the best solution I found
Answer: i think it's best to simply put the image on a new axis...
in this way you have full control on where to put it without having to bother with existing axes
import matplotlib.image as image
import matplotlib.pyplot as plt
# create a plot
f, ax = plt.subplots()

im = image.imread("path-to-logo.png")

# put a new axes where you want the image to appear
# (x, y, width, height)
imax = f.add_axes([0.8, 0.75, 0.1, 0.1])
# remove ticks & the box from imax
imax.set_axis_off()
# print the logo with aspect="equal" to avoid distorting the logo
imax.imshow(im, aspect="equal")

Comment: This works quite well and i the simplest solution I've found.  Thanks.
Comment: This positions relative to the figure.  Is there an easy way to position the image relative to the ticks in another axis?  It's surely obvious and easy, but I'm not seeing it.
Comment: @jma what you are searching for is the `transform` argument... e.g. use `f.add_axes([...], transform=ax.transAxes)` to specify the coordinates relative to the position of the axes (for more details see https://matplotlib.org/stable/tutorials/advanced/transforms_tutorial.html)
Comment: This is excellent! Most answers are still relative to the data in the plot and mess with the aspect ratio. This solves both of those issues and is reproducible across many plots.

Matplotlib Pyplot logo/image in Plot


How do I display two different views for a single content?

Question: I'm quite new to drupal and trying to learn this after working with a very different CMS system the past ten years.  Here is my issue/question:
I have a content type that I'd like to have two distinctly different views. The first view contains a form (that does not use any drupal module).  When a user submits the form, I'd like to show a 'confirmation page' view for that same content type (since it has info that I'd like to show in the confirmation view).  What would be the url to use for the different view?
Comment: define "the different view"
Comment: you need extra info being displayed when the user submit the form or new structure of the displayed node
Comment: New structure of displayed node.  Example - one CTD, one content, two different views.  The second view would have different verbiage, layout than the view containing the form.
Answer: You will need a module for your form in this content type, there is no other way. (unless you want something complicated within an iFrame).
Either write a custom module yourself, or use the usual Webform module
Comment: It should not matter.  That is irrelevant if I use their form or make a module.  All I am asking is how to create two distinct pages using the same content and how would the URL be defined?


How to catch user cancel in Companion Device Pairing screen?

Question: In Android 8.0 and above, we may use the CompainonDeviceManager to pair out app with a bluetooth or wifi device. The android documentation tells us how to handle:

The happy path (i.e. the user selects a device from the presented list)
Pairing failure (e.g. no devices found, the request times out)

What the documentation does not tell is how to catch the case where the companion device scan is successful and presents one or more devices to the user, but the user cancels the pairing.
How can I catch the negative result of a user pressing Cancel in the Companion Device Pairing screen?
Answer: I hope this is not too late! I was wondering the same thing. It turns out that the documentations tells you to include the following in the onActivityResult() method:
if (requestCode == SELECT_DEVICE_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
     // User has chosen to pair with the Bluetooth device.
     BluetoothDevice deviceToPair = data.getParcelableExtra(CompanionDeviceManager.EXTRA_DEVICE);
}

Notice that the code also checks if resultCode is equal to RESULT_OK. By checking for this separately you can catch the "Cancel" click, like this:
if (requestCode == SELECT_DEVICE_REQUEST_CODE) {
            if (resultCode == RESULT_OK) {
                // user has selected a device
                BluetoothDevice device = data.getParcelableExtra(CompanionDeviceManager.EXTRA_DEVICE);
            } else {
                // cancel handled here
            }
}

Comment: I cannot verify this at the moment, but presume it is correct. Good advice!


Programmatically assigning IIS Application Pool Identity "users" to Groups

Question: The Problem: When new IIS Application Pools are created and set to use the Application Pool Identity for permissions, I am unsure how to add those identities to User Groups such as Administrator or Performance Counter Users.
The Background: I'm currently writing a C#.NET library which uses Microsoft.Web.Administration in order to do the following:

Detect if IIS 7.x is installed, and if so, what components.
Install or upgrade IIS 7.x to a provided list of required components.
Create/manage one or more web sites through IIS.
Automatically create/manage one application pool per web site

The context is that this library is to be used by executable installers to provide automated deployment of a web server and web sites/services on Windows Server OSes as part of a larger software deployment. So far, all of the above has been implemented, tested, and is (mostly) functional except for the automation of some permissions that need to be performed on Application Pool / Website creation.
In my method for installing a new website, I create a new Application Pool and force it to use the Application Pool Identity:
static public void InstallSite(string name, string path, int port)
{
    Site site;
    var appPoolName = ApplicationPoolBaseName + name;

    using (var iisManager = new ServerManager())
    {
        // Set up a custom application pool for any site we run.
        if (!iisManager.ApplicationPools.Any(pool => pool.Name.Equals(appPoolName)))
        {
            iisManager.ApplicationPools.Add(appPoolName);
            iisManager.ApplicationPools[appPoolName].ManagedRuntimeVersion = "v4.0";
        }
        iisManager.CommitChanges();
    }

    // ... other code here ('site' gets initialized) ...

    using (var iisManager = new ServerManager())
    {
        // Set anonymous auth appropriately
        var config = iisManager.GetWebConfiguration(site.Name);
        var auth = config.GetSection("system.web/authentication");
        auth.SetMetadata("mode", "Windows");
        var authSection = config.GetSection("system.webServer/security/authentication/anonymousAuthentication");
        authSection.SetAttributeValue("enabled", true);
        authSection.SetAttributeValue("userName", string.Empty); // Forces the use of the Pool's Identity.
        authSection = config.GetSection("system.webServer/security/authentication/basicAuthentication");
        authSection.SetAttributeValue("enabled", false);
        authSection = config.GetSection("system.webServer/security/authentication/digestAuthentication");
        authSection.SetAttributeValue("enabled", false);
        authSection = config.GetSection("system.webServer/security/authentication/windowsAuthentication");
        authSection.SetAttributeValue("enabled", false);

        iisManager.CommitChanges();
    }

    // ... other code here ...
}

As I understand it, this would be the best security practice, and I would then add permissions to specific web sites for anything more than minimal system access. Part of this process would be to add these Application Pool identities to User Groups, such as Administrator or Performance Monitor Users. This is where complications arise.
Now, as documented elsewhere, each Application Pool Identity exists in the format of IIS AppPool\\<pool_name> but this faux-user is not listed through the normal GUI user management controls, and does not seem to be accessible through libraries such as System.DirectoryServices.AccountManagement when following this example on SO. Also, other questions about the Application Pool Identity seem to relate to referencing it from within a child website, not from within an installation context.
So, does anyone know what the proper methods are for

a) Referencing and accessing Application Pool Identities programmatically.
b) Giving Application Pool Identities permissions by adding them User Groups.
Answer: Thanks for your well-written question.  It is exactly the problem that I was trying to solve last night and it gave me enough to go on that I was able finally cobble together an answer that uses only managed code.  There were three steps that I found to getting the framework to find and work with the virtual user:

using new System.Security.Principal.NTAccount(@"IIS APPPOOL\<appPoolName>") to get a handle on the account.
using .Translate(typeof (System.Security.Principal.SecurityIdentifier)) to convert it to a SID
understanding that Principal.FindByIdentity() treats that SID like it is a group, rather than a user

A final working program (Windows Server 2012 for my test) is as follows:
using System;
using System.DirectoryServices.AccountManagement;

namespace WebAdminTest
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            var user = new System.Security.Principal.NTAccount(@"IIS APPPOOL\10e6c294-9836-44a9-af54-207385846ebf");
            var sid = user.Translate(typeof (System.Security.Principal.SecurityIdentifier));

            var ctx = new PrincipalContext(ContextType.Machine);

            // This is weird - the user SID resolves to a group prinicpal, but it works that way.
            var appPoolIdentityGroupPrincipal = GroupPrincipal.FindByIdentity(ctx, IdentityType.Sid, sid.Value);

            Console.WriteLine(appPoolIdentityGroupPrincipal.Name);
            Console.WriteLine(appPoolIdentityGroupPrincipal.DisplayName);

            GroupPrincipal targetGroupPrincipal = GroupPrincipal.FindByIdentity(ctx, "Performance Monitor Users");

            // Making appPoolIdentity "group" a member of the "Performance Monitor Users Group"
            targetGroupPrincipal.Members.Add(appPoolIdentityGroupPrincipal);
            targetGroupPrincipal.Save();

            Console.WriteLine("DONE!");
            Console.ReadKey();
        }
    }
}

Comment: I'm going to try swapping out my solution for this one in order to reproduce the results. This looks promising, thanks for sharing!
Answer: A solution presented itself sooner than I expected, though it's not the one I preferred. For anyone interested, there are a couple of additional options on this pinvoke page. The managed solution did not work for me, but the sample using DllImport worked. I ended up adjusting the sample to handle arbitrary groups based on mapping an enum to SID strings, and including another DllImport for:
[DllImport("advapi32.dll", SetLastError = true)]
static extern bool ConvertStringSidToSid(
    string StringSid,
    out IntPtr ptrSid);

The modified (working) function looks something like this:
static public bool AddUserToGroup(string user, UserGroup group)
{
    var name = new StringBuilder(512);
    var nameSize = (uint)name.Capacity;
    var refDomainName = new StringBuilder(512);
    var refDomainNameSize = (uint)refDomainName.Capacity;
    var sid = new IntPtr();
    switch (group)
    {
        case UserGroup.PerformanceMonitorUsers:
            ConvertStringSidToSid("S-1-5-32-558", out sid);
            break;
        case UserGroup.Administrators:
            ConvertStringSidToSid("S-1-5-32-544", out sid);
            break;
        // Add additional Group/cases here.
    }

    // Find the user and populate our local variables.
    SID_NAME_USE sidType;
    if (!LookupAccountSid(null, sid, name, ref nameSize,
        refDomainName, ref refDomainNameSize, out sidType))
        return false;

    LOCALGROUP_MEMBERS_INFO_3 info;
    info.Domain = user;

    // Add the user to the group.
    var val = NetLocalGroupAddMembers(null, name.ToString(), 3, ref info, 1);

    // If the user is in the group, success!
    return val.Equals(SUCCESS) || val.Equals(ERROR_MEMBER_IN_ALIAS);
}

Hopefully this will be of interest to someone else, and I would still like to know if anyone comes across a working, fully managed solution.


Open a webpage in python in default browser, in a specific named window

Question: In Python, is there a way to open a specific url in the default browser, and specify the target name of the window to open it into?
I suppose you can do that using an automation framework such as selenium, but is there a solution which is not so "heavy"?
The html equivalent of this is a "a href" link with the target specified.
Comment: please post the command you would use with the webbrowser module (which i'm aware of obviously), that would open the url in a window named "xyz".  The test would be to send the command to open that url twice, and make it open in the same tab, so you would have one "instance" of that page and not two.
Comment: What is heavy? Posting an question on [so] is every aspect heavier than googling "python webbrowser open" and hitting the first thing that is presented ( the "webbrowser" module in the standard library).
Comment: https://developer.mozilla.org/en/docs/Web/HTML/Element/a indicates that '[t]he following keywords have special meanings' for the `target` attribute: `_self, _blank, _parent,` and `_top`. This would appear to be at odds with what you are asking about; would you please clarify?
Comment: Did you ever find a way to do this? I'm trying to avoid reopening the same url in multiple tabs. I haven't found a workaround either (e.g. a bash script) that doesn't involve adding bulky dependencies like selenium
Comment: FWIW after some more digging it looks like react-dev-utils (part of create-react-app) is able to do something similar to this on macOS using applescript, but falls back to opening in a new tab every time on other devices. It looks like it also only searches for the URL, not the `target`: https://github.com/facebook/create-react-app/blob/71facade56a0d0f3bcae22c12ecc93a791ce33d4/packages/react-dev-utils/openBrowser.js#L67
Answer: Use webbrowser module:
<code>import webbrowser

webbrowser.open_new(url)
</code>
Comment: that is not enough to satisfy the requirements, read the last part of the question please.
Comment: Create a page using Tkinter, place your links with webbrowser.open_new  as a callback.


Given true positive, false negative rates, can you calculate false positive, true negative?

Question: I have values for True Positive (TP) and False Negative (FN) as follows:
TP = 0.25
FN = 0.75

From those values, can we calculate False Positive (FP) and True Negative (TN)?
Answer: There is quite a bit of terminological confusion in this area. Personally, I always find it useful to come back to a confusion matrix to think about this. In a classification / screening test, you can have four different situations:
                      Condition: A        Not A

  Test says "A"       True positive   |   False positive
                      ----------------------------------
  Test says "Not A"   False negative  |    True negative

In this table, "true positive", "false negative", "false positive" and "true negative" are events (or their probability). What you have is therefore probably a true positive rate and a false negative rate. The distinction matters because it emphasizes that both numbers have a numerator and a denominator.
Where things get a bit confusing is that you can find several definitions of "false positive rate" and "false negative rate", with different denominators.
For example, Wikipedia provides the following definitions (they seem pretty standard):

True positive rate (or sensitivity): $TPR = TP/(TP + FN)$
False positive rate: $FPR = FP/(FP + TN)$
True negative rate (or specificity): $TNR = TN/(FP + TN)$

In all cases, the denominator is the column total. This also gives a cue to their interpretation: The true positive rate is the probability that the test says "A" when the real value is indeed A (i.e., it is a conditional probability, conditioned on A being true). This does not tell you how likely you are to be correct when calling "A" (i.e., the probability of a true positive, conditioned on the test result being "A").
Assuming the false negative rate is defined in the same way, we then have $FNR = 1 - TPR$ (note that your numbers are consistent with this). We cannot however directly derive the false positive rate from either the true positive or false negative rates because they provide no information on the specificity, i.e., how the test behaves when "not A" is the correct answer. The answer to your question would therefore be "no, it's not possible" because you have no information on the right column of the confusion matrix.
There are however other definitions in the literature. For example, Fleiss (Statistical methods for rates and proportions) offers the following:

"[…] the false positive rate […] is the proportion of people, among those responding positive who are actually free of the disease."
"The false negative rate […] is the proportion of people, among those responding negative on the test, who nevertheless have the disease."

(He also acknowledges the previous definitions but considers them "wasteful of precious terminology", precisely because they have a straightforward relationship with sensitivity and specificity.)
Referring to the confusion matrix, it means that $FPR = FP / (TP + FP)$ and $FNR = FN / (TN + FN)$ so the denominators are the row totals. Importantly, under these definitions, the false positive and false negative rates cannot directly be derived from the sensitivity and specificity of the test. You also need to know the prevalence (i.e., how frequent A is in the population of interest).
Fleiss does not use or define the phrases "true negative rate" or the "true positive rate" but if we assume those are also conditional probabilities given a particular test result / classification, then @guill11aume answer is the correct one.
In any case, you need to be careful with the definitions because there is no indisputable answer to your question.
Comment: Very good (+1). I immediately jumped on one interpretation, but you are absolutely right that the alternative definition is standard.
Comment: @gui11aume. Thanks! It was my feeling but thinking about it, I am not so sure anymore. Looking at the references, it might depend on the field (machine learning vs. medical testing).
Comment: Here's a publication on the differences:  http://link.springer.com/article/10.1007/s10899-006-9025-5#enumeration
Note the new terminology "Test FPR" vs. "Predictive FPR"
Comment: My experience is that the latter definition, TPR = TP/(TP + FP), FPR = FP/(TP + FP) is more standard.
Answer: EDIT: see the answer of Gaël Laurans, which is more accurate.
If your true positive rate is 0.25 it means that every time you call a positive, you have a probability of 0.75 of being wrong. This is your false positive rate. Similarly, every time you call a negative, you have a probability of 0.25 of being right, which is your true negative rate.
Comment: Depends on what one is trying to characterize: the test in the setting on knowing the truth beforehand, or trying to decide on the post-test probability just given the results in hand.
Answer: None if this makes any sense if "positive" and "negative" do not make sense for the problem at hand.  I see many problems where "positive" and "negative" are arbitrary forced choices on an ordinal or continuous variable.  FP, TP, sens, spec are only useful for all-or-nothing phenomena.
Answer: http://www.statsdirect.com/help/default.htm#clinical_epidemiology/screening_test.htm
1) True +ve and false -ve make 100%
2) False +ve and true -ve make 100%
3) There is no relation between true positives and false positives.


Refresh iFrame (Cache Issue)

Question: We are getting a weird issue on which we are not sure what exactly cause it. Let me elaborate the issue. Suppose, we have two different html pages a.html and b.html. And a little script written in index.html:

    <form>

        <input type="button" value="Load a.html" onclick="reloadFrame(document.getElementById('myFrame'), 'a.html')">
        <input type="button" value="Load b.html" onclick="reloadFrame(document.getElementById('myFrame'), 'b.html')">
    </form>

A server component is continuously updating both files a.html and b.html. The problem is the content of both files are successfully updating on the server side.  If we open we can see the updated changes but client getting the older content which doesn't show the updated changes.
Any idea?
Answer: Add this in a.html and b.html

    <meta http-Equiv="Cache-Control" Content="no-cache" />
    <meta http-Equiv="Pragma" Content="no-cache" />
    <meta http-Equiv="Expires" Content="0" />

To force no cache checks
Comment: @Ben - there is nothing to suggest XHTML is being used in this question. For example, the inputs do not have closing tags either.
Comment: This solution don't work for me, please check [this question](http://stackoverflow.com/questions/22451674/wrong-content-when-refresh-a-page-contains-iframes-in-ie)
Answer: If you can add server-side instructions to those HTML files, you could send the appropriate headers to prevent caching:
Making sure a web page is not cached, across all browsers (I think the consensus is that the 2nd answer is best, not the accepted one)
Simone's answer already deals with Meta tags.
A cheap quick trick is to add a random number as a GET parameter:
page_1.html?time=102398405820

if this changes on every request (e.g. using the current time), reloading wil get forced every time, too.
Comment: Here is adding time to iframe.src in javascript.
function reloadIframe()
{
var iframe = document.getElementById('iframeId');
 var d = new Date();
iframe.src = iframe.src + "?"+ d.getTime();
}
Comment: A caveat with a naive implementation of the random number trick is that you can end up with urls like `"page_1.html?time=123?time=456?time=789?time=012"` on repeated invocations. Harmless, but ugly IMHO.
Answer: Try something like the following:

This will force the iframe to be reloaded even if it was cached by the browser
Comment: Is that documented anywhere?
Answer: I want to put Vishwas comment as a separate answer, extending
Pekka's answer
//ensure iframe is not cached
function reloadIframe(iframeId) {
    var iframe = document.getElementById(iframeId);
    var d = new Date();
    if (iframe) {
        iframe.src = iframe.src + '?ver=' + d.getTime();
        //alternatively frameElement.contentWindow.location.href = frameElement.src; //This will force the iframe to be reloaded even if it was cached by the browser
    }
}
reloadIframe('session_storage_check');

Answer: Homero Barbosa's Solution worked like a charm.  In my case, I had a varying number of iframes on the page, so I did the following:
$('.some_selector').each(function () {
  var $randid = Math.floor(Math.random() * 101);
  $(this).attr({'id': 'goinOnaSafari-' + $randid});

  var $frame = document.getElementById('goinOnaSafari-' + $randid);
  $frame.contentWindow.location.href = $frame.src;
});

Answer: I could not get the HTML to work.

    <meta http-Equiv="Cache-Control" Content="no-cache" />
    <meta http-Equiv="Pragma" Content="no-cache" />
    <meta http-Equiv="Expires" Content="0" />

For development in chrome I checked the console Network tab and found where the iframe is loaded.
I confirmed that it was loaded with a 304 response wich means it loads from cache.
Right click -> clear browser cache.
Will not work in production, but at least helps with development.
Answer: For one possible solution to this, pass a "cache parameter" to your calls to a.html and b.html.  For example
HTML
<input type="button" value="Load a.html" onclick="cacheSafeReload('a.html');">

Javascript
function cacheSafeReload(urlBase) {
    var cacheParamValue = (new Date()).getTime();
    var url = urlBase + "?cache=" + cacheParamValue;
    reloadFrame(document.getElementById('myFrame'), url);
}

Refresh iFrame (Cache Issue)


Reliability of S.M.A.R.T. Selftest

Question: I let smartd check my hard drives regularly. Recently I have been notified about a failed short selftest on one of my hard-drivers.
<code> smartctl 6.4 2014-10-07 r4002 [x86_64-linux-3.16.0-0.bpo.4-amd64] (local build)
    Copyright (C) 2002-14, Bruce Allen, Christian Franke, www.smartmontools.org

    === START OF INFORMATION SECTION ===
    Model Family:     Western Digital RE4
    Device Model:     WDC WD1003FBYX-01Y7B0
    Serial Number:    WD-WCAW31677053
    LU WWN Device Id: 5 0014ee 25b0c013e
    Firmware Version: 01.01V01
    User Capacity:    1.000.204.886.016 bytes [1,00 TB]
    Sector Size:      512 bytes logical/physical
    Rotation Rate:    7200 rpm
    Device is:        In smartctl database [for details use: -P show]
    ATA Version is:   ATA8-ACS (minor revision not indicated)
SATA Version is:  SATA 2.6, 3.0 Gb/s
Local Time is:    Mon Dec  7 13:13:22 2015 CET
SMART support is: Available - device has SMART capability.
SMART support is: Enabled

=== START OF READ SMART DATA SECTION ===
SMART overall-health self-assessment test result: PASSED

General SMART Values:
Offline data collection status:  (0x85) Offline data collection activity
                                        was aborted by an interrupting command from host.
                                        Auto Offline Data Collection: Enabled.
Self-test execution status:      (   0) The previous self-test routine completed
                                        without error or no self-test has ever
                                        been run.
Total time to complete Offline
data collection:                (16680) seconds.
Offline data collection
capabilities:                    (0x7b) SMART execute Offline immediate.
                                        Auto Offline data collection on/off support.
                                        Suspend Offline collection upon new
                                        command.
                                        Offline surface scan supported.
                                        Self-test supported.
                                        Conveyance Self-test supported.
                                        Selective Self-test supported.
SMART capabilities:            (0x0003) Saves SMART data before entering
                                        power-saving mode.
                                        Supports SMART auto save timer.
Error logging capability:        (0x01) Error logging supported.
                                        General Purpose Logging supported.
Short self-test routine
recommended polling time:        (   2) minutes.
Extended self-test routine
recommended polling time:        ( 172) minutes.
Conveyance self-test routine
recommended polling time:        (   5) minutes.
SCT capabilities:              (0x303f) SCT Status supported.
                                        SCT Error Recovery Control supported.
                                        SCT Feature Control supported.
                                        SCT Data Table supported.

SMART Attributes Data Structure revision number: 16
Vendor Specific SMART Attributes with Thresholds:
ID# ATTRIBUTE_NAME          FLAG     VALUE WORST THRESH TYPE      UPDATED  WHEN_FAILED RAW_VALUE
  1 Raw_Read_Error_Rate     0x002f   200   200   051    Pre-fail  Always       -       1
  3 Spin_Up_Time            0x0027   176   173   021    Pre-fail  Always       -       4191
  4 Start_Stop_Count        0x0032   100   100   000    Old_age   Always       -       37
  5 Reallocated_Sector_Ct   0x0033   200   200   140    Pre-fail  Always       -       0
  7 Seek_Error_Rate         0x002e   200   200   000    Old_age   Always       -       0

      9 Power_On_Hours          0x0032   070   070   000    Old_age   Always       -       21991
     10 Spin_Retry_Count        0x0032   100   253   000    Old_age   Always       -       0
     11 Calibration_Retry_Count 0x0032   100   253   000    Old_age   Always       -       0
     12 Power_Cycle_Count       0x0032   100   100   000    Old_age   Always       -       37
    192 Power-Off_Retract_Count 0x0032   200   200   000    Old_age   Always       -       35
    193 Load_Cycle_Count        0x0032   200   200   000    Old_age   Always       -       1
    194 Temperature_Celsius     0x0022   110   088   000    Old_age   Always       -       37
    196 Reallocated_Event_Count 0x0032   200   200   000    Old_age   Always       -       0
    197 Current_Pending_Sector  0x0032   200   200   000    Old_age   Always       -       0
    198 Offline_Uncorrectable   0x0030   200   200   000    Old_age   Offline      -       0
    199 UDMA_CRC_Error_Count    0x0032   200   200   000    Old_age   Always       -       0
    200 Multi_Zone_Error_Rate   0x0008   200   200   000    Old_age   Offline      -       0

    SMART Error Log Version: 1
    No Errors Logged

    SMART Self-test log structure revision number 1
    Num  Test_Description    Status                  Remaining  LifeTime(hours)  LBA_of_first_error
    # 1  Short offline       Completed without error       00%     21981         -
    # 2  Extended offline    Completed without error       00%     21972         -
    # 3  Short offline       Completed without error       00%     21963         -
    # 4  Extended offline    Completed: read failure       90%     21934         4631341
    # 5  Short offline       Completed: read failure       50%     21933         4631341
    # 6  Short offline       Completed without error       00%     21909         -
    # 7  Short offline       Completed without error       00%     21885         -
    # 8  Short offline       Completed without error       00%     21861         -
    # 9  Short offline       Completed without error       00%     21837         -
    #10  Short offline       Completed without error       00%     21813         -
    #11  Short offline       Completed without error       00%     21789         -
    #12  Extended offline    Completed without error       00%     21769         -
    #13  Short offline       Completed without error       00%     21765         -
    #14  Short offline       Completed without error       00%     21742         -
    #15  Short offline       Completed without error       00%     21718         -
    #16  Short offline       Completed without error       00%     21694         -
    #17  Short offline       Completed without error       00%     21670         -
    #18  Short offline       Completed without error       00%     21646         -
    #19  Short offline       Completed without error       00%     21622         -
    #20  Extended offline    Completed without error       00%     21602         -
    #21  Short offline       Completed without error       00%     21598         -
    2 of 2 failed self-tests are outdated by newer successful extended offline self-test # 2

    SMART Selective self-test log data structure revision number 1
     SPAN  MIN_LBA  MAX_LBA  CURRENT_TEST_STATUS
        1        0        0  Not_testing
        2        0        0  Not_testing
        3        0        0  Not_testing
        4        0        0  Not_testing
        5        0        0  Not_testing
    Selective self-test flags (0x0):
      After scanning selected spans, do NOT read-scan remainder of disk.
    If Selective self-test is pending on power-up, resume after 0 minute delay.
</code>
I then started an extended offline self-test and it also aborted because of a read failure on the same LBA. I then removed the disk from mdadm-raid and started a destructive test with badblocks - it passed three times and surprisingly no errors were found. After another self-test the log error count decreased to 0.
Is my drive cheating on me? (It's a Western Digital RE4.) It reports no Current_Pending_Sector, Offline_Uncorrectable or Reallocated_Event_Count. It reports 1 at Raw_Read_Error_Rate and it reported 1 for Multi_Zone_Error_Rate but this is back at 0 now.
I will replace the drive, but I am not sure if I should overthink my assumption that an extended offline self-test is reliable.
Comment: Is the test reliable **at what**?  As the famous google paper made clear, if SMART says your drive is going to fail, it almost certainly will fail, and soon; if SMART says your drive is OK, that doesn't mean it's *not* going to fail.  See eg [this answer](http://serverfault.com/a/223043/55514) for more detail.
Comment: That's my point about the google paper.  Once you realise that a *failed* test indicates *dire doom*, but a successful test tells you *nothing*, it isn't odd that a failed test is followed by successful ones.  The successful ones don't contradict the failed ones, because they aren't telling you that everything's all right: they're merely telling that you, in a single three-hour test (short tests are worse than useless) nothing heinous could be found.  You have a record that it once was, and you're doing the sane thing, replacing the disc.
Comment: I  know that google paper, the question is how reliable is the output regarding the read errors in the past and the number of reallocated sectors and if a succeeding Extended offline test indicates that any single existing sector on the disk can be read. The problem is it first said it will fail and now seems to have forgotten it. The drive WILL be replaced, I'm just curios. I never experienced a succeeding self-test after a failed one.
/deleted old comment because my previous answer could lead to misunderstandings
Comment: `2 of 2 failed self-tests are outdated by newer successful extended offline self-test # 2`
Comment: Yes, Michael, exactly that's what I don't understand, how the result of an extended self-test could change. I doubt that this is reliable as it failed in the past. I thought it would possibly only pass again in case sectors are reallocated but at the same time no sectors were reallocated. SMART seems to be reporting something false what it should "know" better.
Comment: I see, but data is not only useless, also false. How can LBA 4631341 be not errourneous anymore while no blocks have been reallocated. S.M.A.R.T. seems to be very D.U.M.B. here. But facing the fact, that three complete wipes with badblocks did not find any problem it seems that negative results are not reliable, too.
Comment: Are you seriously asking if a read failure can be intermittent?  Because yes, it can.  What you're seeing indicates flaky hardware, to me, and you're doing what we should all do with flaky hardware: skipping it.  SMART is only seeming dumb to you because you are expecting it, in three hours, and without testing writes, to give you a meaningful test of the current capabilities and the future health of a disc.
Comment: Sorry for being dumb, I just never have seen a drive where an extended selftest reports the same LBA as corrupt several times and succeed later on the same, and I've examined a lot of hard drives when I worked as a technician in a hosting providers datacenter for several years. It's just something seems odd here. I have never seen a drive where SMART reports errors while a triple full wipe with badblocks don't while at the same time smart reports 0 reallocated sectors.
Comment: I just wonder if the disk has done some magic to reallocate a block without SMART knowing...if there are probably some vendor-specific technology I might not be aware of... what effectively makes SMART more unreliable. Again, sorry for being dumb.
Answer: Does your SMART status now report reallocated sectors? You did a destructive test, which writes. When the drive finds sectors it can't write, it will reallocate them. Keeping an eye on the change of this SMART value is important.
Generally, SMART more often does not see errors than it makes up errors. Self tests and reallocated sectors are the more reliable parameters, so your drive is probably 'busting' (on it's way to being 'busted' :)).
Comment: This is what I expected to happen when running badblocks over the whole drive - but it didn't. No reallocated sectors and no pending sectors after full badblocks run over two days. I'll add more smartctl output.  And selftest also does not find the broken LBA anymore. That's why I am confused and doubt what my hard-drive is telling me :D

Reliability of S.M.A.R.T. Selftest


Não consigo achar o botão com o querySelector

Question: Olá,estou tentando achar um botão pelo document.querySelector porém não estou conseguindo..Tentei procurar ele com o comando:
document.querySelector("button.tabindex[class='btn btn-inverse btn-large pull-right']");

O comando está errado??
No elemento do botão diz assim:
<button tabindex="-1" class="btn btn-inverse btn-large"> Botao1 </button>

Answer: Isso aqui button.tabindex está procurando por um elemento <button class='tabindex'>. Outro ponto é que o elemento que você está buscando não possui classe pull-right, logo o seletor não irá bater.
Pode fazer a consulta assim:

const button = document.querySelector('button.btn.btn-inverse.btn-large[tabindex="-1"]')

console.log(`outer: ${button.outerHTML}`)
<button tabindex="-1" class="btn btn-inverse btn-large"> Botao1 </button>
Comment: Ok,muito obrigado <3
Comment: Posso usar isto: const button = document.querySelector('button.btn.btn-inverse.btn-large[tabindex="-1"]') e depois button.click();  ??
Comment: @lololololo nesse caso, `querySelector` irá retornar um `HTMLButtonElement`, então sim.
Comment: posso trocar o const pelo var?
Comment: [`var`, `const` ou `let`? Qual usar?](https://pt.stackoverflow.com/q/206117/4808)
Answer: Sim, está incorreto para acessar um propriedade que não é o id nem a classe usasse [propriedade="valor"], igual ao que fez para as classes. Ao usar o seletor .tabindex você está procurando um elemento com a classe tabindex
Correto:
button[tabindex][class='btn btn-inverse btn-large pull-right']

Ou ainda:
button.btn.btn-inverse.btn-large.pull-right[tabindex]

Comment: ficaria assim então var botao = document.querySelectorAll('button.btn.btn-inverse.btn-large[tabindex]'); ??
Comment: Sim, ou usando o outro seletor para classe
Answer: Você poderia colocar um id nesse botão, além de ser mais fácil, ficaria um código bem mais limpo e visível
ex : <button tabindex="-1" class="btn btn-inverse btn-large" id= "idBOTAO" > Botao1
 </button>
na chamada do query você simplesmente faria
const button = document.querySelector('#idBOTAO')

console.log(button)

espero que tenha ajudado ;)
Comment: com o id seria mais complicado, pois eu teria que colocar o ID toda hora, porque eu fico atualizando a pagina constantemente


Drupal Commerce Paypal WPP Programatically Create a Transaction

Question: I stumbled on a thread over at: https://drupal.org/node/1867768 and I am trying to do a similar integration with a "one page checkout" where the customer selects the product, puts in shipping information and cc information all on one page and I'm capturing that info using drupal's form api submit callback. I can programmatically create the order, add the profile type to the order but I'm getting a little stuck when it comes to the transaction. By the looks of it Ryan had mentioned that each payment gateway has a different way of declaring the transaction. I'm using Paypal Payments pro also know and Website Payments Pro (WPP) and was wondering how to go about creating a WPP transaction programmatically and seeing if anyone had dealt with this before?
Thanks,
Answer: I was able to solve this issue.  Instead of retyping it, the answer can be found on drupal.org at this link: https://drupal.org/node/1867768#comment-8755925
Comment: Hello @tthenne, please, can you add the code that you are using in your custom module?


How to shared items in different testing files

Question: I want to shared items in many different testing files, just like global variable but only in testing scope.
./1_test.go
./2_test.go
./3_test.go

// shared between these files
var item *test.global

Comment: Well with `go test 1_test.go` you're essentially telling the tool to only include that specific file in the test, i.e. you're telling it to ignore all the other `_test.go` files. See how this works when you test the whole package: https://imgur.com/p0qqV55
Comment: You share variables between test files within the same package by declaring the variable in one of those files at the package level. Proper Go test files are not included in the final binary, therefore a variable declared in one of those test files will NOT be available to code declared in a normal file.
Comment: It may not be shared if you are executing only a specific test rather than the whole package. Can you show how you are executing the `go test` tool?
Comment: For details see: https://pkg.go.dev/cmd/go#hdr-Test_packages & https://pkg.go.dev/cmd/go#hdr-Package_lists_and_patterns. *"As a special case, if the package list is a list of .go files from a single directory, the command is applied to a single synthesized package made up of exactly those files, ignoring any build constraints in those files and ignoring any other files in the directory. "* -- Unless you know exactly what you're doing you should *not* pass a file to any of the `go ` tools, including `go test`.
Comment: Are you asking whether or not it has to be exported (i.e. start with upper case letter)? No it doesn't have to. You can share unexported variables between files within the same package just as well as exported: https://imgur.com/BbO6srl
Comment: I tried to do this before, and these three test files are in the same package name, but the item in one file can not be shared for three.
Comment: I just do the unit not the integration testing, `go test 1_test.go` e.g.
Comment: Is it possible to change the `Value` to `value` to shared this variable?
Answer: Let's say the current package name is cpx, you can use the package name cpx_test for all 3 test files. Go allows 1 package (with one or more files) and 1 test package (with one or more files) in the same directory.
cpx
├── cpx.go
├── cpx_1_test.go
├── cpx_2_test.go
└── cpx_3_test.go

By using this, you can declare global variables in cpx_test scope that are only limited to the 3 test files. You should import original package in test as an external package.
import "gitlab.com/VagueCoder0to.n/Project/cpx"

Let's say we have the following snippet in cpx_1_test.go
var (
    complex1, complex2, complex3 *cpx.Complex
)

func TestAdd(t *testing.T) {
    complex1 = &cpx.Complex{
        Real: 1,
        Imag: 10,
    }

    complex2 = &cpx.Complex{
        Real: 2,
        Imag: 9,
    }

    complex3 = cpx.ComplexAdd(complex1, complex2)
}

The 3 variables can be used by other 2 files as well. But the limitations here are:

Testing the cpx_2_test.go and cpx_3_test.go file separately may give you false errors as the initiation of variables is done in cpx_1_test.go alone.
Order of test files in execution matters.

go test cpx_1_test.go cpx_2_test.go cpx_3_test.go

Order of test cases also matters. The test TestAdd should be tested before any other test function.

Alternatively, I use the sub-tests in use-cases, which goes against your initial idea, but it makes sense if the unit tests are related. i.e., have some similar classification, say TestOperators, with sub tests TestAdd, TestSubtract, TestMultiply, TestDivision. The testing package provides Run method on type *testing.T to define sub tests.
func TestOperators(t *testing.T) {
    var complex1, complex2, complex3 *cpx.Complex
    complex1 = &cpx.Complex{
        Real: 1,
        Imag: 10,
    }

    complex2 = &cpx.Complex{
        Real: 2,
        Imag: 9,
    }

    t.Run("TestAdd", func(t *testing.T) {
        complex3 = cpx.ComplexAdd(complex1, complex2)
        assert.NotNil(t, complex3)
    })

    t.Run("TestSubtract", func(t *testing.T) {
        complex3 = cpx.ComplexSubtract(complex1, complex2)
        // Tests here
    })

    t.Run("TestMultiply", Multiply)

    // More sub tests...

}

func Multiply(t *testing.T) {
    // Tests here
}

You may use inline anonymous functions (like in TestAdd and TestSubtract) or general test cases (as in TestMultiply). If using functions, make sure the function name (identifier) doesn't start with the work "Test". Else, go tools will consider that as a separate test case. Output will be:
go test -v ./...
?       gitlab.com/VagueCoder0to.n/Project  [no test files]
=== RUN   TestOperators
=== RUN   TestOperators/TestAdd
=== RUN   TestOperators/TestSubtract
=== RUN   TestOperators/TestMultiply
--- PASS: TestOperators (0.00s)
    --- PASS: TestOperators/TestAdd (0.00s)
    --- PASS: TestOperators/TestSubtract (0.00s)
    --- PASS: TestOperators/TestMultiply (0.00s)
PASS
ok      gitlab.com/VagueCoder0to.n/Project/cpx  0.004s


The book you'll need when someone came up with a random car plate number

Question: I believe I've seen this book in a bookstore somewhere: it was a directory of integers, in ascending order, annotated with why each integer is interesting in certain aspects. e.g. the smallest (nonnegative) prime number that satisfies some condition, etc. Obviously it must be influenced by Ramanujan's taxicab number 1729. Could anyone identify this book?
It was not The Penguin Dictionary of Curious and Interesting Numbers nor Glynne-Jones' The Book of Numbers. It seemed more professional than these, and almost (if not entirely) consisted of integers.
Comment: Maybe Roberts's [Lure of the Integers](https://www.ams.org/books/spec/005/spec005-endmatter.pdf)?
Comment: I don't know the book, but I note that I would broadly be interested in seeing a website that collects interesting tidbits on various integers too. The trick, though, would be a database with *only interesting or at least semi-interesting* tidbits (which is perhaps too subjective to exist).
Answer: Found it! It's Those Fascinating Numbers (2009) by Jean-Marie De Koninck, which goes on like:

5777

the smallest composite Stern number (see the number 137).

5778

the only triangular number > 3 which is also a Lucas number (L. Ming [137]).

from 1 to the Skewes number.


How many integral triplets ($x, y, z$) satisfy the equation $x^2 + y^2 + z^2 = 1855$?

Question: How many integral triplets $(x, y, z)$ satisfy the equation $x^2 + y^2 + z^2 = 1855$ ?
solution:- Note that 1855 = 7 mod 8 while all perfect squares are 0, 1 or 4 mode8. So it is impossible for 3 squares to sum up to 7 mod8. So no solutions are there.
Could anyone please explain how we choose number to take mod with, on both the sides.Here for example, we took mod 8..why not, mod 4?
How we chose 8 here.
Answer: Honestly, it comes from experience with such proofs. When dealing with sums of two squares, it's typical to work modulo $4$. With sums of three squares, every residue class modulo $4$ is accessible, so we typically work modulo $8$ to eliminate cases.
You should check out the proofs of which integers can be written as sums of $2$ and $3$ squares. You'll find $\bmod 4$ and $\bmod 8$ reasoning all over the place.


What is the diffrence between struct and typedef?

Question: What is the diffrence between this :
struct foo
{
   ......
};

and
typedef struct foo
{
   ......
};

Comment: This isn't really a duplicate of http://stackoverflow.com/questions/612328/difference-between-struct-and-typedef-struct-in-c -- `struct` declarations behave differently in C++ than in C.
Comment: A `struct` declaration defines a new structure type. A `typedef` declaration merely creates a new name for an existing type. The syntax permits you to combine them into a single declaration.
Comment: In this case, beyond the duplicate [**here**](http://stackoverflow.com/questions/1675351/typedef-struct-vs-struct-definitions), another difference is the second snippet wouldn't compile, as there is no alias name.
Comment: I've expanded on this in [this answer](http://stackoverflow.com/a/26389105/827263) that I just posted to [this question](http://stackoverflow.com/q/1675351/827263).
Answer: First declares a structure tag foo while second define a structure type foo.
Comment: i.e. in the former your code would declare variable bar as struct foo bar; in the latter it would be foo bar.
Comment: Dowvoter care to explain ?


Value of logarithmic form

Question: I'm having trouble grasping the viability/value of log'ing a dataset. This post mentioned that it's used to normalize (read: shrink extremes of) a dataset and make it easier to fit a curve. But, doesn't that just distort the data? Is this a trade-off that just warps the data when it comes to the outliers to make it a more generally-useful curve?
Please forgive any misused vocabulary. I'm an engineer, not a statistician.
Answer: The question you link to doesn't seem to say anything about fitting a curve to data. The answer says "fit them on the same curve" which is actually talking about displaying the data (see the reference to tick marks), and the graph they're discussing (at the linked article).
[I wouldn't have used the word 'curve' there, myself.]
When it's made clear that the data are log scale (and that should be made clear on the plot, not just in the text), what is being distorted exactly?
From what I've seen log-log plots are used widely in engineering applications, and often for much the same reasons it might be done here.
What they are useful for is making power-relationships linear (the power becomes a slope) and facilitating comparisons in percentage terms (on both variables).
Besides making relationships into a simpler form, which may be more easily discussed, when data span several orders of magnitude, it can be the case that a few large values make it very hard to perceive the broader relationship at all; then a log-transformation may reveal what would otherwise be hidden.
Note that the text discussed the effect of a certain percentage increase in terms of a certain percentage increase in the other variable ("1 percent increase in population generates a slightly smaller (between 0.8 and 0.9 percent) increase in emissions"); this information would correspond to the slope of a line on the log-log graph.
Rather than distorting, it makes it easier to reveal a particular kind of information. One reason why is discussed in the answer to the question you linked to.
Comment: Sorry, it's not 100% clear what you mean. When there are strongly curving relationships where big values are very big, or when you anticipate a power relationship, or you're interested in describing things in percentage changes, you might use a log-log transformation. In the power-function case you'll get a linear relationship after taking logs, but in the other two situations it might simply make the relationship more clear rather than actually linear.
Comment: (1) That's very interesting. It's hard to divine the usefulness of logs in the greater scheme of things based on naive Internet searches. The power becomes slope? That's fantastic (and amazing, to the ignorant). (2) How can you tell if something is "log scale"? It seems like you're implying that there is a form that may or may not resemble log(x). (3) Those types of plots are probably somewhat more familiar to optimization personnel (whether engineering or not). We might [infrequently] generate the data, but we'd rarely be their target audience.
Comment: $y=ax^p$ $\implies$ $\log y = \log a + p \log x$ ... I've seen such a transformation is used in mechanical engineering, chemical engineering, and electrical engineering many times (to name only a few). Do engineers not calculate any more? Indeed, in the days of slide rules and log tables and nomograms *there was really no other practical way* to deal with such power relationships, and the list of relationships of that form would fill books. [Indeed, it does fill books; I have books on my shelf where page after page there's another new equation with powers in it.]
Comment: Just an example grabbed at random via an internet search - [see here (pdf)](http://ocw.mit.edu/courses/materials-science-and-engineering/3-11-mechanics-of-materials-fall-1999/modules/ss.pdf), figure 9 page 7. Looks like MIT still teach taking logs of power relationships (and using log-log plots to display them) to materials engineers, for example.
Comment: Another: *Standard Handbook of Petroleum and Natural Gas engineering* (Lyons & Plisga), p6-219 "*The primary diagnostic tool for this [the pumping] period is the slope of the log-log plot of net pressure [...] versus pumping time*". Indeed a search turns up many more across a wide variety of engineering areas (and none of them directly related to optimization as far as I can see).
Comment: *Engineering Flow and Heat Exchange*, by Levenspiel, p113, just below eqn 5.18: "*Experimentally all we need do is measure the torque at a number of N values, plot on a log-log scale, and evaluate the slope at various N values.*" ... well, three examples is enough, it looks like log-log plots is clearly still a thing in engineering.
Comment: Further clarification: I'm a computer scientist that isn't involved with image-processing or machine-learning to any significant degree. "Log" generally only comes up when considering computational-complexity. I went back to finish the last couple of classes for my degree, and my current "computational statistics" course is the only class of its kind required.
Comment: Any comment on (2)? Is "log scale" anything that looks like a logarithmic curve when log'd?
Comment: That's exactly what I was asking. Thanks, @Glen_b.

Value of logarithmic form


Drupal 8 Image Styles Not Generating - LEMP on CentOS 7

Question:
Centos 7
Nginx 1.10.2
PHP Version 7.1.5
Database 5.5.52-MariaDB
Drupal 8.3.2

I have exhausted just about every possible google result and every forum post I can feasibly find. Thank you in advance for any help you can offer me.
PROBLEM:
Images are uploading to the appropriate folders under /sites/default/files/WHATEVER-SUBDIRECTORY
Image styles are not generating under the /styles folder and I am getting broken images whenever they should appear on-page.
I HAVE TRIED:

Rewriting my Nginx config.
Setting all permissions to 777 (for testing purposes).
Adding $conf['image_allow_insecure_derivatives'] = TRUE; to
settings.php.
All directories and files are owned by the correct user/group.
Flushing cache as well as image stores.
The only type of errors I have been able to find are in my nginx
access.log: "GET
/sites/default/files/styles/large/public/2017-05/my_image.jpg?itok=Ax9jzc70
HTTP/1.1" 404 571 "https://mysite.mysite.come/node/1" "Mozilla/5.0
(Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)
Chrome/58.0.3029.96 Safari/537.36" "-"Safari/537.36" "-"

nginx.conf:
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

events {
    worker_connections 1024;
}

http {
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    '$status $body_bytes_sent "$http_referer" '
    '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    keepalive_timeout   65;
    types_hash_max_size 2048;

    include             /etc/nginx/mime.types;
    default_type        application/octet-stream;

    server {
        listen 443 ssl http2;
        server_name     mysite.mysite.com;
        root /var/www/drupal;
        ssl_certificate SSL CERT HERE;
        ssl_certificate_key SSL CERT KEY HERE;
        ssl_session_cache shared:SSL:100m;
        ssl_session_timeout 30m;
        ssl_protocols TLSv1.1 TLSv1.2;

    location / {
        try_files       $uri /index.php?$query_string;
    }

    location @rewrite {
        rewrite ^/(.*)$ /index.php?q=$1;
    }

    location ~ /vendor/.*\.php$ {
        deny    all;
        return  404;
    }

    location ~ \.php(/|$) {
        fastcgi_split_path_info ^(.+?\.php)(|/.*)$;
        include fastcgi_params;
        fastcgi_param   HTTP_PROXY "";
        fastcgi_param   SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param   PATH_INFO $fastcgi_path_info;
        fastcgi_param   QUERY_STRING $query_string;
        fastcgi_intercept_errors        on;
        fastcgi_pass    127.0.0.1:9000;
    }

    location ~ ^(/[a-z\-]+)?/system/files/ {
        try_files $uri /index.php?$query_string;
    }

    location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
        expires max;
        log_not_found   off;

    }

    location ~* /sites/.*/files/styles { # For Drupal >= 7
        access_log      off;
        expires         max;
        try_files $uri @rewrite;
    }
    }

server {
listen       80 default_server;
server_name  mysite.mysite.com;
root         /var/www/drupal;
return 301 https://$server_name$request_uri;
}
}

Everything else seems to be working like a dream, but I can't for the life of me seem to figure out these image styles. Any guidance would be greatly appreciated. Thanks again.
Comment: You may try this pattern `location ~ ^/sites/.*/files/styles/ ` instead of `location ~* /sites/.*/files/styles` . Also have a look at styles and subfolders permissions, and give `rwx` permission to nginx user (in most cases, www-data, be with apache or nginx)
Comment: Thanks for the response, but unfortunately this didn't work. Tried the suggested nginx config change and set all permissions recursively to 777 throughout the entire drupal deployment (for testing purposes). :-/
Comment: I finally found a solution to this problem! As it turns out, systemd is configured to give php-fpm a private /tmp. I had to edit the .service file to set PrivateTmp=false. It is worth noting that if you're running multiple sites on of the same server, PrivateTmp should be set to =true for security reasons. **[For reverence, here is the thread that saved my rump in the end.](https://stackoverflow.com/questions/30444914/php-has-its-own-tmp-in-tmp-systemd-private-nabcde-tmp-when-accessed-through-ng)** Thanks again.
Comment: I had a similar issue and it turns out it was because mod_rewrite wasn't enabled in apache2
Answer: I had a very similar problem to yours, and found out that to image URL was added "?h=xxxxxxx&" before "itok=", so after deleting this string and pasting URL in browsers, these files were created without any problems.
The only way I found out how to remove this strings from being added was to add in settings.local.php (or settings.php depend on how You config your website) this line:
$config['image.settings']['allow_insecure_derivatives'] = TRUE;
Answer: as for me, this one was caused by nginx config issue
just replace "location" directive with one below:
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
            try_files $uri @rewrite;
            expires max;
            log_not_found off;
        }

and reload nginx
sudo systemctl start nginx ( on cent os )
it helped me
rights on sites/default/files 775
owner nginx
Answer: inside de server you have to add rewrite rule and use it inside assets location. You can see bellow:
server {
    # MY OTHER NGINX SERVER CONFFS GOES HERE

    location @rewrite {
        rewrite ^/(.*)$ /index.php?q=$1;
    }
    location ~* \.(css|gif|ico|jpeg|jpg|js|png)$ {
        try_files $uri @rewrite;
        expires max;
        log_not_found off;
    }
}


Erro ao criar filtro Django

Question: Estou tentando criar um filtro, mas recebo o erro: Related Field got invalid lookup: icontains
msm se eu usar o related_name antes do atributo n funciona.
class VersoesPublicadasList(generics.ListAPIView):
    """
        get:
        Retorna uma lista de todas as publicações
    """
    queryset = VersoesPublicadas.objects.all()
    serializer_class = VersoesPublicadasSerializer
    filter_backends = [SearchFilter]
    search_fields = ['publicacoes_empresas_pb_nome']

Alguém já passou por isso?
Comment: Poste o código de onde você esta aplicando o filtro.
Comment: Postado o trecho do codigo, @AugustoA
Answer: De acordo com a documentação do Django REST Framework, você deve passar os parâmetros dentro de uma tupla ao invés de uma lista, ou seja:
filter_backends = (SearchFilter,)
search_fields = ('publicacoes_empresas_pb_nome',)

Comment: Consegui resolver.
Comment: filter_backends = [DjangoFilterBackend]
    filter_fields = ['publicacoes__nome', 'publicacoes__numero_versao', 'publicacoes__data_publicacao']

Erro ao criar filtro Django


How to push an object into an array with React Hooks

Question: I am trying to push an obj into an array located in a nested object. What would be the best approach because I want it to render the component as well with the new obj.
What I want to achieve with this is for the user to be able to create new categories for the tasks
const [formElements, setFormElements] = useState({
    task: {
        type: 'text',
        value: 'text',
        className: 'task-input'
    },
    categories: {
        type: 'select',
        value: 'select',
        className: 'categories-input',
        cat: [
            {value: 'money', displayValue: 'Money'},
            {value: 'health', displayValue: 'Health'},
            {value: 'daily', displayValue: 'Daily'},
            {value: 'food', displayValue: 'Food'}
        ]

    }
})

   const buttonAddCategoryHandler = (e) => {
        e.preventDefault()
        setFormElements(prevState => {
            ???

        })
    }

I know this might be a bad question but I have a problem understanding how to update the state in a situation like this. Or this way of having a state is bad from the start?
Answer:    const buttonAddCategoryHandler = (e) => {
        e.preventDefault()
        const newArray = [...formElements.categories.cat, {value: 'newVal', displayValue: 'Friendly Value'}]
        setFormElements({
          ...formElements,
          categories: {
             ...formElements.categories,
             cat: newArray

          }

        })
    }

Answer: I would take a look at using the slightly more advanced hook; useReducer.  Check out this note from the react docs:

Unlike the setState method found in class components, useState does not automatically merge update objects. You can replicate this behavior by combining the function updater form with object spread syntax. Another option is useReducer, which is more suited for managing state objects that contain multiple sub-values.

Using useReducer, your example above might look something like:
const [state, dispatch] = useReducer((state, action) => {
    switch(action.type){
        case "UPDATE_CAT":
            return {
                ...state,
                categories: {
                    ...state.categories,
                    cat: [...state.cat, action.value]
                }
            }
        default:
            return state
    }
})

   const buttonAddCategoryHandler = (e) => {
        e.preventDefault()
        setFormElements(prevState => {
            dispatch({ type: "UPDATE_CAT", value: { value: "vitamins", displayValue: "Vitamins" } })
        })
    }

Answer: There are several ways to achieve this, but try using spread operator:
setFormElements((prevState) => {
  return({
    ...prevState,
    categories: {
      ...prevState.categories,
      cat: [
        [...prevState.categories.cat,
        {value: '123', displayValue: 'abc'}]
      ]
    }
  })
})

Answer:

const [formElements, setFormElements] = useState({
    task: {
        type: 'text',
        value: 'text',
        className: 'task-input'
    },
    categories: {
        type: 'select',
        value: 'select',
        className: 'categories-input',
        cat: [
            {value: 'money', displayValue: 'Money'},
            {value: 'health', displayValue: 'Health'},
            {value: 'daily', displayValue: 'Daily'},
            {value: 'food', displayValue: 'Food'}
        ]

    }
});

const updatedCategories = (categories) => {
   const catUpdated = categories.cat;
   catUpdated.concat({value: 'new', displayValue: 'NEW'});
   return {
      ...categories,
      cat: catUpdated
   }
}

   const buttonAddCategoryHandler = (e) => {
        e.preventDefault()
        const updatedState = {
          ...formElements,
          categories: updatedCategories(formElements.categories)
        }
        setFormElements(updatedState);
    }

You can use your old state and update it before making another setState.