text:
Q: How to use the same jQuery scrolling function for multiple elements I have a scrolling function that reveals a 'scroll to top' element  when user scrolls to 160 pixels, when clicked this element the page scrolls to the top of the page.
I want to use that function create more scroll buttons which will be revealed at different stages in the document and that scroll to different areas.
For example when the user scrolls to 400 pixels down the element "next" appears when clicking it page scrolls 300px down, they get to 900px from top a new scroll element appears which when clicked scrolls down to 1300px, and so on.
here is the jQuery code i have:
   $(document).ready(function(){

$(window).scroll(function(){
    if ($(this).scrollTop() > 160)  {
        $('.scrollToTop').fadeIn();
    } else {
        $('.scrollToTop').fadeOut();
    }

});

$('.scrollToTop').click(function(){
    $('html, body').animate({scrollTop : 0},800);
    return false;
});
});

HTML:

Scroll to top

i hope thats not too confusing.
Thanks

A: Maybe you can use a function like this I made reusing some parts of your code:
function scroll(id,show,limit,timeout){
  $(window).scroll(function(){
    if ($(this).scrollTop() > show)  {
      $(id).fadeIn();
    } else {
      $(id).fadeOut();
    }
 });
 $(id).click(function(){
   $('html, body').animate({scrollTop : limit},timeout);
   return false;
 });
}

And then use it like this:
scroll(".scrollToTop",160,0,800);

where first parameter is class or id you want to be affected, second is the position of the element at certain height (from top), third is limit (where you want to scroll up) and last one is the duration of the animate function.

EDIT: You may also like to stop on specific px, not only scroll to top, so I changed the function to set the scrollTop position at your desire.


text:
Q: ¿Por qué lm no considera todos mis efectos? Estoy corriendo el siguiente modelo lineal general en R:
model1<-lm(leche ~ MT1 + ednp + cnv3 + poly(DIM, 3) + HTD, data=misdatos)

MT1, ednp, cnv3 y HTD son factores, los he predefinido como tal; mientras que DIM es una variable continua que utilizo como covariable en el modelo. Ejecutando el modelo de esta manera, mi anova considera todos los efectos
Analysis of Variance Table

Response: leche
                Df     Sum Sq   Mean Sq  F value    Pr(>F)
MT1              1    2788946   2788946   67.049 2.703e-16 ***
ednp             9   87481407   9720156  233.680 < 2.2e-16 ***
cnv3             2    4457347   2228674   53.579 < 2.2e-16 ***
poly(DIM, 3)     3  947794411 315931470 7595.244 < 2.2e-16 ***
HTD           1012  762410521    753370   18.112 < 2.2e-16 ***
Residuals    57613 2396468010     41596
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Sin embargo, cuando cambio el orden de mis efectos a
model2<-lm(leche ~ HTD + MT1 + cnv3 + poly(DIM, 3) + ednp, data=misdatos)

el resultado omite la salida para MT1, lo que creo que carece de sentido porque en teoría el orden no debería alterar el resultado, ¿no?
Analysis of Variance Table

Response: leche
                Df     Sum Sq   Mean Sq  F value    Pr(>F)
HTD           1013 1350638499   1333306   32.054 < 2.2e-16 ***
ednp             9   45711618   5079069  122.105 < 2.2e-16 ***
cnv3             2    1413259    706630   16.988 4.211e-08 ***
poly(DIM, 3)     3  407169256 135723085 3262.891 < 2.2e-16 ***
Residuals    57613 2396468010     41596

¿Qué puede estar pasando? Esto ya me crea inseguridad en los resultados que obtengo y no se me ocurre que puede estar pasando. ¿Alguna idea?

A: Respuesta corta: en el anova de un solo modelo el orden de los términos sí importa. Para ver todos los términos de una regresión siempre se puede usar summary(modelo).
Respuesta larga:
Según se documenta en la ayuda de anova.lm()

Cuando se especifica un solo objeto da como resultado una tabla de análisis de varianza secuencial para ese modelo. Esto es, las reducciones en la suma de cuadrados residuales a medida que se agrega cada término a la fórmula se presentan como filas de una tabla, así como el residual de la suma de cuadrados. (Traducción propia, original en inglés debajo)

Es decir, si en lugar de comparar varios modelos se hace el análisis sobre un solo modelo, lo que hace anova.lm() es ir incluyendo cada término (predictor o variable independiente) en el orden en que aparecen en la fórmula. Cuando llega al punto en que el siguiente término no reduce los residuos cuadrados, entonces ese "siguiente término" ya no se incluye.
La función anova() se usa principalmente para comparar el ajuste de dos o más especificaciones de modelos para los mismos datos. Dicho de otro modo, es una especie de prueba de hipótesis para decidir si un modelo tiene mejor ajuste que otro, para lo cuál calcula un p-value. De este modo tendrías información para decidir si te quedas con el modelo con menos términos o lo descartas en favor del que tiene más términos. La idea es encontrar un modelo parsimonioso.
La literatura actual desaconseja este tipo de procedimientos para seleccionar predictores, tanto para fines predictivos como de inferencia causal.

*

*Si el modelo es para fines predictivos porque la R cuadrada tiende a premiar modelos sobreajustados, que dan peores resultados estimando datos no vistos (i.e. haciendo predicciones). En ese caso sería mejor hacer la selección de predictores por validación cruzada o separar los datos en test y entrenamiento. Mejor todavía usar un modelo lasso.

*Si fuera para fines inferenciales (lo que intuyo, ya que usas la palabra efecto) porque hacer primero selección de variables y hacer luego las pruebas de hipótesis sobre el modelo con las variables seleccionadas tiende a reducir los p-value de manera espuria. Lo que se aconseja es ajustar un modelo penalizado, como podría ser alguna variante del lasso.
Este paper tiene una muy buena discusión sobre el tema, lamentablemente está en inglés y no he encontrado nada en español sobre el tema aún.

Specifying a single object gives a sequential analysis of variance table for that fit. That is, the reductions in the residual sum of squares as each term of the formula is added in turn are given in as the rows of a table, plus the residual sum of squares. (original de la ayuda de anova.lm, considerando los autores de la función se lo puede tomar como referencia canónica)

redpajama_set_name: RedPajamaStackExchange


text:
Q: iSpin LTL property evaluation only with activated "assertion violations"? I am trying to get used to iSpin/Promela. I am using:
Spin Version 6.4.3 -- 16 December 2014,
iSpin Version 1.1.4 -- 27 November 2014,
TclTk Version 8.6/8.6,
Windows 8.1.
Here is an example where I try to use LTL. The verification of the LTL property should produce an error if the two steps in the for loop are non-atomic:
1   #define ten ((n !=10) && (finished == 2))
2
3   int n = 0;
4   int finished = 0;
5   active [2] proctype P() {
6       //assert(_pid == 0 || _pid == 1);
7
8           int t = 0;
9           byte j;
10          for (j : 1 .. 5) {
11              atomic {
12                  t = n;
13                  n = t+1;
14              }
15          }
16      finished = finished+1;
17  }
18
19  ltl alwaysten {[] ! ten }

In the verification tap I just want to test the LTL property, so I disable all safety properties and activate "use claim". The claim name is "alwaysten".

But it seems that the LTL property is just evaluated if I activate "assertion violations". Why? A collegue is using iSpin v1.1.0 and he does not need to activate this? What am I doing wrong? I want to prove assertions and LTL properties independently...
Here is the trace:
pan: elapsed time 0.002 seconds
To replay the error-trail, goto Simulate/Replay and select "Run"
spin -a  1_2_ConcurrentCounters_8.pml
ltl alwaysten: [] (! (((n!=10)) && ((finished==2))))
C:/cygwin/bin/gcc -DMEMLIM=1024 -O2 -DXUSAFE -w -o pan pan.c
./pan -m10000  -E -a -N alwaysten
Pid: 6980
warning: only one claim defined, -N ignored

(Spin Version 6.4.3 -- 16 December 2014)
    + Partial Order Reduction

Full statespace search for:
    never claim             + (alwaysten)
    assertion violations    + (if within scope of claim)
    acceptance   cycles     + (fairness disabled)
    invalid end states  - (disabled by -E flag)

State-vector 36 byte, depth reached 57, errors: 0
      475 states, stored
      162 states, matched
      637 transitions (= stored+matched)
        0 atomic steps
hash conflicts:         0 (resolved)

Stats on memory usage (in Megabytes):
    0.024   equivalent memory usage for states (stored*(State-vector + overhead))
    0.291   actual memory usage for states
   64.000   memory used for hash table (-w24)
    0.343   memory used for DFS stack (-m10000)
   64.539   total actual memory usage

unreached in proctype P
    (0 of 13 states)
unreached in claim alwaysten
    _spin_nvr.tmp:8, state 10, "-end-"
    (1 of 10 states)

pan: elapsed time 0.001 seconds
No errors found -- did you verify all claims?

A: This is because your LTL is translated into a claim with an assert statement. See the following automaton.

So, without checking for assertion violations, no error can be found.
(A possible explanation of different behaviors: previous versions of Spin might translate this differently, perhaps using accept instead of assert.)


text:
Q: Get raw file from repository I want to get a file content in gitlab by using its api.
Firstly, I check my gitlab version, its written as,
GitLab Community Edition 9.4.3 b125d21 update asap
Then I create a private token and
http://gitadress/api/v4/projects/id/repository/files?private_token=PRIVATE_TOKEN
returns as;
{"error":"404 Not Found"}

then I modify the query as;
http://gitadress/api/v4/projects/222/repository/tree?private_token=PRIVATE_TOKEN
this request returns as;
[{"id":"8078365d80c","name":"test.js","type":"blob","path":"test.js","mode":"100644"}]

What I want is to get the content of the test.js but whatever I tried I couldn't achieve it.
http://gitadress/api/v4/projects/id/repository/tree/test.js/raw?private_token=PRIVATE_TOKEN&ref=master
returns as;
{"error":"404 Not Found"}

How can I get the raw file content by using gitlab api?
Documentation is here;
https://github.com/gitlabhq/gitlabhq/blob/master/doc/api/repository_files.md#get-raw-file-from-repository

A: The documentation mentions:

Url encoded full path to new file. Ex. lib%2Fclass%2Erb

That means you need to URL encode test.js: test%2Ejs.
(See Percent encoding: character data)
http://gitadress/api/v4/projects/id/repository/files/test%2Ejs/raw?private_token=PRIVATE_TOKEN

You can add ?ref=master to make sure to get the content from the master branch for instance.
http://gitadress/api/v4/projects/id/repository/files/test%2Ejs/raw?ref=master&private_token=PRIVATE_TOKEN

That being said, you have the gitlab-ce issue 31470 which is still open:

API to "Get raw file from repository" fails for files with dots

A fix is in progress: gitlab-ce merge_request 13370, and will be delivered for GitLab 9.5.


text:
Q: Generalised Stirling number that each partition has more than one component We know that the Stirling number of the second kind is the number of ways to partition a set of $n$ objects into $k$ non-empty subsets and is denoted by $s(n,k)=\frac{1}{k!}\sum_{j=0}^{k}(-1)^{k-j}\begin{pmatrix}
k\\
j
\end{pmatrix}j^n$
This formula is for the case that the partitions have at least one component. I am trying to find the similar formula for the case that each partition has at least $m$ component. Does anyone have any ideas?

A: The first question you should be asking is where does the formula
$$ s(n,k) = \frac1{k!} \sum_{j = 0}^k \binom{k}{j} j^n (-1)^{k - j} $$
come from? Then once you understand that, perhaps you will be able to generalize.

Note that the generating function for nonempty sets is $e^x - 1 = x + \frac{x^2}{2!} + \frac{x^3}{3!} + \cdots$. The generating function for a set of size $k$ is $x^k/k!$. Thus the generating function for a set of size $k$ whose elements are non-empty sets is
$$ \sum_{n \ge 0} s(n,k)\frac{x^n}{n!} = \frac{(e^x - 1)^k}{k!} $$
and therefore
$$ \sum_{k \ge 0} \sum_{n \ge 0} s(n,k)\frac{x^n}{n!}y^k = \exp(y(e^x - 1)). $$
Therefore
\begin{align}
  s(n,k) &= \left[ \frac{x^n}{n!}y^k \right] \exp(y(e^x - 1)) \\
 &= \frac{1}{k!} \left[ \frac{x^n}{n!} \right] (e^x - 1)^k \\
 &= \frac{1}{k!} \left[ \frac{x^n}{n!} \right] \sum_{j = 0}^k \binom{k}{j} e^{jx}(-1)^{k - j} \\
 &= \frac{1}{k!} \sum_{j = 0}^k \binom{k}{j} j^n(-1)^{k - j}.
\end{align}

