Set of real polynomials, organized as a vectorspace over $\mathbb{R}$.

Question: I'm currently studying for a Linear Algebra exam in january, thus I'm going through some older exam questions, and I'm at the following question.
Let $\mathbb{R}[x]$ denote the set of all real polynomials, which is organized as a vectorspace over $\mathbb{R}$.

A. Assume that $U=\{p\in\mathbb{R}_{1}[x]|p(2)=0\}$. Determine a basis for $U$ and its dimension.
B. Add $p(x)=x-2$ to a basis $B$ for $\mathbb{R}_3[x]$, and determine the coordinate vector $[q]_B$ for $q(x)=3+2x+x^2$
C. Determine a subspace $W\subset \mathbb{R}_3[x]$ such that $U\oplus W=\mathbb{R}_3[x]$. Determine $\dim W$.
D. Find the matrix $M(T)$ with respect to $B$ when $T=4D+3I$, where $D$ denote differentiation and $I$ denotes the identical map. Determine whether $T$ is injective, surjective or bijective.
E. Let $L$ denote the set of all real numbers $\lambda$ such that $S=4D-\lambda I$ has $span(1,x^2,x^3)$ as a subspace which is invariant under $S$. Determine $L$.

My answers are,
A. $q(x)=x-2$ is a basis for $U$ and its dimension is 1.
B. I add $p(x)=x-2$ to the standard basis of $\mathbb{R}_3[x]$, such that $B=(x-2,1,x,x^2,x^3)$, this is not a basis of $\mathbb{R}_3[x]$ as $x$ can be written as a linear comb. of the previous elements (vectors?), thus I reduce it to a basis by removing $x$ from the list so $B=(x-2,1,x^2,x^3)$. Now I write the matrix with respect to this basis and add $\begin{bmatrix}3\\2\\1\\0\end{bmatrix}$ to the matrix, and then I compute the coordinate vector $[q]_B$ by gauss elimination.
$\begin{align}
\begin{bmatrix}
-2 & 1 & 0 & 0 & 3\\
1 & 0 & 0 & 0 & 2\\
0 & 0 & 1 & 0& 1\\
0 & 0 & 0 & 1 & 0
\end{bmatrix}
\sim
\begin{bmatrix}
1 & 0 & 0 & 0 & 2\\
0 & 1 & 0 & 0 & 7\\
0 & 0 & 1 & 0 & 1\\
0 & 0 & 0 & 1 & 0
\end{bmatrix}
\end{align}$
Thus
$[q]_B = \begin{bmatrix}2 \\7\\1\\0\end{bmatrix}$
C. From B. $\mathbb{R}_3[x]$ had the basis $(x-2,1,x^2,x^3)$, and the basis of $U=(x-2)$, so $W=(1,x^2,x^3)$, thus $U\oplus W$ will span $\mathbb{R}_3[x]$. $\dim W=3$
I'm stuck at D. and E. I assume that I start by differentiating the basis of $B$, then representing $B'$ as a matrix which I substitute into $D$ and then add the $3I$? I'm not sure that I'm capable of solving E. without knowing the methods from D.
I hope that some of it is right, and I hope to get some tips, correction and some help with the last two questions.
Best regards Jens.
Answer: Up till now all correct :)
For  exercise D) you'll need The differentiation Matrix $$D=
\begin{bmatrix}
0 & 1 & 0 & 0 \\
0 & 0 & 2 & 0 \\
0 & 0 & 0 & 3 \\
0 & 0 & 0 & 0
\end{bmatrix}$$
$$T:=4D+3I=\begin{bmatrix}
3 & 4 & 0 & 0 \\
0 & 3 & 8 & 0 \\
0 & 0& 3 & 12 \\
0 & 0 & 0 & 3
\end{bmatrix} $$
T is bijective because $\det(T)=3^4\neq 0$ If you have not learned about determinants jet you can simply use the Gauss-algorithm to Calculate $A^{-1}$.
Then have to write T with as a Matrix with Respect to the Basis B. For this you will need the Transformation Matricies $[id]^B_S$ and $[id]^S_B$ (where S denotes the standart-Basis) then $[T]^B_B=[id]^B_S T [id]^S_B$
hint:
$[id]^B_S$ the transformation matrix from S to B is:
$$[id]^B_S=\begin{bmatrix}
-2 & 1 & 0 & 0 \\
1 & 0 & 0 & 0 \\
0 & 0 & 1& 0 \\
0 & 0 & 0 & 1
\end{bmatrix} $$
to understand this look at $[id]^B_S e_j $.
Also note $[id]^B_S=([id]^S_B)^{-1}$
Comment: Wolfram alpha gives me the same answer,
Comment: I think I'm doing something wrong when trying to calculate the $[id]^S_B$ matrix. I get a matrix with a zero in the diagonal such that it isn't invertible.
Comment: I have misunderstood some things, but correct me if I'm wrong.

I just calculated the matrix in the hint, but i thought that it was $[id]^S_B$ not $[id]^B_S$. When you write $e_j$, do you refer to the j'th orthonormal basisvector. I'm not really sure what that should clarify.

Last I calculate the inverse of $[id]^B_S$ to be $\begin{bmatrix}0 & 1 & 0 & 0\\ 1 &2 &0&0\\0&0&1&0\\0&0&0&1\end{bmatrix}$. My previous comment said that I didn't think this was invertible because one of the diagonals had a zero, which seems to be wrong. Is it right to say it isn't diagonizable then?
Comment: the matrix seems right, it is the inverse of the matrix I've written (i'm not quite sure about my notation i might have done it the wrong way round) , $e_j$ is the j-basisvektor $e_1=(1,0,0,0),e_2=(0,1,0,0),e_3=(0,0,1,0),e_4=(0,0,0,1)$
Comment: You might be right about it, its just I don't use the same notation, it took a minute to figure the id meant the identity :p
So multiplying $[id]^B_Se_j$ for each $e_j$ would yield a basis for $B$, right?

After finding $[id]^B_S$ and its inverse I determine

$[T]^B_B=\begin{bmatrix}3&4&0&0\\0&3&0&0\\8&16&3&0\\0&0&12&3\end{bmatrix}$

To summarize to find the matrix of $T$, $M(T)=[T]^B_B$, I first compute $T$ from the assumptions, then find an invertible matrix $[id]^B_S$ wrt the basis B, finding its inverse, $[id]^S_B$ then I compute $M(T)=[id]^B_ST_S[id]^S_B$?
Comment: That is Correct
Comment: Wonderful, thank you!
Comment: I edited my answer i noticed that T should have been transposed sorry.
Comment: Why is that? Is it because $D$ was supposed to be the transpose of the one you wrote?
Comment: yes, idk why i mixed that up
Comment: With the same computations i now get.

$[T]_B^B=\begin{bmatrix}-5&-16&8&0\\4&11&0&0\\0&0&3&12\\0&0&0&3\end{bmatrix}$ Is that right?
Comment: Super, thank you.


What is a simple component of a root system?

Question:
The above is from Knapp's Lie Groups; Beyond an introduction', 2ed, page 397.
Question 1: What is a simple component of a reduced root system? Or, more specifically, given a root system $\Delta$ and orthogonal roots $\alpha, \beta$ with $\alpha \pm \beta \in \Delta$, what is the simple component of the root system containing $\alpha$ and $\beta$?
These terms don't seem to appear in the index of Knapp, and don't seem to appear on Google either. I glanced back at the classification theory of root systems/Cartan matrices/Dynkin diagrams and couldn't get anything
Question 2: Why can't a simple component of a reduced root system have more than two root lengths?
This bound on number of root lengths doesn't seem to hold for root systems of dimension $\geq 3$? But it does seem to be true for two-dimensional root systems?
Blease help me
Answer: Question 1: Here Knapp means irreducible component of a root system. As for modules, people sometimes use simple and irreducible as a synonym.
Question 2: This is a well-known fact, see for example this duplicate:
At most two values for the length of the roots in an irreducible root system
Comment: You should wear a cape.
Comment: Say, do you understand the comment about Dynkin diagrams in the screenshot? I thought vertices in Dynkin diagrams come from simple roots. Without loss of generality, we can assume $\alpha$ is simple (because it is a reduced root). But, in order to get the double line, is Knapp also assuming that one of $\alpha \pm \beta$ is part of the same simple system as $\alpha$?


Real Time MIDI Controlled Accompaniment

