how can i rotate a body with a tween?

Question: i'm trying rotate a body that i had created, but it's appear rotated when refresh the page, i use matter js (http://brm.io/matter-js/) and tween js (https://www.createjs.com/tweenjs), matter js don't has tween, so for that reasson i used tween js, but don´t works correctly
$(document).ready(function() {
    //walls
    barra_izquierda_vaso_moleculas = Bodies.rectangle(200,200,10,200,{isStatic: true});
    barra_derecha_vaso_moleculas = Bodies.rectangle(500,200,10,200,{isStatic: true});
    barra_inferior_vaso_moleculas = Bodies.rectangle(350,300,300,10,{isStatic: true});

   //construction of my body
   vaso_moleculas = Body.create({
      parts: [barra_izquierda_vaso_moleculas, barra_derecha_vaso_moleculas, barra_inferior_vaso_moleculas],
      restitution: 0,
      friction: 0,
      frictionStatic: 0,
      frictionAir: 0,
      inertia: Infinity,
      mass: 1,
      isStatic: true,
   });

   // add to world
   World.add(world, vaso_moleculas);

   //tween
   createjs.Tween.get(vaso_moleculas).to(2, 9000);
});

Comment: I think you need to indicate position properties by createjs.Tween.get(vaso_moleculas).to({x: 400}, 9000); or properties of that kind.
Answer: You can draw your shape using p5.js and in your draw() loop, set your background with a lower alpha, such as background( 0, 32 ). This will create the illusion of motion blur or tweening. You can see it here, kind of.

how can i rotate a body with a tween?


How to nest a field collection?

Question: How to nest Field Collections in Drupal 8?
I have Field Collection installed and working fine. What I want to achieve is that for example, I'll have a box on the front end which may contain 6 tabs of content, or two boxes each containing 3 tabs.
First part is working: I have a 'tabs' Field Collection with which I can 'add another item' (tab).
For the second option I need a 'box' Field Collection that contains nothing but the 'tabs' Field Collection.
Comment: IMO sounds like a problem better suited for Paragraphs.
Comment: I wouldn't bet on it @iain-g, The D8 release only made it as far as alpha and it's basically been abandoned (no updates for more than 18 months now). The project page even states _Paragraphs is likely to replace field collection for Drupal 8. Field collection is on its way to being deprecated. It is recommended to use paragraphs instead of field collection for Drupal 8 projects._
Comment: Thanks - Kevin, I'll look at that as well, had seen a few posts about theming nested Field Collections though, so assumed it was possible, couldn't find anything on how to actually do it though...
Comment: OK - Thanks both of you, I'll go and check out Paragraphs.
Answer: Using the Field collection module in Drupal 8 seems to NOT be a good idea anymore. It currently only has an alfa1 release from April 2016). Instead you may want to try to use Paragraphs instead, as suggested also on the Field collection project page, i.e.:

Paragraphs is likely to replace field collection for Drupal 8. Field collection is on its way to being deprecated. It is recommended to use paragraphs instead of field collection for Drupal 8 projects.

How to nest a field collection?


Typing to hidden input field