Let us agree to write $s_m(n,k)$ for the number of ways to partition a set of size $n$ into $k$ subsets of size at least $m$.
Then the same thing happens as before except instead of using $e^x - 1$ for non-empty sets, we use $$ e^x - 1 - x - \frac{x^2}{2!} - \dots - \frac{x^{m - 1}}{(m - 1)!} = \frac{x^m}{m!} + \frac{x^{m + 1}}{(m + 1)!} + \frac{x^{m + 2}}{(m + 2)!} + \cdots $$
for sets with at least $m$ elements. So we have
$$ \sum_{n,k} s_m(n,k)\frac{x^n}{n!}y^k = \exp \left[ y \left( e^x - 1 - x - \frac{x^2}{2!} - \dots - \frac{x^{m - 1}}{(m - 1)!} \right) \right]. $$
And like before,
\begin{align}
 s_m(n, k) &= \frac{1}{k!} \left[ \frac{x^n}{n!} \right] \left( e^x - 1 - x - \frac{x^2}{2!} - \dots - \frac{x^{m - 1}}{(m - 1)!} \right)^k \\
&= \frac{1}{k!} \left[ \frac{x^n}{n!} \right] \sum_{i + j_0 + \dots + j_{m - 1} = k} \binom{k}{i,j_0,\dots,j_{m-1}} e^{ix}(-1)^{j_0}\left( -x \right)^{j_1} \cdots \left( -\frac{x^{m - 1}}{(m - 1)!} \right)^{j_{m - 1}}
\end{align}
Now we group together the minus signs: $(-1)^{j_0 + \dots + j_{m - 1}} = (-1)^{k - i}$ giving
\begin{align}
&\frac{1}{k!}\left[ \frac{x^n}{n!} \right] \sum_{i + j_0 + \dots + j_{m - 1} = k} \binom{k}{i,j_0,\dots,j_{m-1}} e^{ix}(-1)^{k - i}\left( x \right)^{j_1} \cdots \left( \frac{x^{m - 1}}{(m - 1)!} \right)^{j_{m - 1}} \\
&= \frac{n!}{k!} \sum_{i + j_0 + \dots + j_{m - 1} = k} \binom{k}{i,j_0,\dots,j_{m-1}} \frac{1}{0!^{j_0}\cdots (m-1)!^{j_{m - 1}}} [x^n] e^{ix}(-1)^{k - i} x^{0j_0 + \dots + (m - 1)j_m} \\
&= \frac{n!}{k!} \sum_{i + j_0 + \dots + j_{m - 1} = k} \binom{k}{i,j_0,\dots,j_{m-1}} \frac{1}{1!^{j_1}\cdots (m-1)!^{j_{m - 1}}} [x^{n - 1j_1 - \dots - (m - 1)j_m}] e^{ix}(-1)^{k - i} \\
&= \frac{n!}{k!} \sum_{i + j_0 + \dots + j_{m - 1} = k} \binom{k}{i,j_0,\dots,j_{m-1}} \frac{1}{1!^{j_1}\cdots (m-1)!^{j_{m - 1}}} i^{n - j_1 - 2j_2 - \dots - (m - 1)j_{m - 1}} (-1)^{k - i}.
\end{align}


text:
Q: Обучение нейронной сети теореме Пифагора Хочу обучить НС теореме Пифагора. Всё вроде правильно сделал, нормализовал данные, модель правильная, а вот в чём ошибка не понятно..
import numpy as np

from keras.models import Sequential
from keras.layers.core import Dense, Activation
from keras.utils import np_utils

np.random.seed()

NB_EPOCH = 500
VERBOSE = 1

X_in = [[ 0 , 44 ], [ 0 , 18 ], [ 38 , 0 ], [ 48 , 14 ], [ 0 , 36 ], [ 14 , 0 ], [ 34 , 0 ], [ 0 , 0 ], [ 0 , 38 ], [ 32 , 0 ], [ 28 , 0 ], [ 36 , 0 ], [ 20 , 48 ], [ 0 , 6 ], [ 0 , 20 ], [ 0 , 42 ], [ 0 , 8 ], [ 24 , 32 ], [ 4 , 0 ], [ 6 , 8 ], [ 24 , 10 ], [ 0 , 22 ], [ 16 , 12 ], [ 30 , 40 ], [ 0 , 32 ], [ 0 , 32 ], [ 16 , 0 ], [ 48 , 20 ], [ 0 , 8 ], [ 32 , 0 ], [ 0 , 46 ], [ 0 , 22 ], [ 0 , 8 ], [ 10 , 24 ], [ 0 , 36 ], [ 14 , 0 ], [ 0 , 22 ], [ 42 , 0 ], [ 16 , 12 ], [ 40 , 30 ], [ 44 , 0 ], [ 40 , 0 ], [ 34 , 0 ], [ 0 , 32 ], [ 40 , 30 ], [ 32 , 0 ], [ 0 , 30 ], [ 24 , 18 ], [ 0 , 26 ], [ 22 , 0 ], [ 0 , 4 ], [ 16 , 0 ], [ 10 , 0 ], [ 0 , 32 ], [ 0 , 42 ], [ 2 , 0 ], [ 0 , 38 ], [ 32 , 24 ], [ 48 , 0 ], [ 20 , 0 ], [ 0 , 18 ], [ 0 , 38 ], [ 14 , 48 ], [ 40 , 42 ], [ 16 , 12 ], [ 26 , 0 ], [ 0 , 20 ], [ 40 , 30 ], [ 16 , 30 ], [ 36 , 48 ], [ 36 , 0 ], [ 18 , 24 ], [ 34 , 0 ], [ 16 , 0 ], [ 0 , 24 ], [ 0 , 24 ], [ 0 , 18 ], [ 38 , 0 ], [ 28 , 0 ], [ 0 , 34 ], [ 0 , 36 ], [ 24 , 32 ], [ 16 , 30 ], [ 40 , 30 ], [ 24 , 0 ], [ 0 , 14 ], [ 8 , 6 ], [ 12 , 0 ], [ 16 , 0 ], [ 16 , 30 ], [ 48 , 14 ], [ 0 , 30 ], [ 38 , 0 ], [ 38 , 0 ], [ 0 , 8 ], [ 36 , 48 ], [ 0 , 32 ], [ 10 , 24 ], [ 46 , 0 ], [ 24 , 10 ], [ 30 , 0 ], [ 0 , 48 ], [ 40 , 0 ], [ 42 , 0 ], [ 32 , 24 ], [ 32 , 0 ], [ 12 , 16 ], [ 0 , 4 ], [ 0 , 28 ], [ 32 , 0 ], [ 40 , 42 ], [ 46 , 0 ], [ 0 , 24 ], [ 30 , 16 ], [ 36 , 48 ], [ 40 , 0 ], [ 24 , 0 ], [ 0 , 22 ], [ 40 , 42 ], [ 10 , 24 ], [ 0 , 16 ], [ 14 , 48 ], [ 22 , 0 ], [ 0 , 22 ], [ 30 , 0 ], [ 0 , 2 ], [ 48 , 20 ], [ 6 , 0 ], [ 6 , 0 ], [ 28 , 0 ], [ 20 , 0 ], [ 0 , 40 ], [ 42 , 0 ], [ 48 , 36 ], [ 14 , 0 ], [ 10 , 24 ], [ 0 , 30 ], [ 48 , 20 ], [ 40 , 30 ], [ 0 , 0 ], [ 42 , 40 ], [ 0 , 48 ], [ 32 , 24 ]]
X_answer = [[44] ,[18] ,[38] ,[50] ,[36] ,[14] ,[34] ,[0] ,[38] ,[32] ,[28] ,[36] ,[52] ,[6] ,[20] ,[42] ,[8] ,[40] ,[4] ,[10] ,[26] ,[22] ,[20] ,[50] ,[32] ,[32] ,[16] ,[52] ,[8] ,[32] ,[46] ,[22] ,[8] ,[26] ,[36] ,[14] ,[22] ,[42] ,[20] ,[50] ,[44] ,[40] ,[34] ,[32] ,[50] ,[32] ,[30] ,[30] ,[26] ,[22] ,[4] ,[16] ,[10] ,[32] ,[42] ,[2] ,[38] ,[40] ,[48] ,[20] ,[18] ,[38] ,[50] ,[58] ,[20] ,[26] ,[20] ,[50] ,[34] ,[60] ,[36] ,[30] ,[34] ,[16] ,[24] ,[24] ,[18] ,[38] ,[28] ,[34] ,[36] ,[40] ,[34] ,[50] ,[24] ,[14] ,[10] ,[12] ,[16] ,[34] ,[50] ,[30] ,[38] ,[38] ,[8] ,[60] ,[32] ,[26] ,[46] ,[26] ,[30] ,[48] ,[40] ,[42] ,[40] ,[32] ,[20] ,[4] ,[28] ,[32] ,[58] ,[46] ,[24] ,[34] ,[60] ,[40] ,[24] ,[22] ,[58] ,[26] ,[16] ,[50] ,[22] ,[22] ,[30] ,[2] ,[52] ,[6] ,[6] ,[28] ,[20] ,[40] ,[42] ,[60] ,[14] ,[26] ,[30] ,[52] ,[50] ,[0] ,[58] ,[48] ,[40]]
X_in = np.asarray(X_in, dtype=np.float32)
X_answer = np.asarray(X_answer, dtype=np.float32)

X_in /= np.amax(X_in)
X_answer /= np.amax(X_answer)

model = Sequential()
model.add(Dense(10, input_dim = 2, activation='relu'))
model.add(Dense(10, activation='relu'))
model.add(Dense(1, activation='softmax'))

model.compile(loss='mean_squared_error', optimizer='adam', metrics=['accuracy'])

history = model.fit(X_in, X_answer, epochs=NB_EPOCH, verbose=VERBOSE)