Question: I'm part of a small theater group looking to add some big sound to our small orchestra. I was wondering if anyone knew of a software package that would allow an artist to record an instrument, say a guitar, then control that recording's playback at show time via the MIDI outputs on a digital keyboard. The software would have to adjust tempo etc based on the way the keyboard is played. Any info would be appreciated!
Comment: I use [Anvil Studio](http://www.anvilstudio.com/) for this.
Comment: What computer platform are you talking about using? Macintosh? Windows? iPad? Something else?
Comment: I would suggest MaxMSP here, but again, like other responses, the program would cost money and time to learn how to control tempo via motion sensors.  Not to mention programming language etc.
Answer: MIDI Maestro is one professional system designed for this purpose.
If you know someone who is an expert at the Ableton Live environment, you could construct something useful.
There are also several musical theater-related companies that will rent you a turn-key system of computer and samplers with the entire orchestration for a particular hit musical or opera, for augmenting your live orchestra with pre-recorded or MIDI-sequenced performance tracks that can be controlled by a live human conductor tapping out a tempo on a MIDI controller. Those have been around for more than twenty-five years. These companies seem to be rather secretive and proprietary, and I do not know where to look to identify a list of them or find out what systems they can rent you for which musicals or operas, and what it would cost.
Answer: The only way that the software can adjust and control the tempo is if it is given a reference beat from the drummer or some other instrument that provides a known quantity of beats per bar. MIDI software can be set up to respond to that kind of trigger. But this won't work in your case, because the keyboard player most likely will not be providing constant rhythmic pulses. Any time the keyboard player pauses, this will throw the software out of whack. You would want to set it up to respond to the drummer, not the keyboardist.
Comment: False.  This information is incorrect. There are programs dictated by motion control that can adjust tempo according to player movement fluctuation and are not dependent on a percussionist for tempo.
Comment: @jjmusicnotes. You're taking what I'm saying too literally. Any type of automatic tempo control requires a steady reference of some kind. You can choose to call it a drum beat, you can choose to use a motion, it doesn't matter as long as it is a steady and constant point of reference. This is the main thing to understand. Which "programs" do you refer to? I can tell you how they are designed and on what principles they work. I am a software engineer, after all.
Comment: I do not take things too literally - one should not say what one does not mean. If you meant a "steady reference" or *input value*, then that is the phrase you should have used, because declaring the *only* way it can be done is with a *reference beat* is very different than having a constant input value.  I am referring to MaxMSP, of which I am already familiar, so you can spare the lecture.  To that end, since your training is by admission software engineering and not music, it is even more imperative to make sure information is correct and accurate before posting answers.
Comment: @jjmusicnotes the fact that you make assumptions about my training says a lot. Actually I was trained as a musician long before I did any sort of training in the sciences. I'm ambidextrous you could say.
Comment: I did not make an assumption - I visited your website and read your biography, and to my knowledge, the most it mentions of your musical training is that you grew up playing certain instruments. When I speak to training in music, I am referring strictly to either conservatory, university, or specialized apprenticeship, so my comments are based upon information that you provided.
Comment: @jjmusicnotes I suppose because I don't feel the need to talk myself up that I gloss over those type of details, but since you're asking - I studied music for several years under Michael Mauldin - that would be my "formal" study which is probably what you're looking for. But I've also played pop music (by which I mean various styles of music) in groups/bands for many years and it is primarily this experience that my knowledge of harmony, electronic equipment, midi, etc comes from.

Real Time MIDI Controlled Accompaniment


extension of sequential probability ratio tests to particle filters?

Question: I've been wondering if there are extensions of the sequential probability ratio test to account for particle filters. I ask because, in my research, I'm working with distributions that cannot be represented in closed form, hence the use of particle filters.
Does anyone have some insights on this?
Thanks!
Answer: I don't know much about sequential testing. You might get a better answer if you gave a simple example that demonstrates the basic ideas. I can tell you, though, that if you want to take into account the uncertainty of your sample-based estimates, the central limit theorems for particle filters are valid under fairly mild regularity conditions. What you end up with ais a recursive (in time) formula for the asymptotic variances. You could get a p value or something using that.
Comment: Links to the paper that discusses this?
Comment: @Glassjawed [this friendly tutorial](https://www.stats.ox.ac.uk/~doucet/doucet_johansen_tutorialPF2011.pdf) has a couple stated ones (bottom of page 18). [This textbook](https://www.springer.com/gp/book/9780387402642) has some nice introduction to the theory (e.g. triangular arrays, Lindeberg conditions, etc.)


Erro ao exibir a soma em um SELECT

Question: Não estou conseguindo somar o valor total.
View

Banco

Valores que estão no banco:
R$ 70,88
R$ 70,88
R$ 70,88
Valor que aparece

R$ 210

Valor que tem que aparecer

R$ 212,64

Código
<?php
     $numerocontrato = trim($_GET["numerocontrato"]);
     $consulta = $DB->query("SELECT sum(valordependente) as dep FROM cadastro_clientes where numerocontrato = $numerocontrato");
     while ($linha = $consulta->fetch(PDO::FETCH_ASSOC)) {
            echo "
" . $linha['dep'] . "
";
     }
?>

Comment: Pronto @VirgilioNovic a imagem.
Comment: @Ivcs já o fiz independente do que você acha eu não faria dessa forma também, agora se tem que aprender que também tem espelho de vidro eu já sinalizei o que você fez de errado ontem numa pergunta de PHP, que é muito grave ao meu ver. Eu alertei ele que o melhor é decimal, mas, isso não compete a mim resolver ele tem que fazer no seu sistema, não tenho nada contra ninguém também, mas, receber votos sem merecer também acho inválido. Não sou eu que estou fazendo errado.
Comment: Não tem que agrupar -> `SELECT sum(valordependente) as dep, adesao FROM cadastro_clientes where numerocontrato = $numerocontrato GROUP BY adesao`
Comment: ja fiz isso @VirgilioNovic
Comment: Coloque na pergunta uma cópia dos dados um imagem qualquer coisa!
Comment: Então eu tinha que ver os dados na tabela do banco de dados essa ai não ajuda ela é um resultado de alguma lista que você fez inclusive ela somada realmente dá o valor que você precisa. Valores do banco de dados seria o ideal.
Comment: Veja ai amigo, @VirgilioNovic
Comment: se está gravando como texto ???
Comment: Sim, estou salvando como texto @VirgilioNovic, como procedo?
Comment: eu coloquei uma resposta por favor faço o teste, tem que usar 2 funções por causa disso.
Comment: @MauroSantos eu nao ia comentar novamente para deixar o Virgilio te ajudar, mas vendo que ele está ajudando da maneira errada tenho que entrar no meio, o jeito **correto** é ir no banco de dados e alterar o tipo da coluna valordependente para `DOUBLE`, pois é um tipo próprio para ligar com valores decimais. Até mais.
Comment: Obrigado @lvcs vou mudar isso, vou fazer os testes aqui e fazer o certo. Correto é Double (10,2)?
Comment: @Ivcs vou denunciar você pode editar um resposta ontem de maneira a te favorecer desculpa já que está me fazendo dessa forma também seguirei seus passos.
Comment: @VirgilioNovic qual resposta? Quando edito é com intuito de corrigir algo, e por favor, em assuntos que não se trata da pergunta comente no **chat**. PS: nada contra você, só não acho que aqui é local para gambiarra.
Answer: O correto é você gravar esses valores em decimal para que não fique convertendo os dados dessa maneira abaixo:
<?php
   $numerocontrato = trim($_GET["numerocontrato"]);
   $sql =" SELECT sum(cast(replace(valordependente,',','.') as decimal(18,2))) as dep ";
   $sql .= " FROM cadastro_clientes where numerocontrato = $numerocontrato ";
   $consulta = $DB->query($sql);
   while ($linha = $consulta->fetch(PDO::FETCH_ASSOC)) {
        echo "
" . $linha['dep'] . "
";
   }

Funciona, mas, se isso for feito em uma tabela aonde os resultados são muitos pode causar baixo desempenho.
Comment: Obrigado @VirgilioNovic
Comment: -1 porque o certo é gravar o valor no banco de dados como DOUBLE ou FLOAT
Comment: Parse error: syntax error, unexpected '$consulta' (T_VARIABLE)
Comment: @Ivcs eu sei disso eu ia falar para ele mas, isso não é culpa minha
Comment: @MauroSantos faltou um ponto e virgula.
Comment: @VirgilioNovic o dever da comunidade é guiar o outro membro para um caminho correto, não deixar ele no caminho errado achando que está certo.
Comment: Apareceu 212.64 posso trocar esse (ponto) por vírgula onde? @VirgilioNovic
Comment: @Ivcs eu sei muito bem disso eu ainda estava respondendo a questão. Não vejo motivos para isso. Você compreende isso ou não?
Comment: @MauroSantos tem que formatar com `number_format` do `PHP`

Erro ao exibir a soma em um SELECT


Is it possible to create the selected row event though it has merge cell?

Question: I made a table for showing list of data. This table contains merging two rows which is I really need it to look that way. The tricky problem came when I try to highlight a single row.
It turns out that single TR is highlighted

script


How is 3D plane normal vector related to its rotation

Question: What i am trying to do http://www.youtube.com/watch?v=CaTI2d0tQME 3:15
In my 3D api there is quad.rotation[x,y,z], quad[x,y,z] which is center of it and width/height. I understand that vertices are being calculated from all of the given. And normal can be calculated from vertices but i have a feeling i should be able to get it just from the rotation?
Answer: Yes you can !
Your quad must be axis-oriented (along the X, Y or Z axis, which is its normal vector in its local space). Compose this vector with the quad rotation matrix and you will have your new, nice and shiny normal vector in world space !
A little warning : if the quad transformation matrix is generated by any 3D engine, it could contain scaling factors that will mess the normal vector up. In this case, the classical solution is to compute the transposed inverse of the matrix, or to generate your custom transformation matrix with the quad's rotation values.
Comment: A rotation matrix can be represented by 3x3 values as described [here](http://en.wikipedia.org/wiki/Rotation_matrix).
You only have to [multiply](http://en.wikipedia.org/wiki/Matrix_multiplication) the normal vector with this matrix and you're done.


Acoustic fingerstyle uneven sound

Question: I'm a beginner at fingerstyle guitar. When I play with longer nails, I get a nice crisp sound, but the volume is uneven based on which finger I use. Sometimes I get this horribly loud/scraping sound (usually from the index finger) that just overpowers the other strings. I'm using a steel-string guitar.
Is this normal for a beginner? How do I get a more even sound? I think the angle of my hand is problematic (it's usually at 45 degrees). When I play perpendicularly to the strings, the volume is more even, but it's awkward on my wrists.
Answer: This usually happens because not all your fingers have the same strength and you don't know how to control your finger strength. It's pretty common for a beginner, nothing to worry about.
In order to get an evenly balanced sound on all of the fingers, try working only with the fingers on open strings. Play all of the fingers and try to use the same strength. It will seem a bit boring at first, because you'll have to think about the strength on each and every finger, but after some practice, it'll come naturally to you.
Μy guess is that your thumb, index and middle fingers have more strength than the others, so you might have to work on the other two a bit more.

Acoustic fingerstyle uneven sound


How to apply boolean operators not, and

Question: codepen
div:not(.wayne) div:not(.garth) .content {
  background-color:red;
}

Party On Garth

Party On Wayne

One punch.

Dattebayo

The background should be red unless the class is either .garth or .wayne.  How can I do this for all .content?
Saitama and Naruto should have red backgrounds.  Right now nothing has a red background.  Any similarly added new characters should also have a red background.
Pseudocode
if(!(wayne || garth)){ apply red background to .content}
I'm willing to use JavaScript if necessary.  I prefer css.
Comment: Google search: [site:stackoverflow.com css multiple not selector](https://www.google.com/search?q=site%3Astackoverflow.com+css+multiple+not+selector)
Comment: Google search: [div not multiple classes](https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=div%20not%20multiple%20classes)
Answer: Chain the :not together

div:not(.wayne):not(.garth) .content {
  background-color:red;
}

Party On Garth

Party On Wayne

One punch.

Dattebayo

Answer: If you want to have multiple :not selectors, you need to change your CSS to look like this
CSS
div:not(.wayne):not(.garth) .content {
  background-color:red;
}

CodePen
Answer: You are using a descendant combinator: . Your selector means:
"Select each element with class content which is a descendant of any div element without garth class which is a descendant of any div element without wayne class."
Remove it.
div:not(.wayne):not(.garth) > .content {
  background-color:red;
}

"Select each element with class content which is a child of a div element without garth nor wayne classes."

How to apply boolean operators not, and


jQuery clone and trigger create

Question: I'm trying to create a jQuery function to clone and append a text-field and select-box into the bottom of a div, like this:
$(".inline-form .copyIng:first-child").clone().appendTo(".inline-form");
$(".copyIng").trigger("create");

See this: http://jsfiddle.net/rxwL6/
But the 2 elements get's cloned twice and looks wired, any ideas why this happens?
Greeting :)
I'm sorry for answering my own question
, but the solution looks like this:
$(document).ready(function(){
  $("#newIng").click(function(){
  $(".inline-form .copyIng:first-child").clone().appendTo(".inline-form");
  });

  $("#newOve").click(function(){
    $('
<input type="text" name="c[]" class="field" placeholder="Overskrift">
').appendTo(".inline-form");
    $(".field").textinput();
  });
});

Comment: Is it what you want http://jsfiddle.net/rxwL6/2/ ?
Comment: Exactly, but later on when I add a text field, I need to trigger create.
Answer: Seems like you should use refrash event. The create event is suited for enhancing raw markup that contains one or more widgets. The refresh method should be used on existing (already enhanced) widgets that have been manipulated programmatically and need the UI be updated to match.
jsFiddle: http://jsfiddle.net/rxwL6/5/
Comment: Okay, great, but why can't i select anything from the dropdown created?

jQuery clone and trigger create


Is $x \sim y$ iff $y - x \in \mathbb Q$ an equivalence relation?

Question: I can easily show that the relation $x\sim y$ iff $y - x \in \mathbb Q$ and $x,y \in (0,1]$ is an equivalence relation since it is reflexive (the number zero is rational), symmetric (the negative of a rational number is rational) and transitive as the sum/difference of two rational numbers is rational but I get stuck in what follows. Specifically, I know that equivalence relations induce mutually disjoint equivalence classes but I can't verify that here. My silly counterexample is that if $x=\frac{1}{3}$ then clearly $y=\frac{3}{3}$ is in the equivalence class but $y=\frac{3}{3}$ is also in the equivalence class of $x=\frac{2}{3}$ as that difference too is rational. My question therefore is, what have I misunderstood here? Thank you.
Comment: what about x = 1, y = pi, z = 0, h = pi-3
Comment: @shai  et al.  **Read** $x, y \in (0, 1]$ and see that $0$ is not included.
Comment: If you know that your relation is an equivalence relation, you do not have to verfiy it because it is implied. What about $e$ or $\sqrt{2}$: are they also in the same equivalence class as $\frac{1}{3}$?
Comment: @Moritz Okay these are irrationals but I can't yet see what you mean by this.
Comment: The symbol "$=$" is not a drop-in replacement for the English word "is". It means _is equal to_, and there are no $x$ and $y$ such that $x-y$ is equal to the word "rational". If you want to write symbolically that $y-x$ is a rational number, write "$y-x\in\mathbb Q$".
Comment: neither is pi, im just trying to illustrate different partitions on a finite set, i shouldn't have included 0 it makes it not a equivalence relation in general because 0 would be in every partion @amwhy
Comment: @shaihorowitz Why would zero be in every partition?
Answer: The numbers $\frac{1}{3}, \frac{2}{3}, \frac{3}{3}$ are all in the same equivalence class, they are all equivalent to each other.


Search dictionary key in a column of sentences python

Question: I was trying to find if a dictionary key is contained in a sentence stored in a column of a data frame. Here an example.
I have the following dictionary:
dictionary = {"yellow":1234, "light blue":112, "orange":34,'blue':1}

And the following data frame:
df_data = {"sentence": ["the summarine is yellow", "the sky was an amazing light blue, you should have see it",
" the grass is green", "why you face is purpule?"], "extra":['a','b','c','d'] }
df = pd.DataFrame(df_data)

Do you have an idea on how can I search for the dictionary key inside each sentence? If then the key is find I will save it in a new column, but this should not be a problem.
I had a similar problem in the past but the key was number and with .map() I was able to find it. I tried to use the same method now but is not working.
One thing that concerned me is the fact that the dictionary key may be composed of multiple words like in the case of "light blue" and I can not split each sentence in word and then search for the key because I will not be able to find the correct key.
Comment: What does your expected output look like?
Answer: You can concatenate them with an "or" operator (|):
patterns = '|'.join(dictionary.keys())
df.sentence.str.contains(patterns)

Output:
0     True
1     True
2    False
3    False
Name: sentence, dtype: bool

Answer:
extract the keys from the sentence via extract
use the map to fetch the values of the key from the dictionary.

df['new_col'] = df.sentence.str.extract(pat = f"({'|'.join(dictionary.keys())})")[0].map(dictionary)

OUTPUT:
                                            sentence extra  new_col
0                            the summarine is yellow     a   1234.0
1  the sky was an amazing light blue, you should ...     b    112.0
2                                 the grass is green     c      NaN
3                           why you face is purpule?     d      NaN

Comment: What if I have in the same sentence multiple keys can I use the same reasoning?


How can I configure the WordPress development environment locally?

Question: Some third-party developers have created the sites and they were given to them for ongoing site maintenance such as editing posts, adding new posts, etc.
They just gave an WordPress administrator account. While I am logging into my account, it shows a lot of options to add/modify the page/post. How can I set the local development environment for my site and publish to the live site?
Can we do all the changes by using the online WordPress  administrator account itself or is there a limitation by doing it online?
Answer:
How can I set the local development environment for my site and publish to the live site? Download the WordPress application from Bitnami

Can we do all the changes by using the online WordPress administrator account itself or is there a limitation by doing it online? Yes you can do all the actions you need using the admin account, however, I would advise you create a user for yourself with the correct privileges for your needs.
Comment: I would unzip them into htdocs, you will have to create a local database in the way you would like but make sure WordPress is connected to it
Comment: Thanks @Switch Case. Are you aware of how to get the code files can be downloaded from word press admin account which project files can be used for local set up.
Comment: How does that answer the question? Can you expand the answer (by [editing it](https://stackoverflow.com/posts/45251865/edit), not here in comments)? E.g., how is that application supposed to address the OP's concerns? Currently, it is not much more than a link-only answer.
Comment: @PeterMortensen this is 1. from 2017, 2. I have answer one of the two questions via this link.

> How can I set the local development environment for my site and publish to the live site?

If you want an answer to the 2nd one, happy to.

> Can we do all the changes by using the online WordPress administrator account itself or is there a limitation by doing it online? Yes you can do all the actions you need using the admin account, however, I would advise you create a user for yourself with the correct privileges for your needs.


Minimal generating sets for homogeneous polynomial ideal in two variables

Question: This question is (somehow) related to System of generators of a homogenous ideal
Let $A$ be the ring $A={\mathbb R}[X,Y]$, and let $m \geq 1$. Let
$$
{\cal S}_m=\lbrace X^m, X^{m-1}Y,X^{m-2}Y^2, \ldots ,Y^m \rbrace
$$
and let  $I$ be the ideal of $A$ generated by ${\cal S}_m$. Now let $S'$ be another finite set of polynomials in $A$ such that $I$ is also the ideal of $A$ generated by $S'$.  Does it necessarily follow that $S'$ has at least $m+1$ elements ? Note that $I$ is an homogeneous ideal, and perhaps the theory of Groebner bases can help here, though I don't see how.
Answer: The answer is yes.
Denote by $I_m$ the ideal of $A$ generated by $S_m$. Then $I_{m+1}\subset I_m$ and the quotient $I_m/I_{m+1}$ is a vector space of dimension $m+1$ (a basis is given by the classes of the elements of $S_m$). So $I_m$ can't be generated by less than $m+1$ elements.


Countable intersection of open dense subsets of $\mathbb{R}$

Question: This particular question was asked in my analysis assignment and I was unable to solve it. Kindly help.

Let A be a subset of $\mathbb{R}$ satisfying $A=\bigcap_{n\geq 1} V_n$, where for each n $\geq1$, $V_n$ is an open dense subset of $\mathbb{R}$ . Which 1 of following is correct?

A.  A is non -empty
B A is countable
C A is uncountable
D A is dense in $\mathbb{R}$.
I marked B which is wrong . A is correct and I marked it.For C,D i don't know how to attempt them. SO, Kindly tell me how to reason b,c,d,
Waiting for your help.
Comment: Check out Baire's category theorem and its proof.
Answer: A space in which the intersection of countably many dense open sets is dense is called a Baire space, and the tool that you want is the Baire category theorem, specifically, the version that says that every complete metric space is a Baire space: $\Bbb R$ is a complete metric space, so it is a Baire space.
This immediately tells you that $A$ is dense in $\Bbb R$ and hence that (D) is true. Of course the empty set is not dense in $\Bbb R$, so (A) is also true. To dispose of (B) and (C), suppose that $A$ is countable, say $A=\{a_n:n\in\Bbb Z^+\}$. For each $n\in\Bbb Z^+$ let $U_n=\Bbb R\setminus\{a_n\}$. Let
$$\mathscr{W}=\{U_n:n\in\Bbb Z^+\}\cup\{V_n:n\in\Bbb Z^+\}\,;$$
each $U_n$ is dense and open in $\Bbb R$, so $\mathscr{W}$ is a countable family of dense open subsets of $\Bbb R$, and it's easy to check that $\bigcap\mathscr{W}=\varnothing$, contradicting the Baire category theorem. Thus, (B) must be false, and (C) must therefore be true.
Comment: I don't think there is need of proving $\bigcap W = \phi$ ? ( in 2nd last line)
Comment: @Tim: We need to prove that $\bigcap\mathscr{W}$ isn't dense in $\Bbb R$, and the easiest way to do that is to show that it's empty — which is both rather trivial and exactly what the argument was constructed to do.


Problema de instalar novo Nuget Pack

Question: Eu tento baixar PDF.js via Nuget, porém dá problema:
Erro: Could not install package 'PDF.js 1.3.91'. You are trying to install this package into a project that targets '.NETFramework,Version=v4.5.2', but the package does not contain any assembly references or content files that are compatible with that framework. For more information, contact the package author.
Estou usando Visual Studio do ano 2015.
Alguém já passou por isso ? E como resolver ?
Answer: Isso ocorre quando a versão do .NET Framework no qual foi compilada o pacote NuGet é diferente da versão do projeto em que se está tentando instalar.
O problema maior é que o proprietário do pacote Nuget não especificou qual é versão do .NET Framework o pacote NuGet depende. E acabamos recebendo esse error super incoveniente.
No caso desse pacote em específico, para piorar, o link para o site do projeto é fake. Então sequer podemos ir no site oficial do componentar para conferir a versão compilada.
O que vc pode fazer para tentar rodar é mudar a versão do .NET Framrwork que irá compilar seu projeto, até encontrar uma que a instalação funcione.
No site do pacote NuGet tem um link "Contact Owners". Vc também pode mandar uma mensagem para eles perguntando pela versão e pedindo para adicionarem a versão do .NET Framework como dependencia.
Comment: Oi @Thiago Lunardi, eu corro risco de mudar a versão de NET Framrwork ?
Comment: Se quiser usar o pacote PDF.js, sim. Ter'a que mudar, pois esse nao suporta a versao v4.5.2.

Problema de instalar novo Nuget Pack


Irreducibility in $\operatorname{Proj}S$

Question: $\newcommand{\proj}{\operatorname{Proj}}\newcommand{\spec}{\operatorname{Spec}}$
It is well know that in $\spec A$, $V(I)$ is irreducible if and only if $\sqrt{I}$ is a prime ideal. Is it also true for $\proj S$? Using the standard argument, here is as far as I can show:

If $V_+(J)$ is irreducible and $I,K\subset S$ are graded ideals such that $IK\subset\sqrt{J}$, then $I_+\subset\sqrt{J}$ or $K_+\subset\sqrt{J}$.

This is not quite sufficient to say that $\sqrt{J}$ is a prime.
Edit: For $\operatorname{Proj}S$, the ideals are assumed to be graded, and $I_+:=I\cap S_+$. $V_+(I)$ is the set of all graded prime ideals not containing $S_+$.
Answer: I think you can firstly put all the prime homogeneous ideals into affine case,in fact the topology on $P^n$ and that of (n+1)-dimensional are compatible. So you can prove that the set of all ireducible algebraic sets and the set of all prime like $\sqrt{J}$
are 1-1 corresponing to one another just like in the affine case.
Answer: It is not true: consider the ring $S=(\mathbb{Z}/(6))[x]$ and its prime ideal $\mathfrak{p}=(\bar{2})[x]$.
$V_+(\mathfrak{p})=V_+(\mathfrak{p}_+)$ is irreducible, but $\sqrt{\mathfrak{p}_+}\subset S$ is not a prime ideal; to see this, first note that the nilradical of the ring $\mathbb{Z}/(6)$ is the zero ideal.
This implies $\sqrt{\mathfrak{p}_+}=\mathfrak{p}_+$, and $\mathfrak{p}_+\subset S$ is not a prime ideal since $\bar{2},\bar{3}\not\in\mathfrak{p}_+$ but $\bar{2}\cdot\bar{3}=\bar{0}\in\mathfrak{p}_+$.
Comment: I've thought you are working in polynomial rings over *fields*.


How do you add a input and a select field with webforms?

Question: I would like to add a select element that has an input field attached, so the user can input a value from the list without having to scroll through hundreds of options. Is this possible to do with the module webforms? I have researched it and the only thing I can find is the chosen module but I have no idea how the two integrate, and alot of people say it is incompatible in some browsers. Thank you for your help.
Answer: Welcome to the Drupal Answers Mel.
You can use the Select or Other module. When you enable it, you get another element called Select other. Please take a look at the below screenshots:

Hope that helps.


Trigonometric ratio of multiple and sub multiple angles

Question: Given that $a$ lies in 1st quadrant and
$$ \sin a +\cos a +\operatorname{cosec} a+\sec a+\tan a+\cot a=7$$
then we have to prove that $\sin(2a)$ is a root of $$x^2-44x-36.$$ I have tried to break all of them in respect of sine and cosines but that only makes my problem complex. I just cannot relate to the root part. Can anyone help?
Answer: Combine $\sin a$ and $\csc a$, $\cos a$ and $\sec a$, and $\tan a$ and $\cot a$. And convert all the terms in $\sin$ and $ \cos$. Then cross multiply. You should get:$$\sin a\cos a(\sin a+\cos a)+(\sin a+\cos a)+1-7\sin a\cos a=0$$
Substitute $\sin a+\cos a=t$, you have $\sin a\cos a=\frac{t^2-1}{2}$, you get a cubic:
$$t^3-7t^2+t+9=0$$$$(t+1)(t^2-8t+9)=0$$
You will have to reject the $t=-1$ case.(You can figure that out).
Taking the root of the second equation you get:
$\sin a+\cos a=4-\sqrt 7$. Squaring both sides, you get:
$$1+\sin 2a=23-8\sqrt 7$$$$\sin 2a=22-8\sqrt 7$$ And therefore the other root of a quadratic with rational coefficients would be $22+8\sqrt 7$, and hence the result follows that $\sin 2a$ will be a root of $x^2-44x+36=0$
Comment: Very Well Done!! +1
Comment: Excellent! Marvelous!


ubuntu system crontab works, but root crontab does not

Question: I am having a strange problem about ubuntu crontab here.
If I add the following line to system crontab(/etc/crontab), it works well
*/1 * * * * root /bin/date >> /root/text

but if I edit root crontab by using crontab -e with root user, and add
*/1 * * * * /bin/date >> /root/text

it does not work at all.
Can you please help me on this?
Thank you
update and answer
I got my answer after searching server fault, the reason is explained in this post.
The reason is that crontab file need a newline in the end, otherwise it will not work.
Comment: Have you used `sudo crontab -e' ? To create crontab for root you may need `sudo crontab -eu root'
Comment: Probably belongs on serverfault
Comment: I did not use sudo. I actually logged in as root directly
Comment: Btw can you tell the difference between `*/1` and solely `*` in the first column?
Answer: OP found the solution:

I got my answer after searching server fault, the reason is explained in this post.
The reason is that crontab file need a newline in the end, otherwise it will not work.
Answer: You may can check if you have /etc/cron.allow and/or /etc/cron.deny files and contents of these files. Here you have excerpt from man page crontab(1):

If the /etc/cron.allow file exists, then you must be listed therein in order to be allowed to use this command.  If  the  /etc/cron.allow  file  does  not  exist  but  the /etc/cron.deny  file  does exist, then you must not be listed in the /etc/cron.deny file in order to use this command.  If neither of these files exists, then depending on site-dependent configuration parameters, only the super user will be allowed to use this command, or all users will be able to use this command. For standard  Debian  systems, all users may use this command.
Comment: thank you for answering. I just checked whether cron.allow or cron.deny exists in /etc. But I found neither of them there.
Is there any other reason why I can not get root crontab working?
Comment: According to docs it should work for root user and as I see you found your answer :).

 But you can always put empty `cron.deny` file for allow all users to access to the cron or put only allowed users in cron.allow file. I think it will more precise that doesn't have any of these files (in that case the behavior is not consistent between different systems) .
Comment: AFAIK cron.deny and cron.allow do not exist by default in debian based distros. Only centos redhat ship them by default.


How to solve MALA when the target density is known up to a constant?

Question: If you look at the wikipedia explanation of Metropolis adjusted Langevin Algorithm, the acceptance ratio is given by

The second equation involves taking the gradient of the log of $\pi(x)$. However, the whole reason for doing MCMC is that you do not know the exact formula for $\pi(x)$, only within a multiplicative constant. That's why take the ratio as shown in the 1st equation is ok.
So how do you implement MALA given this limitation?
Answer: If you know $\pi(\cdot)$ up to a constant, a requirement for Metropolis-Hastings algorithms, the gradient
$$\nabla \log \pi(\cdot)$$is also independent from this constant.
Answer: Expanding on Xi'an's answer, if $\pi(x) = c f(x)$, where $c$ is the unknown normalizing constant, then
\begin{align*}
\pi(x) & = c f(x)\\
\log \pi(x) & = \log(c) + \log f(x)\\
\Delta\log \pi(x) &= \Delta \log f(x).
\end{align*}
Thus, the normalizing constant is not required.


Como acessar a câmera do celular via Web Site?

Question: Tem como acessar a câmera do celular em um sistema web(Não é app) utilizando javascript?

Qual a solução para isso?
Comment: Configura minha resposta Igor, eu testei e funcionou!
Comment: Ok. Irei testar, obrigado Marconi!
Answer: Aqui nessa resposta How to access a mobile's camera from a web app?
No iPhone iOS6 e do Android ICS em diante, o HTML5 tem a seguinte tag, que permite que você tire fotos do seu dispositivo:
 <input type="file" accept="image/*" capture="camera">

capture pode ter valores como câmera, filmadora e áudio.
Comment: Então, eu gostaria de acessar o recurso(Câmera) direto, sem ter que selecionar a imagem.
Answer: O html5 permite isso utilizando o tag
capture="camera"

Comment: Qual tag? Não está clara sua resposta


How to deal with NSError in an iphone application?

Question: Is there a good way to deal with NSError in ios development?I was going trough some online references and i found that most of them were using [NSApp presentError] to present the error??
This is definitely not possible in ios as there is nothing called NSApp in the ios realm..
I was wondering how should one go about handling NSErrors other than just printing what
the error really is using [error localizedDescription]
Should one access the error code property of the NSError class and handle all the possible
error codes that one might expect in a particular situation using an else if/ladder??
**It would also be helpful if one could explain the major difference between NSError and
NSException? an why we have two seperate thing at the first place**
Answer: An NSError is a return code, where you tried to do something, but what you tried didn't work.  For example, you tried to open a file, but it wasn't there.  An NSError indicates an error condition where, with the same call on a different set of circumstances, you might not get an error (the file is there). An NSException indicates something fatally bad.  You tried to write to null, you tried to write past the end of a string or an array.  NSExceptions should be cleaned up by you, the programmer, NSErrors may just be happenstance errors.
What you do with an NSError is dependent on context.  Sometimes you want to notify the user with an alert, sometimes you want to ignore it (like you test for a resource that's not there before you write a new one).  Probably at the very least, you want to NSLog your NSErrors (given that you use a macro to strip NSLogs out of your final code).
Answer: Whatever you do with NSErrors depends on your particular application, just use common sense.
Unlike other languages like Java exceptions are resource-intensive in Objective-C. Therefore,

Use exceptions to indicate non-recoverable program errors. The program catching such an exception should quit soon afterwards. Frameworks are not designed to let you recover from exceptions.
Don't use exceptions to indicate user errors, recoverable errors, or for general flow-control. These cases should handled with NSError instead.


Yii 2 Getting unknown property: common\models\User::newMessagesCount

Question: i'm trying to build forum in my website using Yii2 Podium. But after I installed it I can't access the

podium/home

and I got this message :
Unknown Property – yii\base\UnknownPropertyException
Getting unknown property: common\models\User::newMessagesCount

and this is the Component file

in C:\xampp\htdocs\tugasakhir\vendor\yiisoft\yii2\base\Component.php

public function __get($name)
{
    $getter = 'get' . $name;
    if (method_exists($this, $getter)) {
        // read property, e.g. getName()
        return $this->$getter();
    }

    // behavior property
    $this->ensureBehaviors();
    foreach ($this->_behaviors as $behavior) {
        if ($behavior->canGetProperty($name)) {
            return $behavior->$name;
        }
    }

    if (method_exists($this, 'set' . $name)) {
        throw new InvalidCallException('Getting write-only property: ' . get_class($this) . '::' . $name);
    }

    throw new UnknownPropertyException('Getting unknown property: ' . get_class($this) . '::' . $name);
}

What would be the problem?
Comment: the error is in `User` Model inside your `common/models` folder it cannot find the field name in the table `user` you must be running a select query with count and `newMessagesCount` is an alias. is it true?
Comment: update your question and add  your User model
Answer: You don't have to change anything in \vendor\yiisoft\yii2\base\Component.php, but you have to controllorae as they set the variables in \models\user.


Using the Heine-Borel theorem to show compactness of an ellipsoid

Question: I want to show that $E$ is compact in $\mathbb{R}^3$ where
$$E=\left\{(x,y,z)\in \mathbb{R}^3\;\middle|\;\frac{x^2}{4}+\frac{y^2}{4}+\frac{z^2}{9} =1\right\}$$
Now boundedness, doesn't that require a metric? Well, if I use the Euclidean metric (maybe I need to use this metric to employ the Heine-Borel theorem), take $O=(0,0,0)$ and then $d(O,x)\lt 5$ for all $x\in E$. Hence $E$ is bounded.
Now I need to show that $E$ is closed.
How would I show closure? I can 'see' that all neighborhoods of a point will have another point within them. But I am not sure how to show this properly
Comment: to show closure, you might show that $E$ is the inverse image of a closed set of $\mathbb{R}$ through a continuous function...
Comment: You're missing $\le1$ in the defining conditions, I believe.
Comment: @egreg Sorry haha
Comment: Observe that E is the level set of a continuous function. Does that help?
Comment: @JónÁskellÞorbjarnarson What is a level set?
Answer: The set is
$$
E=\left\{(x,y,z)\in \mathbb{R}^3\;\middle|\;\frac{x^2}{4}+\frac{y^2}{4}+\frac{z^2}{9}= 1\right\}
$$
If $\|(x,y,z)\|>3$, then $(x,y,z)\notin E$, because from $x^2+y^2+z^2>9$ we deduce
$$
\frac{x^2}{4}+\frac{y^2}{4}+\frac{z^2}{9}
\ge\frac{x^2}{9}+\frac{y^2}{9}+\frac{z^2}{9}>1
$$
and so $(x,y,z)\notin E$. Therefore $E$ is bounded.
Since $E$ is the inverse image of $\{1\}$ under the continuous function
$$
f\colon \mathbb{R}^3\to\mathbb{R},
\quad
f\colon(x,y,z)\mapsto\frac{x^2}{4}+\frac{y^2}{4}+\frac{z^2}{9}
$$
the set $E$ is closed.
Note that the Heine-Borel theorem requires using the Euclidean metric.
Comment: @SkiesBurn A set is closed if and only if its complement is open; the inverse image of the complement of a set is the complement of the inverse image of the set.
Comment: What is the theorem for pre image of a continuous function, thus closed?
Comment: @SkiesBurn A function is continuous if and only if inverse images of open sets are open, which is equivalent to saying that inverse images of closed sets are closed.
Comment: continuous iff inverse image of open set is open

And since our function is continuous, we know that our closed point $\{1\}$ can't map to an 'open' $E$, so $E$ isn't open, nor clopen, and the only thing left is closed, so it must be closed?
Comment: @SkiesBurn The function is continuous, so the inverse image of the closed set $\{1\}$ is closed. You seem to believe that a set is closed if it's not open, which is false: a set may be neither open nor closed.
Comment: Well then how does 'a function is continuous if and only if inverse images of open sets are open' itself imply that 'inverse images of closed sets are closed'? Given that they aren't opposites, sorry just trying to understand
Comment: I am kindly surprised to see you using `\;\middle|\;` rather than `\mathrel{}\middle|\mathrel{}`.
Comment: @AsafKaragila That would leave too much space: two thick spaces on the left and on the right, because `\middle|` is an Ord atom. The proper way should be `\mathrel{-\mskip\thickmuskip}\middle|\mathrel{-\mskip\thickmuskip}` but in this case it's overkill.
Comment: I knew that `\middle|` by itself produces insufficient spacing. The proper way seems quite an overkill here. But I'll try to remember it for my usual batch of macros. Thanks!
Answer: To show that the set is closed, let $\{ (x_n,y_n,z_n) \}_{n=1}^{\infty}$ be a sequence of points on the ellipsoid that converges in $\mathbb{R}^{3}$ to some $(x,y,z)$. Then $x_n \rightarrow x$, $y_n \rightarrow y$, and $z_n\rightarrow z$. Therefore,
$$
        \frac{x^{2}}{4}+\frac{y^{2}}{4}+\frac{z^{2}}{9} = \lim_{n}\frac{x_n^{2}}{4}+\frac{y_n^{2}}{4}+\frac{z_n^{2}}{9} = \lim_n 1 = 1.
$$
So $(x,y,z)$ is on the ellipsoid, which means the ellipsoid is closed.
You can show compactness using this because, if $\{ (x_n,y_n,z_n) \}$ is any sequence of points on the ellipsoid, then $\{ x_n \}$ is bounded by $2$, $\{ y_n \}$ is bounded by $2$, and $\{ z_n \}$ is bounded by $3$. So you can choose a subsequence of the points that converges in the $x$ coordinate, and then choose a subsequence of the subsequence that converges in the second coordinate (the subsequence of the subsequence will converge in $x$ automatically because a subsequence of a convergent sequence is convergent)... continuing, you obtain a subsequence $\{ (x_{n_k},y_{n_k},z_{n_k}) \}$ that converges in all three coordinates; then the argument of the first paragraph shows that the limit of this subsequence will be on the ellipsoid.
Comment: So we know any sequence of points must converge to a point on the ellipsoid, thanks!
Answer: The closure comes from the fact that {0} is closed and the surface itself is the inverse image of {0} of the continuous function x^2/4+y^2/4+z^2/9-1. The boundedness comes from ability of enclosing the surface inside the sphere x^2+y^2+z^2=100


Obtain MAC address of remote, unconfigured device?

Question: I have a device that goes on the network.  I need it's MAC address.  There is no label on it.  How do I do that?  I have no access to the device itself.  I can power it on and plug it in to a switch or a laptop, and that's it.  There is no serial port or any other way of interfacing with the device.
To stave off the inevitable, but irrelevant, questions... we need the MAC address to "register" it on the network.  Then it can get an IP address, and then "somebody else" accesses and configures it.  It's a black box to us, but we have to have a MAC to register it.  Yes, this is insane, but we did not design the device or decide to ship it without a label :-)  Please, no responses about how this makes no sense... we know.
Comment: Boot the device up, look at your DHCP server logs for the MAC address.
Comment: What @yoonix said. Or, look at the CAM table of the switch it's connected to.
Comment: Can't - we have no access to the DHCP server.  There is an interface for the switch which might show this.  But I'm looking for some test that I can positively perform... connect a cable to the device and do X to discover the MAC.  If I had a Linux laptop I could install dhcpd, but the only systems I have ready access to are Apple Macs.
Comment: You didn't specify your os. If you run unix you might look to `arp-scan`
Comment: Anything arp related will require it to be configured with an IP address
Answer: Connect to the device via a crossover cable or on the same network segment (preferred) via a switch/hub and run a network sniffer (netmon/wireshark/tcpdump) in promiscuous mode to identify the MAC address of the black box.
Answer: If you can connect physically to the device, or at least to the same network segment, you might be able to use
<code>arp -a
</code>
to show you the mac address table on your server.
Comment: being connected to same network segment does not guarantee the presence of entry in the host's arp table
Comment: It would require an IP address to have an entry in the arp table


Xpages mobile controls not visible on browser

Question: I am extremely new for mobile controls of xpages, according to the documentation, I have changes the setting in the "Xsp Properties page" selected the check-box "use mobile theme for Xpages with prefix: _m".
Then checked into the source tab and the status is
xsp.ajax.renderwholetree=false
xsp.error.page.default=true
xsp.library.depends=com.ibm.xsp.extlib.library,com.ibm.xsp.extlibx.library
xsp.persistence.mode=file
xsp.resources.aggregate=true
xsp.theme=oneuiv2.1
xsp.theme.mobile.pagePrefix=m_

Then I have stated with the test xpages using mobile controls The code for test page is
    <?xml version="1.0" encoding="UTF-8"?>
<xp:view xmlns:xp="http://www.ibm.com/xsp/core"
    xmlns:xe="http://www.ibm.com/xsp/coreex">
    <xe:singlePageApp id="singlePageApp1"
        selectedPageName="topicList">
        <xe:appPage id="appPage2" pageName="topicList">
            <xe:dataView id="dataView1">
                <xe:this.data>
                    <xp:dominoView var="view1" viewName="topic"></xp:dominoView>
                </xe:this.data>
                <xe:this.summaryColumn>
                    <xe:viewSummaryColumn columnName="subject"></xe:viewSummaryColumn>
                </xe:this.summaryColumn>
                <xe:this.extraColumns>
                    <xe:viewExtraColumn columnName="MainContent"></xe:viewExtraColumn>
                    <xe:viewExtraColumn></xe:viewExtraColumn>
                </xe:this.extraColumns>
            </xe:dataView>
            <xe:djxmHeading id="djxmHeading1" label="Topics"></xe:djxmHeading></xe:appPage>
        <xe:appPage id="appPage1" pageName="topicDetails">
            <xe:djxmHeading id="djxmHeading2" label="Details"
                back="Back" moveTo="topicList">
            </xe:djxmHeading></xe:appPage>
    </xe:singlePageApp>
              </xp:view>

No errors shows in designer and when i am trying see the result in safari browser or any browser it returns a blank page.
 I am not getting exactly what I an missing,and why I am not able see the page layout in browser.
Any suggestion will be helpful for me,
I could see the result as

Edit 2:error caught in console
Comment: errors may be hiden. take a look into IBM_TECHNICAL_SUPPORT directory on server for xpages*.log files, it may contain something useful
Comment: I have just now checked the logs there is no error returned
Answer: Best guess is that you haven't included the "m_" prefix on the name of the XPage. What did you call the XPage? It should be something like m_thexpage, thus the XPages runtime sees the m_ prefix and knows to render the page using the mobile theme. If it's completely blank, it also suggests there are no documents in the view.
From the comments below:

Server version is 8.5 and the extension library is 9.0 –  Ajit Hogade

I'm afraid you can't install a 9.0 extlib on top of an 8.5 server. The 9.0 extlib is dependent on features from the 9.0 xpages runtime. To use 9.0 extlib, you will need to upgrade your domino server to match. This explains why the mobile stuff isn't working for you.

finally i found the error in browser console which image i have uploaded in new the edit. Agree with the comment about the version difference,but as far, I am using this I found no problem with the extension library controls with works perfectly fine in the browser, the only issue I had with mobile controls. –  Ajit Hogade 7 mins ago

You are lucky not to have experienced other problems. The 9.0 ExtLib expects to have Dojo 1.8.1, which is part of the 9.0 domino server. The 8.5 domino server has a much older version, 8.5.3 = dojo 1.6.1, 8.5.2 = dojo 1.4.3. The mobile controls are heavily dependent on dojo, so the version mis-match is undoubtedly the root of your problem, illustrated by the error you found in the browser console.
Comment: I have a page name m_mob.xsp and even I have crossed checked with the view data which has 5 documents.
Comment: What version is the server, and what ExtLib is installed on it? Use the server console command "tell http osgi ss com.ibm.xsp.extlib" to see the list of installed plugins
Comment: Also, when you say "blank page" what exactly do you see? Do you see a blank white page, a blank black page, do you see heading with no documents? Just to be 100% clear on what you are experiencing
Comment: Just now I have edited the question with the browser view picture,So the above image is the result,
Comment: Server version is 8.5 and the extension library is 9.0
Comment: I'm afraid you can't install a 9.0 extlib on top of an 8.5 server. The 9.0 extlib is dependent on features from the 9.0 xpages runtime. To use 9.0 extlib, you will need to upgrade your domino server to match. This explains why the mobile stuff isn't working for you.
Comment: finally i found the error in browser consol which image i have uploaded in new the edit.
Comment: Agree with the comment about the version difference,but as far, I am using this I found no problem with the extension library controls with works perfectly fine in the browser, the only issue I had with mobile controls.
Comment: You are lucky not to have experienced other problems then. The 9.0 ExtLib expects to have Dojo 1.8.1, which is part of the 9.0 domino server. The 8.5 domino server has a much older version, 8.5.3 = dojo 1.6.1, 8.5.2 = dojo 1.4.3. The mobile controls are heavily dependent on dojo, so the version mis-match is undoubtedly the root of your problem, illustrated by the error you found in the console.
Answer: Mobile controls are specifically for browsers on mobile devices. The XPages runtime can identify the device requesting the page and use controls accordingly. So they're unlikely to render for desktop browsers.
Use a user agent switcher to test mobile controls in a desktop browser. However, bear in mind that this does not guarantee complete fidelity with the appropriate mobile device's browser.
Comment: I have just now tried with the user agents switcher, but no change,Is there any thing which I am missing in configuration?Is it mandatory to create a separate nsf database use mobile-controls?I have made this test page in existing database which runs on browser.


How to set the last n bits of a given octet (byte) to zero?

Question: I got a octet (byte) and a number of relevant-bits and I want to keep the first n (relevant-bits) of that given byte and set the remaining bits to zero.
E.g.
The number 217 where the first 4 bits are relevant would convert to
208
0                    0
0 1 2 3 4 5 6 7      0 1 2 3 4 5 6 7
+-+-+-+-+-+-+-+  ==> +-+-+-+-+-+-+-+
1 1 0 1 1 0 0 1      1 1 0 1 0 0 0 0

The number 255 where the first 8 (or greater) bits are relevant would not change at all
0                    0
0 1 2 3 4 5 6 7      0 1 2 3 4 5 6 7
+-+-+-+-+-+-+-+  ==> +-+-+-+-+-+-+-+
1 1 1 1 1 1 1 1      1 1 1 1 1 1 1 1

I wrote this function to solve the problem
(defun list-of-bits (integer)
  (let ((bits '()))
    (dotimes (position (integer-length integer) bits)
      (push (ldb (byte 1 position) integer) bits))))

(defun calculate-octet (byte rel-bits)
  (if (< rel-bits 8)
      (parse-integer
       (FORMAT nil "~{~a~}"
           (replace (list-of-bits byte)
            '(0 0 0 0 0 0 0 0)
            :start1 rel-bits
            :end1 8
            :start2 0
            :end2 rel-bits))
       :radix 2)
      byte))

But this solution seems bad for two reasons

it splits the integer into a list before processing it
it prints the list into a string which is again parsed

I know that common-lisp provides functions to directly access the bits and bytes (ldb,logbitp) but I could not figure out a way to use them for my problem.
Is there a way to solve the problem more efficient (or at least more elegant)?
Answer: CL-USER 6 > (mask-field (byte 4 4) 217)
208

Note also that it does not mask the field of the original number, but returns a new number with the bit field masked.
Comment: @Sim: not really, we want to mask 4 bits, not 8. `byte` takes *size* and *position*. We want to mask 4 bits from position 4 onwards. We don't want to mask 8 bits from position 4 onwards. For this question it makes no difference, since there are only 8 bits in the byte. Thus the bits from 0..7 are interesting and the bits from 8.. onwards are zero anyways.
Comment: wouldn't it have to be `(mask-field (byte 8 (- 8 relevant-bits)) byte)` to work?
Comment: I wonder why this is not accepted answer, it seems to be most natural solution.
Answer: There are already three answers, so I may as well add another two:
No one suggested DPB yet.  Always nice with a nod to the PDP-10.
(defun calculate-octet (byte bits)
  (dpb 0 (byte bits bits) byte))

Again with the LOGAND.
(defun calculate-octet (byte bits)
  (logand byte (ash -1 (- 8 bits))))

Answer: ash does the trick:
(defun calculate-octet (byte bits)
  (let ((shift (- 8 bits)))
    (ash (ash byte (- shift)) shift)))

Testing:
? (calculate-octet 217 4)
208
? (calculate-octet 255 8)
255

Comment: works like a charm, only problem occurs when bits is greater 8. Simple if would fix that.
Comment: @Sim Your question was about an octet, so I assumed 8. You can either make the number of bits a parameter, or better, express the number of bits you want to set to 0.
Comment: no you are right, my bad, I assumed that a negative shift (e.g. 8 - 9 = - 1 -> shift = -1) would affect the number. But when testing it with a number greater 8 it turned out to work properly
Answer: I think what you need is LOGAND.
(defun calculate-octet (byte rel-bits)
  (ecase rel-bits
    (0 0)
    (1 (logand byte #b10000000))
    (2 (logand byte #b11000000))
    (3 (logand byte #b11100000))
    (4 (logand byte #b11110000))
    (5 (logand byte #b11111000))
    (6 (logand byte #b11111100))
    (7 (logand byte #b11111110))
    (8 byte)))

Comment: Here's a suitable situation for logandc2: `(logandc2 byte (1- (expt 2 rel-bits)))`
Comment: if you substitute `ecase` with `case` and `(8 byte)` by `(otherwise byte)` it works like a charm
Comment: Hardcoded masks for every value of `rel-bits`? This is not Lispy. -1


How can q(z,l,u,c|x) be factorized to q(z|x)q(l|x)q(c|z)q(u|c,z)?

Question: How can q(z,l,u,c|x) be factorized to q(z|x)q(l|x)q(c|z)q(u|c,z)?
I don't know what assumptions are behind this equation, which is I want to know. I think normal chain rule of probability is in the process, but only chain rule can't derive the formula.
What I know is that z, l, u follows gaussian distribution, and c follows multinomial distribution.
It's from the paper Xu C, Lopez R, Mehlman E, Regier J, Jordan MI, Yosef N. Probabilistic harmonization and annotation of single-cell transcriptomics data with deep generative models. Mol Syst Biol. 2021 Jan;17(1):e9620. doi: 10.15252/msb.20209620. PMID: 33491336; PMCID: PMC7829634.
That formula is used for derive ELBO, since the model is similar to VAE.
Comment: Does this perhaps arise in a book or paper you're reading? It would be helpful to know the citation for context.
Comment: It's from paper 'Probabilistic harmonization and annotation of single-cell transcriptomics data with deep generative models'

https://www.embopress.org/doi/full/10.15252/msb.20209620

That formula is used for derive ELBO, since the model is similar to VAE.
Answer: It is a basic theorem of conditional probability that $$P(A,B \mid C) = P(A \mid B,C) \cdot P(B \mid C).$$
Furthermore, if $A$ and $B$ are conditionally independent given $C$, then $P(A \mid B,C) = P(A \mid C)$, and so $$P(A,B \mid C) = P(A \mid C) \cdot P(B \mid C).$$
Conversely, if $A$ depends on $C$ only via $B$, then $P(A \mid B,C) = P(A \mid B)$, and so $$P(A,B \mid C) = P(A \mid B) \cdot P(B \mid C).$$
The factorization $q(z,l,u,c \mid x) = q(z \mid x)q(l \mid x)q(c \mid z)q(u \mid c,z)$ given in your question can thus be interpreted as a description of how the various variables are assumed to (approximately) depend on each other.  In particular, we can see that:

$z$ and $l$ are assumed to be conditionally independent, given $x$; and
$c$ and $u$ are assumed to depend on $x$ only via $z$ (and to be conditionally independent of $l$).

(Note that we cannot say anything about the dependence between $c$ and $u$, except that it is assumed to be potentially non-negligible.  In particular, $q(c \mid z) q(u \mid c,z)$ and $q(c \mid u,z) q(u \mid z)$ are both equally valid factorizations of $q(c,u \mid z)$.  Remember that statistical dependence is not causality, and always goes both ways, even when the notation might make it look otherwise.)
Answer: It can't be factorised that way.  The paper doesn't claim it can. What they say is that they are computing a variational approximation using a product of that form. It's fairly common for variational approximations to be products, even when the true posterior or likelihood doesn't factorise as a product of independent components.
Comment: @NeverneverNever if you feel you know the answer to the question, you can write your own answer. Doing so will help future readers with the same question & allow you to accrue more points.
Comment: I know it can't be derived the formula exactly, but I wanted to know how they assume this way, e.g) they assume some distributions are independent, and use chain rule to derive this assumption.

but I think I found my answer by myself now. And thank you for your time and answer.
Answer: In general $P(XY | A) = P(X | YA) P(Y | A)$.
If $X$ and $Y$ are conditionally independent given $A$ then $P(X | YA) = P(X | A) $ and $P(XY | A) = P(X | A) P(Y | A)$.
For your problem, if you assume the appropriate conditional independence structure for your variables, you can write that factorization.
I haven't looked at that paper, but something that's extremely common is to make some assumptions about what's conditionally independent of what to make the model more tractable and useful. In the best case, the assumptions are true (or in some sense close to true)! In other settings, the assumptions are even clearly false (e.g. Naive Bayes applied to language) but still produces useful enough results compared to alternatives that the assumptions are deemed worth making.
I often come back to the aphorism of George P. Box that "all models are wrong, but some are useful."


How to override default cardinality for the field widget?

Question: I've custom widget which consist multiple input elements in hook_field_widget_form() as part of one field (like address field).
The problem is that Drupal complains about:

this field cannot hold more than @count values

which happens in field_default_validate(), when I've multiple input filled, so it doesn't recognise that this is one single field.
I've tried to change my cardinality in every possible place as below, but without success:
/**
 * Implements hook_field_info().
 */
function my_address_field_field_info() {
  return [
    'my_address_field' => [
      'label' => t('My Address Field'),
      'settings' => array('cardinality' => FIELD_CARDINALITY_UNLIMITED),
      'instance_settings' => array('cardinality' => FIELD_CARDINALITY_UNLIMITED),
      'default_widget' => 'my_address_field_widget',
      'default_formatter' => 'my_address_field_default',
      'cardinality' => FIELD_CARDINALITY_UNLIMITED,
    ],
  ];
}

/**
 * Implements hook_field_widget_info().
 */
function my_address_field_field_widget_info() {
  return [
    'my_address_field_widget' => [
      'label' => t('Default'),
      'field types' => ['my_address_field'],
      'settings' => array(
        'size' => 60,
        'cardinality' => FIELD_CARDINALITY_UNLIMITED,
      ),
      'behaviors' => array(
        'multiple values' => FIELD_BEHAVIOR_NONE,
        'default value' => FIELD_BEHAVIOR_NONE,
      ),
      'cardinality' => FIELD_CARDINALITY_UNLIMITED,
    ],
  ];
}

/**
 * Implements hook_field_widget_properties_alter().
 */
function my_address_field_field_widget_properties_alter(&$widget, $context) {
  $widget['cardinality'] = FIELD_CARDINALITY_UNLIMITED;
}

/**
 * Implements hook_field_formatter_info().
 */
function my_address_field_field_formatter_info() {
  return [
    'my_address_field_default' => [
      'label' => t('Default'),
      'field types' => ['my_address_field'],
      'multiple values' => FIELD_BEHAVIOR_DEFAULT,
    ],
  ];
}

/**
 * Implements hook_field_widget_form().
 */
function my_address_field_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {

  $widget = array();
  $widget['label'] = array(
    '#title' => $instance['label'],
    '#theme' => 'form_element_label',
  );
  $widget['address_line_1'] = array(
    '#type' => 'textfield',
    '#title' => t('Address line 1'),
  );
  $widget['address_line_2'] = array(
    '#type' => 'textfield',
    '#title' => t('Address line 2'),
  );
  // more text fields here ...

  return $widget;
}

Including defining hook_field_validate which I thought it'll override default field validation handler, but this was not the case.
What's the right way of assigning unlimited cardinality for my widget?
Comment: The problem might be in `hook_field_widget_form()` (you might need to go one level deeper in the array you return), could you add your code for that function?
Comment: @Clive I've added my implementation of hook_field_widget_form. Possibly that I'm implementing multi-input field in the wrong way, and it needs to be rewritten as Drupal treats them as separate elements. So as simple workaround I wanted to disable the validation, but it seems it's not possible.
Comment: It's hard to say what's wrong just by looking at the code. How can I reproduce this? Do you also have a schema? By the way, have you looked at the [multifield module](https://www.drupal.org/project/multifield)?
Answer: You can use Field instance cardinality module which allows the cardinality of specific instances of fields to be overridden.

This module allows the cardinality of specific instances of fields to be overridden.
This currently only works with fields that use options widgets (ie select list or checkboxes), and only allows them to be overridden to be single-valued.
Comment: Hello. Could you add excerpt from module page?
Answer: Since the widget form (hook_field_widget_form) returns multiple elements at once, by default Drupal recognise them as multiple values of one widget. To override that behaviour, you need to define your properties  in property_callbacks hook as part of your hook_field_info which can return value of your property (in the format documented for your data type). See: Entity property information.
Then make sure corresponding properties have their Field API schema for a field structure by implementing hook_field_schema in your .install file. Also don't forget to define hook_field_is_empty which tell what constitutes an empty item for a field type.
Here is example code:
/**
 * Implements hook_field_schema().
 *
 * This should be placed in .install file.
 */
function MYMODULE_field_schema($field) {
  $column_names = array(
    'addressline1',
    'addressline2',
  );
  $columns = array();
  foreach ($column_names as $column_name) {
    $columns[$column_name] = array(
      'type' => 'varchar',
      'length' => 255,
      'not null' => FALSE,
    );
  }
  return array(
    'columns' => $columns,
  );
}

/**
 * Implements hook_field_info().
 */
function MYMODULE_field_info() {
  return array(
    'MYFIELD' => array(
      'label' => t('My Field'),
      'description' => t('Provides a custom field.'),
      'settings' => array(),
      'instance_settings' => array(),
      'property_type' => 'MYFIELD',
      'property_callbacks' => array('MYMODULE_property_info_callback'),
    ),
  );
}

/**
 * Callback to alter the property info of custom field.
 */
function MYMODULE_property_info_callback(&$info, $entity_type, $field, $instance, $field_type) {
  $name = $field['field_name'];
  $property = &$info[$entity_type]['bundles'][$instance['bundle']]['properties'][$name];

  $property['type'] = 'MYFIELD';
  $property['getter callback'] = 'entity_metadata_field_verbatim_get';
  $property['setter callback'] = 'entity_metadata_field_verbatim_set';

  unset($property['query callback']);
}

/**
 * Implements hook_field_is_empty().
 */
function MYMODULE_field_is_empty($item, $field) {

  // Check if required address components are empty.
  foreach (array('addressline1', 'addressline2') as $required_component) {
    if (empty($item[$required_component])) {
      return TRUE;
    }
  }

  return FALSE;
}

For complete example, check how Address Field module implements its field properties, so they work correctly with cardinality settings.
See also: How to write a property callback for a custom field


Checking if a class has been instantiated in iOS

Question: I am trying to check to see if a class has been instantiated in iOS.  If it has been instantiated then I want to release it.
something like
for (UIView* views in self.view.subviews) {
        if ([views isKindOfClass:[CCGLView class]])
            [views removeFromSuperview];
    }

For that's when I already know the it's a some sort UIViews, but how do I check for other classes?
Comment: You don't need to check.  You can message nil in ObjC.
Comment: Check this https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/ObjCRuntimeRef/Reference/reference.html
Comment: I looking for example code.
Comment: I'm getting the impression that you want to find out if an instance of class XYZ exists or not, or find all such instances.  AFAIK, there's no way to do this (in the general case) unless you keep track of the instances yourself (for which there are several possible techniques).
Answer:
I am trying to check to see if a class has been instantiated in iOS.

You don't need to.  Objective-C allows you to message nil without any adverse side effects.  Besides, subviews are not allowed to be nil, because they are added to an internal NSMutableArray, which, in turn, doesn't allow nil pointers to be added to itself.

For that's when I already know the it's a some sort UIViews, but how do I check for other classes?

If you're looking to release every UIView (and related subclasses), you don't need to be as specific in your comparison, seeing as the base class (UIView) is the one that declares removeFromSuperview, which in turn, solves the deallocation portion of your question.  When a view is removed from it's superview, it's reference count is decreases by one.
Now that I have a little more context, what you're asking for is trivial.  If you're using ARC, this snippet here will find all objects of type CustomClass, then set them to nil.
for (NSObject *object in self.someCollection) {
    if ([object isKindOfClass:[CustomClass class]])
        object = nil;
}

If you're using MRC (and if you are, what the heck is wrong with you?), then you should, in fact, check for it being an active instance.
for (NSObject *object in self.someCollection) {
    if ([object isKindOfClass:[CustomClass class]] && object != nil) {
        [object release];
    }
}

Comment: for example, if I have MyClass got instantiated? How does Message nil would check for this? I am not too clear.  Give one or two lines of codes for clarification.
Comment: No, you're thinking too hard about this.  You don't need to check if an object is nil because you can message nil!  If you wanted to send nil removeFromSuperview, you could.
Comment: No, MyClass is not a View class it's some kind of class. Cannot removeFromSuperview.
Comment: Then do what you did before, check for a class, then set the pointer to nil (under arc), or call release.
Comment: OK, I want to know what's self.someCollection?  That someCollection must be category of class like self.view.suviews.  Can I say self.MyClass?
Comment: No.  Do you know what a collection is?  Perhaps you need to read a little more into what ObjC is, and how it works.


Questions about specifying linear mixed models in R for repeated measures data with additional nesting structure

Question: Data Structure
<code>> str(data)
 'data.frame':   6138 obs. of  10 variables:
 $ RT     : int  484 391 422 516 563 531 406 500 516 578 ...
 $ ASCORE : num  5.1 4 3.8 2.6 2.7 6.5 4.9 2.9 2.6 7.2 ...
 $ HSCORE : num  6 2.1 7.9 1 6.9 8.9 8.2 3.6 1.7 8.6 ...
 $ MVMNT  : Factor w/ 2 levels "_Withd","Appr": 2 2 1 1 2 1 2 1 1 2 ...
 $ STIM   : Factor w/ 123 levels " arti"," cele",..: 16 23 82 42 105 4 93 9 34 25 ...
 $ DRUG   : Factor w/ 2 levels "Inactive","Pharm": 1 1 1 1 1 1 1 1 1 1 ...
 $ FULLNSS: Factor w/ 2 levels "Fasted","Fed": 2 2 2 2 2 2 2 2 2 2 ...
 $ PATIENT: Factor w/ 25 levels "Subj01","Subj02",..: 1 1 1 1 1 1 1 1 1 1 ...
 $ SESSION: Factor w/ 4 levels "Sess1","Sess2",..: 1 1 1 1 1 1 1 1 1 1 ...
 $ TRIAL  : Factor w/ 6138 levels "T0001","T0002",..: 1 2 3 4 5 6 7 8 9 10 ...
</code>
Full Model Candidate
<code>model.loaded.fit <- lmer(RT ~ ASCORE*HSCORE*MVMNT*DRUG*FULLNSS
                              + (1|PATIENT) + (1|SESSION), data, REML = TRUE)
</code>

Reaction times from trials are clustered within sessions, which in turn are clustered within patients
Each trial can be characterized by two continuous covariates of ASCORE and HSCORE (ranging between 1-9) and by a movement response (withdraw or approach)
Sessions are characterized by drug intake (placebo or active pharmacon) and by fullness (fasted or pre-fed)

Modeling and R Syntax?
I'm trying to specify an appropriate full model with a loaded mean structure that can be used as a starting point in a top-down model selection strategy.
Specific issues:

Is the syntax correctly specifying the clustering and random effects?
Beyond syntax, is this model appropriate for the above within-subject design?
Should the full model specify all interactions of fixed effects, or only the ones that I am really interested in?
I have not included the STIM factor in the model, which characterizes the specific stimulus type used in a trial, but which I am not interested to estimate in any way - should I specify that as a random factor given it has 123 levels and very few data points per stimulus type?
Comment: Hi @Cel, it looks like you've got *ALL* interactions in the model, including the 5-way, 4-way and 3-way interactions. I'm not sure about this case, but that will typically wildly overfit the data, which will make your results less generalizable. Backward selection (if you must use it) does not need to start with a completely saturated model - it should start with the largest model you find plausible. Can you reduce that at all?
Comment: if i cannot find advice here i really dont know who i could ask? maybe you know of any dedicated mixed models forums or even an expert willing to consult for a little money?
Comment: @Macro great to know, i'll include only the interactions that seem plausible then. do you have suggestions regarding the other issues? if you do, maybe put it as an answer so i could accept it.
Answer: I will answer each of your queries in turn.
Is the syntax correctly specifying the clustering and random effects?
The model you've fit here is, in mathematical terms, the model
$$ Y_{ijk} = {\bf X}_{ijk} {\boldsymbol \beta} + \eta_{i} + \theta_{ij} + \varepsilon_{ijk}$$
where

$Y_{ijk}$ is the reaction time for observation $k$ during session $j$ on individual $i$.
${\bf X}_{ijk}$ is the predictor vector for observation $k$ during session $j$ on individual $i$ (in the model you've written up, this is comprised of all main effects and all interactions).
$\eta_i$ is the person $i$ random effect that induces correlation between observations made on the same person. $\theta_{ij}$ is the random effect for individual $i$'s session $j$ and $\varepsilon_{ijk}$ is the leftover error term.
${\boldsymbol \beta}$ is the regression coefficient vector.

As noted on page 14-15 here this model is correct for specifying that sessions are nested within individuals, which is the case from your description.
Beyond syntax, is this model appropriate for the above within-subject design?
I think this model is reasonable, as it does respect the nesting structure in the data and I do think that individual and session are reasonably envisioned as random effects, as this model asserts. You should look at the relationships between the predictors and the response with scatterplots, etc. to ensure that the linear predictor (${\bf X}_{ijk} {\boldsymbol \beta}$) is correctly specified. The other standard regression diagnostics should possibly be examined as well.
Should the full model specify all interactions of fixed effects, or only the ones that I am really interested in?
I think starting with such a heavily saturated model may not be a great idea, unless it makes sense substantively. As I said in a comment, this will tend to overfit your particular data set and may make your results less generalizable. Regarding model selection, if you do start with the completely saturated model and do backwards selection (which some people on this site, with good reason, object to) then you have to make sure to respect the hierarchy in the model. That is, if you eliminate a lower level interaction from the model, then you should also delete all higher level interactions involving that variable. For more discussion on that, see the linked thread.
I have not included the STIM factor in the model, which characterizes the specific stimulus type used in a trial, but which I am not interested to estimate in any way - should I specify that as a random factor given it has 123 levels and very few data points per stimulus type?
Admittedly not knowing anything about the application (so take this with a grain of salt), that sounds like a fixed effect, not a random effect. That is, the treatment type sounds like a variable that would correspond to a fixed shift in the mean response, not something that would induce correlation between subjects who had the same stimulus type. But, the fact that it's a 123 level factor makes it cumbersome to enter into the model. I suppose I'd want to know how large of an effect you'd expect this to have. Regardless of the size of the effect, it will not induce bias in your slope estimates since this is a linear model, but leaving it out may make your standard errors larger than they would otherwise be.
Comment: wow. thank you Macro, i wish i could give more points.
Comment: Since the random effects are crossed rather than random, should the notation be $\eta_{i}$ and $\theta_{j}$ (rather than $\theta_{j}$), since since is crossed (and not nested) with patient?


Divisor on curves, Proposition (II.6.9) from Hartshorne

Question: I have some question related to the proof of Proposition (II.6.9) from  Hartshorne's book:

Let $f:X \rightarrow Y$ be a finite morphism of nonsingular curves over a field $k$. Then for any divisor $D$ on $Y$, $\operatorname{deg}f^*D=\operatorname{deg}f\operatorname{deg}D$.

In proof, let $Q$ be a closed point of $Y$ and let $V=\operatorname{Spec}B$ be an affine open of $Y$ containing $Q$. Let $K(X),K(Y)$ are the function field of$X,Y$, respectively.
Note that if $A$ is the integral closure of $B$ in $K(X)$, then $f^{-1}(V)=U=\operatorname{Spec}A$. Let $m_Q$ be the maximal ideal of $B$ and $t$ is a local parameter at $Q$ and let $C=A_{m_Q}$. Let $P_i \in X$ be such that $f(P_i)=Q$ and $m_i$ be a maximal ideal of $C$ corresponding to $P_i$.
I have three questions:

if $[K(X):K(Y)]=r$, then why $\operatorname{dim}_k(C/tC)=r$?
$tC=\cap_i(C_{m_i}\cap C)$?
$\operatorname{dim}_k(\mathcal{O}_{P_i}/t\mathcal{O}_{P_i})=v_{P_i}(t)$?, where $v_{P_i}$ is a valuation.
Answer: As far as I understand it:

As stated in the proof, $C$ is a free $\mathcal{O}_Q$-module of rank $r$. Furthermore, $v_Q(t) = 1$, in other words: $t \in m_Q$ and $t \not \in m_Q^2$ and thus $m_Q = (t)$ and  $t\mathcal{O}_Q = m_Q$. This gives $C/tC = (\oplus_{i = 1}^r \mathcal{O}_Q)/(\oplus_{i = 1}^r m_Q) = \oplus_{i = 1}^r (\mathcal{O}_Q/m_Q)$. $\mathcal{O}_Q/m_Q$ is the residue field of $Y$ at $Q$ and since $k$ is algebraically closed, the closed points of $Y$ are rational which means that the residue fields are isomorphic to $k$.
You probably mean $tC=\cap_i(tC_{m_i}\cap C)$. I think this is because $t \in m_i$ and thus $t$ is not invertible in $C_{m_i}$ and $tC_{m_i}\cap C = tC$.
$t \mathcal{O}_{P_i} = m_i^n$ for $n = v_{P_i}(t)$. Thus $\dim_k(\mathcal{O}_{P_i}/t\mathcal{O}_{P_i}) = n$.

I'm not very certain about these answers and would be grateful for any discussion/correction, since I'm learning the subject myself at the moment.


How to configure an authoritative time server in Windows Server

Question: I have a performance lab running behind a firewall, so none of the machines in the lab has internet access. All machines in the lab are part of a domain with the domain controller also present inside the lab. The problem is that some server's time are drifting heavily.
Some background info:
The DC is Win Server 2K3 Enterprise SP2.

9 machines are running Server 2K3 Standard. (These are all within 1 minute, so not a
problem)
3 machines are Win Server 2K8 R2 Standard (These are
Physical Servers) - (These vary by between 1 and 6 minutes and never
sync up again)
6 Machines are Win Server 2K8 R2 Core (These are Hyper-V hosts) (Some also Vary)

On those 6 machines we host 1 instance of Win 2K8 R2 Standard on each.(These vary by between 1 and 6 minutes and never sync up again)

1 machine running win 2K8 R2 Enterprise
acting as the SCVMM.(6 minutes out and never sync up again)

From the above, it seems the issue is with the 2008 servers.
I found the following:
How to configure an authoritative time server in Windows Server [to use an internal hardware clock]
http://support.microsoft.com/kb/816042
From here I have installed "Microsoft Fix it 50394" on PT-DC01 (The domain controller)
I also found:
How to configure an authoritative time server in Windows Server
http://support.microsoft.com/kb/816042
From here I have installed "Microsoft Fix it 50395" on SSVMM (A Server in the environment) with the following settings:

NtpServer: pt-dc01.pt.local,0x1
SpecialPollInterval: 900 (15 minutes*)
MaxPosPhaseCorrection: 3600 (1 Hour*)
MaxNegPhaseCorrection: 3600 (1 Hour*)

* Excluding anything in brackets obviously.
I've also restarted the Windows Time Service on both servers.  I've done only these two servers to prove that it works first. The problem is that it doesn't seem to: At time of writing SSVMM's time was 12:10 and PT-DC01's time was 12:04.
I checked in the registry and none of these values have changed so I manually updated the NtpServer and also left the MaxPosPhaseCorrection and MaxNegPhaseCorrection at 0xffffffff which means they will always update.
Restarting the servers had no effect.

c:\>w32tm /resync /nowait

had no effect
I also ran the following commands from http://www.zimbio.com/open+source+consulting/articles/193/Troubleshooting+w32tm+issues
<code>w32tm /config /manualpeerlist:"pt-dc01.pt.local",0×1 /syncfromflags:MANUAL
w32tm /config /update
net stop w32time
net start w32time
w32tm /resync /nowait
pause
</code>
Also with no effect. I also tried it with 0x8 instead of 0x1 in the first line.
Any help would be much appreciated.
Comment: NOTE: to specify multiple ntp servers use: `w32tm /config /manualpeerlist:"server1.com,0x1 server2.com,0x1" /syncfromflags:MANUAL`
Answer: All domain members should automatically sync their time with the domain controller that they authenticated against last. Those DCs will, in turn, sync from the DC with the PDC Emulator role on it. There's no need to get crazy with configuring this unless you have a real reason to. It's all default settings.
Comment: Yea, every peice of documentation I've read says the same thing. Thanks for the help.
Answer: If you are running some of the servers on AMD processors and the VMs (on the AMD-based boxes) do not have a "sync client time to host" option active, you will get some drift.  This appears to be AMD-specific, it does not affect Intel based chips.  The drift, however, is not something that will throw you off - we're talking seconds at worst.
Active Directory will auto-magically sync to domain controllers elsewhere (as pointed out by MarkM) but the period in which they do so is laughably long...sometimes several hours.  All of this occurs with Windows Time Service, which is (I believe) by default enabled.  Kerberos typically has a +/- 5 minute tolerance.  If you are drifting more than 5 minutes on your clocks, something is seriously wrong.
If you are desperate, and it continues despite all other efforts, you may want to get a 3rd party NTP service installed if it keeps up.  Install the service once, on physical hardware (not a VM!), and point all of the other machines at it.
Comment: Thanks for the reply Avery. The specific machines are fairly old... All the hardware that no-one else can use any more has been crammed together to create this lab. The DC is a Physical machine. We seem to be having this problem in other environments too. Some machines are running AMD processors, so this is something I can look deeper into.
Answer: The above is true only if you have NetBIOS enabled.
Also, for virtual servers running on Hyper-V: Hyper-V has a default setting when you create a virtual machine that states that the VM should synchronise it's time with the host. This seems to be enforced no matter what you do on the VM. So, either then make sure your host's time is synced with your PDC or disable the setting in Hyper-V (VM Properties -> Hardware Configuration -> Integration Services -> Time synchronisation).
Comment: I know this is really old, but do you have or even vaguely remember where you ran across this NetBIOS requirement?


Simple Android / Java Countdown App

Question: I'm trying to create a Countdown app for an event. I will need to subtract the current time from the future event time, and display the difference in Days, Hours, minutes and seconds.
So far I have managed to make an app that displays the time with this code below. What do I need to add to it to display the time until say Christmas, for example? Preferably the results would change in real time.
<code>    Calendar c = Calendar.getInstance();
    System.out.println("Current time => " + c.getTime());

    SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
    String formattedDate = df.format(c.getTime());

    text.setText(formattedDate);
</code>
Answer: <code> Calendar thatDay = Calendar.getInstance();
  thatDay.set(Calendar.DAY_OF_MONTH,25);
  thatDay.set(Calendar.MONTH,7); // 0-11 so 1 less
  thatDay.set(Calendar.YEAR, 1985);

  Calendar today = Calendar.getInstance();

long diff = today.getTimeInMillis() - thatDay.getTimeInMillis(); //result in millis
</code>
Here's an approximation...
<code>long days = diff / (24 * 60 * 60 * 1000);
</code>
Comment: sir...,.how can we add ,can you give any example
Comment: means http://stackoverflow.com/questions/21701393/android-how-to-make-calender-like-countdown-clock
Comment: i have used calender with timer its working..,but i want t o move it in opposite way.like thishttp://www.timeanddate.com/countdown/generic?iso=20140320T1257&p0=418&msg=Countdown+till+Spring+2014
Comment: see this http://www.timeanddate.com/countdown/generic?iso=20140320T1257&p0=418&msg=Countdown+till+Spring+2014
Comment: i want to do like this,currently my timer is working in forward mode.,i wnat to move it in reverse mode
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/47379/discussion-between-rajshree-and-digvesh-patel)
Comment: here is the link of chat
Answer: Also take a look at https://developer.android.com/reference/android/text/format/DateUtils.html
There are several support methods for caluclating time distances.

Simple Android / Java Countdown App


Python - Erro import pandas

Question: Pessoal estou com problemas quando tento usar o pandas no meu projeto, vejam esse erro:
File "c:\Users\jua2544825\Desktop\front_reembolso\main.py", line 10, in <module>
    from pandas import read_csv as pd
  File "C:\Users\jua2544825\AppData\Local\Programs\Python\Python39\lib\site-packages\pandas\__init__.py", line 16, in <module>
    raise ImportError(
ImportError: Unable to import required dependencies:
dateutil: No module named 'dateutil'

Alguém sabe o que pode estar ocasionando esse erro?
fiz a instalação do pandas normalmente, testei em outra maquina minha e funciona normalmente.
Answer: Você fez a instalação utilizando o pip?
pip3 install python-dateutil

Comment: FIz esse comando e funcionou, muito obrigado pela força :D

Python - Erro import pandas


$e \in C,$ then $e$ is a loop of $M,$ or $C - e$ is a circuit of $M/e.$

Question: Here is the relation I am trying to understand
Let $C$ be a circuit of a matroid $M.$ For e in $E(M)$:
If $e \in C,$ then $e$ is a loop of $M,$ or $C - e$ is a circuit of $M/e$ ( M contract e).
Does anyone has a justification for this idea? it is used a lot but I do not know why this is true.
Answer: Well, either $C = \{e\}$ or not, if it is, then $C$ is a loop. If not, then $|C|>1$ and in $M/e$ the independents are independents of $M$ such that when added $e$ they remain independent. In this way, $C$ is not independent, so its dependent. Furthermore, because $C$ is circuit if $f\in C\setminus \{e\}$ then $C\setminus \{f\}$ is independent and so $C\setminus \{f,e\}$ is independent in $M/e$ for every $f$, hence $C\setminus \{e\}$ is minimal dependent, which is the definition of being a circuit.
Comment: I did not get the general idea of the proof, could you please elaborate the ideas you are using more?
Comment: the following statement "in $M/e$ the independents are independents of $M$ such that when added $e$ they remain independent " I do not know from where did you get this idea? Is it from proposition 3.1.7 on pg. 101?
Comment: I mean in Oxley, second edition.


How do I allow SSH access to a range of IP's in AWS ec2 Security groups

Question: I want to allow access from 184.108.40.206 to 220.127.116.11 But amn't usre how to do this using CDIR notation.
(without explicitly allowing 18.104.22.168/24, 18.104.22.168/24 etc...)
Many thanks,
Danny.
Answer: There are tools online such as this one that will help you with this. When I input your IP range into that tool I get the following 3 CIDR groups
<code>18.104.22.168/20
18.104.22.168/22
22.214.171.124/24
</code>
So you would need to add three rules to the Security Group to effectively allow access to that entire IP range.


Como pego dados do Axios e retorno em um componente de função no React?

Question: Tô tentando pegar o id da URL, pra mostrar um post específico da API. Não posso usar componente de classe, porque useParams só funciona com funções. Eu tentei botar os dados dentro da variável post, mas não funcionou.
import { useParams } from "react-router-dom";
import axios from "axios";

const Post = () => {
    let params = useParams();
    let post = null;
    axios.get('https://jsonplaceholder.typicode.com/posts/' + params.post_id)
    .then(res => {
        post = res.data ? (

{res.data.title}

{res.data.body}

        ) : (

Loading post...

        );
    });

    return (

{post}

    )
}

export default Post

Answer: Não está funcionando pois vocẽ não está utilizando um estado, e sim uma variável normal. Dessa forma o react não "sabe" que ele tem que reagir a mudança deste estado.
Utilize o useState para definir qual o estado inicial e a função de alterar este estado;
import { useState } from "react";
import { useParams } from "react-router-dom";
import axios from "axios";

const Post = () => {
    let params = useParams();
    const [post, setPost] = useState(null);
    axios.get('https://jsonplaceholder.typicode.com/posts/' + params.post_id)
    .then(res => {
        setPost(res.data ?
        (

{res.data.title}

{res.data.body}

        )
        :
        (
Loading post...
));
    });

    return (

{post}

    )
}

export default Post


Laravel save updates another timestamp column

Question: I am having an issue when updating a column in a model with 2 timestamp column, where if you update one column, it also updates the other column for some reason, not only that, it is always -8 hours. Code snippet below.
$punchIn = $user->punches()
      ->whereNotNull('start')
      ->whereNull('end')
      ->firstWhere('schedule_id', $schedule->id);

if($punchIn) {
      // something is happening here during saving. it also updates the start column for some reason.
      // this thing substracts 8 hours from the end column and updates the start column with it.
      // I have been debugging this for 3 days now.
      $punchIn->end = Carbon::now();
      $punchIn->save(); // I also tried the other way to update, but still same thing.
      $punchIn->refresh(); // this has the new value of start and end.
}

This is the migration file:
Schema::create('user_punches', function (Blueprint $table) {
    $table->id();
    $table->foreignId('user_id')->constrained('users')->cascadeOnDelete();
    $table->foreignId('schedule_id')->constrained('schedules')->cascadeOnDelete();
    $table->timestamp('start')->nullable(); // overrides
    $table->timestamp('end')->nullable(); // overrides
    $table->timestamps();
});

And this is the user eloquent relationship:
class User extends Authenticatable implements MustVerifyEmail {
    use HasApiTokens, HasFactory, Notifiable, HasRoles;

    public function punches()
    {
        return $this->hasMany(UserPunch::class);
    }
}

UserPunch model:
class UserPunch extends Model {
    use HasFactory;

    protected $fillable = [
        'schedule_id',
        'start',
        'end',
    ];

    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

I have been on this issue for days now. I have tried other similar cases here, like problem could be with Mysql's timestamp if not null, but still the issue is being persistent.
Anybody can point me out to the right direction? I would really appreciate any explanation on this one. Right now, I am stuck to this. My last option is to use datetime instead of timestamp but that would mean I would trace back the long codes and all relationships which I am trying to avoid.
Answer: Holy moly. I figured it out.

So apparently, it is set to update into CURRENT_TIMESTAMP by default. And the migration file that I have was already the solution for it, but was overwritten when I restored from a dump file coming from production database that had the issue.
Answers to these 2 questions here, really gave me enlightenment of this issue. I will paste it here for reference purposes in case other people stumbled upon this.
Laravel 6 - Updating the model timestamps
Laravel Timestamp Being Updated Without Explicit Call To Do So
Lesson learned, when dealing with timestamps, always make them nullable