Question: I have a special type of problem on my hands, for which i would like some suggestions from ppl who might have implemented something similiar.
I have a client using EAM scanners to scan barcodes, coupled to mobile units by Bluetooth as a keyboard unit.
On said mobile units we have a web framework running with JQuery Mobile/HTML5. They would like to use the scanners with this. The thing we want to achieve is to have the scanner pick up a barcode to an invisible field of some sort, then this would be used to enable a previously disabled collapsible in the UI depending on what value was scanned.
I have performed tests on using a text field and triggering the keyup-event, to keep checking as each character is passed, if the value entered corresponds to a data attribute on the collapsible. This appears to work fine.
But i don't want the user to see the input field (it should be completely hidden) but it still needs focus and to be able to accept keypresses. If i set visibility:none in styles it no longer trigger the keyup events.
So, how can i create an input field that is not visible in the UI but can be set to be in focus by code, and will accept text to trigger the keyup?
I tried input type="hidden" as well but that seems to not accept input or focus.
My testcode:
     $(document).ready(function() {
          $( '#f1' ).collapsible("disable");
          $( '#f1' ).trigger("create");
          $( '#f2' ).collapsible("disable");
          $( '#f2' ).trigger("create");
          var value = ""; //Store entered information
      //Add key handler, to the div including the text field, to avoid other text
      //  field being blocked out
    $( "#page_wrapper" ).keypress(function(event) {
     //Translate key to char and append

     value += String.fromCharCode(event.which);

     /*
      * Cut out
      */

     //Iteration here to check all collapsibles if the data value entered is valid for
     //one of them, after checking
     //input lenght, to make sure it is a complete EAN barcode

     //Make sure to clear to limit input
     $( "#scanfield" ).val("");

        //Focusing on the field
        $( '#scanfield' ).focus(); /* CUT */

Comment: Style your `` element with `position: absolute; left: -10000px;`.
Answer: Have you tried the JQM class ui-hidden-accessible?
from JQM CSS:
.ui-hidden-accessible {
  position: absolute !important;
  height: 1px;
  width: 1px;
  overflow: hidden;
  clip: rect(1px,1px,1px,1px);
}

Comment: Didn't know about that one. I'll check to see if it solves it.
Comment: wow genius approach!

Typing to hidden input field


Intuition of both OLS intercept being positive when response and predictor variables are exchanged

Question: I'm confused with how to interpret the results of an OLS regression when you switch the response and predictor variables and both intercepts are positive. More concretely
$$
y = \beta_{x}x + \alpha_{x} \\
x = \beta_{y}y + \alpha_{y}
$$
then the OLS estimators are
$$
\hat{\alpha_{x}} = \bar{y} - \hat{\beta_{x}}\bar{x} \\
\hat{\beta_{x}} = \frac{Cov(x,y)}{\sigma^{2}_{x}}
$$
and
$$
\hat{\alpha_{y}} = \bar{x} - \hat{\beta_{y}}\bar{y} \\
\hat{\beta_{y}} = \frac{Cov(x,y)}{\sigma^{2}_{y}}
$$
respectively. Then substituting in for $\beta$ in each equation we get
$$
\hat{\alpha_{x}} = \bar{y} - \frac{Cov(x,y)}{\sigma^{2}_{x}}\bar{x} \\
\hat{\alpha_{y}} = \bar{x} - \frac{Cov(x,y)}{\sigma^{2}_{y}}\bar{y} \\
$$
If we want both $\hat{\alpha_{x}} > 0 $ & $\hat{\alpha_{y}} > 0$, it's straightforward enough to satisfy this in the above equations. For example choosing
$$
\begin{align}
\bar{y} &= 2 \\
\bar{x} &= 1 \\
Cov(x,y) &= 1.9 \\
\sigma_{x}^{2} &= 1 \\
\sigma_{y}^{2} &= 9 \\
\end{align}
$$
from which we obtain
$$
\hat{\alpha_{x}} = \bar{y} - \frac{Cov(x,y)}{\sigma^{2}_{x}}\hat{x} = 2 - \frac{1.9}{1} \cdot 1 = 0.1
$$
and
$$
\hat{\alpha_{y}} = \bar{x} - \frac{Cov(x,y)}{\sigma^{2}_{y}}\bar{y} = 1 - \frac{1.9}{9} \cdot 2 \approx 0.58
$$
this is confirmed using some simulated data in $R$.
set.seed(42)
N <- 1000
eps1 <- rnorm(N)
eps2 <- rnorm(N)
X <- 1 + eps1
Y <- 2 + 1.9*eps1 + sqrt(9-1.9^2)*eps2

Regressing $Y$ on $X$ we get
summary(lm(formula = Y ~ X))

Call:
lm(formula = Y ~ X)

Residuals:
    Min      1Q  Median      3Q     Max
-6.7849 -1.5295 -0.0193  1.5388  8.3292

Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept)  0.06545    0.10101   0.648    0.517
X            1.92279    0.07228  26.602   <2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 2.29 on 998 degrees of freedom
Multiple R-squared:  0.4149,    Adjusted R-squared:  0.4143
F-statistic: 707.7 on 1 and 998 DF,  p-value: < 2.2e-16

And vis versa
summary(lm(formula = X ~ Y))

Call:
lm(formula = X ~ Y)

Residuals:
     Min       1Q   Median       3Q      Max
-2.62005 -0.52981  0.01435  0.53093  2.44786

Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept) 0.555875   0.028912   19.23   <2e-16 ***
Y           0.215776   0.008111   26.60   <2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.7672 on 998 degrees of freedom
Multiple R-squared:  0.4149,    Adjusted R-squared:  0.4143
F-statistic: 707.7 on 1 and 998 DF,  p-value: < 2.2e-16

However I find this result somewhat counterintuitive.
What is the intuition of both intercepts in an OLS regressions being greater than 0 when x and y are exchanged as predictor and response variables. Does anyone have any good visuals or explanations of the subset of dependency structures that would lead to this kind of result?
Answer: Due to regression toward the mean, it would (for example) be expected to occur fairly readily if the means of $x$ and $y$ were positive (with $x$ and $y$ positively correlated), and the total least squares line went sufficiently close to 0 (where "sufficiently close" depends on how strong the relationship is as well as the scales* and the location of the mean point - the weaker the relationship the further the intercept on the TLS line could stray from 0 without causing either least-squares intercept to go negative)
Here's an example I constructed following exactly that recipe:

The green line is obtained from principal component analysis. The red line is
the least squares line for the regression of y on x, while the blue line is for the regression of x on y.
Regression toward the mean pulls the red line clockwise and the blue line anti-clockwise from the green one, which means the y-intercept for the red line will be above the green one and that for the blue line will be below the green one. The green line will fall to one side of the origin; you just need the origin to be relatively close to it so that the regression line that's on the same side of it as the origin is will lay the opposite side of the origin point, in which case it will have its least--squares-line intercept being positive.
* on reflection, it may have been better to frame it in terms of a regression based on PCA of the correlation matrix (PCA on standardized variates), but I'll leave it as is for now.
Comment: This is an interesting way to think about it, thanks. However I'm a bit confused by your footnote, I don't really understand how standardizing $x$ and $y$ would conceptually change the explanation?
Comment: It doesn't change the form of the explanation at all; it just makes the plot look more "intuitive"; the green line would sit nearer the middle of the two ordinary regression lines. The same effect could be achieved by rescaling my $y$ to have the same variance as $x$ and sticking with ordinary orthogonal regression.


JPA não reflete os dados alterados no BD manualmente

Question: Tenho uma aplicação JavaFX com Hibernate (JPA).
Nesta aplicação eu atualizo uma TableView com os dados que busco do BD (MySql).
Toda vez que clico para o sistema buscar no BD algum dado, ele executa o seguinte código:
public Task<List<Pedido>> getPedido(EntityManager em, String numeroPedido){
        return new Task<List<Pedido>>(){
            @Override
            protected List<Pedido> call() throws Exception {
                TypedQuery<Pedido> query;
                query = em.createQuery("SELECT p FROM Pedido p WHERE p.numPedido = :arg1", Pedido.class);
                query.setParameter("arg1", numeroPedido);
                List<Pedido> lst = query.getResultList();

                return lst;
            }
        };
    }

Esta execução trás uma lista de pedidos cujo numero do pedido vai na cláusula WHERE. Até ai, tudo bem.
Mantendo a aplicação aberta, eu vou até o BD e altero manualmente os dados.
Feito isso eu executo novamente a consulta que deve trazer os dados que acabei de alterar, mas,  os dados que recebo ainda são os antigos.
Se eu fechar e abrir a aplicação, ai eu recebo as alterações que fiz manualmente no BD.
A impressão que dá, é que existe algum tipo de cache configurado.
Também já tentei colocar a linha abaixo no meu persistence.xml mas não obtive sucesso.

<property name="cache.provider_class" value="org.hibernate.cache.NoCacheProvider" />

O que pode estar ocorrendo para que a minha aplicação, mesmo depois de executar a query, não busca os dados do BD que alterei manualmente?
Complemento da resposta:
Seguindo as orientações do colega Joaquim, criei uma classe de conexão com o BD. Esta classe possui uma fábrica de conexões onde solicito uma conexão toda vez que acesso o BD.
public class Conexao {

    private static final Logger logger = LogManager.getLogger("Conexao");
    private static EntityManagerFactory emf;

    static
    {
        try {
            emf = Persistence.createEntityManagerFactory("crp");
        } catch (Exception e) {
            logger.error("Erro em Persistence.createEntityManagerFactory(crp) => " + e.getMessage() );
            e.printStackTrace();
        }
    }

    public EntityManager getEntityManager() throws Exception {
        //responsavel pela persistencia
        return emf.createEntityManager();
    }

    public void close() {
        emf.close();
    }
}

Quando preciso chamar uma função de leitura, eu abro a conexão, efetuo a leitura e fecho a mesma.
public Task<List<Pedido>> getPedido(String numeroPedido){
        return new Task<List<Pedido>>(){
            @Override
            protected List<Pedido> call() throws Exception {
                EntityManager em = MainApp.getConexao().getEntityManager();

                TypedQuery<Pedido> query;
                query = em.createQuery("SELECT p FROM Pedido p WHERE p.numPedido = :arg1", Pedido.class);
                query.setParameter("arg1", numeroPedido);
                List<Pedido> lst = query.getResultList();

                em.close();

                return lst;
            }
        };
    }

Dessa forma, mesmo que o BD seja alterado por alguma outra aplicação, sempre que chamar a função getPedido(), terei os dados atualizados.
Answer: Existe a implementação nativa do First Level Cache, veja mais aqui, uma solução é você utilizar o .clear() antes das consultas, no seu caso é realmente necessário essas alteração diretamente na base? Tente evitar esse tipo de abordagem.
entityManager.clear();

Comment: Lendo sua resposta, achei o que estava errando. Na verdade eu criava um EntityManager para toda a aplicação e utilizava apenas ele. Pelo que entendi, eu devo instanciar uma fábrica de EntityManager e para cada solicitação ao BD, requisitar um EntityManager. Vou editar minha pergunta e colocar lá o código da fábrica EntityManager. Obrigado pela ajuda...


Extracting relative risk from survival parameters

Question: Brief background: statins are drugs that lower cholesterol. Trials comparing statins with placebo show that statins lower mortality (in terms of hazard ratio) by almost 20% (hazard ratio 0.8). There are numerous trials conducted with similar findings. Mean follow-up is approx 4 years in these studies.
Now comes this study: http://bmjopen.bmj.com/content/5/9/e007118
- which is based on the statin trials and this study concludes that in terms of survival time, satins prolong life by 5 days.
This cannot be mathematically sound.
Could I go backwards and estimate the hazard ratio that these numbers would yield? Because the hazard ratio should be approimately equal to the studies it was based on. This is a way of prooving that the study results are incorrect.
Comment: I did not read the paper, if the statin can only prolong life for 5 days, I would prefer do not take these medicines for the cost and incovenient!
Answer: Which mortality is reduced by statins? The overall mortality, or the specific mortality from heart disease? If the latter, this can certainly be consistent with extending lifespans by only five days.
Compare the effect that more frequent screening can detect cancers in early stages that can be treated and healed (increasing cancer survival rates) - but that these cancers would likely never have been fatal, so people will die of other causes anyway, with or without screening. So overall, screening artificially inflates cancer survival, but does little to nothing about life expectancy or mortality.
Comment: In these trials, mortality is primarily driven by cardiovascular disease (these are generally high risk persons with respect to cardiovasc dis) so the large reduction in cardiovasc mortality should be reflected upon overall survival.
Comment: I just found this: http://bendixcarstensen.com/DMreg/YLL-handout.pdf which I presume explains what they did wrong?


See if value exists in any column of every row in PostgresQL

Question: Imagining I have this table, I want to be able to find the brands that exist associated with every id.
Note that this is not equivalent to finding if the value exists for every row, since a single id may exist several times.
The result I would expect in this case would be Mercedes-Benz.
 id |    brand1     |    brand2     |    brand3
----+---------------+---------------+---------------
  1 | Mercedes-Benz |               | Fiat
  2 | Honda         |               | Mercedes-Benz
  3 | Audi          |               | Audi
  3 | Audi          |               | Mercedes-Benz
  4 | Mercedes-Benz |               | Mercedes-Benz
  5 | Mercedes-Benz | Mercedes-Benz |
  5 | Mercedes-Benz | Mercedes-Benz |
  6 | Mercedes-Benz |               | Mercedes-Benz
  7 | Mercedes-Benz | Mercedes-Benz |
  8 | Audi          |               | Audi
  8 | Audi          |               | Mercedes-Benz

I have tried using EXIST, but I haven't been able to find an elegant "postgresql" way to iterate in the id columns.
Result:
  |    brand      |
  +---------------+
  | Mercedes-Benz |

Comment: Odd table design. Why 3 brand columns? I'd have only one, and more rows instead.
Comment: Specify the expected result as well, having that table data.
Comment: That's _describing_ the result.  Now _specify_ it!
Comment: Okay, I have edited the question @jarlh
Comment: Thanks for the edit, @jarlh
Comment: The result I am expecting is just a column named brand, which contains all of the brands that exist associated with every id.  So Audi would be left out, since it does not exist for id 4,5,6,7. Honda would be out since it does not exist for id 1, 2,4,5,6,7,8. Fiat would be out for similar reasons.  As for the table design, this is actually the byproduct of another more complex query. Thank you for your help
Comment: Unrelated, but: Postgres 9.1 [is no longer supported](https://www.postgresql.org/support/versioning/) you should plan an upgrade to the current version as soon as possible.
Answer: Unpivot the data -- I recommend using a lateral join -- and then aggregate:
select v.brand
from t cross join lateral
     (values (t.brand1), (t.brand2), (t.brand3)) v(brand)
group by brand
having count(distinct t.id) = (select count(distinct t.id) from t);

Answer: You can normalize the data (if possible, change the table structure, otherwise you can run a query to build it on the fly)
SELECT id, brand1 AS brand FROM table
UNION
SELECT id, brand2 FROM table
UNION
SELECT id, brand3 FROM table

From there, you can use standard aggregation functions to find the information you need : GROUP BY brand, and COUNT the number of ID
Comment: I am not familiar with lateral joins to judge with certainty, but instinctively a keyword should be more efficient than a query that try to mimic it, so the solution of Gordon Linoff should be better.
Comment: This also seems to work. Which one is more efficient, this one or the one using cross join?


Is the ring of formal power series in infinitely many variables a unique factorization domain?

Question: Is $R[[x_1,x_2\dots]]$ a unique factorization domain where the notation means infinite sums where each term is a finite product over the $x_i's$ with coefficients in $R$.
I am most interested in the case where $R = \Bbb R$ or $\Bbb C$.
Answer: The answer is yes, for sufficiently nice $R$ (including the case where $R$ is a field).  This was proved by Hajime Nishimura in the paper "On the unique factorization theorem for formal power series", J. Math. Kyoto Univ. Volume 7, Number 2 (1967), 151-160, available in open access on Project Euclid.
The precise statement for countably many variables is as follows:

If the ring $R[[x_1, \ldots, x_n]]$ is a unique factorization domain for any positive integer $n$, then so is $R[[x_1, x_2, \ldots]]$.

The ring $R[[x_1, x_2, \ldots]]$ is denoted by $R\{X\}_{\aleph_0}$ in the paper, where the above is found as (a special case of) Theorem 1.
In particular, the result is true if $R$ is a field, or even a principal ideal domain.


Matrix of adjoint linear map is transposed matrix

Question: I am stuck with some exercise and hope that someone can give me a hint:

Let $V$ and $W$ be vector spaces and let $B_V = \big\{ v_1, \ldots, v_n \big\}$ and $B_w = \big\{ w_1, \ldots, w_n \big\}$ be bases of $V$ and of $W$.

Let furthermore be $\big\{ \alpha^1, \ldots, \alpha^n \big\}$ be the dual basis of $B_V$ and let $\big\{ \beta^1, \ldots, \beta^n \big\}$ be the dual basis of $B_W$.

Let $\varphi : V \longrightarrow W$ be a linear map and let $A^i{}_j$ be its matrix representation with respect to the bases $B_V$ and $B_W$. Show that the matrix representation of the adjoint map $\varphi^{\ast} : W^{\ast} \longrightarrow V^{\ast}$ is the transpose of $(A^i{}_j)^T$.

I cannot quite close the proof for this. My attempt is as follows:
1. Let $\varphi(X) = Y$, then
$$ \beta^i(Y) = \beta^i(Y^j w_j ) = Y^j \beta^i(w_j) = Y^j \delta^i_j = Y^i $$
and therefore
$$Y^i = \beta^i(Y) = \beta^i \big( \varphi(X) \big) = X^j \beta^i \big( \varphi(v_j) \big)$$
Consequently, the matrix representation of $\varphi$ in said bases is
$$ A^i{}_j = \beta^i \big( \varphi( v_j ) \big)$$
${}$
2. Now, doing an analogous calculation yields the following: Let $\Psi = \varphi^{\ast}(\Omega)$, then
$$ \Psi(v_i) = \big( \Psi_j \alpha^j \big)(v_i) = \Psi_j \alpha^j(v_i) = \Psi_j \delta^j_i = \Psi_i$$
and therefore
$$\Psi_i = \Psi(v_i) = \varphi^{\ast}(\Omega)(v_i) = \varphi^{\ast} \big( \Omega_j \beta^j \big) (v_i) = \Omega_j \, \varphi^{\ast}(\beta^j)(v_i) $$
and consequently the matrix representation $C^i{}_j$ of $\varphi^{\ast}$ with respect to the considered dual bases is
$$C^j{}_i = \varphi^{\ast}(\beta^j)(v_i)$$.
${}$
3. The adjoint map is defined as
$$\varphi^{\ast}(\Omega)(X) = \Omega \big( \varphi(X) \big) \quad , \qquad \text{for some} \enspace \Omega \in W^{\ast} , X \in V$$
and so
$$C^j{}_i = \varphi^{\ast}(\beta^j)(v_i) = \beta^j \big( \varphi(v_i) \big) = A^j{}_i$$

What am I missing here? The transposed matrix of $A^i{}_j$ is supposed to be $A_j{}^i$. This is however not my result here. Can anyone help me find and correct my error?
Answer: I think you've just made a mistake in part 2. I'm not used to the notation you're using, but I'll try to keep it the same (so if something is off in my notation let me know). I'm going to use lower case letters for the matrix entries though.
In your part 1 you get $a^i_j=\beta^i(\varphi(v_j))=\varphi^*(\beta^i)(v_j)$, which is correct. A way to think about this is the following. The map $\varphi$ sends $v_j$ to $\sum_l a^l_j w_l$, i.e. $a^i_j$ is the $i$-th coordinate of $\varphi(v_j)$ with respect to the $B_W$ basis. But, by definition of dual basis, $\beta^i$ picks out the $i$-th coordinate of a vector in $W$ with respect to the $B_W$ basis. So $$\beta^i(\varphi(v_j))=\text{$i$-th coordinate of $\varphi(v_j)$}=a^i_j.$$
Now let's apply this approach to $\varphi^*$. If $C$ is the matrix, then $\varphi^*$ sends $\beta^i$ to $\sum_l c^l_i \alpha^l$, i.e. $c^j_i$ is the $j$-th coordinate of $\varphi^*(\beta^i)$ with respect to the dual basis $B_V^*$. That is, $$\varphi^*(\beta^i)=\sum_l c^l_i\alpha^l.$$
Let's evaluate both sides of the above at $v_j$:
$$(LHS):\quad \varphi^*(\beta^i)(v_j)=a^i_j$$
$$(RHS):\quad \sum_l c^l_i\alpha^l(v_j) = \sum_l c^l_i \delta^l_j = c^j_i.$$
Comparing the above we get $a^i_j=c^j_i$, as desired.
Comment: Thank you very much for your answer. However, I think a small error occured within it. In the sentence "[...] If $C$ is the matrix, then $\varphi^{\ast}$ sends $\beta^i$ to $\sum_l c^l_i \alpha_l$ [...]" you are indexing $\alpha$ by down-indices. Since $\alpha$ is the dual basis to $v$ it should be indexed with up-indices, shouldn't it?

If $\alpha$ would be indexed that way, then the last two equations combined would read

$$a^i_j = c^i_j$$

which is again my initial problem.
Comment: P.S.: I updated the question so to include calculation in point **2.**
Comment: I did mean to write $\alpha^l$, thanks. I'll edit it. Although this indexing doesn't really matter, you could just denote it as $\alpha_l$ (this is the notation I would use, hence my preamble).
Comment: I'm sorry but I'm afraid I still don't quite understand it. What bothers me, is that - when using summation convention - the equation for $\varphi^{\ast}(\beta^i)$ should rather look something like

$$\varphi^{\ast}(\beta^i) = c^i_l \alpha^l$$

Instead of

$$\varphi^{\ast}(\beta^i) = c^l_i \alpha^l$$

I don't know how to connect your version to my version.
Comment: I was assuming that the superscript represents the row and the subscript represents the column. So in the sums that I have we want to sum along the rows.
Comment: I see! Thank you for your answer and your time!


Need of EnumSet / EnumMap over generified Set / Map

Question: EnumSet/EnumMap can be created by specifying the defined enum to produce set/map instance as shown in below sample code.
So far I read, difference between EnumSet/EnumMap with that of Set/Map is that we cannot add objects other than the specified Enumin the EnumSet/EnumMap.
If this is the case, then just the generified Set/Map itself will be enough, isn't it?
Please find the EnumSet/EnumMap and their respective generified Set/Map as follows,
enum Value {
    VALUE_1, VALUE_2, VALUE_3
};

public class Sample {
    public static void main(String args[]) {
        EnumSet<Value> enumSet = EnumSet.of(Value.VALUE_1);

        Set<Value> enumGenerifiedSet = new HashSet<Value>();
        enumGenerifiedSet.add(Value.VALUE_1);

        EnumMap<Value, Integer> enumMap = new EnumMap<Value, Integer>(Value.class);
        enumMap.put(Value.VALUE_1, 1);

        Map<Value, Integer> enumGenerifiedMap = new HashMap<Value, Integer>();
        enumGenerifiedMap.put(Value.VALUE_1, 1);
    }
}

So can you please tell me what is the need of having EnumSet/EnumMap eventhough we can able to create the set/map that is generified to the defined Enum?
Thanks in advance.
Answer: The interfaces are nearly identical. Though, the performance and the underlying mechanisms are completely different.
The documentation is pretty clear on this:

Enum sets are represented internally as bit vectors. This representation is extremely compact and efficient. The space and time performance of this class should be good enough to allow its use as a high-quality, typesafe alternative to traditional int-based "bit flags." Even bulk operations (such as containsAll and retainAll) should run very quickly if their argument is also an enum set.
[...]
null elements are not permitted. Attempts to insert a null element will throw NullPointerException. Attempts to test for the presence of a null element or to remove one will, however, function properly.
[...]
Implementation note: All basic operations execute in constant time. They are likely (though not guaranteed) to be much faster than their HashSet counterparts. Even bulk operations execute in constant time if their argument is also an enum set.
java.util.EnumSet, JDK 11


Library for visualizing computation graph

Question: Does anyone know a tool or library (preferable JavaScript) that can visualize an equation as a computational graph, such that for example the sigmoid function with inputs $\mathbf{w}$, $\mathbf{x}$ and $b$:
$$
\frac{1}{1 + e^{-\mathbf{w}*\mathbf{x}+b}}
$$
looks similar to this:

I think that internally libraries such as TensorFlow or Pytorch generate such graphs, but can I extract the separate nodes in these two libraries. If it works with TensorFlow, that would be great as I can directly include it in my JS Code.
Answer: Maybe :

Parsing mathematical equation to generate computation graphs by OLIVIER WULVERYCK

HTH


Can I convolve over spatially remote pixels in 1DConv in Keras

Question: I was successfully able to use keras's Conv1D layer for sentence multi-category classification. Now I would like to use it for binary classification deciding whether a person is going to ask for a loan based on some info about people. I consider the input as a sentence [age, income, education ...] --> 'A person with age, income and education ...' so I assume I can use Conv layer to slide over words and build filters over word n-grams. Regular convolution layer tries to filter adjucent vector fields (top of the image shows convolution lengths of 2 with stride 1). Since I do not know which input variable might corelate, I would like to try filters over combinations of all words and thus do convolutions as on the bottom of the picture in case of kernel_size=2 [age-income, age-eduction, age-..., income-education, income-..., education-...].

Is there some fuctionality like that in Keras already? Do I have to augment the input vector and create all combinations of the input variables ? Did you try similar approach for this kind of clasification task?
Answer: Finally I have realized a work around. After I played with strides, delation and input tensor modification; in the end I used brute force and combine each of the pairs in the input using itertools.combinations to concatenate embedding layers for each input. This improved my prediction by 1.5 percent points over the simple dense layers model (I tested over hundred combinations of those).
Assuming you have an input pandas dataframe named features containing integers (label were tokenized) I create the model like this:
embedding_output_dim = 8

em, inputs = {}, {}
for name in features:
    vocabulary = features[name].max()+1 #for lookups max = nunique()
    inputs[name] = Input(shape=(1,))
    em[name] = Embedding(vocabulary,embedding_output_dim)(inputs[name])

conv,concatem = [], []
i = 0
for a,b in list(itertools.combinations([key for key in em], 2)):
    print(a,b,i)
    concatem.append(concatenate([em[a],em[b]],axis=1))
    conv.append(Conv1D(filters=32, kernel_size=2,  activation='relu')(concatem[i]))
    i += 1

convmerge = concatenate([con for con in conv],axis=1)
convmerge = Conv1D(filters=64, kernel_size=2,  activation='relu')(convmerge)
#possibly add further Conv1D and MaxPooling1D
flatten = Flatten()(convmerge)
d = Dense(1, kernel_initializer='normal', activation='sigmoid')(flatten)

model = Model(inputs=[inputs[name] for name in features], outputs=d)

For training your model you would use original features dataframe.
batch_size = 32
history = model.fit(x = [features[name] for name in features], y = np.array(y), batch_size = batch_size, epochs = 1, validation_split=.1)

Don't be scared by the number of parameters. In case one of your input variables have very high vocabulary size (e.g. Age goes up to 100, bude Income can go to milions (of course you can scale it down)), then embedding parameters can grow a lot, though the training might still be quite quick since training of the embedding layers is not that resource consumming.


Plan curve with zero area has at least two points of zero curvature

Question: Let $\alpha=(x,y)$ be a smooth closed plan curve defined on $[a,b]\subset \mathbb{R}$. We can define the oriented area of $\alpha$ by $A=\int_{a}^{b} x(s)y'(s)ds$. So, if A=0 then there exists $t_1 \neq t_2 \in [a,b] $ such that $k(t_1)=k(t_s)=0.$ Is it true?
Answer: An idea of counterexample is found on every Mac keyboard:
⌘
Imagine going along this curve, turning always to the left. The four loops at corners are traced counterclockwise, contributing positive area. The central part is traced clockwise, contributing negative area. It becomes clear that adjusting the sizes, one can achieve total area zero.
Here is a larger version, with zero area and nonvanishing curvature. It can be described in complex coordinates as
$$\alpha(t)=\sqrt{3}e^{-it}+e^{3it} \tag1$$
The oriented area bounded by parametric curve $t\mapsto \sum_{n\in\mathbb Z} c_ne^{int}$ is equal to $\pi \sum_{n\in\mathbb Z} n|c_n|^2$, which is zero for the curve (1).
In real coordinates,
$$x(t)=\sqrt{3}\cos t +\cos 3t,\quad  y(t)=-\sqrt{3}\sin t+\sin 3t  $$


Is there a second-order conic relaxation method for the bilinear term $z=xy$?

Question: I hope to find a second-order conic (SOC) relaxation for $z = xy$, but it seems very hard.
Answer: The 3x3 moment matrix is $\begin{pmatrix} 1 & x & y\\x & x^2 & xy\\y & xy & y^2\end{pmatrix}$ which is psd and rank-1. Introduce relaxation variables and your semidefinite relaxation is $\begin{pmatrix} 1 & x & y\\x & X_{20} & X_{11}\\y & X_{11} & X_{02}\end{pmatrix}\succeq 0$ (with $z$ thus being $X_{11}$). For this to be psd, all minors have to be psd, so a necessary condition is (i.e. relaxation)
$$\begin{pmatrix} 1 & x\\x & X_{20}\end{pmatrix}\succeq 0,\begin{pmatrix} 1 & y\\y & X_{02}\end{pmatrix}\succeq 0, \begin{pmatrix} X_{20} & X_{11}\\X_{11} & X_{02}\end{pmatrix}\succeq 0$$
A 2x2 semidefinite constraint $\begin{pmatrix} a &b\\b &
c\end{pmatrix}\succeq 0$ can be represented with an SOCP by looking at the minors and after an SOCP representation of the quadratic constraint you have $\left|\left|\begin{matrix}2b\\a-c\end{matrix}\right|\right|\leq a + c, a\geq 0, c\geq 0$
Comment: Nice answer. One thing to note: this relaxation is looser than the SDP relaxation, since it doesn't enforce the constraint that the determinant of the $3 \times 3$ matrix is non-negative. In general we can't enforce $3 \times 3$ SDP constraints using SOCP, as proved by Fawazi [here](https://link.springer.com/article/10.1007/s10107-018-1233-0). However, since there is a diagonal entry of "1" it *might* (I haven't checked) be possible to do a congruence transform from the moment matrix to one with arrow structure, and then enforce the SDP constraint (see reference 7 in the article I linked).
Comment: Good point, will make that more clear
Comment: Thank you both very much. Your answers inspire me a lot.


Pseudo median from Wilcoxon signed rank test larger than sample median?

Question: I am left wondering, why I can be in a situation where the pseudo median (population estimator) of a Wilcoxon signed rank test, can be larger than the simple differences between sample medians? I am performing a paired signed rank test, since my data is dependent.
I have uploaded my dataset here: Dataset as a .csv file.
I am using R to test this, with the following "standard" code:
wilcox.test(SARD, SBP, alternative = "two.sided", mu=0, conf.int=T, conf.level = 0.99, paired = TRUE)

The sample medians are: GICS=22.1% and SBP=20.5%, i.e. indicating that the simple difference is 1.6%. When running the wilcoxon test, I am getting a pseudo median LARGER than this of 1.9% (statistically significant at 1%) which I do not intuitively understand how is even possible..
Can someone help my understanding?
Comment: Because the pseudo-median is not the same as the median? What kind of information are you seeking? (It's difficult to guess what you need and to guess what you might find intuitive)
Comment: Incidentally I am getting an error when I try to download your data. It may be a problem my end but it's probably worth double-checking that you can download it.
Comment: I updated the link, to a working one.

What I would like to postulate is, how much better on average the SBP is, relative to GICS, by looking at the median value (lower is better).
Comment: I don't follow what you mean, sorry (particularly by "on average"); if you want to look at medians, why not do that? I have attempted an intuitive explanation of how it's possible for the two to differ.
Answer: Consider the following data:
 y    x
 1   1.4
 2   1.6
 9    3

The difference in medians m(y)-m(x) = 0.4
The pair-differences $y_i-x_i$ are -0.4, 0.4 and 6, and
the pairwise averages (including the self-averages) are
 0, 2.8, 3.2, -0.4, 0.4, 6, for which the median is 1.6;
hence the pseudo-median (1.6) is quite different to the difference in medians (0.4) for this example.
How did I construct it? Mainly making the x-sample not too far from symmetric (/mildly skew) and the y-sample more heavily skew in order to get a skewed set of pair-differences; this pulls the pair-averages up relative to the differences in median.
My guess is you'll probably see some skewness in your pair-differences as well.
Looking at your data, this is indeed the case -- the pair differences are somewhat skew, with more of a tail to the right.
Comment: No, even with near symmetry you wouldn't have the pseudo-median of pair differences bounded *between* the two medians, but instead it should be close to the difference in medians (consider samples with medians of 100 and 101 and a small spread around those; the pseudo-median of pair differences will not be anywhere near 100, but it might be more-or-less near 1). But with fairly asymmetric pair-differences, you don't generally expect them to be close. None of this is much related to power (at least not directly).
Comment: I am quite sure it will be bounded (it's a function of the data, it should be possible to establish some kind of bounds from the data), but it cannot be bounded by the two medians themselves (i.e. the medians cannot in general be upper and lower bounds for the pseudo-median). Even when the difference in medians exactly equals the pseudo-median, the two medians won't be likely to bracket their own difference (you probably meant to say something else instead).
Comment: Alright, I can actually see your point; so no matter the statistical "power" of the Wilcoxon signed rank test, the pseudo median is not necessarily bounded between the two sample medians; because skewness of the samples plays a role? Hope I understood it correctly. :)
Comment: Okay, that actually makes much more sense. Naturally, I was led to believe that it would be bounded. Do you have any literature I can study, specific to my question?


Cannot install "global" composer requirements because "composer.json is not writeable"

Question: I want to install Laravel but again and again I got the below error,

rukon@rukon-HP-Notebook:~$ composer global require laravel/installer
Changed current directory to /home/rukon/.config/composer
./composer.json is not writable. rukon@rukon-HP-Notebook:~$

I tried to make writable composer.json by
$chmod 777 ./composer.json

but it's not working. my file owner is not root
Comment: What have you tried to debug the problem? Can you share the current permissions of that file?
Comment: to clarify, `./composer.json` refers to `/home/rukon/.config/composer/composer.json` right?
Answer: When you run any composer global command, the composer.json used is the one at your HOME directory, not at your projects directory. E.g. at ~/.composer/composer.json.
Looks like your home directory composer is owned by root.
At some point you've executed composer with root and messed up your installation.
To find out where your composer's home directory is at, you should run this (as shown here):
composer config --list --global | grep home

E.g. given your output, it seems your home directory sits at "/home/rukon/.config/composer":
So you'd need to run:
sudo chown -R $USER: ~/.config/composer

To fix your "global" composer configuration directory.
You should be able to run composer global commands after that.
If you have more permissions problems, you'd better fix your home directory so everything in there is owned by your user, and nothing by root as shown here:
sudo find ~ -type d -user root -exec sudo chown -R $USER: {} +

For a regular installation the above should be safe (all the files in your home directory belong to to your own user), but if you have anything special in there you should probably be aware and take a more surgical approach (checking each directory).
Comment: rukon@rukon-HP-Notebook:~$ sudo chown -R $USER: ~/.composer
[sudo] password for rukon:
chown: cannot access '/home/rukon/.composer': No such file or directory
rukon@rukon-HP-Notebook:~$                                                                                it's showing this.
Comment: rukon@rukon-HP-Notebook:~$ composer config --list --global | grep home
[vendor-dir] vendor (/home/rukon/vendor)
[bin-dir] {$vendor-dir}/bin (/home/rukon/vendor/bin)
[cache-dir] /home/rukon/.cache/composer
[data-dir] /home/rukon/.local/share/composer
[cache-files-dir] {$cache-dir}/files (/home/rukon/.cache/composer/files)
[cache-repo-dir] {$cache-dir}/repo (/home/rukon/.cache/composer/repo)
[cache-vcs-dir] {$cache-dir}/vcs (/home/rukon/.cache/composer/vcs)
[home] /home/rukon/.config/composer
it's showig this
Comment: rukon@rukon-HP-Notebook:~$ sudo chown -R $user ~/
[sudo] password for rukon:
chown: missing operand after '/home/rukon/'
Try 'chown --help' for more information.
rukon@rukon-HP-Notebook:~$                        after giving this command i tried also for laravel installation but there have problem on cache folder
Comment: Installation failed, reverting ./composer.json and ./composer.lock to their original content.

  [ErrorException]
  copy(/home/rukon/.cache/composer/files/laravel/installer/62491603ec89eb9d8c
  fec6fdc1ee7d3ae2ffce42.zip): Failed to open stream: Permission denied                Showing now this error when give the command $composer global require laravel/installer
Comment: Your home directory permissions are broken. Try to use the solution above and the linked answer to fix your home directory permissions. And try not to run composer as root in the future.


Unable to set #default_value for a date field

Question: I have a form with a date field.
<code>$form['filter_dates']['start_date'] = [
    '#type' => 'date',
    '#title' => $this->t('From'),
    '#description' => $this->t('Start event date'),
    '#default_value' => [
        'year' => 2015, 'month' => 05, 'day' => '09',
    ]
];
</code>
But when the form is displayed the date field doesn't contain the value "09.05.2015". The date field is empty.
Could you clarify me, how can I fill the date field with the value ?
I watched it as on my form as on the examle form from the Examples module.
Answer: Set it like this
<code>$form['filter_dates']['start_date'] = [
    '#type' => 'date',
    '#title' => $this->t('From'),
    '#description' => $this->t('Start event date'),
       '#default_value' => [
        '2015-05-09',
    ]
];
</code>
Comment: I did like "#default_value" => '2015-05-09',
It works.
But why it is written about year, month and day in Drupal API ?
https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Render%21Element%21Date.php/class/Date/8.2.x
Comment: I created an issue some time ago here about the documentation being wrong: https://www.drupal.org/node/2836530


WorkManager not initialized exception even though WorkManagerInitializer not disabled in manifest

Question: I got an app that uses WorkManager for several background tasks. Lately I see a lot of crashes in my production logs due to WM not being initialized even though I did not disable WorkManagerInitializer in the manifest.
java.lang.IllegalStateException: WorkManager is not initialized properly. The most likely cause is that you disabled WorkManagerInitializer in your manifest but forgot to call WorkManager#initialize in your Application#onCreate or a ContentProvider.
        at androidx.work.WorkManager.getInstance(WorkManager:161)
        ...

The WM documentation says

By default, WorkManager auto-initializes itself using a built-in ContentProvider. ContentProviders are created and run before the Application object, so this allows the WorkManager singleton to be setup before your code can run in most cases.

The interesting part there is in most cases. I wonder in what circumstances it is not initialized properly before the app starts.
My initial guess was that a bug in my code might have created too many WM tasks that take too long to initialize, but I was not able to recreate the crash in that way.
Anyone has seen this behavior before and has an idea what could go on here? Why is WorkManager not initialized before app start?
Answer: Add below code in your manifest file
   <provider
    android:name="androidx.work.impl.WorkManagerInitializer"
    android:authorities="${applicationId}.workmanager-init"
    android:exported="false"
    tools:node="remove" />

Comment: I realize that Is one possible solution, but I was specifically asking about the auto init, hence NOT having this in the manifest. Btw, since I was not able to find an answer for the auto init, this is exactly what I am doing now.


What kind of web filter is in web flux

Question: What kind of web filter is in web flux. I found only couple line about HandlerFilterFunction but in function mode. Is it right solution and does anyone have an example based on annotations.
Thanks
Answer: You're right, the Spring WebFlux functional model provides HandlerFilterFunction (for both client and server).
If you're looking for Servlet-like filters, Spring WebFlux provides org.springframework.web.server.WebFilter and org.springframework.web.server.WebFilterChain.
Comment: Thanks, it was very easy.  Is it possible to map WebFilter to some resource or it should be done inside filter by internal logic?
Comment: There's no filter mapping with patterns mechanism, if that's what you're asking. So that part would need to be done internally.

What kind of web filter is in web flux


Distance between $(-3, 0, 1)$ and the line $(2t, -t, -4t)$

Question: Could you please help me with this problem?
How do I calculate the distance between $(-3, 0, 1)$ and the line with the following parametric equation: $(x, y, z) = (2t, -t, -4t)$?
I'm really lost with this one.
Thanks in advance!
Comment: [Wikipedia link](https://en.wikipedia.org/wiki/Distance_from_a_point_to_a_line#Vector_formulation)
Answer: To calculate the distance between a line $\ell: x = x_0 + tr$, $x_0 \in \mathbf R^3$, $r \in \mathbf R^3 - \{0\}$ (in your case $x_0 = 0$ and $r = (2,-1,-4)$) and a point $p \in \mathbf R^3$, you can do the following:
Denote by $E$ the plane perpendicular to $\ell$ containing $p$. The point of intersection between $E$ and $\ell$ is the point on $\ell$ which is nearest to $p$. Note that $E$ has $r$ (the direction of $\ell$) as a normal vector, that is, $E$ is given by
$$ E = \{x \in \mathbf R^3 \colon \def\<#1>{\left<#1\right>}\<x-p, r> = 0 \}. $$
In your case:
$$ E : 2x_1 - x_2 - 4x_3 = \<p,r> = -10 $$
To calculate the point of intersection, plug $\ell$ into the equation of $E$, we have
\begin{align*}
  4t + t + 16t &= -10\\
    \iff t &= -\frac{10}{21}
\end{align*}
So $E$ and $\ell$ intersect in
$$ q = \left(-\frac{20}{21}, \frac{10}{21}, -\frac{40}{21}\right) $$
Now calculate the distance between $p$ and $q$.
Answer: Hint: To determine the distance from a point $\vec p$ to the straight line given by $t\vec v$ just calculate the length of the cross product of $\vec p$ and the unit vector of $\vec v$. Do you see why this is the desired distance?
Answer: Let $A=(-3,0,1)$. Note the nearest point on the line is the point  $H$ such that $\overrightarrow{AH}$ is orthogonal to the directing vector $\vec u=(2,-1,-4)$, and the distance is equal to $\;\lVert\overrightarrow{AH}\rVert$.
Hence we have to solve first:
$$\overrightarrow{AH}\cdot\vec u=0\iff 2(2t+3)-(-t)-4(-4t-1)=21t+10=0\iff t=-\frac{10}{21}.$$
The distance is $$\sqrt{\Bigl(\frac{43}{21}\Bigr)^2+\frac{10}{21}\Bigr)^2+\frac{61}{21}\Bigr)^2}=3\sqrt{\frac{10}7}.$$
Answer: Hint: Find the expression for the distance between your point and an arbitrary point on the line for a parameter value of $t$ and then square it. This defines a geometric curve in $t$. Finding the minimum distance is now easily accomplished by differentiating.


How to delete an element of a vector through a getter function?

Question: I am new to C++ and I am working on a game that is using a Singleton design pattern and various state machines.Currently I have most of my games update information within my Engine class update function and I need to move the majority of code over into the Update function in my gamestate class.
Some of the code I need to move manages and deletes enemies in my enemy vector as seen below.      Since I am accessing some of these vectors outside of the class I am using the getter function below. I am trying to delete my enemies if they travel off the screen.This compiles however when an enemy travels off the screen the following Unhandled exception is thrown:
_Mylast was 0xDDDDDDE5. Any help that can be provided is really appreciated.
for (int i = 0; i < (int)m_vEnemies.size(); i++)
    {
        m_vEnemies[i]->Update();
        if (m_vEnemies[i]->GetDstP()->x < -56)
        {
            delete m_vEnemies[i];
            m_vEnemies[i] = nullptr;

        }
    }

vector<Enemy*> Engine::getEnemies()
{
    return m_vEnemies;
}
for (int i = 0; i < (int)Engine::Instance().getEnemies().size(); i++)
    {
        Engine::Instance().getEnemies()[i]->Update();
        if (Engine::Instance().getEnemies()[i]->GetDstP()->x < -56)
        {
            delete Engine::Instance().getEnemies()[i];
            Engine::Instance().getEnemies()[i] = nullptr;

        }
    }

Comment: Beware that when you delete this element and set it to `nullptr` that the next time you iterate over your `vector` you need to ensure you handle elements of `m_vEnemies` being `nullptr` (which you are not currently doing).
Comment: And when you used your debugger to run your program, what did you see? This is what a debugger is for. If you don't know how to use a debugger this is a good opportunity to learn how to use it to run your program one line at a time, monitor all variables and their values as they change, and analyse your program's logical execution flow. Knowing how to use a debugger is a required skill for every C++ developer, no exceptions. With your debugger's help you should be able to quickly find all bugs in this and all future programs you write, without having to ask anyone for help.
Answer: You're deleting the object pointed to by m_vEnemies[i] and setting m_vEnemies[i] to nullptr, but the next time you iterate through the array, that nullptr is still there and you'll try to dereference it. You also need to erase the item from the vector. Items are erased from vectors by using iterators.
However, you can't just iterate through a vector using standard for (auto it = v.begin(); it != v.end(); it++) semantics and erase the item in the middle of the loop, because erasing an item from a vector invalidates its iterators.
The trick is to get in iterator to the item you're removing using
std::vector<T *>::iterator erase_iterator = v.begin() + i;

which you can then use to remove the item from the vector after appropriately deleting it.
When you find an item to delete you:

delete the allocated memory
Decrement your loop variable. On the next loop iteration, you want to check the new item that occupies this same memory address
Acquire an iterator of the appropriate type that identifies the current item
Call std::vector::erase(iterator) to erase the item from the vector.

Not that this causes a reshifting of all pointers in the vector, since items are stored in an array contiguously.
#include <iostream>
#include <vector>

void print_container_info(std::vector<int *>& container)
{
    std::cout << "Container size: " << container.size() << "\n";
    std::cout << "Container contents: ";
    for (auto& item : container)
    {
        std::cout << *item << " ";
    }
}

int main(int argc, char** argv)
{
    std::vector<int*> p_int_vec = { new int(3), new int(1), new int(2), new int(2), new int(3), new int(3), new int(2) };
    print_container_info(p_int_vec);
    std::cout << "\n\n";

    std::cout << "Removing all elements equal to 2 using for loop\n";
    for (std::size_t i = 0; i < p_int_vec.size(); i++)
    {
        if (*p_int_vec[i] == 2)
        {
            auto erase_iterator = p_int_vec.begin() + i;
            delete p_int_vec[i];
            p_int_vec.erase(erase_iterator); //no need to set to nullptr, we're removing it from the container
            --i; // must decrement
        }
    }
    print_container_info(p_int_vec);
    std::cout << "\n\n";
}

You could also include the algorithm library, and use the std::remove_if function. remove_if applies a predicate on each item of the container, and moves the item to the end of the container (potentially invalidating its data) if a criteria is met. Since the pointer may be invalidated after moving it to the end of the container, we need to delete it before the move (i.e., before we return true from the functor).
Then, the container contains all valid elements at the start of the vector, with order preserved, and all invalidated elements at the end. remove_if returns an iterator to the start of the range where the invalidated elements start. After calling remove_if, you should call std::erase on the range between this dummy-start iterator and the end of the container.
#include <iostream>
#include <vector>
#include <algorithm>

void print_container_info(std::vector<int *>& container)
{
    std::cout << "Container size: " << container.size() << "\n";
    std::cout << "Container contents: ";
    for (auto& item : container)
    {
        std::cout << *item << " ";
    }
}

int main(int argc, char** argv)
{
    std::vector<int*> p_int_vec = { new int(3), new int(1), new int(2), new int(2), new int(3), new int(3), new int(2) };
    print_container_info(p_int_vec);
    std::cout << "\n\n";

    std::cout << "Removing all elements equal to 2 using for loop\n";
    auto dummy_begin = std::remove_if(p_int_vec.begin(), p_int_vec.end(),
        [](int* p_int) {
            if (*p_int == 2)
            {
                delete p_int;
                return true;
            }
            return false;
        });
    p_int_vec.erase(dummy_begin, p_int_vec.end());
    print_container_info(p_int_vec);
    std::cout << "\n\n";
}

Comment: Awesome thank you so much for all the information! I tried your first suggestion howeverI keep getting an error saying my vector erase iterator is outside range. The code I wrote from your help is  if
(Engine::Instance().getEnemies()[i]->GetDstP()->x <=-56)
  {
   auto erase_iterator = Engine::Instance().getEnemies().begin() + i;
   delete Engine::Instance().getEnemies()[i];
   Engine::Instance().getEnemies().erase(erase_iterator+i); //no need to set to nullptr, we're removing it from the container
   --i; // must decrement
  }
Comment: @eric The iterator that describes the element you want to delete is `x.begin() + i`, not `x.begin() + i + i`. You're adding `i` twice, which has the potential to go outside bounds at best, and to delete the wrong element silently at worst.
Comment: Hi John, thanks again for the help. I added that as I was still getting the error that the vector erase iterator is outside range without having the extra +1. So with the code
if (Engine::Instance().getEnemies()[i]->GetDstP()->x <=-56)
  {
   auto erase_iterator = Engine::Instance().getEnemies().begin()+i;
   delete Engine::Instance().getEnemies()[i];
   Engine::Instance().getEnemies().erase(erase_iterator); //no need to set to nullptr, we're removing it from the container

   --i;
    // must decrement
  } I still get the same error message
Comment: What does your for loop look like?
Comment: My for loops looks like this:
for (int i = 0; i < (int)Engine::Instance().getEnemies().size(); i++) {}
My enemies get generated on a timer if that makes a difference
Comment: Your `getEnemies` function should return a reference to `m_vEnemies`. Right now it's copying the vector. You're able to call `delete` on the pointer just fine, because a copy of a pointer still dereferences to the correct location, but when you try to `erase` it from the vector, you're only erasing from the copy, not from the original. You should also see some speedup in your code since you're not copying the vector anymore every time you call `getEnemies()`. Change the function signature to `std::vector& Engine::getEnemies()`
Comment: Awesome that workes thank you so much I really appreciate it!!!!!!


$MA(q)$ : Show $\sqrt{n}\hat{\rho}(q + l)\overset{d}{\to} N(0, 1 + 2\sum _{j=1}^q\rho ^2\left(j\right)), l\ge 1 $

Question: I am trying to show that for an $MA(q)$ process,
$$\sqrt{n}\hat{\rho}(q + l)\overset{d}{\to} N(0, 1 + 2\sum _{j=1}^q\rho ^2\left(j\right)), \quad l\ge 1. $$
I'm having a hard time doing this. I'm not exactly sure how to start this off. I thought it might be similar to showing $$\sqrt{n}(\bar{X}-\mu)\overset{d}{\to} N(0, \sum _{h=-\infty}^\infty\gamma_X\left(h\right))$$ but it doesn't seem to work.
I tried to show $$\sum _{h=-\infty}^\infty\rho\left(h\right) = 1 + 2\sum _{j=1}^q\rho ^2\left(j\right)$$ but this doesn't seem to work and I think it was a bad idea, which resulted in me wasting 5 pages and 4 hours, and still no breakthroughs on how to solve the problem.
I think it might be a Bartlett's Formula problem, but I'm not sure how to apply it here.
Any help would be appreciated. This problem is on time series and the textbook being used in class can be found here.
I have an exam coming up and I really want to be able to understand this problem and how to solve it. Please help!
Thank you
Comment: @Zhanxiong the relation I wrote is exactly the practice problem given to solve. I think it requires use of the Bartlett's formula to prove it, but I'm not quite sure how to apply it
Comment: Why estimate the  autocorrelation at lags greater than q?
Comment: @Taylor I'm not quite sure, i thought that the idea was that up to q, the values are observed, then after q, they are future values. So when we estimate correlation at lags greater than q, we get relation for next values. I'm not sure if I'm thinking about it correctly
Comment: @Zhanxiong I'm so confused. What exactly do I need to show/prove then? The material I've covered so far is chapters 1-3 from the textbook linked in the post. Am I not thinking of the right concepts then? Is it not asymptotic distribution?
Comment: @eddie After a second thought, the problem still makes sense.  I will add an answer below.
Comment: @Zhanxiong thank you, I really appreciate your help. I have an exam in 2 days, and this problem has been driving me crazy all week.
Answer: Because for MA($q$), the true autocorrelation $\rho(q + l) = 0$ for $l \geq 1$, the key of the proof is to apply the Bartlett's formula (as you correctly pointed out) to compute the asymptotic variance of $\sqrt{n}\hat{\rho}(q + l)$.  The Bartlett's formula (Theorem 7.2.1, Time Series:  Theory and Methods by Brockwell and Davis) gives the asymptotic covariance between $\sqrt{n}\hat{\rho}(i)$ and $\sqrt{n}\hat{\rho}(j)$:
\begin{align}
w_{ij} = \sum_{k = -\infty}^\infty\{&\rho(k + i)\rho(k + j)
+ \rho(k - i)\rho(k + j) + 2\rho(i)\rho(j)\rho^2(k) \\
& - 2\rho(i)\rho(k)\rho(k + j) - 2\rho(j)\rho(k)\rho(k + i)\}. \tag{1}
\end{align}
Since the problem of interest only concerns with $\hat{\rho}(q + l)$, the asymptotic
variance of $\sqrt{n}\hat{\rho}(q + l)$ can be obtained by setting $i = j = q + l =: r$ in $(1)$, which returns
\begin{align}
w_{rr} &= \sum_{k = -\infty}^\infty\{\rho^2(k + r) + \rho(k - r)\rho(k + r) + 2\rho^2(r)\rho^2(k) - 4\rho(r)\rho(k)\rho(k + r) \} \\
&= \sum_{k = -\infty}^\infty\{\rho^2(k + r) + \rho(k - r)\rho(k + r)\} \tag{$\dagger$} \\
\end{align}
In $(\dagger)$, we use $\rho(r) = 0$ since $r > q$ and it is an MA($q$) process. So it remains to evaluate the two summations in $(\dagger)$.
The first summation is easy, again by noting $\rho(s) = 0$ for all $|s| > q$ in MA($q$), it follows that
\begin{align}
\sum_{k = -\infty}^\infty \rho^2(k + r) = \sum_{t = -\infty}^\infty\rho^2(t)
= \sum_{t = -q}^q\rho^2(t) = 1 + 2\sum_{j = 1}^q\rho^2(j). \tag{$\dagger\dagger$}
\end{align}
For the second summation, note that the summand $\rho(k - r)\rho(k + r) \equiv 0$ for all $k \in \mathbb{Z}$. This can be verified by considering $k - r < -q$ and $k + r > q$ separately (for each category, the product of
$\rho(k - r)$ and $\rho(k + r)$ is zero -- again, use $\rho(s) = 0$ for all $|s| > q$ in MA($q$), and the union of these two categories covers $\mathbb{Z}$).
Combining $(\dagger)$ and $(\dagger\dagger)$ gives the desired result.
Comment: I don't completely understand this part "Since the problem of interest only concerns with $\hat{\rho}(q + l)$, the asymptotic
variance of $\sqrt{n}\hat{\rho}(q + l)$ can be obtained by setting $i = j = q + l =: r$ in $(1)$"
Why do we set $i=j=q+l=r$?
Comment: Can you read the reference I mentioned in the answer?  Basically $(1)$ gives the covariance of two estimates $\hat{\rho}(i)$ and $\hat{\rho}(j)$, but your problem only asked the variance of $\hat{\rho}(r)$.  It is just as simple as substitution.
Comment: oh okay, I didn't know that I could apply substitution into the formula like that
Comment: How do the last 2 summations here equal each other?\begin{align}
\sum_{k = -\infty}^\infty \rho^2(k + r) = \sum_{t = -\infty}^\infty\rho^2(t)
= \sum_{t = -q}^q\rho^2(t) = 1 + 2\sum_{j = 1}^q\rho^2(j). \tag{$\dagger\dagger$}
\end{align}
Comment: Use $\rho(t) = \rho(-t)$ and $\rho(0) = 1$.
Comment: okay, thank you!


numpy/pandas vectorize custom for loop

Question: I created some example code that mimic what code I got:
import numpy as np

arr = np.random.random(100)
arr2 = np.linspace(0, 1, 20)
arr3 = np.zeros(20) # this is the array i want to store the result in
for index, num in enumerate(list(arr2)):
    arr3[index] = np.mean(arr[np.abs(num - arr) < 0.2])

>>> arr3
array([0.10970893, 0.1132479 , 0.14687451, 0.17257954, 0.19401919,
       0.23852137, 0.29151448, 0.35715096, 0.43273118, 0.45800796,
       0.52940421, 0.60345354, 0.63969432, 0.67656363, 0.72921913,
       0.78330793, 0.82693675, 0.83717402, 0.86651827, 0.89782569])

My problem is this code runs on much larger data. I want to know if it is possible to make some combination of numpy or pandas to do it in a vectorized way without using explicit loops. I tried many approaches but don't have something in my mind.
Comment: Look at `arr2[:,None]-arr`.  That should be a (20,100) array.  `np.mean` takes an `axis` parameter letting you reduce that to a (20,) result.
Comment: Im not quite sure I understand... can you demonstrate it?
Comment: I'd recommend `np.empty_like` rather than `np.zeros` for `arr3`
Comment: No need to turn `arr2` into a list to enumerate it. It will iterate just fine as an array
Comment: @hpaulj. The difference you show builds a mask. How do you propose applying it to compute the mean? Masked arrays?
Answer: I would recommend a completely different approach if you are dealing with large arrays. Right now, you are searching through the entirety of arr for every element in arr2. This is clearly overkill. Instead, you can operate on a sorted arr and simply sum between the insertion points obtained from np.searchsorted.
Sort arr in place if you can:
arr.sort()

You know the width of your interval, so find the bounding values. I'm making the array shaped (20, 2) to match the bounds more easily:
bounds = arr2.reshape(-1, 1) + [-0.2, 0.2]

Now find the insertion indices:
ind = np.searchsorted(arr, bounds)

ind is the same shape as bounds. ind[i, :] are the start (inclusive) and end (exclusive) indices into arr that correspond to the ith element of arr2. In other words, for any given i, arr3[i] in the original question is arr[ind[i, 0]:ind[i, 1]].mean(). You can use this directly for a non-vectorized solution:
result = np.array([arr[slice(*i)].mean() for i in ind])

There are a couple of ways to vectorize the solution. In either case, you'll want the number of elements in each run:
n = np.diff(ind, axis=1).ravel()

A quick and dirty solution that is prone to rounding errors uses np.cumsum and fancy indexing using ind:
cumulative = np.r_[0, np.cumsum(arr)]
sums = np.diff(cumulative[ind], axis=1).ravel()
result = sums / n

A more robust solution would extract only the sums that you actually need using np.add.reduceat:
arr = np.r_[arr, 0]  # compensate for index past the end
sums = np.add.reduceat(arr, ind.ravel())[::2]
result = sums / n

You can compare the results of both approaches to arr3 computed in the question to verify that the second approach is noticeably more accurate, even with your toy example.
Timing
def original(arr, arr2, d):
    arr3 = np.empty_like(arr2)
    for index, num in enumerate(arr2):
        arr3[index] = np.mean(arr[np.abs(num - arr) < d])
    return arr3

def ananda(arr, arr2, d):
    arr_tile = np.tile(arr, (len(arr2), 1))
    arr_tile[np.abs(arr - arr2[:, None]) >= d] = np.nan
    return np.nanmean(arr_tile, axis=1)

def mad_0(arr, arr2, d):
    arr.sort()
    ind = np.searchsorted(arr, arr2.reshape(-1, 1) + [-d, d])
    return np.array([arr[slice(*i)].mean() for i in ind])

def mad_1(arr, arr2, d):
    arr.sort()
    ind = np.searchsorted(arr, arr2.reshape(-1, 1) + [-d, d])
    n = np.diff(ind, axis=1).ravel()
    sums = np.diff(np.r_[0, np.cumsum(arr)][ind], axis=1).ravel()
    return sums / n

def mad_2(arr, arr2, d):
    arr.sort()
    ind = np.searchsorted(arr, arr2.reshape(-1, 1) + [-d, d])
    n = np.diff(ind, axis=1).ravel()
    arr = np.r_[arr, 0]
    sums = np.add.reduceat(arr, ind.ravel())[::2]
    return sums / n

Inputs (reset for each run):
np.random.seed(42)
arr = np.random.rand(100)
arr2 = np.linspace(0, 1, 1000)

Results:
original: 25.5 ms ± 278 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
  ananda: 2.66 ms ± 35.3 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
   mad_0: 14.5 ms ± 48.6 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
   mad_1:  211 µs ± 1.41 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
   mad_2:  242 µs ± 1.93 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

For 100 elements with 1k bins, the original approach is ~10x slower than using np.tile. Using a list comprehension is only 2x better than the original approach. While the np.cumsum approach appears to be a little faster than np.add.reduce, it is potentially not as numerically stable.
Another advantage of using the methods I suggest is that you can change arr2 arbitrarily, while arr only needs to be sorted once.
Comment: there is an error, tough it seems right, but i cant figure out the error because i stiull didnt fully understand the whole process... error:in line  `sums = np.diff(cumulative[ind], axis=1)`  error: `IndexError: index 100 is out of bounds for axis 0 with size 100`
Comment: im testing it and trying to figure out if you have an idea i will be  waiting here :) thank you very much!
Comment: @adirabargil. I'll work out the bugs when I get to a desktop. In the meantime, to help you visualize, try this: compare `arr[ind[i, 0]:ind[i, 1]].mean()` in my version to `arr3[i]` in your implementation. The error happens because of weird indexing rules for `reduceat` and an offset I forgot about in `cumsum`.
Comment: @adirabargil. I've fixed the answer and added a third option.
Comment: Thank you very much, it's evening here sonill check it out tommorow!
Comment: @adirabargil. No worries. I added some timings.
Comment: Wow thank you very much! This is alot of effort here, btw the size of arr as 100 and arr2 as 1000 this is more realistic to my situation.. ill get into it tomorrow, good night and thanks again!
Comment: @adirabargil. I've updated with your suggested numbers. Sorting and indexing is still 100x better than your original, 10x better than tiling.
Comment: are you sure mad 1 is not  faster because that the array is already sorted?
Comment: @adirabargil. I generate a new array for each function in the test. I'm sure it's not sorted. Also, sorting 10 elements is not going to have a noticeable impact
Comment: i looked into the mad_1 answer and it works perfectly... thank you very much! you are a total genius!
Comment: @adirabargil. Neat. I remember this! I like using numpy to dice numbers. It's a nice challenge sometimes.
Answer: Unless arr2 is larger than arr, you will get very little performance improvement (if any) by vectorizing that loop.  All vectorized approaches will need to boardcast arr to arr2 giving an NxM structure with a size that will offset the benefits.
I measured various approaches:
import numpy as np

def original(arr,arr2):
    arr3 = np.zeros(arr2.size) # this is the array i want to store the result in
    for index, num in enumerate(list(arr2)):
        arr3[index] = np.mean(arr[np.abs(num - arr) < 0.2])
    return arr3

def vectorized1(arr,arr2):
    delta  = (np.abs(arr2[:,None]-arr)<0.2).astype(np.int)
    return np.sum(arr*delta,axis=1)/np.sum(delta,axis=1)

def vectorized2(arr,arr2):
    return np.fromiter((np.mean(arr[np.abs(num-arr)<0.2]) for num in arr2),np.float64)

def vectorized3(arr,arr2):
    return np.apply_along_axis(lambda num:np.mean(arr[np.abs(num-arr)<0.2]),1,arr2[:,None])

def vectorized4(arr,arr2):
    select  = np.array([np.nan,1])[(np.abs(arr2[:,None]-arr)<0.2).astype(np.int)]
    return np.nanmean(select*arr,axis=1)

def vectorized5(arr,arr2):
    arr_tile = np.tile(arr, (len(arr2), 1))
    arr_tile[np.abs(arr - arr2[:, None]) >= 0.2] = np.NaN
    return np.nanmean(arr_tile, axis=1)

Note that vectorized2 and vectorized3 are not actually vectorizations of the calculations. They merely hide the loop that is being performed. Vectorized5 is Ananda's solution
Results when arr is larger than arr2:
from timeit import timeit
count = 1

arr  = np.random.random(10000)
arr2 = np.linspace(0, 1, 2000)

t = timeit(lambda:original(arr,arr2),number=count)
print("original    time:",t)

t = timeit(lambda:vectorized1(arr,arr2),number=count)
print("vectorized1 time:",t)

t = timeit(lambda:vectorized2(arr,arr2),number=count)
print("vectorized2 time:",t)

t = timeit(lambda:vectorized3(arr,arr2),number=count)
print("vectorized3 time:",t)

t = timeit(lambda:vectorized4(arr,arr2),number=count)
print("vectorized4 time:",t)

t = timeit(lambda:vectorized5(arr,arr2),number=count)
print("vectorized5 time:",t)

original    time: 0.14478049999999998
vectorized1 time: 0.3868172580000001
vectorized2 time: 0.14587923599999986
vectorized3 time: 0.15062318699999988
vectorized4 time: 0.6438709420000002
vectorized5 time: 0.543624409

Results when arr2 is larger than arr:
arr  = np.random.random(100)
arr2 = np.linspace(0, 1, 200000)

print()
print(f"arr {arr.size}, arr2 {arr2.size}")
t = timeit(lambda:original(arr,arr2),number=count)
print("original    time:",t)

t = timeit(lambda:vectorized1(arr,arr2),number=count)
print("vectorized1 time:",t)

t = timeit(lambda:vectorized2(arr,arr2),number=count)
print("vectorized2 time:",t)

t = timeit(lambda:vectorized3(arr,arr2),number=count)
print("vectorized3 time:",t)

t = timeit(lambda:vectorized4(arr,arr2),number=count)
print("vectorized4 time:",t)

t = timeit(lambda:vectorized5(arr,arr2),number=count)
print("vectorized5 time:",t)

original    time: 1.7699030359999997
vectorized1 time: 0.38871579499999953
vectorized2 time: 1.782099327
vectorized3 time: 2.443001885
vectorized4 time: 0.5951444290000012
vectorized5 time: 0.4536258110000002

note that this apparent improvement only holds true up to a point because, when memory is exceeded, the vectorized times will explode again even when arr2 is larger than arr.
Comment: In fact on that measure, Arr2 is larger then arr... arr2 for about 5-10 times...
Comment: `vectorized2` and `vectorized3` are not vectorized at all. Increasing the number of dimensions is vectorizing, but is not the right approach, I think. Try the three sorting approaches I show.
Answer: One way of solving this would be by setting all the numbers that doesn't fit your condition to nan and taking the mean of the rest.
import numpy as np

arr = np.random.random((100))
arr2 = np.linspace(0,1,20)
arr3 = np.zeros(20) # this is the array i want to store the result in...

for index,num in enumerate(list(arr2)):
    arr3[index] = np.mean(arr[np.abs(num - arr) < 0.2])

arr_tile = np.tile(arr, (len(arr2), 1))
arr_tile[np.abs(arr - arr2[:, None]) >= 0.2] = np.NaN
res = np.nanmean(arr_tile, axis=1)

np.allclose(res, arr3)

This gives True
Comment: Oh i see i was confused because you left the for loop.. let me try this when o get to my office
Comment: Yes sorry, I just left it so as to show that it does give the same solution as yours.
Comment: your solution i seems really smart and works well, but the issue is the memory size, it can overflow easily for bigger datasets... im still trying to figure out
Comment: thank you very much your solution eventually came in handy..!
Comment: This seems like the slowest approach: for large arrays, its a lot slower than the approach in the question.
Comment: after further investigation i see that numpy oerations that contains `nan` keyword are relativly slow...
Comment: Thanks for the feedback, good to know about both the instances :-)

numpy/pandas vectorize custom for loop


PayPal sandbox recurring payment error: The link you have used to enter the PayPal system is invalid. Please review the link and try again

Question: I have paypal sandbox account. Everything works fine for single payments - I set firstname.lastname@example.com and make a payment using ...firstname.lastname@example.com account which was created under "Test Accounts" menu of the sandbox. However when I try to do the same for recurring payments, I get an error. At first everything looks fine - I get redirected to paypal where I can see the detail of subscription but when I try to sign in with ...email@example.com, it redirects me to a page that says: The link you have used to enter the PayPal system is invalid. Please review the link and try again.
Thanks ahead!
Comment: It sounds like your configuration is invalid; make sure your PDT token is correct and that the form values you are submitting are valid.
Answer: Well, I am not fully sure what exactly was wrong but in case someone else has the same problem and stumbles on this question: all I had to do is re-create both seller and buyer test accounts from under my main sandbox account. The accounts that I tested on seemed valid but they were created many months (if not years) ago so probably paypal had some wrong (i.e. old) configs associated with them. The newly created accounts work just fine.


logger behavior when basicConfig() is used which creates root at WARNING

Question: import logging
import sys

FORMAT3 = '%(asctime)s %(name)s %(levelname)s - %(message)s' # for root logger

logger = logging.getLogger("mylogger")
logger.setLevel(logging.DEBUG) # allow >= DEBUG

logging.basicConfig(format=FORMAT3) # creates a StreamHandler with a given Format and adding it to the root logger. The default stream is sys.stderr
# When a handler is created, the level is set to NOTSET (which causes all messages to be processed).
# root logger is created at WARNING level.

logger.debug("This is a debug message with propagate True") # why does this log, if root is at WARNING - (A)
logger.info("This is a info message with propagate True") # why does this log, if root is at WARNING - (B)
logger.warning("This is a warning message with propagate True")

logger.propagate = False # now logger has no handlers, logging.lastResort handler that permits >=WARNING will be used
logger.debug("This is a debug message after propagate is False") # does not log
logger.info("This is a info message after propagate is False") # does not log
# logging.lastResort = None
logger.warning("This is a warning message after propagate is False") # uses logging.lastResort and logs the message

Output
$ python3 minimal-example.py 1>out 2>err
$
$ cat out
$
$ cat err
2021-09-17 23:58:05,976 mylogger DEBUG - This is a debug message with propagate True
2021-09-17 23:58:05,976 mylogger INFO - This is a info message with propagate True
2021-09-17 23:58:05,976 mylogger WARNING - This is a warning message with propagate True
This is a warning message after propagate is False
$

Why are (A) and (B) logging?  Is it because the level on root is completely ignored and only the root's handler is used which is at NOTSET. In that case, perhaps the flowchart here should be modified.How logging works. I think the language "set current logger to parent" should be skipped (since root is at WARNING and so should skip DEBUG and INFO logs, but doesn't), or am I reading the flowchart incorrectly?
Answer: You're reading the flowchart wrong. There's no logger level check once the propagation loop starts. The only logger level check happens at the start, when it checks whether the original logger is enabled for the given level.
Every handler's level is checked when deciding whether to trigger that handler, but the only logger whose level gets checked is the original logger.


Right exactness of tensor product in $k$-abelian categories from $\operatorname{Mod}(R^{op})\times \operatorname{Mod}(R,C)\to C$

Question: $\DeclareMathOperator{\Hom}{Hom}$ $\DeclareMathOperator{\Mod}{Mod}$ $\DeclareMathOperator{\End}{End}$ $\DeclareMathOperator{\coker}{coker}$
When talking about tensor product of abelian groups, or modules over some ring, I can prove that it is right exact, for instance by showing it is a left adjoint. But I'm currently dealing with slight issues dealing with the tensor product in a slightly more general setting, first let me state the theorem I'm talking about.

Let $k$ be a commutative ring (with unity). Let $C$ be a $k$-abelian category and $R$ a $k$-algebra. Assume that $C$ admits small inductive limits. Then for any $X\in \Mod(R,C)$ and $N\in \Mod(R^{op})$ the functor $Y\mapsto \Hom_{R^{op}}(N,\Hom_C(X,Y))$ is representable. Furthermore, denoting $N\otimes_R X$ its representative, the functor $$\bullet \otimes_R \bullet : \Mod(R^{op})\times \Mod(R,C)\to C $$ is additive and right exact in each variable.

To avoid any confusion by what I mean here, $k$-Abelian category is the same as an abelian category but $\Hom_C(X,Y)\in \Mod(k)$ (instead of $\Mod(\mathbb{Z}))$, with composition being $k$-bilinear. Also, $\Mod(R,C)$, the category of left $R$ object in $C$, is defined as follows :

The objects are pairs $(X,\alpha_X)$ where $X$ is an object in $C$ and $\alpha_X:R\to \End_C(X)$ is a $k$-algebra morphism.
A morphism $(X,\alpha_X)\to(Y,\alpha_Y)$ is a morphism $f:X\to Y$ in $C$ such that $\alpha_Y\circ f = f\circ\alpha_X$

When $C$ is $k$-abelian, $\Mod(R,C)$ is as well, and the forgetful functor $\Mod(R,C)\to C$ is faithful and exact. I have been able, with some help, to prove that the functor $Y\to \Hom_{R^{op}}(N,\Hom_C{(X,Y}))$ is representable. This ends up giving an isomorphism $\Hom_C(N\otimes_R X,Y)\simeq \Hom_R(N,\Hom_C (X,Y))$, hence $\bullet\otimes_R X$ is a left adjoint to $\Hom_C(X,\bullet)$, hence $\otimes_R X$ is right exact. But then I'm not sure how to prove that $\bullet\otimes_R\bullet$ is exact in its second variable, at first I thought the isomorphism above would also allow me to conclude that $N\otimes_R\bullet$ is a left adjoint to some other functor, but I haven't been able to do so.
I have similar issues with the additivity, it feels like it should be an easy consequence of the construction, but I don't actually know how to show it's additive in each variable.
Answer: So you are interested in the bifunctor $\otimes_R$ defined by the following natural isomorphism:
$$\textrm{Hom}_\mathcal{C} (N \otimes_R X, Y) \cong \textrm{Hom}_{R^\textrm{op}} (N, \textrm{Hom}_\mathcal{C} (X, Y))$$
You seek a right adjoint for $N \otimes_R {-} : \textrm{Mod} (R, \mathcal{C}) \to \mathcal{C}$.
For this, we should assume $\mathcal{C}$ is complete.
Then $\mathcal{C}^\textrm{op}$ is a cocomplete $k$-linear abelian category and we can apply the dual of the theorem constructing $\otimes_R$ to obtain a bifunctor $\pitchfork_S$ defined by the following natural isomorphism:
$$\textrm{Hom}_\mathcal{C} (Y, P \pitchfork_S Z) \cong \textrm{Hom}_S (P, \textrm{Hom}_\mathcal{C} (Y, Z))$$
Here, $S$ is a $k$-algebra, $P$ is a left $S$-module, and $Z$ is an object in $\textrm{Mod} (S, \mathcal{C})$.
We can apply this in particular when $S = k$ to obtain a bifunctor ${\pitchfork_k} : \textrm{Mod} (k)^\textrm{op} \times \mathcal{C} \to \mathcal{C}$.
Contravariant functoriality in the first variable implies that any right action on $P$ induces a left action on $P \pitchfork_k Z$.
Hence, $N \pitchfork_k Y$ is an object in $\textrm{Mod} (R, \mathcal{C})$.
It can then be shown that we have the following natural isomorphism:
$$\textrm{Hom}_{R^\textrm{op}} (N, \textrm{Hom}_\mathcal{C} (X, Y)) \cong \textrm{Hom}_{\textrm{Mod} (R, \mathcal{C})} (X, N \pitchfork_k Y)$$
Thus, $N \pitchfork_k {-}$ is the required right adjoint for $N \otimes_R {-}$.
(Incidentally, $N \otimes_R X$ is bilinear in $N$ and $X$ simply because the RHS of the defining isomorphism is bilinear in $N$ and $X$.
This is a standard transport-of-structure argument.)
Comment: Completeness is not _necessary_. You can get preservation of colimits by a Yoneda-type argument too. The point is that the RHS of the defining isomorphism preserves limits in $X$ (which is an object in $\textrm{Mod} (R, \mathcal{C})^\textrm{op}$ for this purpose), so the LHS also preserves limits in $X$, so $N \otimes_R {-}$ preserves colimits.
Comment: More generally, right exact functors are automatically additive(since they carry biproducts to biproducts), so you get additivity in the two variables automatically.
Comment: Yes, but here we also want $k$-(bi)linearity.
Comment: So just one last detail : completeness of $C$ is necessary for $N\otimes_R \bullet$ to be right exact ? Or is there an argument proving right exactness not invoking the dual of the theorem constructing $\otimes_R$ ? Because the author just says right exactness in each variable is obvious and doesn't mention $C$ needing to be complete for that.


Como re-criar uma URL com Accept-Language + split ?

Question: Estou com um código em PHP criado pelo membro @Maia, ele informa o idioma do navegador e retorna com um redirecionamento.
Código
<?php
$lang = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
header("Location: http://meusite.com/$lang" ) ;
?>

Ele redireciona para:
meusite.com/pt-BR,pt;q=0.8,en-US;q=0.6,en;q=0.4

O certo seria ele redirecionar para meusite.com/pt-BR porque o meu navegador está com o idioma pt-BR.
Será que criando um split resolveria?

O membro @Maia fez assim:
$lang = split(",", $_SERVER['HTTP_ACCEPT_LANGUAGE'])[0];

No caso a URL iria só até a primeira vírgula, deixando assim só: meusite.com/pt-BR.
Só que o código parece estar errado, não funciona.
Gostaria de fazer isso com a URL, deixando até /pt-BR, ou até mesmo deixá-lo:
meusite.com/pt

O membro sugeriu que eu trocasse o índice de [0] para 1 deixando assim:
$lang = split(",", $_SERVER['HTTP_ACCEPT_LANGUAGE'])[1];

Só que não funciona, então gostaria de algum exemplo de como fazer com que redirecione para /pt-BR ou como redirecionar para /pt
Comment: Segue uma solução sem muita otimização, só pra vc parar de mimimi :P
Comment: É o clássico [ProblemaXY](http://meta.pt.stackoverflow.com/a/1202/70). Na minha humilde opinião, a [pergunta original](http://pt.stackoverflow.com/questions/22861/) era muito melhor, mas me parece que você deu accept na primeira resposta, que apesar de boa talvez não tenha resolvido inteiramente seu problema.
Comment: @Bacco
Como posso resolver isso? Ajuda-me novamente man! rs
Comment: Ela resolve, agora minha dúvida é só como mudar a URL. #Simplesmente
Comment: No momento não posso te ajudar, pq estou resolvendo outras coisas, mas vamos torcer pra alguém dar mais alternativas naquela questão, pois há vários meios pra se lidar com isso. Até servidores como o Apache já tem essa funcionalidade internamente, pode notar que a instalação padrão (a página de bem vindo do apache) atende a linguagem do sew browser automaticamente, mesmo sem PHP: https://httpd.apache.org/docs/2.2/content-negotiation.html
Comment: Sempre que eu peço ajuda a você, você diz que está ocupado... Típico. rsrsrs Mais não tem problema! ;)
Answer: Segue uma solução rápida 1:
<?php

$langs = array();
if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {

   // Cá entre nós, usar regex pra isso é forçar a amizade, mas lá vai :)
   preg_match_all('/([a-z]{1,8}(-[a-z]{1,8})?)\s*(;\s*q\s*=\s*(1|0\.[0-9]+))?/i', $_SERVER['HTTP_ACCEPT_LANGUAGE'], $lang_parse);

   //Aqui vamos ordenar por preferência do usuário
   if (count($lang_parse[1])) {
      $langs = array_combine($lang_parse[1], $lang_parse[4]);
      foreach ($langs as $lang => $val) {
         if ($val === '') $langs[$lang] = 1;
      }
      arsort($langs, SORT_NUMERIC);
   }
}

// Aqui você põe apenas as linguagens que seu site REALMENTE tem:
foreach ($langs as $lang => $val) {
   if ( strpos($lang, 'pt') === 0) {
      header( "Location: http://meusite.com/pt/" ) ;
      exit();
   } else if (strpos($lang, 'en') === 0) {
      header( "Location: http://meusite.com/en/" ) ;
      exit();
   }
}
// Se nao achar nenhuma:
header( "Location: http://meusite.com/pt/" ) ;
exit();

?>

Não precisa por pt-BR, nem en-US, a não ser que queira separar por exemplo o pt-BR do pt-PT, e assim por diante.
1. pesquisada no Duck Duck Go, correndo.
Fonte:http://www.thefutureoftheweb.com/blog/use-accept-language-header
Comment: Essa solução (assim como a do apache que eu comentei) é boa por respeitar a vontade do usuário. Só pq um brasileiro viaja pros EUA nao quer dizer que ele vá ler sites em ingles, por exemplo (o que aconteceria se fosse mudar a lingua por IP ou geolocalização). Geolocalização é bom se o cara for procurar um restaurante perto, ou coisa do tipo. E IP é bom pra estatisticas suas, e nao pro usuário final.
Comment: Agradeça ao autor original e ao http://ddg.gg
Comment: Isso é muito top! É muito melhor do que redirecionamento por IP.
Comment: Qual você acha melhor, por IP ou por Idioma ? Pelo Idioma é bom pelo fato de respeitar a vontade do usuário, só que e se o navegador estiver com linguagem `en`? como o seu Iron. Já por IP ele não respeitará a vontade do usuário. Estou em dúvida. E você? Por Idioma pode ser melhor? Diz aí! :D
Comment: @AlexandreLopes o meu Iron tá em en pq eu deixei em en, se quiser é só mudar nas configs tambem. É que meu windows está em ingles tambem, entao ficou com a linguagem padrão do sistema.


Pickerviews and Tableviews

Question: Can I use just one controller to have a Tableview (bottom half of the screen) shared with a Pickerview (top half of the screen)?
Also, is the Tableview the best way to implement an eight row by two column view used for display purposes only, or is there a better - easier - way?
Answer: Yes
The pickerview uses a delegate protocol, so get your tableview controller to conform to the UIPickerViewDelegate protocol: info here http://developer.apple.com/IPhone/library/documentation/UIKit/Reference/UIPickerViewDelegate_Protocol/Reference/UIPickerViewDelegate.html
Tableview sounds like the right way to do it.  The wrong way would be to layout 2x8 controls onto a scrollview (IMHO). Once you have the hang of a table view, its really easy to use - ditto the pickerview delegates.

Pickerviews and Tableviews


why there is the factor $n$ in the RHS of the Cauchy-Schwartz inequality for matrices?

Question: In the book of Analysis on Manifolds by Munkres, at page 64, it is given that
$$|x_0-x_1| = |E^{-1} \cdot (E\cdot x_0 - E \cdot x_1 )| \leq n |E^{-1}| \cdot |E\cdot x_0 - E \cdot x_1|.$$
I can see that the author uses the Cauchy-Schwartz inequality, but I cannot understand why there is the factor $n$ in the RHS ? I mean he multiplies the dimension the matrix in such inequalities all the time, so I figured it should be a term in the matrix version of Cauchy-Schwartz inequality.
Comment: @JefferyOpoku-Mensah Munkres defines $|A|$ as $\max|a_{ij}|$.
Comment: If it is the matrix norm, try looking [here.](https://math.stackexchange.com/questions/1767993/matrix-norm-inequality-proof-does-this-use-cauchy-schwarz)
Comment: What is $|E^{-1}|$? The determinant?
Comment: @JefferyOpoku-Mensah No idea.
Comment: Schwarz not Schwartz !
Answer: Check out: Theorem 1.3, page 5.


Is it possible to move product category description alignment in drupal

Question: Can any one suggest me to move Product description from top to bottom in drupal product category page.
Example Like :

First all product Image.
And Bottom content are shown.
Answer: This can be also done through the admin dashboard. Follow the below steps:

Go to admin/structure/types.
Select your content/Product type and manage Display according to your requirement.
Comment: can you provide me communication id for understand in brief..How to do in back-end side.
Comment: Follow the steps I mentioned above. Back-end side means you want to customize the product type using `tpl.php` files?
Comment: [Drupal customizing content types](https://api.drupal.org/api/drupal/modules%21node%21node.tpl.php/7). Follow this link for the detailed explanation for customizing `node.tpl.php` files.
Answer: create node--product.tpl.php to theme the product category page.
Comment: can you provide me communication id for understand in brief.
Comment: Sorry i'm quite busy these days my id is firstname.lastname@example.com


How to analyse the memory usage of Mongo DB in windows operating system?

Question: I have installed mongodb-win32-x86_64-3.0.6 in windows operating system. I want to analayse the memory usage by Mongodb at any given time.
Answer: I found the solution. The command db.serverStatus().mem will give the details like total allocated memory and currently used memory. The user needs clusterAdmin role to execute the serverstatus command.


CKEditor + IMCE file uploader. What am I missing?

Question: I've got CKEditor and IMCE modules installed and enabled. I've got an "Insert image" link at the bottom of the "body" text area. However, I can't seem to get the wysiwyg editor to display.
What am I missing?
In admin/config/content/formats
I only have Plain text format.
Should I add Fitered HTML, full HTML and php manually?
Or shoud have they been created automatically with one of the modules?
Comment: Have you selected the correct filter. depending on your settings wysiwyg would be enabled for some of the filters only. may be just for the Full HTML
Comment: Thanks. But I don't even get that dropdown menu where I can select between full/filtered/plain html or whatever.
All I see is this:
Insert image or link.

More information about text formats

    No HTML tags allowed.
    Web page addresses and e-mail addresses turn into links automatically.
    Lines and paragraphs break automatically.
Comment: could you take a screenshot and send it.
Comment: How do I attach files?
Comment: You can upload them with [Skitch](http://evernote.com/skitch/) and link them if you do not yet have permissions to attach them to your posts here.
Answer: Depending on what version of Drupal you're using, my first inclination is to say the Media module is what you're missing.
That aside, there are a number of steps to take to configure the WYSIWYG image experience.

How did you install CKEditor? Did you install the WYSIWYG module and the CKEditor library properly?
Did you install the correct version of CKEditor? I think you might need the 3.6 version.
Have you set up the correct input format? Does your user have permissions to use it?
Have you set up a CKEditor profile with the correct image insert buttons that integrate with IMCE?

Those are the main things that come to mind, though knowing more about what happens (i.e., when you disable rich text, does anything display in the editing window?) and what steps you've already taken would help narrow it down.
Comment: Thank you Beth
I am using IMCE instead of the CKEditor Library.
Comment: I think beth has covered most of the things that you should check. For more help it would be good to get some more info from you. You can attach the image to your question rather than the comment
Comment: How do I attach images?

I just installed the media module but still no luck.

I've got ckeditor, wysiwyg, imce, media modules enables. They are all in the modules directory. I've got the same structure on another site and the editor works fine...
Comment: In admin/config/content/ckeditor/edit/Advanced

Under Basic setup - Text formats
I only have one option, which is Plain text.

However, on the site which does display the ckeditor correctly I've got the following options:

Filtered HTML
Plain text
PHP code

Why would this be the case?
Comment: In admin/config/content/formats
I only have Plain text format.

Should I add Fitered HTML, full HTML and php manually?

Or shoud have they been created automatically with one of the modules?
Comment: Do not add PHP unless you have a really really good reason, but by all means add Filtered and/or Full HTML for trusted users, and enable CKEditor for those input formats.
Comment: Thank you Beth. Added filtered html manually and it's now available when i edit content. YAY
Answer: In my case there was some error on javascript side. When I started debuging using Firebug, then I got exact the line number with error and commented out the line. This solve my issue and all button appear in IMCE File browser.
I am using Wyswing. module , IMCE and Wysysing IMCE Bridge module in Drupal 7
ANOTHER POSSIABLE REASON IS : YOU MAY HAVE NOT ASSIGNED THE USER PROFILE OF IMCE TO ROLE.
1) GO TO admin/config/media/imce
2) ASSIGN EACH ROLE A USER PROFILE USER-1
3) AND SAVE.
Answer: I found that the sharebar module conflicts with the imce / ckeditor
https://drupal.org/project/sharebar
there is even a open issue for this.
https://drupal.org/node/2058939
once I turn off sharebar module, imce image upload buttons reappear.
Answer: An old problem, but still relevant ;-) In my case it was a jquery incompatability issue with bootstrap. Enabling Jquery update module was the solution.