Что до 100 эпох, что до 500 один и тот же результат:
Epoch 1/100
143/143 [==============================] - 0s 2ms/step - loss: 0.2966 - acc: 0.0280
Epoch 2/100
143/143 [==============================] - 0s 52us/step - loss: 0.2966 - acc: 0.0280
Epoch 3/100
143/143 [==============================] - 0s 52us/step - loss: 0.2966 - acc: 0.0280
Epoch 4/100
143/143 [==============================] - 0s 38us/step - loss: 0.2966 - acc: 0.0280
Epoch 5/100
143/143 [==============================] - 0s 52us/step - loss: 0.2966 - acc: 0.0280
Epoch 6/100
143/143 [==============================] - 0s 45us/step - loss: 0.2966 - acc: 0.0280
Epoch 7/100
143/143 [==============================] - 0s 45us/step - loss: 0.2966 - acc: 0.0280
Epoch 8/100
143/143 [==============================] - 0s 42us/step - loss: 0.2966 - acc: 0.0280
Epoch 9/100
143/143 [==============================] - 0s 45us/step - loss: 0.2966 - acc: 0.0280
Epoch 10/100
143/143 [==============================] - 0s 42us/step - loss: 0.2966 - acc: 0.0280
Epoch 11/100
143/143 [==============================] - 0s 38us/step - loss: 0.2966 - acc: 0.0280
Epoch 12/100
143/143 [==============================] - 0s 45us/step - loss: 0.2966 - acc: 0.0280
Epoch 13/100
143/143 [==============================] - 0s 42us/step - loss: 0.2966 - acc: 0.0280
Epoch 14/100
143/143 [==============================] - 0s 42us/step - loss: 0.2966 - acc: 0.0280
Epoch 15/100
143/143 [==============================] - 0s 42us/step - loss: 0.2966 - acc: 0.0280
Epoch 16/100
143/143 [==============================] - 0s 45us/step - loss: 0.2966 - acc: 0.0280
Epoch 17/100
143/143 [==============================] - 0s 38us/step - loss: 0.2966 - acc: 0.0280
Epoch 18/100
143/143 [==============================] - 0s 38us/step - loss: 0.2966 - acc: 0.0280
Epoch 19/100
143/143 [==============================] - 0s 42us/step - loss: 0.2966 - acc: 0.0280
Epoch 20/100
143/143 [==============================] - 0s 35us/step - loss: 0.2966 - acc: 0.0280
Epoch 21/100
143/143 [==============================] - 0s 45us/step - loss: 0.2966 - acc: 0.0280
Epoch 22/100
143/143 [==============================] - 0s 42us/step - loss: 0.2966 - acc: 0.0280
Epoch 23/100
143/143 [==============================] - 0s 35us/step - loss: 0.2966 - acc: 0.0280
Epoch 24/100
143/143 [==============================] - 0s 45us/step - loss: 0.2966 - acc: 0.0280
Epoch 25/100
143/143 [==============================] - 0s 38us/step - loss: 0.2966 - acc: 0.0280
Epoch 26/100
143/143 [==============================] - 0s 42us/step - loss: 0.2966 - acc: 0.0280
Epoch 27/100
143/143 [==============================] - 0s 42us/step - loss: 0.2966 - acc: 0.0280
Epoch 28/100
143/143 [==============================] - 0s 45us/step - loss: 0.2966 - acc: 0.0280
Epoch 29/100
143/143 [==============================] - 0s 45us/step - loss: 0.2966 - acc: 0.0280
Epoch 30/100
143/143 [==============================] - 0s 45us/step - loss: 0.2966 - acc: 0.0280
Epoch 31/100
143/143 [==============================] - 0s 45us/step - loss: 0.2966 - acc: 0.0280
Epoch 32/100
143/143 [==============================] - 0s 52us/step - loss: 0.2966 - acc: 0.0280
Epoch 33/100
143/143 [==============================] - 0s 42us/step - loss: 0.2966 - acc: 0.0280
Epoch 34/100
143/143 [==============================] - 0s 45us/step - loss: 0.2966 - acc: 0.0280
Epoch 35/100
143/143 [==============================] - 0s 38us/step - loss: 0.2966 - acc: 0.0280
Epoch 36/100
143/143 [==============================] - 0s 42us/step - loss: 0.2966 - acc: 0.0280
Epoch 37/100
143/143 [==============================] - 0s 49us/step - loss: 0.2966 - acc: 0.0280
Epoch 38/100
143/143 [==============================] - 0s 38us/step - loss: 0.2966 - acc: 0.0280
Epoch 39/100
143/143 [==============================] - 0s 45us/step - loss: 0.2966 - acc: 0.0280
Epoch 40/100
143/143 [==============================] - 0s 42us/step - loss: 0.2966 - acc: 0.0280
Epoch 41/100
143/143 [==============================] - 0s 42us/step - loss: 0.2966 - acc: 0.0280
Epoch 42/100
143/143 [==============================] - 0s 38us/step - loss: 0.2966 - acc: 0.0280
Epoch 43/100
143/143 [==============================] - 0s 38us/step - loss: 0.2966 - acc: 0.0280
Epoch 44/100
143/143 [==============================] - 0s 45us/step - loss: 0.2966 - acc: 0.0280
Epoch 45/100
143/143 [==============================] - 0s 38us/step - loss: 0.2966 - acc: 0.0280
Epoch 46/100
143/143 [==============================] - 0s 45us/step - loss: 0.2966 - acc: 0.0280
Epoch 47/100
143/143 [==============================] - 0s 45us/step - loss: 0.2966 - acc: 0.0280
Epoch 48/100
143/143 [==============================] - 0s 42us/step - loss: 0.2966 - acc: 0.0280
Epoch 49/100
143/143 [==============================] - 0s 38us/step - loss: 0.2966 - acc: 0.0280
Epoch 50/100
143/143 [==============================] - 0s 42us/step - loss: 0.2966 - acc: 0.0280
Epoch 51/100
143/143 [==============================] - 0s 42us/step - loss: 0.2966 - acc: 0.0280
Epoch 52/100
143/143 [==============================] - 0s 42us/step - loss: 0.2966 - acc: 0.0280
Epoch 53/100
143/143 [==============================] - 0s 42us/step - loss: 0.2966 - acc: 0.0280
Epoch 54/100
143/143 [==============================] - 0s 42us/step - loss: 0.2966 - acc: 0.0280
Epoch 55/100
143/143 [==============================] - 0s 49us/step - loss: 0.2966 - acc: 0.0280
Epoch 56/100
143/143 [==============================] - 0s 45us/step - loss: 0.2966 - acc: 0.0280
Epoch 57/100
143/143 [==============================] - 0s 38us/step - loss: 0.2966 - acc: 0.0280
Epoch 58/100
143/143 [==============================] - 0s 45us/step - loss: 0.2966 - acc: 0.0280
Epoch 59/100
143/143 [==============================] - 0s 35us/step - loss: 0.2966 - acc: 0.0280
Epoch 60/100
143/143 [==============================] - 0s 42us/step - loss: 0.2966 - acc: 0.0280
Epoch 61/100
143/143 [==============================] - 0s 35us/step - loss: 0.2966 - acc: 0.0280
Epoch 62/100
143/143 [==============================] - 0s 38us/step - loss: 0.2966 - acc: 0.0280
Epoch 63/100
143/143 [==============================] - 0s 38us/step - loss: 0.2966 - acc: 0.0280
Epoch 64/100
143/143 [==============================] - 0s 38us/step - loss: 0.2966 - acc: 0.0280
Epoch 65/100
143/143 [==============================] - 0s 52us/step - loss: 0.2966 - acc: 0.0280
Epoch 66/100
143/143 [==============================] - 0s 38us/step - loss: 0.2966 - acc: 0.0280
Epoch 67/100
143/143 [==============================] - 0s 45us/step - loss: 0.2966 - acc: 0.0280
Epoch 68/100
143/143 [==============================] - 0s 38us/step - loss: 0.2966 - acc: 0.0280
Epoch 69/100
143/143 [==============================] - 0s 52us/step - loss: 0.2966 - acc: 0.0280
Epoch 70/100
143/143 [==============================] - 0s 42us/step - loss: 0.2966 - acc: 0.0280
Epoch 71/100
143/143 [==============================] - 0s 42us/step - loss: 0.2966 - acc: 0.0280
Epoch 72/100
143/143 [==============================] - 0s 45us/step - loss: 0.2966 - acc: 0.0280
Epoch 73/100
143/143 [==============================] - 0s 39us/step - loss: 0.2966 - acc: 0.0280
Epoch 74/100
143/143 [==============================] - 0s 42us/step - loss: 0.2966 - acc: 0.0280
Epoch 75/100
143/143 [==============================] - 0s 38us/step - loss: 0.2966 - acc: 0.0280
Epoch 76/100
143/143 [==============================] - 0s 45us/step - loss: 0.2966 - acc: 0.0280
Epoch 77/100
143/143 [==============================] - 0s 42us/step - loss: 0.2966 - acc: 0.0280
Epoch 78/100
143/143 [==============================] - 0s 49us/step - loss: 0.2966 - acc: 0.0280
Epoch 79/100
143/143 [==============================] - 0s 38us/step - loss: 0.2966 - acc: 0.0280
Epoch 80/100
143/143 [==============================] - 0s 49us/step - loss: 0.2966 - acc: 0.0280
Epoch 81/100
143/143 [==============================] - 0s 42us/step - loss: 0.2966 - acc: 0.0280
Epoch 82/100
143/143 [==============================] - 0s 35us/step - loss: 0.2966 - acc: 0.0280
Epoch 83/100
143/143 [==============================] - 0s 42us/step - loss: 0.2966 - acc: 0.0280
Epoch 84/100
143/143 [==============================] - 0s 35us/step - loss: 0.2966 - acc: 0.0280
Epoch 85/100
143/143 [==============================] - 0s 42us/step - loss: 0.2966 - acc: 0.0280
Epoch 86/100
143/143 [==============================] - 0s 38us/step - loss: 0.2966 - acc: 0.0280
Epoch 87/100
143/143 [==============================] - 0s 38us/step - loss: 0.2966 - acc: 0.0280
Epoch 88/100
143/143 [==============================] - 0s 42us/step - loss: 0.2966 - acc: 0.0280
Epoch 89/100
143/143 [==============================] - 0s 38us/step - loss: 0.2966 - acc: 0.0280
Epoch 90/100
143/143 [==============================] - 0s 49us/step - loss: 0.2966 - acc: 0.0280
Epoch 91/100
143/143 [==============================] - 0s 38us/step - loss: 0.2966 - acc: 0.0280
Epoch 92/100
143/143 [==============================] - 0s 45us/step - loss: 0.2966 - acc: 0.0280
Epoch 93/100
143/143 [==============================] - 0s 38us/step - loss: 0.2966 - acc: 0.0280
Epoch 94/100
143/143 [==============================] - 0s 45us/step - loss: 0.2966 - acc: 0.0280
Epoch 95/100
143/143 [==============================] - 0s 42us/step - loss: 0.2966 - acc: 0.0280
Epoch 96/100
143/143 [==============================] - 0s 42us/step - loss: 0.2966 - acc: 0.0280
Epoch 97/100
143/143 [==============================] - 0s 42us/step - loss: 0.2966 - acc: 0.0280
Epoch 98/100
143/143 [==============================] - 0s 45us/step - loss: 0.2966 - acc: 0.0280
Epoch 99/100
143/143 [==============================] - 0s 42us/step - loss: 0.2966 - acc: 0.0280
Epoch 100/100
143/143 [==============================] - 0s 38us/step - loss: 0.2966 - acc: 0.0280

A: У вас неправильная функция активации на последнем слое. Softmax ограничен [0..1]
model.add(Dense(1, activation='softmax'))

заменить на
# После слоя не применяется функция активации
model.add(Dense(1))

Еще accuracy здесь бесполезна т.к. задача регрессии.
metrics=['accuracy']

A: Как уже сказал @L.Murashov функция активации softmax применяется в задачах мультиклассовой классификации - она помогает посчитать вероятности принадлежности образца каждому из классов.
Есть еще несколько моментов, на которые стоит обратить внимание:

*

*В обучающей выборке слишком много (около половины) нулевых значений - это вырожденный случай для теоремы Пифагора, когда одна из сторон треугольника имеет нулевую длину.

*Для того, чтобы лучше обучить модель можно выборку взять побольше - в вашем случае не проблема сгенерировать столько данных сколько нужно.

*Для данной (простой) задачи хватит одного скрытого слоя

*В качестве функции активации выходного слоя можно использовать linear

*В качестве функции потери и метрики можно выбрать mean_squared_error

Пример:
import numpy as np
from keras.models import Sequential
from keras.layers.core import Dense, Activation

N = 5000
np.random.seed(1234)
X = np.random.randint(0, 50, size=(N,2))
y = np.linalg.norm(X, axis=1)

NB_EPOCHS = 100
VERBOSE = 1

model = Sequential()
model.add(Dense(20, input_dim = 2, activation='relu'))
model.add(Dense(1, activation='linear'))
model.compile(loss='mse', optimizer='adam', metrics=['mean_squared_error'])
model.fit(X, y, epochs=NB_EPOCHS, verbose=VERBOSE)

Обучение:
...
5000/5000 [==============================] - 0s 22us/step - loss: 0.0057 - mean_squared_error: 0.0057
Epoch 98/100
5000/5000 [==============================] - 0s 22us/step - loss: 0.0048 - mean_squared_error: 0.0048
Epoch 99/100
5000/5000 [==============================] - 0s 22us/step - loss: 0.0045 - mean_squared_error: 0.0045
Epoch 100/100
5000/5000 [==============================] - 0s 22us/step - loss: 0.0043 - mean_squared_error: 0.0043
Out[70]: <keras.callbacks.History at 0xf2d9ac8>

Предсказание:
In [71]: model.predict(np.array([[3,4], [10,10], [5,6]]))
Out[71]:
array([[ 5.018393],
       [14.130004],
       [ 7.841759]], dtype=float32)


text:
Q: Memory requirements of an Object reference on a 64 bit JVM A reference to an Object on a 32 bit JVM (at least on Hotspot) takes up 4 bytes.
Does the 64 bit Hotspot JVM need 8 bytes? Or is some clever compression going on?
If not, every Object[] would require twice as much heap memory, which I somehow think (hope, expect) is not the case.
Update/extra question: Does this really matter, or is this a negligible increase, because most references point to objects that are much larger than a few bytes (whereas one might argue that those objects are in turn mostly comprised of references to other objects)?

A: According to Java Platform Performance it is not strictly defined, but typically 8 bytes on a 64-bit system:

The size of a reference isn't well defined, but it is typically 4 bytes on a 32-bit system and 8 bytes on a 64-bit system.

A: In a 64-bit system, object references are typically 8-byte long. But in recent JVMs from Sun/Oracle you can enable Compressed Oops, which reduce reference size to 4 bytes at the cost of a smaller limit on heap size.


text:
Q: A good way to separate client side templates from the main layout What is the best way to deal with multiple client side templates?
I noticed that if I keep them in my "mother" html file, it soon gets bloated with stuff, so I thought that maybe it would be better if I just put them in separate js files and load them one by one.
Another idea of mine was to avoid putting them separately as templates, but rather write them as strings and sort of couple them with the backbone.js views which are going to use them. I know that this would bring a lot of negative from designers, web developers, and software engineers in general, but for the projects I am working on, this seems like a very speedy way to develop because I have logic and layout at the same place. Plus, by reverse engineering, I proved that a bunch of prominent web services are doing the same so ...

A: One option is to use RequireJS, which includes a 'text' plugin for templates.
You can then use the r.js optimizer to combine all of these (plus JS modules, if you go that route) into a single file.
The optimizer can be run either as part of your build process, or in-process if you're using node.js.

A: You can have them in separate files, but combine into one file on a server side.
And take a lot of negative from me for your idea to keep templates in strings :). It might work until they are simple, but when they get more complex it gets badly, because html structure is not so obvious, so it is harder to write css and so on.

A: As @stusmith said, require.js is a good option.
also, take a look at the boilerplate's examples

*

*http://backboneboilerplate.com/

*https://github.com/thomasdavis/backboneboilerplate/blob/gh-pages/js/views/backbone/page.js
cheers


text:
Q: Htmlunit refreshing a page event I'm having a problem with this site: https://sistemas.tjes.jus.br/siep_consulta/faces/jsp/pesquisar_tramitacao_guias_por_pessoa_pub.jsp
I enter in site and i search by "Nome da Parte"(name of people)
: PAULO DA SILVA SANTOS
I click in "Pesquisar"(Search), but inside Htmlunit i have to download the archives.
I click in radio button and after i click in "gerar relatório do processo"(Generate process report).
When I do this only works when I refresh the page, but when I go to the next page and refresh the page it returns to the first page.
How do I solve this?
My code: `do {
        for (int i = 0; i < 10; i++) {

            ((HtmlRadioButtonInput) page.getByXPath("//*[@id=\"formulario:masterDetail1\"]/table[2]/tbody/tr/td/input").get(i)).setChecked(true);
            Page arch = ((HtmlAnchor) page.getFirstByXPath("//*[@id=\"formulario:masterDetail1\"]/table[1]/tbody/tr/td/table/tbody/tr/td[1]/a[2]")).click();

            IOUtils.copy(arch.getWebResponse().getContentAsStream(),
                    new FileOutputStream("D:\\testepdfs\\arq" + j + ".pdf"));
            page = (HtmlPage) page.refresh();
            j++;
        }

        page = ((HtmlAnchor) page.getFirstByXPath("//*[@id=\"formulario:masterDetail1-nb\"]/tbody/tr/td[7]/a")).click();
        System.err.println(page.asText());

    } while (hasNextPage(page));

`
Thank's! And sorry for my english.


text:
Q: Finding Key from Hashmap using Values(with space) Here i am trying to get key from value in Hashmap, but whenever i am trying "United Kingdom of Great Britain and Northern Ireland", it should return "GBR". It is showing me "No Records Found". How to solve this. Any help will be appreciated.
(Here if you will enter country code then it will return country name and if you will enter country NAME then it will return country CODE.)
public class AppliedWithCS_1 {

public static Object getKeyFromValue(HashMap hashMap, Object value) {
for (Object o : hashMap.keySet()) {
  if (hashMap.get(o).equals(value)) {
    return o;
  }
}
return null;
}

public static void main(String[] args) {

    HashMap hashMap=new HashMap<>();
    hashMap.put("AFG","Afghanistan");
    hashMap.put("GBR","United Kingdom of Great Britain and Northern Ireland");
    hashMap.put("IDN","Indonesia");
    hashMap.put("IND","India");
    System.err.println("Enter Country Code or Country Name=");
    Scanner scanner=new Scanner(System.in);
    String s1=scanner.next();
    if(s1.length()>3&&hashMap.containsValue(s1))
    {
        System.out.println(getKeyFromValue(hashMap,s1));
    }
    else if(hashMap.containsKey(s1))
        System.err.println(hashMap.get(s1));
    else
        System.err.println("No Records Found");
}
}

Output:
   Enter Country Code or Country Name=
   Afghanistan
   AFG

   Enter Country Code or Country Name=
   United Kingdom of Great Britain and Northern Ireland
   No Records Found

A: You have to use     String s1 = scanner.nextLine();, instead of  String s1 = scanner.next();
And it'll work and output  : GBR

Because next() (from the doc) will use by default, spaces as delimiter so it takes only the forst word
In your case after String s1 = scanner.next();, s1 was juste United


text:
Q: Parse XML subtitle and convert into .srt plain text I have an XML document as follow:
<document id="5509769">
  <s id="1">
    <time id="T1S" value="00:00:07,910" />
    <w alternative="Ciske" id="1.1">CISKE</w>
    <w id="1.2">Die</w>
    <w alternative="rot" id="1.3">ROT</w>
    <time id="T1E" value="00:00:10,910" />
  </s>
  <s id="2">
    <time id="T2S" value="00:00:12,320" />
    <w id="2.1">Almal</w>
    <w id="2.2">kan</w>
    <w id="2.3">maar</w>
    <w id="2.4">die</w>
    <w id="2.5">Cholera</w>
    <w id="2.6">kry</w>
    <w id="2.7">,</w>
    <time id="T2E" value="00:00:15,690" />
    <time id="T3S" value="00:00:15,750" />
    <w id="2.8">en</w>
    <w id="2.9">vir</w>
    <w id="2.10">my</w>
    <w id="2.11">part</w>
    <w id="2.12">kan</w>
    <w id="2.13">almal</w>
    <w id="2.14">doodgaan</w>
    <w id="2.15">.</w>
    <time id="T3E" value="00:00:18,890" />
  </s>
  <s id="3">
    <time id="T4S" value="00:00:18,960" />
    <w id="3.1">Ek</w>
    <w id="3.2">het</w>
    <w id="3.3">nie</w>
    <w id="3.4">lus</w>
    <w id="3.5">om</w>
    <w id="3.6">te</w>
    <w id="3.7">leer</w>
    <w id="3.8">nie</w>
    <w id="3.9">.</w>
    <time id="T4E" value="00:00:22,490" />
   </s>
</document>

And I would like to convert this into a .srt plain text file using Linq.
For exemple, the ouput for this XML node would be:
1
00:00:07,910 --> 00:00:10,910
CISKE Die ROT

2
00:00:12,320 --> 00:00:18,890
Almal kan maar die Cholera kry, en vir my part kan almal doodgaan.

3
00:00:18,960 --> 00:00:22,490
Ek het nie lus om te leer nie.

I have tried this:
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(XML);
using (var nodeReader = new XmlNodeReader(xmldoc))
{
   nodeReader.MoveToContent();
   XDocument xdoc = XDocument.Load(nodeReader);
   List<dynamic> elements =
   (
      from item in xdoc.Descendants("s")
      select new
      {
         Begin = (item.FirstNode as XElement).LastAttribute.Value,
         Last = (item.LastNode as XElement).LastAttribute.Value
      }
   ).ToList<dynamic>();
}

But I failed retrieving all w node values.

A: You can get all the w element values by getting all the w descendants from the parent item.
As the code below shows, the NodeValuesInArray is returned as an array of values which you can iterate through later.
Also, I've included a space separated version of the values (NodeValuesCommaSeparated) which can be used directly for display if that's more suitable.
using (var nodeReader = new XmlNodeReader(xmldoc))
{
    nodeReader.MoveToContent();
    XDocument xdoc = XDocument.Load(nodeReader);
    List<dynamic> elements =
    (
        from item in xdoc.Descendants("s")
        select new
        {
            Begin = (item.FirstNode as XElement).LastAttribute.Value,
            Last = (item.LastNode as XElement).LastAttribute.Value,
            NodeValuesInArray = item.Descendants("w").Select(q => q.Value).ToArray(),
            NodeValuesCommaSeparated = string.Join(" ", item.Descendants("w").Select(q => q.Value).ToArray())
        }
    ).ToList<dynamic>();
}


text:
Q: Five year old unopened boxed CPU – is the stock thermal compound still good? I have obtained an unopened, sealed, boxed CPU dating back to 2009. It's an Intel Core 2 Duo E8600 with heatsink + thermal compound pre-applied. Is the stock thermal compound still OK to use after five years on the shelf?

A: It should be, given that in the same amount of time, it could've been attached to a CPU and has to enure that as well.
If you don't trust it, just scrape it off and apply fresh coolingpaste (which is different than those strips. The paste can actually dry out.
Journeyman Geek points out that if its slightly hard it should be ok, if it crumbles like dried toothpaste, you need a fresh coat of the stuff.


text:
Q: What is the maximum likelihood estimate of the covariance of bivariate normal data when mean and variance are known? Suppose we have a random sample from a bivariate normal distribution which has zeroes as means and ones as variances, so the only unknown parameter is the covariance. What is the MLE of the covariance? I know it should be something like $\frac{1}{n} \sum_{j=1}^{n}x_j y_j$ but how do we know this?

A: Under the stated conditions ($\mu_X = \mu_Y = 0$ and $\sigma_X = \sigma_Y = 1$), the likelihood function for a random sample of size $n$ is $$L(\rho\; |\; X, Y) = \frac{1}{(2\pi[1-\rho^2])^{n/2}}\exp \left[-\frac{1}{2(1-\rho^2)}(X'X - 2\rho X'Y + Y'Y)\right].$$
Now find the log-likelihood and take the derivative with respect to $\rho$. Next, set it equal to 0, solving for $\hat{\rho}$.  You should of course do some appropriate test to show what you've found is in fact a global maximum.

A: The estimator for the correlation coefficient (which in the case of a bivariate standard normal equals the covariance)
$$\tilde r = \frac 1n\sum_{i=1}^nx_iy_i$$
is the Method-of-Moments estimator, the sample covariance. Let's see if it coincides with the maximum likelihood estimator, $\hat  \rho$.
The joint density of a bivariate standard normal with correlation coefficient $\rho$  is
$$f(x,y) = \frac{1}{2 \pi   \sqrt{1-\rho^2}}
      \exp\left\{-\frac{x^2 +y^2 -2\rho xy}{2(1-\rho^2)}\right\} $$
and so the log-likelihood of an i.i.d. sample of size $n$ is
$$\ln L = -n\ln(2\pi) -\frac n2\ln(1-\rho^2) - \frac 1{2(1-\rho^2)}\sum_{i=1}^n(x_i^2 +y_i^2 -2\rho x_iy_i)$$
(here the i.i.d assumption is with respect to each draw from the two-dimensional population of course)
Taking the derivative with respect to $\rho$ and setting it equal to zero gives a 3d-degree polynomial in $\rho$:
$$\hat \rho: n\hat \rho^3 -\left(\sum_{i=1}^nx_iy_i\right)\hat\rho^2 -\left(1- \frac 1n\sum_{i=1}^n(x_i^2 +y_i^2) \right)n\hat \rho - \sum_{i=1}^nx_iy_i =0 $$
That the calculations are correct can be verified if one takes the expected value of the derivative evaluated at the true coefficient $\rho$ -it will equal zero.
For compactness, write $(1/n)\sum_{i=1}^n(x_i^2 +y_i^2) =  (1/n)S_2$, which is the sum of the sample variances of $X$ and $Y$. If we divide the 1st-derivative expression by $n$ the MoM estimator will appear, specificaly
$$\hat \rho: \hat \rho^3 -\tilde r \hat \rho^2 + \big[(1/n)S_2-1\big]\hat \rho -\tilde r=0$$
$$\Rightarrow \hat \rho\Big(\hat \rho^2 -\tilde r \hat \rho + \big[(1/n)S_2-1\big] \Big) = \tilde r$$
Doing the algebra, it is not difficult to conclude that we will obtain $\hat \rho = \tilde r$ if,and only if, $(1/n)S_2 =2$, i.e. only if it so happens that the sum of sample variances equals the sum of true variances.
So in general
$$\hat \rho \neq \tilde r$$
So what happens here? Somebody wiser will explain it, for the moment, let's try
a simulation: I generated an i.i.d. sample of two standard normals with correlation coefficient $\rho=0.6$. The sample size was $n=1.000$. The sample values were
$$\sum_{i=1}^nx_iy_i = 522.05,\;\;S_2 = 1913.28$$
The Method-of-Moments estimator gives us
$$\tilde r = \frac {522.05}{1000} = 0.522$$
What happens with the log-likelihood? Visually, we have

Numerically, we have
\begin{array}{| r | r | r |}
  \hline
\hline
  ρ&\text{1st deriv}&\text{lnL}\\
  \hline
0.5&-70.92&-783.65\\
0.51&-59.41&-782.47\\
0.52&-47.7&-781.48\\
0.53&-35.78&-780.68\\
0.54&-23.64&-780.1\\
0.55&-11.29&-779.75\\
0.56&1.29&-779.64\\
0.57&14.1&-779.81\\
0.58&27.15&-780.27\\
0.59&40.44&-781.05\\
0.6&53.98&-782.18\\
  \hline
\end{array}
and we see that the log-likelihood has a maximum a tad before $\rho=0.56$ where also the 1st derivative becomes zero $(\hat \rho = 0.558985)$. No surprises for the values of $\rho$ not shown. Also, the 1st derivative has no other root.
So this simulation accords with the result that the maximum likelihood estimator does not equal the method of moments estimator (which is the sample covariance between the two r.v.'s).
But it appears that "everybody" is saying that it should... so somebody should come up with an explanation.
UPDATE
A reference that proves that the MLE is the Method-of-Moments estimator: Anderson, T. W., & Olkin, I. (1985). Maximum-likelihood estimation of the parameters of a multivariate normal distribution. Linear algebra and its applications, 70, 147-171.
Does it matter that here all means and variances are free to vary and not fixed?
... Probably yes, because @guy's comment in another (now deleted) answer says that, with given mean and variance parameters, the bivariate normal becomes a member of the curved exponential family (and so some results and properties change)... which appears to be the only way that can reconcile the two results.


text:
Q: Continuous movement when a key is held down Is it possible in jQuery to have an element continuously move when the key is held down?
I've tried a few ways but they always have a break in between animation calls. The code I currently have:
$(document).keydown(function (e) {
    if (e.which == 37) {
        $('#you').stop().animate({
            left: '-=16px'
        }, 10);
    }
});
$(document).keyup(function (e) {
    $('#you').stop();
});

A: .animate() isn't always the best way.
// cache jQuery objects for performance
var you = $( "#you" )
, doc = $( document )

// variable to hold motion state
, activeMotion

// goDown motion, adjust numbers to taste
, goDown = function(){
   you.css( "left" , you.css( "left" ) - 16 );
   if ( activeMotion === goDown ) {
      setTimeout( goDown , 10 );
   }
}

doc.keydown( function( e ) {
   if ( e.which === 37 && activeMotion !== goDown ) {
      activeMotion = goDown;
      goDown();
   }
   // all directions can go here in seperate if/else statements
   // be sure to include "activeMotion !== goDown" else every time
   // keydown event fires, it will start a new goDown loop.
} );

doc.keyup( function () {
   // simply ends any motion that checked activeMotion
   activeMotion = null;
} );

A: Instead of animating the element, rather just move it by some amount of pixels. 16 will probably be too much because it will go too fast.

A: I think you are seeing the break between animation calls because of your timing.
If you look at your operating systems keyboard repeat time interval, it should be around 35 milliseconds - test it here.
On top of that you are animating every 10ms, not counting the time it takes to run all the animation functions, etc. So why not simplify the animation and not worry about time intervals (try this demo):
var block = $('.block'),
    leftPos;
$(document).keydown(function (e) {
    leftPos = block.position().left;
    leftPos += (e.which == 37) ? -5 : 0;
    leftPos += (e.which == 39) ? 5 : 0;
    block.css('left', leftPos);
});


text:
Q: Creating and updating entities with a many to many relationship In an ASP.NET core (dotnet 6) web application, we have a small user management functionality in which a user can be assigned to a specific site (physical location) with certain rights. A user can be assigned to one or more sites and a site can also be assigned to one or more users, thus the many to many relationship. We have the following classes:
public class User
{
    public int ID { get; set; }
    public string SamAccountName { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int GroupID { get; set; }
    public bool IsEnabled { get; set; }
    public ICollection<UserSite> UserSites { get; set; }
}

public class Site
{
    public int ID { get; set; }
    public string Name { get; set; }
    public string Code { get; set; }
    public ICollection<UserSite> UserSites { get; set; }
}

The many to many relationship is described in a join table with fluent API:
public class UserSite
{
    public int UserID { get; set; }
    public User User { get; set; }
    public int SiteID { get; set; }
    public Site Site { get; set; }
}

// Fluent API for UserSite table
builder.HasKey(us => new { us.UserID, us.SiteID });

builder.HasOne(us => us.User)
       .WithMany(us => us.UserSites)
       .HasForeignKey(us => us.UserID)
       .OnDelete(DeleteBehavior.Cascade);

builder.HasOne(us => us.Site)
       .WithMany(us => us.UserSites)
       .HasForeignKey(us => us.SiteID)
       .OnDelete(DeleteBehavior.Cascade);

These classes result in the following DTO's:
public class UserDTO
{
    public int ID { get; set; }
    public string SamAccountName { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int GroupID { get; set; }
    public bool IsEnabled { get; set; }
    public IList<SiteDTO> Sites { get; set; }
}

public class SiteDTO
{
    public int ID { get; set; }
    public string Name { get; set; }
    public string Code { get; set; }
}

What we want to know is, what is the best way to create a new user or update an existing user? Just to clarify, the data in the Sites table exists already and is static. What I mean by that is that when creating a new user or updating an existing one, a user can be assigned to one or more existing sites, but no new site is created in the process.
We already tried some things that did work but we are not sure if this is really the best way to this or if there is a far better way to do it. Here is what we tried:
The create method
// Create method
public IActionResult CreateUser(UserDTO userDTO)
{
    if (ModelState.IsValid)
    {
        User user = _mapper.Map<User>(userDTO);
        user.IsEnabled = true;
        AttachSitesToUser(user.ID, user.UserSites);
        _context.Users.Add(user);
        _context.SaveChanges();
        userViewModel = _mapper.Map<UserViewModel>(user);
    }
    return new JsonResult(new[] { userDTO });
}

The update method:
// Update method
public IActionResult UpdateUser(UserDTO userDTO)
{
    if (ModelState.IsValid)
    {
        User user = _context.Users
                            .Include(u => u.Sites)
                            .ThenInclude(s => s.Site)
                            .Single(u => u.ID == userDTO.ID);
        _mapper.Map(userViewModel, user);
        AttachSitesToUser(user.ID, user.UserSites);
        _context.Entry(user).State = EntityState.Modified;
        _context.SaveChanges();
    }
    return new JsonResult(new[] { userDTO });
}

The helper method AttachSitesToUser:
// Helper method that adds the user ID and attaches the site(s) to the context
private void AttachSitesToUser(int userID, IEnumerable<UserSite> userSites)
{
    foreach (UserSite userSite in userSites)
    {
        userSite.UserID = userID;

        if (Context.Entry<Site>(userSite.Site).State == EntityState.Detached)
        {
            Context.Sites.Attach(userSite.Site);
            Context.Entry<Site>(userSite.Site).State = EntityState.Unchanged;
        }
    }
}

As you can see, for the moment we have to loop through the UserSites list in the User entity and attach the sites the user was assigned to manually to the context. Is there no better way to do this or is this the official best practice?


text:
Q: How to calculate running total and reset when value change with Python? I want to calculate running total of Promo, and reset running total when Promo changes. How can I achieve this with Python and Pandas?
Thanks very much!
    Id        Date  Promo  Running_Total
0   19  2015-07-09      0              0
1   18  2015-07-10      0              0
2   17  2015-07-11      0              0
3   16  2015-07-13      1              1
4   15  2015-07-14      1              2
5   14  2015-07-15      1              3
6   13  2015-07-16      1              4
7   12  2015-07-17      1              5
8   11  2015-07-18      0              0
9   10  2015-07-20      0              0
10   9  2015-07-21      0              0
11   8  2015-07-22      0              0
12   7  2015-07-23      0              0
13   6  2015-07-24      0              0
14   5  2015-07-25      0              0
15   4  2015-07-27      1              1
16   3  2015-07-28      1              2
17   2  2015-07-29      1              3
18   1  2015-07-30      1              4
19   0  2015-07-31      1              5

A: Completely changed solution(s):
Values of column Promo was changed with 2 and 3.
For count consecutives all values use compare by ne (!=) by shifted column with cumsum for groups.
Then use groupby by this groups and count by cumcount and add 1 for count from 1:
df['Running_Total'] = (df.groupby(df['Promo'].ne(df['Promo'].shift()).cumsum())
                          .cumcount()
                          .add(1))
print (df)
    Id        Date  Promo  Running_Total
0   19  2015-07-09      0              1
1   18  2015-07-10      0              2
2   17  2015-07-11      0              3
3   16  2015-07-13      2              1
4   15  2015-07-14      2              2
5   14  2015-07-15      2              3
6   13  2015-07-16      1              1
7   12  2015-07-17      1              2
8   11  2015-07-18      0              1
9   10  2015-07-20      0              2
10   9  2015-07-21      0              3
11   8  2015-07-22      0              4
12   7  2015-07-23      3              1
13   6  2015-07-24      3              2
14   5  2015-07-25      3              3
15   4  2015-07-27      1              1
16   3  2015-07-28      1              2
17   2  2015-07-29      1              3
18   1  2015-07-30      1              4
19   0  2015-07-31      1              5

But if need replace rows with 0 in Promo column multiple column by boolean mask - comparing df['Promo'].ne(0) - it multiple by 0 all 0 rows and all another by 1:
df['Running_Total'] = df.groupby(df['Promo'].ne(df['Promo'].shift()).cumsum())
                        .cumcount()
                        .add(1)
                        .mul(df['Promo'].ne(0))
  print (df)

0   19  2015-07-09      0              0
1   18  2015-07-10      0              0
2   17  2015-07-11      0              0
3   16  2015-07-13      2              1
4   15  2015-07-14      2              2
5   14  2015-07-15      2              3
6   13  2015-07-16      1              1
7   12  2015-07-17      1              2
8   11  2015-07-18      0              0
9   10  2015-07-20      0              0
10   9  2015-07-21      0              0
11   8  2015-07-22      0              0
12   7  2015-07-23      3              1
13   6  2015-07-24      3              2
14   5  2015-07-25      3              3
15   4  2015-07-27      1              1
16   3  2015-07-28      1              2
17   2  2015-07-29      1              3
18   1  2015-07-30      1              4
19   0  2015-07-31      1              5

Detail:
print (df['Promo'].ne(df['Promo'].shift()).cumsum())
0     1
1     1
2     1
3     2
4     2
5     2
6     3
7     3
8     4
9     4
10    4
11    4
12    5
13    5
14    5
15    6
16    6
17    6
18    6
19    6
Name: Promo, dtype: int32


text:
Q: Constructing a zero magnetic field in the center of a loop using Biot-Savart An infinitely long wire is oriented like the drawing below.

The wire with a given current I follows the path of 2 tangent lines to the circle of radius $R$ and an arc around the corner $\theta$.
$\theta$ needs to be calculated so that the magnetic field at the centre of the circle is 0.
I already know that the Biot-Savart law has to be used and that two tangents to the circle have to be constructed so that the magnetic field becomes $0$, but I have a bit trouble constructing the integral for this problem.
$$B=\int dB=\int\frac{\mu_0I \sin(\theta)}{4\pi r^2}dl =\int\frac{\mu_0I \vec{dl}\times \hat r}{4\pi r^2}dl $$
But I have no idea how to construct the dimensions for this problem. I tried to simplify the problem using trigonometry, but it's seemed way too difficult. What can I do?

A: I solved this problem. No answers needed. The answer was 2 radians btw.


text:
Q: How to express universal quantifier in the body of a datalog rule? I want to use universal quantifier in the body of a predicate rule, i.e., something like

A(x,y) <- ∀B(x,a), C(y,a).

It means that only if for each a from C(y, a), B(x,a) always has x to match (x,a), then A(x,y) is true.
Since in Datalog, every variable bounded in rule body is existential quantifier by default, the a would be an existential quantifier too. What should I do to express universal quantifier in the body of a predicate rule?
Thank you.
P.S. The Datalog engine I am using is logicblox.

A: The basic idea is to use the logical axiom
∀x φ(x) ⇔ ¬∃x ¬φ(x)
to put your rules in a form where only existential quantifiers are required (along with negation).  Intuitively, this usually means computing the complement of your answer first, and then computing its complement to produce the final answer.
For example, suppose you are given a graph G(V,E) and you want to find the vertices which are adjacent to all others in the graph.  If universal quantification were allowed in a Datalog rule body, you might write something like
Q(x) <- ∀y E(x,y).

To write this without the universal quantifier, you first compute the vertices which are not adjacent to all others
NQ(x) <- V(x), V(y), !E(x,y).

then return its complement as the answer
Q(x) <- V(x), !NQ(x).

The same kind of trick can be used in SQL, which also lacks universal quantifiers.


text:
Q: Why is there a java.lang.NullPointerException when referencing Image from a different class? I am creating a clone of Breakout for PC, earlier tonight I found that there was a NullPointerException being thrown and shown in the console. Oddly, the method run() is told to catch any exceptions that occour and show their stacktrace and then ignore them, but this time it freezes the game at the start, int the log, the keypresses are still tracked, but nothing happens in-game. Obviously, the game didn't abort, but will not repaint.
It seems to be coming from one line of code:
 if (by >= bricks[0].y && by <= bricks[0].y + bricks[0].img.getHeight(null) && bx >= bricks[0].x && bx <= bricks[0].x + bricks[0].img.getWidth(null)) {

Here is the log and stacktrace (the entire thing):
Game starting, menu boot.
Menu Loaded, JFrame visible.
Running thread.
Play clicked, start game initialization.
Creating JFrame.
JFrame created and visible.
Starting game thread
Initialize user variables.
Initialized user variables.
Initialization complete, start game.
java.lang.Execption in line 86/87, class Game. Stacktrace:
java.lang.NullPointerException
    at Game.move(Game.java:195)
    at Game.run(Game.java:86)
    at java.lang.Thread.run(Thread.java:722)
Space hit!
Key ARROWLEFT hit.
Key ARROWLEFT hit.
Key ARROWLEFT hit.
Key ARROWLEFT hit.
Key ARROWLEFT hit.
Key ARROWLEFT hit.
Key ARROWLEFT hit.
Key ARROWLEFT released.
Key ESCAPE Hit!

I hope this problem can be solved.

A: Lets look at that "line":
   if (by >= bricks[0].y &&
       by <= bricks[0].y + bricks[0].img.getHeight(null) &&
       bx >= bricks[0].x &&
       bx <= bricks[0].x + bricks[0].img.getWidth(null)) {

Assuming that bx, by, and the x and y fields are all primitive types (e.g. int), then here's a list of things that could result in an NPE:

*

*the bricks variable is null

*the zeroth element of bricks is null

*the value of bricks[0].img is null
If bx, by, x and/or y is a wrapper type, then one of those could be null.  That would lead to an NPE when unboxing the value.
It is not caused by passing null to the getHeight or getWidth methods, because 1) I believe that is valid and 2) if it wasn't then the NPE would be thrown in a different place to what you stacktrace shows.
(I can't tell if passing null in those calls is correct ... but either way, it is not the cause of this NPE based on the evidence you have provided.)

If you want to figure what is actually causing the problem, debug the code or add some traceprints to test which of the things that could be null is actually null.

A: This answer is assuming that your brick[0].img is of the type java.awt.Image.  You are setting the ImageObserver to null in both the getHeight and the getWidth methods.  If you actually want the image displayed somewhere you need to put that thing as the ImageObserver.
http://docs.oracle.com/javase/7/docs/api/java/awt/image/ImageObserver.html
The Button, Panel or the place you are trying to place the image should probably be passed in to the getWidth and the getHeight methods, because it most likely implements the ImageObserver Interface.


text:
Q: Homology of lens spaces using Morse theory? To test Morse theory, one day I tried to compute the homology of Lens spaces.  You can build a lens space out of $S^3 = \{ |z|^2 + |w|^2 = 1: z, w \in \mathbb{C} \}$ using the quotient by $z \mapsto e^{2\pi i /p}z, w \mapsto e^{2\pi i q/p}w$.  The quotient by this action L(p,q) is a lens space.
With Morse theory estimates the Betti numbers of a manifold by counting the critical points of a specified index.  For any real-valued function $f: L(p,q) \to \mathbb{R}$, we look for critical points where $\nabla f(p_0) = 0$.  Expanding around p0 $f(p) = f(p_0) + (p - p_0)^T A (p - p_0) + O(|p - p_0|^2)$ for some matrix $A$, the Hessian.  If the eigenvalues of A are all real and nonzero and the critical values of f are all different then $f$ is called "Morse".  The Morse theory says L(p,q) is homotopic to a CW-complex with a cell complex of dimension k for each critical point of index k.
The Morse function I chose is $h = r \cos p\theta$ where $r,\theta$ come from $z = r e^{i \theta}$.  Also let $w = \rho e^{i \phi}$.  This function is well-defined on the lens space L(p,q) and its critical points are (+/-1,0,0,0) and its images under the deck transformation.  To see this, notice the gradient in this coordinate system is $$\nabla =  \left( \frac{\partial }{\partial r}, \frac{1}{r}\frac{\partial }{\partial \theta},, \frac{\partial }{\partial \rho}, \frac{1}{\rho} \frac{\partial }{\partial \phi}\right) $$ and you look for points where the gradient is normal to S3.  However, $H_1[L(p,q)]= \mathbb{Z}/p$ suggesting we should have a saddle point of index 1.
I am told that Morse theory only gives you the singular $\mathbb{R}$ homology.  Did I find all the critical points correctly? Is there a way to get the $\mathbb{Z}$ homology using Morse homology or other piece of differential topology?

A: I tried a computation, I hope it's correct. I considered the map h = Re $z^p$ + Re $w^p$ on the sphere, and I found four sets of critical points: (1) ($\mu_{1}^{+} / \sqrt{2}$, $\mu_{2}^{+} / \sqrt{2}$), (2) ($\mu_{1}^{-}/ \sqrt{2}$, $\mu_{2}^{-} / \sqrt{2}$), (3) ($\mu_{1}^{+}$, 0) and (0, $\mu_{2}^{+}$), (4) ($\mu_{1}^{-}$, 0) and (0, $\mu_{2}^{-}$), where $\mu_{j}^+$ denotes a p-root of 1 and $\mu_{j}^-$ denotes a p-root of -1.
The first set gives maxima (where h = 2), the second set gives minima (h=-2) and the other two give index 1 and 2 points (I think). The first and second set contribute to p points in the lens space, the other two contribute 2 points each. Perhaps doing Morse homology as Pietro suggested counting connecting flow lines gives you the correct result.... but I have not tried.

A: Is there a way to get the $\mathbb{Z  }$ homology via Morse Homology? Sure, indeed, historically, the underlying ideas and constructions by means of flow lines were one of the first attempt to build concretely the homology of a manifold. Actually, it seems to me that this construction was a little abandoned for a while, especially by functional analysts, because the alternative Morse theory by means of sublevel sets, popularized e.g. by Richard Palais in the '60, was somehow simpler, as it did not use transversality arguments. Then the Morse complex and homology construction became suddenly in fashion again after Andreas Floer's work, in which it became a spectacular tool to build new invariants aimed to prove the Arnold conjecture.
In any case, yes, you can certainly perform the Morse complex construction with $\mathbb{Z}$ coefficients for a $C^2$ functional $f$, even on a possibly infinite dimensional Hilbert manifold $M$, and prove that the resulting homology is isomorphic to the singular, provided the functional enjoys a list of properties (some of them are given for free in the case of compact manifolds).
Specifically, it should be bounded from below; have nondegenerate critical points (i.e., with invertible Hessian operator) with finite Morse indices; it should have complete sublevel sets, and lastly, it should satisfy the Palais-Smale compactness condition (PS). Up to a $C^{\infty}$-small perturbation of the metric, as an application of the Sard-Smale theorem, you may even assume that the negative gradient flow of $f$ has the property that for any pair of critical points $x$ and $y$, whose Morse indices $m(x)$ and $m(y)$ differ at most by 2 (that's a technical detail), the unstable manifold $W^u(x)$ of $x$ and the stable manifold $W^s(y)$ of $y$ meet transversally.
As a consequence, these intersections are flow-invariant, embedded submanifolds of dimension equal to $m(x)$ - $m(y)$ (thus empty if $m(x)$ $\leq$ $ m(y)$). And orientable in a canonical way, starting from arbitrarily choosen orientations of all unstable manifolds of critical points (the unstable manifold of a critical point is an embedded submanifold diffeomorphic with its tangent space, whose dimension coincides with the Morse index of the critical point). Note: these intersections are in any case orientable, even if $M$ is not. Moreover, if $m(x)-m(y)\leq1$, they meet any regular level set of $f$ in a compact set (thus finite).
As you probably know, this allows to define $C_k(f)$ as the free abelian group generated by the (possibly infinite) set $\mathrm{crit}_k(f)$ of all critical points of index $k$; moreover a boundary operator $$\partial:C_k(f)\to C_{k-1}(f)$$
is well-defined by linear extension starting from the generators $\mathrm{crit}_k(f)$. It just sends $x\in \mathrm{crit}_k(f)$ to a certain algebraic sum of the endpoints $y$ of all flow lines emanating from $x$ at time $-\infty$, and converging to critical points $y$ of index $m(x)-1$ at time $+\infty$. The mentioned compactness property ensures that there are finitely many of these flow lines; and the sign in front of any $y$ in the sum is chosen to be + or - according whether the orientation of $W^u(x)\cap W^s(y)$ coincides or not with the one induced by the gradient flow. Then one proves that this way one has really defined a true boundary, that is, the relation $\partial^2=0$ hold. Finally, one proves that the corresponding complex produces the singular homology. And this is the  Morse homology with $\mathbb{Z}$ coefficients. (it is not completely clear to me whether your query was on the general side, or particularly aimed to your specific function. I hope recalling the general facts may be in any case of some aid.)
Warning. Actually this is one of the way pepole tell the story; it involves not too many technicalities  (if you do it well), but everything looks like a kind of magic. In fact, the whole story should start by a cellular decomposition induced by the functional; this puts the isomorphism of the homologies into a more general and natural fact about cellular homologies (if you want to understand Morse homology, read chapter 5 of Albrecht Dold's Lectures on Algebraic Topology, on cellular spaces and cellular complexes); and then the nice picture of the Morse complex with points and lines becomes rather a representation (of the cellular complex) than a smart construction, which is even closer to the historical developement of these ideas by giants like Morse, Bott, Thom, Smale.


text:
Q: How to add relation correctly to neo4j (cypher)? I tried add relation to neo4j and it doesn't work correctly... (this relations don't exist after executing script)...
my script (i run it in this way: Neo4jShell.bat -file gf.txt) :
 CREATE (j1 { lc :1, ln: 'ln1' });
 CREATE (j2 { lc :2, ln: 'ln2' });
 CREATE (j3 { lc :3, ln: 'ln3' });
 ...
 CREATE (p1 { pc : 1, pn : 'pn1'});
 CREATE (p1 { pc : 2, pn : 'pn2'});
 CREATE (p1 { pc : 3, pn : 'pn3'});
 ...
 CREATE (j1)-[:F]->(p1);
 CREATE (j2)-[:F]->(p2);
 CREATE (j3)-[:F]->(p3);

Are you seeing any mistakes in my big script ?

A: Once you end your statement with a semicolon, you can't refer to the identifiers/nodes created in that statement anymore. It's not going to know what (j1) is, so it's going to create a new node (j1) with no properties.
Update:
Either remove your semicolons, or you'll need to MATCH the nodes again.


text:
Q: write() in sys/uio.h returns -1 I'm using
Ubuntu Server 9.10
AMD Phenom 2 cpu
g++ (Ubuntu 4.4.1-4ubuntu9) 4.4.1
trying to run the application pftp-shit v 1.11, which runs successfully until the remote file list is going to be saved (into .pftp//pftpfxp--).
The following code in tcp.cc is executed successfully:
int outfile_fd = open(name, O_CREAT | O_TRUNC | O_RDWR | O_BINARY)

which returns a file descriptor int (in my case 6) - name is a char array containing a valid path to my file which successfully i created.
and successfully running:
fchmod(outfile_fd, S_IRUSR | S_IWUSR);

and
access(name, W_OK)

The issue occurs during running the function (from sys/uio.h)
write(outfile_fd, this->control_buffer, read_length)

which returns -1. -1 is of returned if nothing was written and otherwise a non-negative integer is returned which is equal to the number of bytes written.
Anyone having a clue how I can get the write function to work?

A:
On error, -1 is returned, and errno is set appropriately.

Perhaps errno could give you some hints about what's wrong.
write(outfile_fd, this->control_buffer, read_length);

Does read_length contain correct number of bytes to be written?

A: Are the directory and file definitely writable by the user attempting the write? Maybe try running it in /tmp just as a test.


text:
Q: What is the meaning of Common Support here I am reading a notes in statistical inference, and I am constantly being confused about the term 'common support', i hardly find any definition of this,here is an example,
'Suppose S is a space of all probability distributions with common support'
and the picture below is what I am reading, and it says ' here pdf of a family $\Bbb P$ of distributions must be of the commmon support of $\Bbb P $ '$(\Bbb P := \{P_\theta,\theta \in \Omega \})$

A: The support of a Borel measure on $\mathbb R^n$, say, is defined as the set of points $x$ such that, for every $r\gt0$, $\mu(B(x,r))\gt0$. In your context, one considers a family $\{P_\theta;\theta\in\Theta\}$ and one asks that the support of $P_\theta$ does not depend on $\theta$.

A: In general, it means the set of all points where at least one density function is non-zero.  For example, if you have two uniform random variables, where one ranges from 0 to 1, and one ranges from 1 to 2, then the common support is 0 to 2.  (Sometimes "common support" means the topological closure of this set, but this probably doesn't matter for you.)
The "common support" assumption is important here because you can truncate an exponential family of random variables, to get a new exponential family of random variables.  For example, if you take the normal distribution (as a family with two parameters — the mean and variance) and force it to be between -3 and 5, what you get is no longer normally distributed, but it still forms an exponential family.  The common support is then [-3, 5].
Some exponential families are only defined on subsets of the reals, rather than the whole real line.  For example the family
$$
e^{-cx^3}
$$
(where $c$ is the parameter) is only defined for $x \geq 0$.  The common support in this instance is $[0, \infty)$.


text:
Q: Digital logic, K Map- Essential Prime Implicants
I have solved  the above problem in two ways.And both the times I have a unique solution with the same number of gates.
According to my understanding of Essential Prime Implicants, This particular case does not contain any essential prime implicants, as two ways of solution is possible.Is my interpretation correct?
But is it possible to have a solution without EPI's?
Help is greatly appreciated.

A: Yes you are correct that this is an example where there are no essential prime implicants. But your first diagram is slightly incorrect, because your $Q'S'$ implicant should be 'circled' to indicate that it is joined at the top and bottom.
Another example with no essential prime implicants is $P'Q'R' + P'QS + PQR + PQ'S'$, which is equivalent to $P'R'S + QRS + PRS' + Q'R'S'$.


text:
Q: Rspec controllertest: collection object is empty I'm working on a Course application made of chapters. Each chapter has a quiz with questions and answers.
Each question can only have one correct answer. I want to test this rule with RSpec.
In my Answers controller test I wrote a test:
  it "does not create a new correct answer when there is already a correct answer" do
        answer2 = Answer.create(title: "correct answer", is_correct: true, question_id: @question.id)
        @question.answers << answer2
        post :create, question_id: @question.id, answer: { title: "new answer", is_correct: true }
        expect(Answer.count).to eq(1)

In this test, I want to make sure that no new answer is created when the question.answers collection already has an answer with the is_correct property set to true.
However, my test is failing. When I check the code in the create action of my answers controller and check that question has at least one answer in it's question.answers collection, it seems that:
question

returns an empty array
=> []

Why is the question.answers collection empty, when in the test I added an answer to the question's answers collection?
@question.answers << answer2

A: I can't answer for sure, but I can provide suggestions to find the actual problem.
There are two things you should try to isolate it, here :

*

*make sure @question from your test and the one in your action are indeed the same (you can check its #id, or even its #object_id)

*in tests (and indeed, everywhere you do not check validation status then), you should use #create! rather than #create, so that failing to create the record will trigger an obvious exception.


text:
Q: Finding the State Table for a Synchronous Sequential Circuit I'm learning about circuits in my ECE class and want to make sure that I have the correct table. I am working with D flip-flops and T flip-flops in this circuit. I want to make sure that I have the right table and, if I don't, what I did wrong here.
Thanks!
By the way, my answer is only the table. The stuff above and below it are for different problems.

A:
Hi, There are a few bugs, marked on the drawing in color. Think green :)


text:
Q: Is it recommended to change RDS instance type regularly to scale down at night? I got an app that is heavily used during the daytime and almost not used at night and on sundays.
RDS MySQL costs are quite high and I am wondering if I can not just downscale at night and upscale in the morning by changing instance type from m5.4xlarge to m5.large and back.
I dont want to fully turn it of since we got some crons running at night and also some users might want to access the system out of business hours but usually the DB just runs around 2% CPU around those hours.
The only recommendations I found about this kind of usage is to turn off instances which I would like to avoid. I manually changed instance type in the last days and to me it seems it should be no problem to automate this. The downtime of aprox. 2min for the instance change is completely acceptable for me and I could schedule this for times where usage is already low.
This question is not about how this is technically possible but if it is generally recommended or if there is any downside I didnt think if yet.
I am really wondering why I didnt find anything about this since it seems quite a common usecase for any business app that is used only in one timezone.
I did that manually and seems to work fine. I searched the internet for hours about this but didnt find anything useful pro or contra.

A: It's not something that people typically do. Amazon Aurora Serverless would be a much better way to handle this.
Aurora Serverless v2 is an on-demand, autoscaling configuration for Amazon Aurora. Aurora Serverless v2 helps to automate the processes of monitoring the workload and adjusting the capacity for your databases. Capacity is adjusted automatically based on application demand. You're charged only for the resources that your DB clusters consume. Thus, Aurora Serverless v2 can help you to stay within budget and avoid paying for computer resources that you don't use.
With the added benefit that Aurora can deliver up to five times the throughput of MySQL.
https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/aurora-serverless-v2.html#aurora-serverless-v2.advantages


text:
Q: JDB(The Java Debugger) Command not accepting spaces in classpath option I am debugging my code from JDB(Java Debugger). My Code uses the external jar files which I have kept in a separate folder.
If the path of external java files contains spaces then JDB gives the error.

If path does not contains any spaces the program executes successfully.

My Path when the error occurs : C:\Users\raunak.choraria\Desktop\External Jars
My Path in case of successful execution : C:\Users\raunak.choraria\Desktop\ExternalJars
As per my understanding, from the point space character occurs it assumes it as class name and searches for the main class.


text:
Q: TortoiseHG: undoing Guess Rename --> Accept Match I'm using TortoiseHG and am trying to handle a renamed file. Unfortunately, I accidentally clicked Accept Match for one of the files and want to undo it. How do I do so without hurting the files I'm trying to commit?

A: In the commit dialog you can right-click on the added file, and select forget. Then the file is no longer marked as copy. When you want the file in the commit, you can add this file again.

A: I'm not sure what's different but for me, there is no "forget" option in this situation.
What worked for me is choosing "revert" on the added file (the one marked as 'A'). This removes the rename, but also restores the original file. (If you renamed asdf.txt to fdsa.txt you will now have two files with those names.)
You then have to manually delete the restored file, and you should be back where you started. Note that I find it's safer to delete files with Windows file explorer, since they will end up in the recycle bin. Files deleted from thg are deleted permanently.


text:
Q: I want plot1 appear on tab1 and plot2 appear on tab2 I have a static shinydashboard that has two tabs. Currently, plot1 and plot2 appear on both tab1 and tab2.
I want plot1 to only appear on tab1. I want plot2 to only appear on tab2.
Please let me know if you need more information.
First plot data:
structure(list(gender = structure(c(1L, 2L, 1L, 2L, 1L, 2L), .Label = c("female",
"male"), class = "factor"), subject = structure(c(1L, 1L, 2L,
2L, 3L, 3L), .Label = c("math", "reading", "writing"), class = "factor"),
    avg_score = c(63.6332046332046, 68.7282157676349, 72.6081081081081,
    65.4730290456432, 72.4671814671815, 63.3112033195021)), class = "data.frame", row.names = c(NA,
-6L))

Second plot data:
structure(list(race_ethnicity = structure(c(1L, 2L, 3L, 4L, 5L,
1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L), .Label = c("1", "2",
"3", "4", "5"), class = "factor"), subject = structure(c(1L,
1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L), .Label = c("math",
"reading", "writing"), class = "factor"), avg_score = c(61.6292134831461,
63.4526315789474, 64.4639498432602, 67.3625954198473, 73.8214285714286,
64.6741573033708, 67.3526315789474, 69.1034482758621, 70.030534351145,
73.0285714285714, 62.6741573033708, 65.6, 67.8275862068966, 70.1450381679389,
71.4071428571429)), class = "data.frame", row.names = c(NA, -15L
))

ui <- dashboardPage(
  dashboardHeader(title = "Student Performance"),
  dashboardSidebar(
    sidebarMenu(
      menuItem("Demographics", tabName = "demographics", icon = icon("id-card")),
      menuItem("Programs", tabName = "programs", icon = icon("folder")))),

  dashboardBody(
    tabItems(
      tabItem(tabName = "demographics",
          fluidRow(box(plotOutput("p1")),
      tabItem(tabName = "programs",
          fluidRow(box(plotOutput(("p2"))))))))))

server <- function(input, output){
output$p1 <- renderPlot({ggplot(df1, aes(x = gender, y = avg_score))+
    geom_col(aes(fill = subject), width = 0.7)})

output$p2 <- renderPlot({ggplot(df2, aes(x = race_ethnicity, y = avg_score))+
    geom_col(aes(fill = subject), width = 0.7)})}

shinyApp(ui, server)

A: I think it may just be your parentheses placement in your UI. This seemed to work:
ui <- dashboardPage(
  dashboardHeader(title = "Student Performance"),
  dashboardSidebar(
    sidebarMenu(
      menuItem("Demographics", tabName = "demographics", icon = icon("id-card")),
      menuItem("Programs", tabName = "programs", icon = icon("folder")))),

  dashboardBody(
    tabItems(
      # Demographic tab content
      tabItem(tabName = "demographics",
              fluidRow(box(plotOutput("p1")))
              ),

      # Programs tab content
      tabItem(tabName = "programs",
              fluidRow(box(plotOutput("p2")))
              )
    )
  )
)


text:
Q: Select element with specific character I have a atomic vector with character with different length for each elements like belows:
 A <- c("ABCDE", "ADLBB", "ASDLB", "ABCDG", "ABCDGDL")

My task is to select those with "DL".
The tricky part is that DL is not always fixed to specific position of the elements.
My ideal answer is:
[1] "ADLBB" "ASDLB" "ABCDGDL"

I tried grep("[DL]", A, value=TRUE) but seems not working.
Thanks.

A: With grep it would be
> A <- c("ABCDE", "ADLBB", "ASDLB", "ABCDG", "ABCDGDL")
> grep("DL", A, value = TRUE, fixed = TRUE)
## [1] "ADLBB"   "ASDLB"   "ABCDGDL"

No need for the [ to capture characters if you set fixed = TRUE.  It will capture "DL" as is.  Another variety is
> A[grep("DL", A, fixed = TRUE)]
## [1] "ADLBB"   "ASDLB"   "ABCDGDL"

Since you mentioned you're learning regular expressions in R, here are some other variations of grep that make it very handy in many situations.
Alone, it returns the indices of the captured regex
> grep("DL", A, fixed = TRUE)
## [1] 2 3 5

When we add invert = TRUE, we get the indices of the vector that did not match (essentially the opposite of the above line)
> grep("DL", A, fixed = TRUE, invert = TRUE)
## [1] 1 4

Adding value = TRUE to that, we get the values that did not match.  Again, the opposite.
> grep("DL", A, fixed = TRUE, invert = TRUE, value = TRUE)
## [1] "ABCDE" "ABCDG"

If we add some elements with lower case letters mixed in, we can capture those with ignore.case.  We also no longer want fixed because we're searching for variations in the cases.
> B <- c(A, "aBcdLe", "Dlabrt", "abcde")

> grep("DL", B, value = TRUE, ignore.case = TRUE)
## [1] "ADLBB"   "ASDLB"   "ABCDGDL" "aBcdLe"  "Dlabrt"

These arguments allow the user to cut down on lengthy regular expressions.

A: Use grepl for this:
A <- c("ABCDE", "ADLBB", "ASDLB", "ABCDG", "ABCDGDL")

grepl("DL", A)

output:
# [1] FALSE  TRUE  TRUE FALSE  TRUE

If you want to select only those observations:
A[grepl("DL", A)]

output:
#[1] "ADLBB"   "ASDLB"   "ABCDGDL"


text:
Q: Is the product of all positive rational numbers equal to one? I've started reading Pinter's Book of Abstract Algebra, and one of the early exercises calls for a proof that in a finite abelian group $G$, $(a_1a_2a_3a_4...a_n)^2 = e$, if there are any $a_n$ that are their own inverses, and that if no $a_n$ is its own inverse, then $(a_1a_2a_3a_4...a_n) = e$.
Since I'm not doing this for a class, I worked out a very informal proof for the second case (no $a_n$ is its own inverse): Since there must be an $a^{-1}$ for each $a$, then $(a_1a_2a_3a_4...a_n)$ can be reduced to so many instances of $(a_1a_1^{-1}a_2a_2^{-1}...a_{n/2}a_{n/2}^{-1})$, which can be simplified to $e^{n/2}$, or just $e$.
Is there a particular reason why this holds only for finite abelian groups?
If one were to list rational numbers in order, as Cantor demonstrated, would the product of this list tend toward one?
Also, would it be fair--albeit relatively meaningless--to say that the group $\mathbb{Q} > 0$ has an odd number of members, as it contains exactly one member that is its own inverse?
(full disclosure--this is basically a hobby for me, so apologies in advance for any obvious errors in logic/notation/etc., but please point them out)

A: In your proof you are making the assumption that $n$ is even and that the inverse of $a_k$ for $1\leq k\leq \frac{n}{2}$ is not in $\{a_1,\ldots,a_{\frac{n}{2}}\}$, so in general, your idea doesn't work.
Also your theorems are flawed. They should read like this:

*

*For any finite group $G$ with elements $a_1,\ldots,a_n$ holds $(a_1\ldots a_n)^2=e$.

*For any finite group $G$ with elements $a_1,\ldots,a_n$ such that the only selfinverse element is $e$ holds $a_1\ldots a_n=e$.

The proof of (2.) is simple. Because of (1.) we know that the element of $G$ of form $a_1\ldots a_n$ is selfinverse (because $(a_1\ldots a_n)^2=e$), but with our assumption in (2.) we then get $a_1\ldots a_n=e$ immediatly.
As for your question: You have the problem that it is not well defined in which order your elements are multiplied. Sure, you can have an order such that the product is $1$. But you could also have an order such that the product is $\frac{1}{2}$ or $2$ or any other number. Even $0$ and $\infty$ are possible. The terms "convergence" and "absolute convergence" are needed here. See for example wikipedia (there it is about sums, but it is the same principle).
For illustration, your claim of the product being one is roughly equivalent to saying that the sum of all integers is $0$. I'm using that because listing all rationals is always a bit tricky.
Lets make an attempt:
$$0+1+(-1)+2+(-2)+\ldots=0+(1+(-1))+2+(-2)+\ldots=0+0+(2+(-2))+\ldots$$
Yeah, $0$ seems reasonable. But wait, what if we do it like this?
$$0+1+2+(-1)+3+4+(-2)+5+6+(-3)+\ldots=0+(1+2+(-1))+(3+4+(-2))+(5+6+(-3))+\ldots = 0+2+5+8+\ldots$$
Clearly we are still adding up all integers (in a way most people would probably not), but suddenly our sum gets bigger and bigger (forever).
Summation order (and multiplication order) often plays a critical role when dealing with infinite sums (or infinite products).
In conclusion you can't say "The product of all positive rationals is $1$", but "There is a way to multiply all positive rationals such that the product is $1$".
EDIT: For the people who are nagging about how using the associative law here makes my answer somehow not mathematically right, not in the spirit of the question or that I would just

write "1" in a countable number of funny ways

if I were to use this technique for multiplying all positive rationals to $1$, I'm proud to tell you that this technique is commonly used.

A: Consider the sequence $\{s_n\}$ where
$$
s_n=\begin{cases}n/2&n\text{ is even}\\
-(n-1)/2&n\text{ is odd}
\end{cases}.
$$
Consider the sum
$$
\sum_{n=0}^\infty s_n.
$$
This sum does not converge, even though every time $k$ is odd,
$$
\sum_{n=0}^k s_n=0.
$$
Suppose that we pick an order on the rationals greater than $1$, so $\{a_n\}$ is a sequence of all rationals greater than $1$.  Then, you're considering the product
$$
\prod_{n=0}^\infty a_na_n^{-1}=1.
$$
It is true that this product is $1$ because every factor is $1$.  However, if you were to look at the sequence $\{b_n\}$ where
$$
b_n=\begin{cases}
b_n=a_{n/2}&n\text{ is even}\\
b_n=a_{(n-1)/2}^{-1}&n\text{ is odd}
\end{cases}
$$
Then, the product
$$
\prod_{n=0}^\infty b_n
$$
has the same problem as before since it is $1$ whenever $n$ is odd, but can be any rational number greater than $1$ when $n$ is even.

A: Infinite products are delicate.  Generally, we say that an infinite product
$$ \prod_{k=1}^{\infty} a_n $$
converges if and only if the series
$$ \sum_{k=1}^{\infty} \log(a_n) $$
converges to some value $\log(a)$.  In this case, the product converges to $a$.  Otherwise, the product diverges.
To understand why this is a reasonable definition, recall that for two elements, we have
$$ a_1 \cdot a_2 = a \iff \log(a_1) + \log(a_2) = \log(a); $$
and that for any finite product we can show by induction that
$$ \prod_{k=1}^{n} a_k = a \iff \sum_{k=1}^{n} \log(a_k) = \log(a). $$
Thus we can understand the properties of products by reducing them to series using the logarithm (since you are reading about abstract algebra, you might consider how the multiplicative group of positive real numbers relates to the additive group of real numbers; are they isomorphic?).
Notice that there are several interesting ways for a product to diverge:  it can oscillate (as a series might), it can diverge to infinity (consider the infinite product $\prod 2$), or it can diverge to zero!  For example, if $\prod \frac{1}{2} = a$, then
$$ \sum_{k=1}^{\infty} \log\left( \frac{1}{2} \right) = \log(a). $$
But the sum diverges to negative infinity, hence the product does not converge.
So, suppose that $\{q_k\}$ is an enumeration of the rational numbers.  Then
$$ \prod_{k=1}^{\infty} q_k = q \iff \sum_{k=1}^{\infty} \log(q_k) = \log(q). $$
There is no rearrangement of the rational numbers such that the series above converges.  To see this, suppose that $\{q_n\}$ is an enumeration of the rationals.  There are infinitely many $n \in \mathbb{N}$ such that $|\log(q_n)| > 1$, which implies that $|\log(q_n)|$ does not converge to zero as $n\to \infty$.  Hence the series $\sum \log(q_n)$ does not converge (the general term doesn't go to zero).

As per Asaf Karagila's comments (below), a set is even if it can be split into two sets of the same "size", or if it can be split into pairs (this characterization requires the Axiom of Choice, but this is a technical point that is beyond the current scope).  If a set cannot be split into pairs, then it is odd.  Since any infinite set can be split into pairs (again, this requires choice), every infinite set—including the rationals—is even.
As such, this argument basically asserts that the concept of "parity" is more or less meaningless for infinite sets.


text:
Q: laravel mysql -problem with data extraction hello I learn laravel I have a problem I have a mysql database with a table breakdowns in it columns machine_name and data_zgnoszeniaawarii, I need help because I do not know how to extract data from the database in the form
machine name and number of occurrences, how to pass it to blade.php, e.g.
machine name
machine - NR01
number of appearances
5
is it something like this:
$quantity_of_of_machine =DB::select( DB::raw("SELECT numer_maszyny, COUNT(*) FROM `awaries` GROUP BY numer_maszyny") );

or
$quantity_of_of_machine = DB::table('awaries')
->select('numer_maszyny')
->groupBy('numer_maszyny')
->where('data_zgloszenia', '!=', null)
->where('user_id', '=', $user_id)
->count();

A: It is better if you add the table scheme, but now I can say you should do something like this:
DB::table('awaries')->selectRaw('numer_maszyny, count(*)')
    ->groupBy('numer_maszyny')
    ->where('data_zgloszenia', '!=', null)
    ->where('user_id', '=', $user_id); // ->get();


text:
Q: JavaFX TabPane: separate tabs from their content I would like to create a tabbed JavaFX layout like on the picture below (this is a recent Firefox version window):

Is it possible to somehow insert fixed content between tabs and tab contents when using javafx.scene.control.TabPane? The same fixed content (e.g. address bar and favorites panel on the screenshot) should be shown for each selected tab.

A: You can share the node with the "fixed" content between tabs, and reparent it to the selected tab's content each time a tab is selected.
Please note that TabPane doesn't seem to be designed with browser-kind usecase in mind. For example, its tabs are not draggable.


text:
Q: JQueryMobile - position and size of select menu I am working on a JQueryMobile page. This page will contain a select element (dropdown) with a custom menu. I am trying to position the menu right below the select button and as well change its width to the width of the select button. Further stylizing will follow as well.
In Firebug I figured out that JQM changes the CSS classes of the select menu (here: select-choice-1-listbox-popup) as well as its position attributes. I thought it might be the proper approach to get this element and simply change the top attribute.
This doesn't work though. I guess my code is executed too early because the first alert does not show a value for the "top" attribute.

[...]

    Choose shipping method:
    <select data-native-menu=false name="select-choice-1" id="select-choice-1">
        <option value="standard">Standard: 7 day</option>
        <option value="rush">Rush: 3 days</option>
        <option value="express">Express: next day</option>
        <option value="overnight">Overnight</option>
    </select>

My question is: How can I change the attributes of a select menu?


text:
Q: Shell script change shell in between I've a shell script with two shebangs, the first one tells #!/bin/sh and after a few lines the other one is #!/usr/bin/env python.
When this script is given executable permission and ran as ./script.sh, the script works fine, uses /bin/sh in first part and uses python interpreter in latter part.
But when the script is run as sh script.sh, the second shebang is not recognized and the script fails. Is there anyway I can force to change the interpreter if the script is run explicitly as sh script.sh.
The reason I need this is because I need to run the scripts through a tool which runs as sh script.sh

A: As far as I know you cannot have two shebang lines in one script. The shebang works only when -

*

*it is on the first line

*it starts in column one

If you need to run python code then have it in another script and then call the script by doing
python path/to/the/script.py

A: A better way to do this would be to use a shell here document. Something like this:
#!/bin/sh
curdir=`pwd`
/usr/bin/env python <<EOF
import os
print os.listdir("$curdir")
EOF

This way, you won't need to distribute the code on two separate files.
As you see, you can even access shell variables from the python code.

A: have your script.sh script invoke the python interpreter directly:
#!/bin/sh
# include full path if needed
python (your python interpreter arguments)


text:
Q: Proof Explanation: $\rho(\tau)=\rho(\tau\sigma)+dim[Im(\sigma)\cap K(\tau)]$ $\tau$ and $\sigma$ are linear transformations. $K(\tau)$ means kernel of $\tau$. $\rho$ is the rank. $dim$ means dimension
The domain and codomain wasn't stated clearly in the book so i think we'll assume $\sigma: U\rightarrow V$ and $\tau:V\rightarrow W$
Proof:
Let $\tau'$ be a new linear transformation such that $\tau':Im(\sigma)\rightarrow W$, and

$\forall \overline{\alpha}\in Im(\sigma),
\tau'(\overline{\alpha})=\tau(\overline{\alpha})$... Does this mean that $Im(\tau')=Im(\tau)$?

.

Then $K(\tau')=Im(\sigma)\cap K(\tau)$... Would this be because $Im(\sigma)\cap K(\tau)=K(\tau)?$ and $Im(\tau')=Im(\tau)$?

and

$\rho(\tau')=dim\{\tau[Im(\sigma)]\}=dim(\tau\sigma(U))=\rho(\tau\sigma)$... Is this also because $Im(\tau')=Im(\tau)$?

Then Theorem 1.6 takes the form, $\rho(\tau')+v(\tau')=dim\{Im(\sigma)\}$ or $\rho(\tau)=\rho(\tau\sigma)+dim[Im(\sigma)\cap K(\tau)]$. $\Bbb{QED}$

A: So it seems as if $\sigma(U)=Im(\sigma)\subseteq V$. Then

$\forall \overline{\alpha}\in Im(\sigma),\tau'(\overline{\alpha})=\tau(\overline{\alpha})$

would mean that $Im(\tau')\subseteq Im(\tau).$ In fact $Im(\tau')=Im(\tau|_{Im(\sigma)})$.
Also $$K(\tau')=\{x: x\in Im(\sigma)\wedge \tau'(x)=0\}=\{x: x\in Im(\sigma)\wedge \tau(x)=0\}=\{x: x\in Im(\sigma)\wedge x\in K(\tau)\}=Im(\sigma)\cap K(\tau)$$ and
$$\rho(\tau')=dim(Im(\tau'))=dim(Im(\tau|_{Im(\sigma)}))=dim(\tau\sigma(U))=\rho(\tau\sigma)$$


text:
Q: Group by an item in a nested array using laravel collection I have an array that has the variable name $array and it is as follows:
$array = [
    "data"=> [
        [
            "company"=>[
                "id"=> 1,
                "name"=> "company1"
            ],
            "reports"=> [
                "active_reports"=> 3,
                "completed_reports"=> 2
            ]
        ],
        [
            "company"=>[
                "id"=> 2,
                "name"=> "company2"
            ],
            "reports"=> [
                "active_reports"=> 6,
                "completed_reports"=> 1
            ]
        ],
        [
            "company"=>[
                "id"=> 2,
                "name"=> "company2"
            ],
            "reports"=> [
                "active_reports"=> 7,
                "completed_reports"=> 5
            ]
        ]
    ]
];

So, I want to group this array by the company id. The id can be found in the nested array with key company
My expected result is below:
{
  "1": [
    {
      "company": {
        "id": 1,
        "name": "company1"
      },
      "reports": {
        "active_reports": 3,
        "completed_reports": 2
      }
    }
  ],
  "2": [
    {
      "company": {
        "id": 2,
        "name": "company2"
      },
      "reports": {
        "active_reports": 6,
        "completed_reports": 1
      }
    },
    {
      "company": {
        "id": 2,
        "name": "company2"
      },
      "reports": {
        "active_reports": 7,
        "completed_reports": 5
      }
    }
  ]
}

So, I tried the following logic:
foreach ($array['data'] as $data) {

   $reportsData = collect($data)->groupBy($data['company']['id']);

   Log::info($reportsData);
}

But this is the result I'm getting after trying the above logic:
[
  {
    "": [
      {
        "id": 1,
        "name": "company1"
      },
      {
        "active_reports": 3,
        "completed_reports": 2
      }
    ]
  },
  {
    "": [
      {
        "id": 2,
        "name": "company2"
      },
      {
        "active_reports": 6,
        "completed_reports": 1
      }
    ]
  },
  {
    "": [
      {
        "id": 2,
        "name": "company2"
      },
      {
        "active_reports": 7,
        "completed_reports": 5
      }
    ]
  }
]

I want to be able to get the expected result as illustrated above.

A: You are passing a value to groupBy currently not a 'column' to group by. Though you have nested data here so you will need to pass a callback to groupBy where you will return what value the entities should be grouped by:
collect($array['data'])
    ->groupBy(fn ($item) => $item['company']['id']);

Or simply using the 'dot' notation (as mentioned by Donkarnash), since we are starting the collection at the 'data' key:
collect($array['data'])->groupBy('company.id');

Laravel 9.x Docs - Collections - Available Methods - groupBy