HTML link with GET parameters: load page html and javascript before executing ajax request

Question: When I paste the HTML link below in my address bar or press the browser "previous page" button my ajax GET request is executed before the html content is fully loaded resulting in my ajax returned content being displayed above my nav bar and therefore breaking my site.
If the same request gets executed from within the site then everything is fine.
How can I make sure the page HTML and javascript loads before the ajax request is fired?
EDIT: SOLVED (answer in post below)
HTML LINK
https://domainName/?action=listy&p=test
JS pushstate
var container = document.querySelector('.lnk');
var url = "";

container.addEventListener('click', function(e) {
  if (e.target != e.currentTarget) {
    e.preventDefault();

    if (e.target.getAttribute('name')) {
      var data = e.target.getAttribute('name')
      url = "?action=list&p=" + data;
      history.pushState(data, null, url);
    }

  }
  e.stopPropagation();
}, false);

window.addEventListener('popstate', function(e) {

  window.location.replace(url);

});

JQuery AJAX
$(document).ready(function() {
  // .....
  success: function(dataBack) {
    $('.content-area').html(dataBack);
  },
});

PHP
if(isset($_GET['action']) && !empty($_GET['action'])) {
$action = $_GET['action'];
$var = $_GET['p'];
switch($action) {

    case 'list' : list($var);break;

}
}

Comment: Can't you make an onload then call a function for the request?
Comment: Im not familiar with onload, will investigate
Comment: Maybe I'm misunderstanding the problem, but why aren't the nav bar and the content in different html elements? Then the nav bar will always be the top element and it won't matter which is loaded first.
Comment: move  every code in JS pushstate to $(document).ready(function () { });
Comment: @FarazPV tried that and it did not work, my ajax call is also inside a `$(document).ready(function ()` as you can see above
Comment: @Shilly I only have a single index.php for the entire site. `.content-area` div is inside so I really don't understand why the div container is "out of place" of the index.php HTML structure.
Comment: @Doer Can't really tell that without having that code. I'd need to know then how the HTML looks like and how the nav bar is included in it. If you just have something like ``, then the element with the container class might get injected in the wrong order depending on where you have written it and  which function you use to add it.
Answer: This works for me (Note this uses the jquery library):
$(document).ready(function () {
     Your code here...
});

This will wait for the page to load then run the function. I personally use this for animations but then the animations also take more time for me so I have to also include the setTimeout function like this:
setTimeout(function () {
       Your code here...
}, 1000);

It waits a specific amount of milliseconds before executing the function.
Comment: What is the purpose of the `setTimeout()`? the `jQuery` DOM ready function `$(document).ready()`will only execute once the `DOM` has loaded
Comment: For my site I have animations that occur once the document has loaded thus the animations take a good 2 seconds of extra actual load time that's why I had to use the function. Just taking precautions he might have something else to execute once the document was loaded. @NewToJS
Comment: tried that and it did not work, my ajax call is also inside a $(document).ready(function () as you can see above. I also tried `setTimeout`
Comment: @Doer did you include the jquery library, also possibly try the timeout altough it  isn't the most efficient way.
Comment: yes please see my edited comment above. Jquery is properly loaded; I use it extensively already.
Comment: @Doer I'm sorry but sadly I can't think of anything else that may help although ill still keep the question open because it may help someone else in the future who passes by.
Comment: no worries, I managed to solve the problem partially (see updates) but still need to solve other major issues; weird stuff how things are different if the ajax is called from "inside" or "outside". Might have to open another topic
Answer: Turns out the issue was coming from my index.php structure;
I moved the php code in separate files and included it at the end of index.php instead of the top.
Now Im having other issues but the main question is resolved.
Comment: I would suggest deleting the question just in case you get some downvotes.
Comment: Can't delete :(


Violin or piano – which instrument makes more sense to start during Coronavirus lockdown?

Question: During this quarantine, I really want to take this chance to learn playing instrument but I dont know which one should I choose? Piano or Violin? And I do have a reason why I want to learn playing instrument. Its because I feel lonely and I hope when I have this skills, I can connect my feeling to the instrument I played, sort of like a coping mechanism? So which one should I choose? I need an instrument that speaks to me the most
Comment: If you want to start with piano, go with a digital one that has 88 real sized, full weight touch sensitive keys and has headphone output so you can practice without disturbing anybody. They also connect with computer, so you can play synthesia or follow online courses.
Comment: The question is obviously very personal, so it's not possible to make that choice for you. Playing each is different, as is the route to being able to play. There's the neighbour problem, and without a lot more detail, this question will likely be closed as subjective.
Comment: Does this answer your question? [What to choose? Violin or piano?](https://music.stackexchange.com/questions/33828/what-to-choose-violin-or-piano)
Comment: I started violin at 16 or 17. Started piano at 27 with some but significantly less instruction and time invested. Violin is still harder and sounds worse than my piano. You can be more expressive with violin but that just means it is harder to sound good at all. More control also means more ways to mess up.
Comment: @Thomas or your neighbours
Comment: @guidot the title was 100% duplicate, yes, but I think the Coronavirus context does make a significant difference.
Comment: Yeah I already decide to learn piano after thinking about it for a while, tq so much for ur opinion btw, I appreciate it very much
Comment: If you do violin without a teacher, you'll be quickly murdered by your wife
Answer: I would normally tend to recommend violin, but as you're asking specifically about what to learn during lockdown: definitely piano.
Violin is almost impossible to learn without a teacher, at least with proper technique, and even then it'll take you years before you'll actually be able to nicely play music. In the first weeks, you will not be able to produce anything but piercingly scratchy noise. If the quarantine by itself doesn't drive you mad, then the violin likely would.
Piano is also difficult to play at concert level, however with a bit of perseverance you can get together something that can be quite satisfying after a very short time. Again, you may acquire a bit of a botched technique without a teacher, but unlike with violin (where bad technique easily ruins not only your tone but your neck and shoulders), bad piano technique won't be too much of an issue until you aspire to actually play fast melodic pieces.
Comment: Also, you can practice pretty adequately on an electric piano without disturbing your likewise locked-down neighbours. The violin is almost impossible to pick up without noise complaints.
Comment: @AlenSiljak - imagine being confined to home, maybe in a flat, with someone practising an instrument next door. Would you prefer that to be a silent piano, or a screeching violin?
Comment: @AlenSiljak because it prevents teacher-student interaction and because it is a reason to choose something that quickly gets satisfying results. Sure, you can also see it the way "lockdown will cause me to practice a lot, so this is a good time to start something difficult" – but I don't think this is really what the OP was aiming for.
Comment: @Crowley - why would it have to be an acoustic (studio or grand)? My digital pianos make as much noise turned on as when turned off. Unless I use an amp. Headphones are available.
Comment: @KilianFoth I thought about writing about that, but didn't want to go into the acoustic vs electric vs digital discussion, that's done elsewhere. (But – for sure, _electric violins are a thing_.)
Comment: Why does lockdown make a difference in the choice of instrument?
Comment: @Tim Piano is not a silent instrument, when me and my brothers practiced, whole four-storey block of flats knew we were practicing. But it was ways far better than idea of screetching violin or a trumpet.
Comment: @AlenSiljak To expand on leftaroundabout's point, piano technique is not too complicated and can be followed fairly easily from online tutorials.  (Most of it comes down to "don't use straight fingers" when you're starting out.)  For violin though, the way you hold it is important, so you don't support it with your left hand or put yourself in a bad position posture-wise.  And bowing technique is impossible to get right without someone physically guiding how your hand and wrist are supposed to go as you move along the bow.  Violin is basically impossible to learn properly without a teacher.
Comment: Thanks, guys. I've added a separate answer so we can have some discussion there, if desired.
Answer: Regarding the quarantine I would definitely suggest the piano. Even though it is loud instrument, it is not as torturous as a violin when one is learning to play. The (in here) famous non-existent inventor Jara Cimrman invented a sound-proof training chamber for beginner violinist.
I played piano for some years and I was not able to connect with the piano; I connected with the music I was playing. So regarding the connection, any instrument, even you own voice, will do.
Piano, on the other hand, has many disadvantages:

It is loud. not as loud as (church) organ but still a whole building knows you are playing.
It is not portable, and heavy. It is more like a big piece of furniture that needs good and stable conditions.
It is hard to tune it. Although, it keeps its tuning for a very long time.

By the way, why did you end with violin-or-piano choice? There are many more instruments you can play that are more portable than a piano and less torturous as violin.
Comment: A good option for lockdown might be an electronic piano. It can be played with headphones, is a lot easier to move, and doesn't go out of tune.
Comment: @Samuel I was in the middle of typing almost exactly that. They vary in quality of course.  I would look for at the minimum something with a full range and weighted keys.  Learning on non-weighted keys is negative training for when you later have access to a real piano, as the feel is quite different.
Comment: @Crowley, ahaha both of the instruments are in my choice because i love both of the sound apart from other musical instrument, i mean i love all but not as much as the sound of piano n violin
Comment: A good digital piano totally solves the first and third disadvantage. I also find that piano in a lot of senses is the *most* portable instrument, in that you often find yourself in a place where there is a piano - whereas your friends who play other instruments never find themselves in that situation (maybe guitar).
Answer: Lockdown or not, I would say go for what your heart tells you to go for. Go for the instrument that makes you happy. And, if you really like both of them equally then flip a coin or something. Or play both.
Adding the lockdown context tells me that it's a kind of a "throwaway fun" that is used to kill time during the pandemic. In that case you might as well play video games, do squats, learn to bake bread, etc. Most of those new skills can be equally enjoyable and will not annoy your neighbours.
Speaking of which, you never made it obvious what are your constraints. Do you live in Oregon, where your nearest neigbour is 20km away? (or should I use miles, if it's Oregon?) Do you live in a small apartment with paper-thin walls and hear neighbours talking loud?
In any case, almost all instruments nowadays can be found in acoustic and electric form. After all, I'm playing drums in my apartment every day during lockdown and not bothering anyone. These are electric, of course. And so can your violin or piano be.
To address some other mentioned arguments - lockdown will equally well prevent a violin teacher from visiting you as it will a piano teacher. In the same way, both teachers will be available online for classes. I would assume that the same amount of relevant material can be found online, if you want to go it alone. If you have any talent, you may not need a teacher during the lockdown and can just enjoy making music, even if it's involving only three different tones. I had tons of fun with an acoustic guitar without ever seeing a teacher. Just use your ears (and fingers). You may need to adjust some technique later on, if you continue playing the instrument but all musicians do that anyways, throughout their lives.
In any case, asking someone else to choose something you will be happy with has never proved to be a good idea for me.
Have fun! Cheers!
For reference, here are some fairly cheap electric violins on Amazon.
There's a lot of material online, including this video of a mostly-self-taught beginner.
Comment: I had to create an account just to up-vote this answer. It is the **only** one here that makes any sense. The pandemic is just a blip. There are so many factors that go into choosing an instrument to play, and the current _very temporary_ situation is too insignificant to be considered at all. If anything about the pandemic seems relevant to the author of the question, then it's hard to understand why they are wasting time learning an instrument at all. Musicianship, like any complex task, requires time and dedication to achieve even the least amount of proficiency, rendering the pandemic moot
Answer: I'd choose the piano simply because it's so good as a second instrument. So if, at any point, you decided to change your main instrument, the skills gained until then will still be most valuable.
Paragraph added to elaborate: I think the piano is regarded as the ideal second instrument and recommended as such in music schools, etc. That's probably to do with how well it highlights every aspect that's important in music... like melody, harmony, rhythm, comping (including bass), improvisation, etc. That aspect is pretty unique and helps understand how the everything comes together as a whole. It's also very visual, with a purposeful layout. I think that's also the reason why the piano is the instrument most song arrangers use.
Comment: Wouldn't the same be said about any instrument?
Comment: I've added some words to explain why I think the answer to this comment is no :-)
Comment: Thanks - the guitar comes a very close second, and in a lot of song writers' cases, first. (Although not in OP's choice list. Wonder why not).
Comment: That's very true, so I've now changed writers to arrangers. Cheers.
Answer: Well, here's my opinion. Both are great instruments, and are a lot of fun to play, but they have disadvantages. For the violin, it's nearly impossible to learn properly without a teacher, and trying it by yourself will antagonize you. On the other hand, it's a lot cheaper than a piano, and it's easy to get. The thing with piano is that while its not super easy to learn, it's easier than a violin. Having a teacher can help, but you could learn it from a book or online. The bad thing is that they cost a lot, and if you don't already own one, it could be challenging to get right now. My best suggestion would be a keyboard or electric piano of sorts. I'm not really sure if I helped, but good luck anyways!
Answer: From a humanitarian viewpoint you should learn piano to avoid putting additional stress on Corona-sick neighbours with the sound of a beginning violin player. :)
There are physical restrictions which are age-dependant when playing a violin.
You have to twist your left arm in a demanding way hold it and have to be able to simultaneously move your hand and fingers freely. Buy yourself one hour of violin teaching to see if you can stand that position at your age.
You usually start learning violin as a child, you can always start learning piano as an adult.
In terms of expressing feelings a violin gives another degree of freedom as you can influence the frequency of tones. You can't do this on a piano.
A violin allows you to play within an orchestra, an important social factor.
To be able to do that as a piano player you have to be extremely goood.
You are playing your piano typically alone.
But a piano allows you to play keys together what would emulate a bunch of single instruments somehow.
Try both instruments and make a decision afterwards.
I learnt piano from 8 to 18 years and had one year of violin lessons at the age of 18 - too late for me (see the left arm story above).
Comment: "You are playing your piano typically alone." – well, you won't play in an orchestra, but as an accompanist one can easily find others to play with. Either for classical sonatas or, much easier, for pop songs.
Comment: There are also pieces for two players sharing one keyboard. Piano is one of the instruments that can be played alone and deliver the composer's ideas thoroughly.
Comment: There is plenty of other music which incorporates piano playing with others, rather than orchestral. Big bands, jazz bands, pop bands, quartets, etc.
Comment: Many pianists do play only from the solo literature. That said, there is a very rich literature from the chamber music world. Haydn, Mozart, Beethoven, Schubert, Brahms, Shostakovich, etc. etc. all wrote chamber music that includes piano. Unfortunately, though, most is inaccessible for beginning players, whether violin of piano.
Answer: I'd choose the piano. It is extremely easy to learn.
For example, take "Mary Had a Little Lamb" (yeah, it's cringy), anyone can play that on the piano.
However, it's quite difficult to play that on the violin as a first-timer due to the difficulty in fingering, the holding of the instrument and the bow, and the pressing down on the strings.

Therefore, I would choose the piano as it is easy to pick up especially during quarantine, and it's fun to play! Just go for some easy piano tutorials online and you should be playing in no time! :)
Answer: Using a piano will allow you to get an electric piano. these allow you more control over the volume and even often allow you to use a headphone, so you're the only one who hears it. An electric violin generally is more of an amplified violin, so it wouldn't have the same result and you'd still hear the sound of the wand vibrating the strings.
As for my own remarks: generally speaking, an electric piano will always be tuned: you don't have the strings slowly losing their tunes over weeks or months of playing, and you don't really need to know how to tighten those strings in order to retune it. if you press C# now, it'll sound the same as it did 3 months ago and as it will in 3 months.
Finally, while I cannot vouch for their quality, there are apps available for modern tablets that claim to be able to teach you how to play a piano. As said, I will not comment on how good they are or if they work well to teach piano, but if they work, they could save you from having to seek out a trainer.
Answer: Honestly, both instruments are great but in my opinion, as a violinist, it is better if you choose the piano. It's really hard to learn the violin and especially if you are an adult (no offense) the violin will give you challenges. I've been playing for about... 6 years and I've only started to sound good (maybe because I was bad or because I got a new instrument) but yeah. So if you want to continue the violin after lockdown, you can try but it will be really hard. So... I think piano is better. Hope you choose soon!


Como comparar parte de strings em C?

Question: Sei apenas comparar duas strings por inteiro em C, mas eu consigo comparar apenas parte de uma string? Queria desenvolver um programa que lê trechos de uma reclamação e baseado nesses trechos dê  uma sugestão de resposta. É possível ler apenas trechos em C? Em Java sei que é possível, mas gostaria de fazer em C. Obrigado.
Comment: Compara apenas uma parte ? Como assim ? Saber se uma string contem outra ? Sugiro que torne a sua pergunta mais clara adicionando exemplos dos resultados que esperaria ver entre algumas comparações
Comment: Vamos lá. Vamos supor que a variável "reclamacao" recebe o texto: "Gostaria de saber horários entre Rio de Janeiro x Aparecida". Gostaria de fazer algo do tipo.

Se na variável "reclamacao" conter a string "saber horários" retorne a String "Para visualizar horários entre no site..."
Answer: Você pode usara função strcasestr() da biblioteca padrão string.h para verificar (sem considerar letras maiúsculas ou minúsculas) se uma string está contida em outra, por exemplo:
#define _GNU_SOURCE

#include <stdio.h>
#include <string.h>

char reclamacao[] = "Gostaria de saber horarios entre Rio de Janeiro x Aparecida";

int main( void )
{
    if( strcasestr( reclamacao, "saber horarios" ) )
    {
        printf("Para visualizar horários entre no site...\n");
    }
    else
    {
        printf("Não Encontrei!\n");
    }

    return 0;
}

Comment: Ótimo amigo, é exatamente isso que eu gostaria. verificar se uma string está contida em outra. Muitíssimo obrigado.
Comment: Está dando erro na linha if( strcasestr( reclamacao, "saber horarios" ) ).
O erro é "[Error] 'strcasestr' was not declared in this scope"
Comment: @ErickNascimento: Corrigido :)
Answer: Sim, é possivel.
Voce precisara usar a funcao memcmp.
Exemplo:
#include <stdio.h>
#include <string.h>

int main ()
{
  char buffer1[] = "DWgaOtP12df0";
  char buffer2[] = "DWGAOTP12DF0";

  int n;

  n = memcmp (buffer1, buffer2, sizeof(buffer1));

  if (n>0) printf ("'%s' is greater than '%s'.\n",buffer1,buffer2);
  else if (n<0) printf ("'%s' is less than '%s'.\n",buffer1,buffer2);
  else printf ("'%s' is the same as '%s'.\n",buffer1,buffer2);

  return 0;
}

Veja o manual da funcao para maiores detalhes.

Como comparar parte de strings em C?


How could we see that $\{n_k\}_k$ converges $\infty$?

Question: Let $x \in \Bbb R\setminus \Bbb Q$ and the sequence $\{\frac {m_k} {n_k}\}_k$  concerges to $x$. The question is from this comment by Ilya:

How could we see that $\{n_k\}_k$ converges $\infty$?

Thanks for your help.
Comment: Are $m_k$ and $n_k$ integers?
Comment: Yesssssssssssss
Answer: Let $M$ be fixed. Show that there exists such $k_0$ that
$$n_k>M, k\geq k_0.$$
By assuming the contradiction, we'll get such subsequance $\{n_{k_j}\}_j$ that
$n_{k_j} \leq M$ for all $j\geq 1$. Note that
$$\frac{m_{k_j}}{n_{k_j}}\to x.$$ Since such fractions can written as
$$\frac{m_{k_j}}{n_{k_j}}=\frac{A_{k_j}}{M!},$$
where $A_{k_j}$ are integers, then $\frac{m_{k_j}}{n_{k_j}}$ cannot tends to an irrational number. So there is no such subsequance $\{n_{k_j}\}_j$.
Answer: A sequence of integers if it's convergent then its limit is also an integer and in this case the limit of $(\frac{m_k}{n_k})$ is a rational which contradicts the hypothesis so what we can conclude?
Comment: Could you say more?
Comment: I think @SamiBenRomdhane is saying that if $m_k$ and $n_k$ converge, then their quotient converges to a rational. Probably true, but that they converge is not equivalent to the non-divergance of $n_k$. They could be bounded but non-convergant.
Answer: If it is bounded, say by $M$, then all the quotients can be written as $A_k/M!$ where $A_k$ is an integer, which clearly does not converge to an irrational.
Answer: This is actually pretty obvious.
The original conception of an irrational number was an "incommensurable length", that is, one that could not be reconstructed from a segment of unit length. That is, $\frac 5 3$ can be constructed by chopping the unit in 3, and then taking five such subsegments. But no matter how finely you chop up the unit, you will never be able to construct $\sqrt 2$.
If you chop up the unit more and more finely, however, it's obvious that you can get arbitrarily close to any irrational length. However, the key here is more and more finely. If you are unable to chop the unit up into pieces smaller than, say, a hundredth, than obviously there's going to be a limit to your approximation. You'll get yea close using $k$ hundredths, and yea close on the opposite side using $k + 1$ hundredths, and whichever is nearer is as close as you'll get.
Of course, maybe you could get closer using a larger subdivision. But there's only finitely many types of subdivision (in our case, there are 99). So one of them is going to be the one that gets you as close as possible (formally: a finite set always contains a minimal element), and if you want to get closer, you'll have to use finer subdivisions.
It's easy to translate this into a rigorous proof:
Let $\frac 1 n \Bbb Z$ denote the set of rationals with $n$ for their denominator. Obviously there is a minimal $|x - r|$ with $r\in \frac 1 n \Bbb Z$, call this minimum $\delta_n$. $\{\delta_n|n\leq N\}$ is finite and therefore has a minimal element, call it $\epsilon_n$. If the sequence defined in the OP has $n_k$ bounded above by, say, $N$, than in will never be closer to $x$ than $\epsilon_N$, contradicting the definition of convergence.


Form of weakly continuous linear functional

Question: This was originally a problem in Stratila and Zsido's "Lectures on von Neumann algebras" (E.1.2). I've spent so much time working on it, and right now I cannot see how the result can be so simple.
The problem goes like this: Let $\omega$ be a weakly continuous linear functional on $B(\mathscr{H})$. Then there exist two families of mutually orthogonal vectors $\{\xi_1,\ldots,\xi_n\},\ \{\eta_1,\ldots,\eta_n\}$ in $\mathscr{H}$ such that $$\omega(T)=\sum_{i=1}^n\langle T\xi_i,\eta_i\rangle,\quad T\in B(\mathscr{H}),$$$$\|\omega\|=\sum_{i=1}^n\|\xi_i\|\|\eta_i\|.$$
I've tried altering the proof that any weakly continuous linear functional can be written in the above form with no extra assumptions on the vectors, and gotten as far as proving that the $\xi_i$'s can be chosen to be mutually orthogonal (orthonormal, in fact), but that's about it. Does anybody have any suggestions of what to do? I thought about using some facts about compact operators, but seeing as it is not a prerequisite of understanding the section containing the problem, I'm assuming the proof can be elementary (even though it's marked as one of the harder exercises).
Answer: By hypothesis we have that $\omega$ is weakly continuous. Then $\omega^{-1}(\{|z|<1\}$ is open and contains $0$. So there is a neighbourhood $V$ with $0\in V$ and
$$
V=\{x:\ |\langle x\xi_j,\eta_j\rangle|<1,\ j=1,\ldots,m\}\subset\omega^{-1}(\{|z|<1\}.
$$
Given an arbitary $x$ the element $x'=\tfrac{x}{2\sum_j|\langle x\xi_j,\eta_j\rangle|}$ is in $V$, so $|\omega(x')|<1$, which gives
$$
|\omega(x)|\leq2\sum_j|\langle x\xi_j,\eta_j\rangle|.
$$
Name $p_j$ the linear functionals $p_j(x)=\langle x\xi_j,\eta_j\rangle$. We have $\bigcap_j\ker p_j\subset\ker\omega$. By removing some elements from the list if necessary, we may assume that $\bigcap_{j\ne k}\ker p_j\subsetneq\bigcap_j\ker p_j$ for each $k$. Thus there exists, for each $k$, an $x_k$ such that $p_k(x_k)=1$ and $p_j(x_k)=0$ for all $j\ne k$.
Now, given any $x$, consider $x_0=x-\sum_jp_j(x)x_k$. For any $j$ we have
$$
p_j(x_0)=p_j(x)-\sum_kp_k(x)p_j(x_k)=p_j(x)-p_j(x)=0.
$$
So $x_0\in\bigcap_j\ker p_j\subset\ker\omega$. Then $\omega(x)=\sum_j\omega(w_j)\,p_j(x)$, showing that
$$
\omega=\sum_j\omega(w_j)\,p_j=\sum_j c_j\langle x\xi_k,\eta_j\rangle=\sum_j \langle x\xi_k',\eta_j\rangle,
$$
where $c_j=\omega(x_j)$ and $\xi_j'=c_j\xi_j$. Let $\{\xi_j''\}$ be an orthnormal basis of $\operatorname{span}\{\xi_1,\ldots,\xi_m\} $ and $\{\eta_j''\}$ be an orthnormal basis of $\operatorname{span}\{\eta_1,\ldots,\eta_m\} $. Then
$$
\omega=\sum_j\langle x(\sum_s \alpha_{js}\xi_s'',\sum_t\beta_{jt}\eta_t\rangle
=\sum_{s,t}\left(\sum_j\alpha_{js}\beta{jt}\right)\,\langle x\xi_s'',\eta_t''\rangle
=\sum_{s,t}\langle x\xi_s''',\eta_t''\rangle,
$$
where $\xi_s'''=\left(\sum_j\alpha_{js}\beta{jt}\right)\,\xi_s''$. After relabelling, we have that $\omega$ is of the form
$$
w=\sum_j\langle\cdot\xi_j,\eta_j\rangle,
$$
with both $\{\xi_1,\ldots,\xi_r\}$and $\{\eta_1,\ldots,\eta_r\}$   orthogonal .
Finally, regarding the norm, we have
$$
\|\omega\|\leq\sum_j\|\langle\cdot\xi_j,\eta_j\rangle\|=\sum_j\|\xi_j\|\,\|\eta_j\|.
$$
And it we take $x$ to be the linear operator that maps $\xi_j\longmapsto \tfrac{\|\xi_j\|}{\|\eta_j\|}\eta_j$ and on the orthogonal complement of $\operatorname{span}\{\xi_1,\ldots,\xi_r\}$ is a unitary that maps onto $\{\eta_1,\ldots,\eta_r\}^\perp$, then $x$ is unitary and
$$
|\omega(x)|=\sum_j\langle x\xi_j,\eta_j\rangle=\sum_j\|\xi_j\|\,\|\eta_j\|.
$$
Thus
$$
\|\omega\|=\sum_j\|\xi_j\|\,\|\eta_j\|.
$$
Comment: Nice answer! A bit weird that it does not have upvotes. It might benefit other readers to note that the proof can be broken down in three steps: (1) show that any weakly continuous form is a linear combination of $\omega_{\xi, \eta}$'s. This is the hard part of the proof, and already proven in the main text in the reference given by the OP.

(2) Show that the $\xi$'s and $\eta$'s may be assumed to be orthogonal. This is a standard linearity argument.

(3) Show that the norm equality holds. One inequality is obvious, the other one requires more work.


Single IBAction for multiple UIButtons versus single IBAction for single UIButton

Question: While using story-board there are two different approaches which my team mates follow:
Approach 1: To bind unique action with each button, ie:

Done button - binded to - doneButtonAction
Cancel button - binded to - cancelButtonAction

OR
Approach 2:  To bind single action to multiple buttons, ie:

Done button - binded to - commonButtonAction
Cancel button - binded to - commonButtonAction

Then in commonButtonAction they prefer to use switch case like this:
<code>- (IBAction)commonButtonAction:(id)sender
{
    UIButton *button = (UIButton *)sender;
    switch (button.tag) {
        case 201: // done button
            [self doneButtonAction:sender];
            break;
        case 202: // cancel button
            [self cancelButtonAction:sender];
            break;
        default:
            break;
    }
}
- (void)cancelButtonAction:(id)sender
{
    // no interesting stuff, simple dismiss of view :-(
}
- (void)doneButtonAction:(id)sender
{
    // some interesting stuff ;-)
}
</code>
Reasoning which they give to follow approach 2 is - in each view controller during code walk through anyone can easily identify where to find code related to button actions.
While others discard this idea because they say that adding an extra switch case is unnecessary and is not a common practice.
What are your views?
Answer: Well, approach 2 just seems like a waste of code to me. If you are using separate methods for separate buttons anyway, you might as well hook them up directly, right?
If you're not using separate methods per button (and if the button logic is one or two lines at most) I can imagine using the switch statement in a generic button method.
But for readability purposes I would recommend directly implementing the specific IBAction, i.e., approach 1.
<code>- (IBAction) cancelButtonAction:(id)sender
- (IBAction) doneButtonAction:(id)sender
</code>


How to create a user with field collections programmatically?

Question: This is what I use to create the user:
    $new_user = array(
        'name' => $form_state['values']['email'],
        'status' => 1,
        'access' => REQUEST_TIME,
        'roles' => array(),
    );

   user_save('', $new_user);

Now I want to add values to the field collection items.
I have a field collection called field_personal_details and a field collection item called field_firstname, but I have no idea how to access it. Can someone help me get started?
Comment: finally, do you solve your problem?
Answer: I think following code should give you an idea.
    //Create a field collection entity
    $field_collection_item = entity_create('field_collection_item', array('field_name' => 'field_personal_details'));
    $field_collection_item->field_firstname[LANGUAGE_NONE][0]['value'] = "Yassin Tahtah";
    //$field_collection_item->field_firstname['und'][0]['value'] = "Yassin Tahtah";
    $field_collection_item->setHostEntity('user', $user);
    // Save the entity.
    $field_collection_item->save(TRUE);

Answer: You can see this example:
$new_user = array(
    'name' => $form_state['values']['email'],
    'status' => 1,
    'access' => REQUEST_TIME,
    'roles' => array(),
);

 //making the field collection
 $values = array();
 $values['field_name'] = 'field_personal_details';
 $values['field_firstname'][LANGUAGE_NONE][0]['value'] = 'Yassin';

 //saving the collection
 $entity = entity_create('field_collection_item', $values);
 $entity->setHostEntity('user', $user);
 $entity->save();

 //saving the user
 user_save('', $new_user);


Options grape representer

Question: I am working on a rails API with Representers, using the following gems: Grape, Roar and Grape-Roar
Now, I try to add conditions to include (or not include) certain properties in my representer based on a condition I pass from my API endpoint as described here (note the representable gem is used by the Roar gem)
I'm probably overlooking something, but I can't figure out how to pass options to my representer, so I can present properties based on a condition
For example, in one of my grape endpoints I call:
present payment_object, with: PaymentRepresenter, include_orders: true
to present a payment object with PaymentRepresenter. As you can see I want to include related order for the payment as well, so in my Payment representer I tried to do:
property :order, extend: OrderRepresenter, if: lambda {
    |args| puts args[:include_orders] #just puts for testing
}

however args[:include_orders] just is nil
Does anyone know what I'm doing wrong here?
Thanks in advance!
Answer: I had this problem myself, and the only solution I came up with was to ditch nice idiomatic present..., with:... and manually extend my collection / record with representer, like this (concerning your example):
payment_object.extend(PaymentRepresenter).to_hash(include_orders: true)

Comment: thank you @yaro this totally works! For others: be sure to include `, env: request.env` in the to_hash() if you require environment variables in your representer, like I did, e.g. for PATH_INFO

Options grape representer


unexpected '' (T_ENCAPSED_AND_WHITESPACE)

Question: error:

Parse error: syntax error, unexpected '' (T_ENCAPSED_AND_WHITESPACE),
  expecting identifier (T_STRING) or variable (T_VARIABLE) or number
  (T_NUM_STRING) in C:\wamp\www\html\updatedtimeline.html on line 109

Im getting this error in my code and i would like to understand why?
Thanks for any help
i want to add the email of the user logged in my html element

line 109:
echo "";

Comment: `{$_SESSION['email']}` <-- note the braces. you may actually need `'{$_SESSION['email']}'` also the quotes
Comment: Did you start the session before the scripting
Comment: @PranavMS Yes i did
Comment: @MrTux Tried the following link and solution couldn't help me
Comment: Value=".$_session['email']." Try this way
Comment: @PranavMS This solved my error but the value of the html element with id myemail isnt changing and this is the relative line:
` `
Comment: Good  ..  before asking questions just debug your code.
Comment: have you checked my comment? you need quotes also.
Comment: @bansi Yes I've changed my line to `echo "";` am i following right? if yes then i'm getting the same problem the html element isn't changing accordingly
Comment: yes that is correct. Check what is the value in `$_SESSION['email']` and re-check if your element has id `myemail`
Answer: Try following:
<?php session_start();?>

    <?php
        echo "";
    ?>

Please make sure that your echo should be placed after

 is printed out.
Please pay attention to the order of the code.
You should make sure

 is printed already before you echo script code.
Comment: I've made this changes and im getting a debug error `Uncaught TypeError: Cannot set property 'value' of null`
Comment: then your `$_SESSION['email']` is not set
Comment: @menna `Uncaught TypeError: Cannot set property 'value' of null` should be happening in javascript console, correct? I have updated the code. Check it out.
Comment: @bansi To check the value of my ` $_SESSION['email']` i tried `echo "welcome " . $_SESSION['email'];` and i got `welcome firstname.lastname@example.com` (Which shows that my value of session is correct) and my html element has an id myemail as the following ` `
Comment: @RayC my code was changed accordingly to ` document.getElementById('myemail').innerHTML = '{$_SESSION['email']}'; ";

?>` and im getting a debug error `Uncaught TypeError: Cannot set property 'innerHTML' of null`
Comment: @menna As I mentioned in my answer, please make sure you have ` ` already printed before you do `echo` thing. My suggestion is, you move `echo` thing to the last part of your code, so that make ` ` is already printed.


Prove $\cos^2x\sin^4x = \frac{1}{32}(2-\cos(2x)-2\cos(4x)+\cos(6x))$

Question: I need help with a problem some may consider odd but here it is.
I have the following trig identity I been working on and I managed to get it to.
$$\cos^2x\sin^4x=\frac{3}{16}-\frac{\cos(2x)}{4}+\frac{3\cos(2x)}{16}+\frac{1}{8}(1+\cos(4x))+\frac{1}{32}(\cos(6x)+\cos(2x))$$
However I am not sure how to make this simplify to $\frac{1}{32}(2-\cos(2x)-2\cos(4x)+\cos(6x))=\cos^2x\sin^4x$
and thus I am stuck.
Answer: $\cos^2x\sin^4x=\cos^2x(1-\cos^2x)^2=\cos^6x-2\cos^4x+\cos^2x$
Now $\cos(2x)=2\cos^2x-1$,
$\cos(4x)=\cos(2\cdot2x)=2\cos^2x-1=2(2\cos^2x-1)^2 - 1 = 8\cos^4x-8\cos^2x+1$ and
$\cos(6x)=\cos(2\cdot3x)=4\cos^3(2x)-3\cos(2x)= 32\cos^6x + 18\cos^2x - 48\cos^4x - 1 $
Let $A\cdot\cos(6x)+B\cdot\cos(4x)+C\cdot\cos(2x)+D=\cos^6x-2\cos^4x+\cos^2x$
$Or, A(32\cos^6x  - 48\cos^4x  + 18\cos^2x- 1)+B(8\cos^4x-8\cos^2x+1)+C(2\cos^2x-1)+D=\cos^6x-2\cos^4x+\cos^2x$
Comparing the coefficients of different powers of $\cos x$,
6th power=>$A=\frac{1}{32}$
4th power=>$-48A+8B=-2$ =>$B=-\frac{1}{16}$
2nd power=>$18A-8B+2C=1$=>$C=-\frac{1}{32}$
constants (power $0$)=$-A+B-C+D=0$=>$D=A+C-B=\frac{1}{16}$
So,  $\cos^2x\sin^4x$
$=\frac{1}{32}\cdot\cos(6x) - \frac{1}{16}\cdot\cos(4x) -\frac{1}{32}\cdot\cos(2x) + \frac{1}{16} $
$=\frac{1}{32}(\cos(6x) - 2\cos(4x) -\cos(2x) + 2) $.

Alternatively, we know $e^{iy}=\cos y+i\sin y$ => $e^{-iy}=\cos y - i\sin y$
So, $\cos y=\frac{e^{iy}+e^{-iy}}{2}$  and $\sin y=\frac{e^{iy} - e^{-iy}}{2i}$
$\cos^2x\sin^4x$
$=(\frac{e^{ix}+e^{-ix}}{2})^2\cdot (\frac{e^{ix} - e^{-ix}}{2i})^4$
$=\frac{1}{64} (e^{ix}+e^{-ix})^2\cdot(e^{ix} - e^{-ix})^4$
$=\frac{1}{64} (e^{ix}+e^{-ix})^2\cdot(e^{ix} - e^{-ix})^2 \cdot(e^{ix} - e^{-ix})^2$
$=\frac{1}{64} ((e^{ix}+e^{-ix})\cdot(e^{ix} - e^{-ix}))^2 \cdot(e^{ix} - e^{-ix})^2$
$=\frac{1}{64} (e^{2ix} - e^{-2ix})^2 \cdot(e^{ix} - e^{-ix})^2$
$=\frac{1}{64} (e^{4ix} + e^{-4ix} -2 ) \cdot(e^{2ix} + e^{-2ix} - 2)$
$=\frac{1}{64} (e^{6ix} + e^{-6ix} -2(e^{4ix} + e^{-4ix}) -(e^{2ix} + e^{-2ix}) +4)$
$=\frac{1}{64} (2\cos6x -2(2\cos4x) -2\cos2x + 4)$
$=\frac{1}{32} (\cos6x -2\cos4x -\cos2x + 2)$
This is probably how the problem came to being.
But if we know the RHS,  the task becomes far easier.
$\cos(6x) - 2\cos(4x) -\cos(2x) + 2$
$=\cos(6x)  -\cos(2x) - 2(1-\cos(4x))$
$=-2\sin4x\sin2x -2\cdot2\sin^22x$ applying $ \cos 2C - \cos 2D=-2\cdot\sin (C+D) \sin(C-D)$ and $\cos2A=1-2\cdot \sin^2A$ formula
$= 2\cdot\sin2x(-\sin4x+2\sin2x)$
$= 2\cdot\sin2x(-2\cdot\sin2x\cos2x+2\sin2x)$   (applying $\sin2A=2\cdot\sin A\cos A$ formula)
$=4(\sin2x)^2(1-\cos2x)$
$=4(2\cdot\sin x \cos x )^2(2\sin^2x)$  (applying $\sin2A$  and $\cos 2A$ formula)
$=32\cos^2x\sin^4x$
Comment: This is impressive math.
Comment: I like the way the identity was solved.
Answer: As AMPerrine pointed out in a comment above (before deleting it), it seems you made a mistake somewhere along the way. Your expression yields $$\frac1{32}\bigl(10-\cos(2x)+4\cos(4x)+\cos(6x)\bigr),$$ which is not identical to $$\frac1{32}\bigl(2-\cos(2x)-2\cos(4x)+\cos(6x)\bigr).$$

Applying the Pythagorean identity gives us $$\cos^2x\sin^4x=\sin^4x-\sin^6x.\tag{1}$$ Consider the double angle identities $$\cos(2\theta)=1-2\sin^2\theta\tag{2}$$ and $$\cos(2\theta)=2\cos^2\theta-1.\tag{3}$$ These give us $$\sin^2\theta=\frac12\bigl(1-\cos(2\theta)\bigr),\tag{$2'$}$$ and $$\cos^2\theta=\frac12\bigl(1+\cos(2\theta)\bigr),\tag{$3'$}$$ which (applied iteratively) let us rewrite even powers of sine--as in the right-hand side of $(1)$--in terms of cosines of multiple angles--as in the right-hand side of the desired identity.
By $(2')$, $$\sin^4x=\frac14\bigl(1-2\cos(2x)+\cos^2(2x)\bigr)=\frac14\bigl(1-2\cos(2x)\bigr)+\frac14\cos^2(2x)\tag{4}$$ and similarly, $$\sin^6x=\frac18\bigl(1-3\cos(2x)\bigr)+\frac18\bigl(3-\cos(2x)\bigr)\cos^2(2x).\tag{5}$$ By $(3')$ $$\cos^2(2x)=\frac12\bigl(1+\cos(4x)\bigr),$$ so from $(4)$ and $(5)$ we get $$\sin^4x=\frac18\Bigl(2\bigl(1-2\cos(2x)\bigr)+\bigl(1+\cos(4x)\bigr)\Bigr)=\frac18\bigl(3-4\cos(2x)+\cos(4x)\bigr)\tag{$4'$}$$ and similarly $$\sin^6x=\frac1{16}\bigl(5-7\cos(2x)+3\cos(4x)-\cos(2x)\cos(4x)\bigr).\tag{$5'$}$$ Applying $(4')$ and $(5')$ to $(1)$ yields $$\cos^2x\sin^4x=\frac1{16}\bigl(1-\cos(2x)-\cos(4x)+\cos(2x)\cos(4x)\bigr),\tag{6}$$ or for simplicity, $$\cos^2x\sin^4x=\frac1{32}\bigl(2-2\cos(2x)-2\cos(4x)+2\cos(2x)\cos(4x)\bigr).\tag{$6'$}$$ It remains, then, only to show that $$\cos(6x)-\cos(2x)=2\cos(2x)\cos(4x)-2\cos(2x)=2\bigl(\cos(4x)-1\bigr)\cos(2x),\tag{#}$$ that is, that there is no difference between the right-hand side of the desired identity and the right-hand side of $(6')$.
Indeed, applying (i) the angle sum formula $\cos(\alpha+\beta)=\cos\alpha\cos\beta-\sin\alpha\sin\beta$, (ii) the double angle formula $\sin(2\theta)=2\sin\theta\cos\theta$, and (iii) formula $(2')$, we have
$\begin{eqnarray*}
\cos(6x) & = & \cos(2x)\cos(4x)-\sin(2x)\sin(4x)\\
& = & \cos(2x)\cos(4x)-2\sin^2(2x)\cos(2x)\\
& = & \cos(2x)\cos(4x)-\bigl(1-\cos(4x)\bigr)\cos(2x),
\end{eqnarray*}$
from which $(\#)$ follows readily.

Additional Calculations: I'm not entirely certain which parts you're referring to in your third comment below, so I'll go ahead and expand those that seem like what you're asking. Let me know if you have any other questions.
First, the Pythagorean identity $\cos^2x+\sin^2x=1$ gives us $\cos^2x=1-\sin^2x$, from which we have $$\cos^2x\sin^4x=(1-\sin^2x)\sin^4x=\sin^4x-\sin^6x.$$
Second, since $\cos^2(2x)=\frac12\bigl(1+\cos(4x)\bigr)$ by $(3')$, we see from $(5)$ that
$\begin{eqnarray*}
\sin^6x & = & \frac18\bigl(1-3\cos(2x)\bigr)+\frac18\bigl(3-\cos(2x)\bigr)\cos^2(2x)\\
& = & \frac18\bigl(1-3\cos(2x)\bigr)+\frac1{16}\bigl(3-\cos(2x)\bigr)\bigl(1+\cos(4x)\bigr)\\
& = & \frac18\bigl(1-3\cos(2x)\bigr)+\frac1{16}\bigl(3+3\cos(4x)-\cos(2x)-\cos(2x)\cos(4x)\bigr)\\
& = & \frac5{16}-\frac7{16}\cos(2x)+\frac3{16}\cos(4x)-\frac1{16}\cos(2x)\cos(4x)\\
& = & \frac1{16}\bigl(5-7\cos(2x)+3\cos(4x)-\cos(2x)\cos(4x)\bigr).
\end{eqnarray*}$
Finally, applying $(4')$ and $(5')$ to $(1)$, we have
$\begin{eqnarray*}
\cos^2x\sin^4x & = & \frac18\bigl(3-4\cos(2x)+\cos(4x)\bigr) - \frac1{16}\bigl(5-7\cos(2x)+3\cos(4x)-\cos(2x)\cos(4x)\bigr)\\
& = & \frac1{16}-\frac1{16}\cos(2x)-\frac1{16}2\cos(4x)+\frac1{16}\cos(2x)\cos(4x)\\
& = & \frac1{16}\bigl(1-\cos(2x)-\cos(4x)+\cos(2x)\cos(4x)\bigr)\\
& = & \frac1{32}\bigl(2-2\cos(2x)-2\cos(4x)+2\cos(2x)\cos(4x)\bigr).
\end{eqnarray*}$
Comment: This answer is very informative as well.
Comment: This answer is excellent as well upon studied closely.
Comment: Well one part slightly confuses me the part on getting sin^6x and then the sin^4-sin^6.
Comment: I will add some more detail at the end.
Answer: The equation you have written is not correct in general.
What you can do is note that there exists some $\theta \in [0, \pi)$ such that $\sin^2 x = \sin \theta$.
Then $1 - \sin^2 x = 1 - \sin \theta \Rightarrow \cos^2 x = 1 - \sin \theta$.
Thus we know that $\cos^2 x \sin^4 x = (1 - \sin \theta) \sin^2 \theta$.
Let $1 - 2 \sin \theta = T$. Then we know:
$\cos^2 x \sin^4 x = (1 - \sin \theta) \sin^2 \theta = \frac{1}{8} (1 + T)(1 - T)^2$.
Similarly,
$\cos(2x) = T,$
$\cos(4x) = 2T^2 - 1,$
$\cos(8x) = 8T^4 - 8T^2 + 1$.
The sum-to-product formula tells us:
$\cos (2x) + \cos (6x) = 2 \cos(4x) \cos (8x) = 32T^6 - 48T^4 + 20T^2 - 2$.
Perhaps you can go somewhere from here.


CanCanCan redirect after rescue

Question: In my application.rb, I have this:
  rescue_from CanCan::AccessDenied do |exception|
    redirect_to authenticated_root_url, :alert => exception.message
  end

Which is fine.
What I want to do though, is once this rescue kicks in and sends them back to the login page, after they login, have them get redirected back to the page they were trying to access.
This comment on this issue has the following suggestion:
redirect_to exception.redirect_path, :alert => exception.message

But that doesn't work. I get this error:
undefined method `redirect_path' for #<CanCan::AccessDenied:0x007fca21c8eea0>

How do I achieve both? i.e. redirect to authenticated_root_url when they aren't logged in, and then redirect :back once they have successfully logged in?
Comment: You would stash the request url in the session when you catch the `CanCan::AccessDenied` and use that after you have signed the user in. There is a guide for how to do this with Devise authentication - same principle but slightly different. https://github.com/plataformatec/devise/wiki/How-To:-Redirect-back-to-current-page-after-sign-in,-sign-out,-sign-up,-update
Comment: Note that you need to redirect to the GET routes (new/edit) so doing this with a catch-all in your ApplicationController is kind of tricky - you may want to do this on per controller basis.
Answer: Use :back in place of your path like so,
    rescue_from CanCan::AccessDenied do |exception|
      redirect_to :back, :alert => exception.message
    end

CanCanCan redirect after rescue


How can I check that I am in the build_phase in the UVM?

Question: I would like to create a function that can only be called during the build_phase().  (Calls during other phases should generate a fatal error.)
How do I find out what uvm_phase I am in?
Answer: The phase that you are in is represented by the phase argument of the *_phase method. There is no single state that represents the current state, because the UVM has many possible phase domains that could be simultaneously active. So you will have to either pass the phase into the function when calling it:
function void my_function(uvm_phase phase);
  if (!phase.is(uvm_build_phase::get()) `uvm_fatal(...);
endfunction

Or if this function is a method of a class derived from uvm_component, you can override the phase_started method
class my_component extends uvm_component;

protected uvm_phase m_current_phase
function void phase_started(uvm_phase phase);
  super.phase_started(phase);
  m_current_phase = phase;
endfunction : phase_started

  function void my_function(..);
      if (!m_current_phase.is(uvm_build_phase::get()) `uvm_fatal(...);
  endfunction

Comment: What you said about multiple domains only applies to the run phase. There is only one build phase shared by all components.
Answer: There's a field in uvm_component called m_current_phase, that contains the most recently executed phase. The field isn't technically part of the standard API, but the comment shows that the developers are considering adding an accessor for it:
class test extends uvm_test;
  function void print_cur_phase();
    m_current_phase.print();
  endfunction // print_cur_phase

  function void build_phase(uvm_phase phase);
    print_cur_phase();
  endfunction // build_phase

  task run_phase(uvm_phase phase);
    print_cur_phase();
  endtask

  // ...
endclass

The most portable way of doing it is to define your own variable like Dave showed in his answer.
Answer: This is how uvm_component::new checks that components are not created after build_phase is done (error messages stripped):
begin
  uvm_phase bld;
  uvm_domain common;
  common = uvm_domain::get_common_domain();
  bld = common.find(uvm_build_phase::get());
  if (bld == null)
    uvm_report_fatal(...);
  if (bld.get_state() == UVM_PHASE_DONE) begin
    uvm_report_fatal(...);
  end
end

This uses the singleton getters for the common domain and uvm_build_phase, so you do not need to manually track any phase starts/states locally, and can just inspect these when your function is called.
Comment: Can you give some example code for using this?


Visualizing of $\sigma$-algebras as "information"

Question: Let $(\Omega,\mathscr{F},\mu)$ be a probability space and $\mathscr{G}\subseteq \mathscr{F}$ a $\sigma$-algebra. I have seen it referred to many times that $\mathscr{G}$ is the "information" which is available to us. I think I kinda understand it, but I am not satisfied in my own understanding of it.
Let us say that $A$ is an event and $\mathscr{G} = \{\emptyset, A,A^c,\Omega\}$. Let $\omega$ be a sample point of the experiment. We do not know which of the events in $\mathscr{G}$ contain $\omega$. Now $\Omega$ certaintly contains $\omega$, but we already knew that, so we do not gain any insight. However, either $A$ or $A^c$ will contain $\omega$. If we somehow knew that $A$ contains $\omega$, then that gives us additional insight.
1) Does anyone have a better way of thinking of $\mathscr{G}$ as our "information"?
2) If $\mathscr{G}'\supseteq \mathscr{G}$, then how do we think of $\mathscr{G}'$ as having "more information"? Obviously, it is a larger $\sigma$-algebra, and it has more events, but ignoring set theory, what should one's intuition be for $\mathscr{G}'$?

Follow up question.
3) Let $\xi:\Omega\to\mathbb{R}$ be a $\mathscr{G}$-measurable. I have seen people refer to $\xi$ as "a random variable whose information is known from $\mathscr{G}$", or something along those lines. What is the motivation for this?
Comment: @Kodiologist see, e.g., https://en.wikipedia.org/wiki/Conditional_expectation#Conditional_expectation_with_respect_to_a_.CF.83-algebra ("see" meaning "see that stuff conditional on sigma-algebras is indeed talked about", not "read and learn" for which the Wikipedia article is probably not the best place).
Comment: I don't really understand your first sentence. What is G, just any old sub-$\sigma$-algebra of F? I see that F is the $\sigma$-algebra needed to define the probability space, but what's G doing here?
Comment: @Kodiologist When you condition on a $\sigma$-algebra G, G is often referred to as "information that you know".
Comment: Huh? But you can't condition on G. It's not an event.
Comment: @Kodiologist You should delete your comments. They are not about the nature of my question, but your question about conditioning on $\sigma$-algebras. Which is a separate question in itself.
Comment: ^ But the comments *are* about investigating whether there is some unclarity in the question (of course, after the issue has been resolved, they may/even should be deleted).
Comment: @JuhoKokkala There was no unclarity in the question, the commentator was simply asking a question (unrelated) about conditional expectation on sigma-algebras.
Answer: $\mathscr{G}$ is our information in the sense that for all $A \in \mathscr{G}$, we know whether $\omega \in A$.
Let us use the Tickets in a box metaphor, extended to handle $\sigma$-algebras so that the ticket mentions for all $A\in \mathscr{F}$ whether the outcome represented by the ticket belongs to $A$. Now, say that someone else picks the ticket and we don't see it. For any $A \in \mathscr{G}$ we may ask whether the ticket says that the outcome is in $A$ and the person holding the ticket tells us. However, if we ask about some $A \in \mathscr{F} \setminus \mathscr{G}$, we hear "Sorry, you don't know that".
Larger $\sigma$-algebra is more information
This also explains why moving to  $\mathscr{G}' \supset \mathscr{G}$ means gaining new information -- now we still get answers to $[X \in A?]$-questions about any$A \in \mathscr{G}$ and additionally to some new questions -- those where $A \in \mathscr{G'} \setminus \mathscr{G}$.
Random variables
So, the tickets also contains the values of random variables. If the random variable $X$ is $\mathscr{G}$-measurable, we get answers to all our questions about its value, such as $[$is $X$ equal to $3]$, since by $\mathscr{G}$-measurability of $X$, $\{\omega \mid X(\omega)=3\}\in\mathscr{G}$. Or, to handle the delicacies of the uncountable case, we may also ask $[$Is $X$ in the set $B]$? (Since for any particular value we think about, the probability of hearing "yes" may be $0$ and that would be boring). So, in this sense we have all information about the realization of the random variable, if our information is $\mathscr{G}$ and the RV is $\mathscr{G}$-measurable.
Caveat: the definition of measurability of random variables restricts the sets $B$ we may ask about. $[$Is $X(\omega) \in B]$ is answered if $B$ is a measurable set in the value space of the random variable (usually Borel $\sigma$-algebra is assumed with $\mathbf{R}$ without mentioning). So, in the uncountable (nondiscrete $X$) case, don't ask whether $X$ is in the Vitali set or the oracle holding the ticket shall be mad.
Reference
I did not cite any reference in the answer but I consulted

J. Jacod and P.E. Protter.  Probability essentials (2nd edition), Springer, 2004

about the definition of measurability of random variables. (And have learned these things from the same book previously, if I recall correctly).


Correlations within Factor in a psychometric measurement instrument

Question: I am working with results of a psychometric test. There are twelve factors and each have three subfactors. My problem is that one of the subfactors correlates very highly 0.3 to 0.7 with subfactors of other factors in fact with all but 10 of 36. And this is a consistent observation across three healthy samples, n1=427, n2= 353 and n3=945. Though this can be explained by looking at the meaning of these traits. But, should it question the robustness of the factor structure or the instrument? Additionally intra factor correlations are also low and insignificant at many instances.
Please note that this is a very well researched and well known psychometric instrument.
Need help with interpreting this information. Any ideas, what I should make of this observation?
Added this for additional information:
Not really, measurement model does shown some strong correlations for the subfactor outside its own factor (3 such correlations are strong), none of which are more than o.5. In my samples I consistently see two correlations at 0.7 and two others at 0.6 (I see 23 of 36 correlations above 0.3). I wish I could share the correlations here, but the information is proprietary. And the subfactor has very low  correlation with another subfactor within its own factor. These others are very high as compared with the correlations given in the manual. Could it be a sampling error? What inferences can I draw for the samples if these correlations are exaggerated (more than what was seen in the norm group)?
Comment: Does the measurement model specify that those factors should not correlate? How about the higher-order factors: are they intended to correlate? Does the problematic factor at least correlate more strongly with other factors that share its higher-order factor? If these factors are supposed to be less correlated, it sounds like a problem for discriminant validity, but if correlation is intended, it could be good news. It's probably not possible to determine whether the model or the instrument is more flawed from what you've said here. That would depend more on how the instrument was designed.
Comment: Is you data set in stone.  There are approaches to augment existing experimental design that allow you to confirm or reject a particular relationship between variables.
Answer: I don't think it's a problem. All sub scales are usually correlated on a health measurement scale. There are measures called item-total correlations where you delete an individual item from a subscale and correlate the item with all subscales. In general, the individual item should correlate most with the subscale it was deleted from and not the others. You can also check Cronbach's alpha within subscales against generally agreed acceptable levels. Lastly, you could apply a confirmatory factor analysis to the data to confirm the subscales exist.
Comment: Cronbach alphas are healthy as per the manual. They are all in the range of 0.7-0.9. And are stronger with in factor even in samples. Could this be a sampling problem, after all these results are not shown in norm group. But again how can the same error be replicated in three different samples?


How is pairwise PERMANOVA/adonis a valid non-parametric approach for pairwise comparisons

Question: Assume that we have taken independent random samples of several individuals from 5 locations that represent 5 populations. The design is fairly unbalanced: the number of individuals sampled from each location is variable (example in code). For each individual, we measured some continuous random variable (e.g., the concentration of some chemical, assuming its value is purely a function of where the respective individual was sampled), and we wish to understand which locations are different using this variable (the concentration of the chemical).
I will simulate example of these data here:
set.seed(123)
data <- data.frame(group = factor(rep(c(paste0("G",1:5)), c(10,24,10,12,9))),
                   val = c(rnorm(10, mean=1.34,sd=0.17),
                           rnorm(24, mean = 1.14, sd=0.11),
                           rnorm(10, mean=1.19, sd=0.15),
                           rnorm(12, mean=1.06, sd=0.11),
                           rnorm(9, mean=1.09, sd = 0.10)))

Let us assume that group denotes the 5 sampling locations, and val denotes the concentration of the chemical in each sample.
Assume that we have conducted a series of omnibus non-parametric tests (using distance matrices, PERMANOVA) that suggest there are differences between the concentration of the chemical between the groups. We want to conduct pairwise analyses to see which groups are different, so we calculate a dissimilarity matrix (using the vegan package in R for this example) for these data using Euclidean distance:
library(vegan)
dist.mat <- vegdist(data$val, method = "euclidean")

There are several packages out there with functions that conduct pairwise versions of what is generally referred to as PERMANOVA/ permutaional MANOVA/ adonis test (based on the approaches by Marti J. Anderson: Anderson, M.J. 2001. A new method for non-parametric multivariate analysis of variance. Austral Ecology, 26: 32-46.)
Some examples can be found in these links:
https://www.rdocumentation.org/packages/RVAideMemoire/versions/0.9-77/topics/pairwise.perm.manova
https://github.com/pmartinezarbizu/pairwiseAdonis/blob/master/pairwiseAdonis/R/pairwise.adonis.R
https://rdrr.io/github/gauravsk/ranacapa/man/pairwise_adonis.html
https://rdrr.io/github/GuillemSalazar/EcolUtils/man/adonis.pair.html
Most of the examples I run across that demonstrate how to use and interpret these approaches in R are applied to count data (mostly species composition in ecological data, which corresponds with Anderson's intentions). However, there are examples of these approaches being applied in other situations, notably in my interest, for continuous data, such as that presented above. In situations like the one I have proposed, if we calculate a dissimilarity matrix using Euclidean distance, and perform the pairwise version of this procedure (I will use the pairwise.adonis() function by @pmartinezarbizu, 2nd link above):
library(pairwiseAdonis)
#default is 999 permutations
res<-pairwiseAdonis::pairwise.adonis(dis.mat, data[,"group"])
res[,3:5] <- round(res[,3:5],2)
res

      pairs Df SumsOfSqs F.Model   R2 p.value p.adjusted sig
1  G1 vs G2  1      0.26   19.95 0.38   0.001       0.01   *
2  G1 vs G3  1      0.09    5.06 0.22   0.038       0.38
3  G1 vs G4  1      0.28   23.98 0.55   0.001       0.01   *
4  G1 vs G5  1      0.34   18.72 0.52   0.001       0.01   *
5  G2 vs G3  1      0.02    1.78 0.05   0.172       1.00
6  G2 vs G4  1      0.01    0.95 0.03   0.323       1.00
7  G2 vs G5  1      0.04    2.92 0.09   0.093       0.93
8  G3 vs G4  1      0.05    3.87 0.16   0.077       0.77
9  G3 vs G5  1      0.09    4.62 0.21   0.047       0.47
10 G4 vs G5  1      0.01    0.78 0.04   0.376       1.00

Am I incorrect in saying that this is equivalent to a simple series of pairwise anovas with p-values calculated according to the observed F statistics probability under the empirical null distribution that was generated through random permutations of group membership (or "location" membership in this case). If so, how can this be a valid non-parametric approach to pairwise comparisons? Let me explain:
Lets use groups 1 and 5 (G1 and G5) as an example:
library(dplyr)
ex <- c("G1","G5")
se <- function(x) sd(x) / sqrt(length(x))
data%>%
  dplyr::filter(., group %in% ex)%>%
  group_by(group)%>%
  summarise_at(., "val", list(mean=mean,med=median,sd=sd,se=se))%>%
  mutate(across(is.numeric, round, 2))

# A tibble: 2 x 5
  group  mean   med    sd    se
  <fct> <dbl> <dbl> <dbl> <dbl>
1 G1     1.35  1.33  0.16  0.05
2 G5     1.05  1.06  0.07  0.02

we know they were heteroscedastic to begin with, but still lets fit a lm and look at residual plots:
ex <- c("G1","G5")
dat2 <- data%>%dplyr::filter(., group %in% ex)
summary(lm(val~group, dat2))
plot(lm(val~group, dat2))

Residuals:
     Min       1Q   Median       3Q      Max
-0.22775 -0.08020 -0.00070  0.06125  0.27887

Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept)  1.35269    0.04061  33.306  < 2e-16 ***
groupG5     -0.29792    0.05901  -5.049  9.9e-05 ***

Now lets do regular ANOVA:
ex <- c("G1","G5")
dat2 <- data%>%dplyr::filter(., group %in% ex)
summary(aov(val ~ group, data = dat2))

            Df Sum Sq Mean Sq F value  Pr(>F)
group        1 0.4204  0.4204   25.49 9.9e-05 ***
Residuals   17 0.2804  0.0165

Now lets do the pairwise adonis procedure for just these two groups:
set.seed(123)
dis.mat <- vegdist(dat2$val, method="euclidean")
res<-pairwiseAdonis::pairwise.adonis(dis.mat, dat2[,"group"])
res[,3:5] <- round(res[,3:5],2)
res

     pairs Df SumsOfSqs F.Model  R2 p.value p.adjusted sig
1 G1 vs G5  1      0.42   25.49 0.6   0.001      0.001  **

We get the same observed model, as we should, and a p-value that is based off of permutations. A little look under the hood shows me that all this function really does is perform the adonis function on each pair (or the single pair in this case). To demonstrate, we get the same answer by doing this:
set.seed(123)
dis.mat <- vegdist(dat2$val, method="euclidean")
res2<- adonis(dis.mat ~ dat2$group, method = "euclidean")
res2$aov.tab

Terms added sequentially (first to last)

           Df SumsOfSqs MeanSqs F.Model      R2 Pr(>F)
dat2$group  1   0.42041 0.42041  25.488 0.59989  0.001 ***
Residuals  17   0.28041 0.01649         0.40011
Total      18   0.70082                 1.00000

So all we have really done here (still using the G1vsG5 example) is

calculate an F test for the raw comparison (of the dissimilarity values, which are mathematically equivalent to differences in the raw data since we used Euclidean distance),
shuffled the raw data and calculated a new F statistic
repeated step 2 999 times to create an empirical F distribution (generating the null model),
and finally calculated the probability of the observed F value occurring under the null model:

perm<-permustats(res2)
densityplot(perm)

So if all we are really doing is comparing F values that are calculated from the normal anova/linear model, is this really a valid "non-parametric" approach to make pairwise comparisons?
Answer:
Am I incorrect in saying that this is equivalent to a simple series of pairwise anovas with p-values calculated according to the observed F statistics probability under the empirical null distribution that was generated through random permutations of group membership (or "location" membership in this case).

No, you are not incorrect.

If so, how can this be a valid non-parametric approach to pairwise comparisons?

It depends what you take to be meant by "non-parametric"?
If you take that to be synonymous with classical rank-based tests, then no, PERMANOVA is not non-parametric.
If you take that term to be something broader, where we relax (to some extent) the distributional assumptions, then PERMANOVA is non-parametric. The distributional assumptions are relaxed because we do not use a parametric distribution to generate the null distribution of the test statistic. Instead we use a permutation test to generate the null distribution of the test statistic.
PERMANOVA used to be called NP-MANOVA and I think the new name or PERMANOVA helps clarify some of your concern. The PER bit stands for permutation and reflects the use of permutations to avoid the stricter distributional assumptions of classical ANOVA or MANOVA.
Regardless, the method is a valid method (and the pairwise part is irrelevant as we can use a pairwise-based test statistic or the omnibus test statistic for the overall model) given a set of assumptions, as with any test.
The important bit is that we can compute any reasonable test statistic for the permutation test and it just so happens that it is easy and useful to compute the F statistic in adonis(). Computing that statistic is just an exercise in math (or computation); we just do the math on the input data. This is all valid at this point.
Where we have issues is if we want to assign a p-value to the result. We could use standard parametric theory here but we'd typically get the wrong answer and biased p-values if we did. Instead we try to resolve that by using a permutation test. The computation of the test statistic itself is not invalidated by the assumptions of ANOVA/MANOVA as those assumptions apply to the theory used to justify the use of the null or reference distribution for construction of the p-value, and not to computation of the statistic itself.


Communication between Windows Client and Linux Server

Question: I want to provide my colleagues with an interface (using Windows Forms or WPF) to control the states of virtual machines (KVM based) on a linux host. On the command line of this server, I'm using a tool, called libvirt, which provides python bindings to access its functionality.
What whould be the best pratice to remotely access several function like libvirt or reading logfiles on the server. I thought about a REST Full Webservice generated by Python. Are there other viable options to consider?
Thanks,
Henrik
Answer: I'd develop an intranet web application, using any python web framework of choice.
That way you don't have to develop/install software on your client. They just point the browser and it works.
Answer: Proxmox VE is a complete solution to manage KVM (and OpenVZ) based virtual machines, including a comprehensive web console, so maybe you can get a full solution without developing anything?
Answer: Because you are using a server-side tool that has Python bindings, you should give a serious look at PYRO which is a Python RPC library.
http://pyro.sourceforge.net/
To use this you would also have to use Python on the client, but that shouldn't be a problem. If you haven't start writing your client, then you could do it all in IronPython. Or, if you need to add this to an already existing client, then you could still bind in either IronPython or CPython as an embedded scripting engine.
For more on PYRO and Ironpython, see this wiki page http://www.razorvine.net/python/PyroAndIronpython


Two different approaches to $x^{(\log_{10}x)^2-3\log_{10}x+1}\gt1000$ with different results

Question:
Problem Statement:-
Find the set of real values of $x$ for which
  $$x^{(\log_{10}x)^2-3\log_{10}x+1}\gt1000$$

Correct Approach:-
Domain of $x^{(\log_{10}x)^2-3\log_{10}x+1}\implies x\gt0$
Now, $$x^{(\log_{10}x)^2-3\log_{10}x+1}\gt1000$$
Taking $\log_{10}$ on both sides, we get
$$((\log_{10}x)^2-3\log_{10}x+1)(\log_{10}x)\gt3$$
Let $z=\log_{10}{x}$
Hence, $(z^2-3z+1)z\gt3\implies z^3-3z^2+z-3\gt0$
Fortunately for factorising the polynomial we dont have to go too far we get the first factor at $z=3$. So, on factorising, we get
$$(z-3)(z^2+1)\gt0$$
As, $\forall z\in\Bbb{R}.(z^2+1\gt0)$, hence $$z-3\gt0\implies z\gt3\implies \log_{10}x\gt3\implies x\gt1000$$
Incorrect Approach:-
Domain of $x^{(\log_{10}x)^2-3\log_{10}x+1}\implies x\gt0$
We also see that for $x=1$ the inequality is not satisfied, so we would not be eliminating any values from the interval satisfying the inequality by putting the condition $x\neq1$
Now, take $\log_{x}$ on both sides to get
$$((\log_{10}x)^2-3\log_{10}x+1)\gt\dfrac{3}{\log_{10}x}\\
\implies ((\log_{10}x)^2+1)\gt\dfrac{3}{\log_{10}x}+3\log_{10}x$$
Using $A.M.\ge G.M.$, we get
$$((\log_{10}x)^2+1)\gt6\implies (\log_{10}x)^2\gt5\implies -\sqrt{5}\lt\log_{10}x\lt\sqrt5\\
\implies 10^{-\sqrt{5}}\lt x\lt10^{\sqrt5}$$
But, as we had excluded $1$ as a solution, so the interval satisfying the inequality comes out to be $x\in(10^{-\sqrt5},10^{\sqrt5})-\{1\}$

I have tried two different approaches to the problem, while one does provide the correct answer and the other doesn't but what is wrong with the incorrect approach.
Answer: There are a couple of mistakes in your last approach
In using $AM \ge GM$ you assume that $z > 3$, which I guess you got from the first result. What follows from there is
$$
\frac{z^2 + 1}{2} > z > 3 \quad\Rightarrow\quad z^2 > 5
$$
What you can conclude from this is
$$
|z| > \sqrt{5} \quad\Rightarrow\quad z > \sqrt{5} \quad\mbox{or}\quad z < -\sqrt{5}
$$
The second region is in contradiction with what you assumed before ($z>3$), so you end up with $z > \sqrt{5}$. So the region is $\{z : z > \sqrt{5}\mbox{  and  } z > 3\} = \{z : z > 3\}$ which is the first result
Comment: If you assume $z=\log_{10}x$ as in my correct approach, then I didn't assume anything for $z$ in my incorrect approach. In fact, I had tried the incorrect approach first rather than the correct one. Also it seems in your statement-"In using $AM \ge GM$ you assume that $z > 3$, which I guess you got from the first result." you are telling that it is necessary to assume $z\gt3$ to apply $AM \ge GM$
Comment: @user350331 Perhaps I misunderstood, but how do you conclude that $z^2 + 1 > 6$?
Comment: By using $AM\ge GM$ on $\dfrac{3}{z}+z$ to get $\dfrac{3}{z}+z\ge2\times3\implies \dfrac{3}{z}+z\ge6$, I might just add a little something which makes a lot of difference and I might just start to see why my second answer is faulty, which is $z\gt0\implies x\gt1$. And, similarly for $z\lt0\implies x\lt1$, we get $\dfrac{3}{z}+z\le-6$, this case is trivial to consider since we would arrive at $z^2+1\gt-6$ which is trivially true.
Answer:
$$((\log_{10}x)^2+1)\gt\dfrac{3}{\log_{10}x}+3\log_{10}x$$
Using $A.M.\ge G.M.$, we get
$$((\log_{10}x)^2+1)\gt6$$

One problem is that you can't use AM-GM to begin with, since at this point it hasn't been established that $\log_{10} x \ge 0$ and AM-GM only works for non-negative numbers.
The major problem with this step, however, is that you essentially need to prove $a \gt b$, but instead you use $a \gt b \gt c$ and prove $a \gt c$, yet this does not prove the original inequality $a > b$.
Consider for example how the same (wrong) logic could be used to prove the obviously false: $$4+4 \gt 1+8$$

Using $A.M.\ge G.M.$, we get

$$4+4 \gt 2 \sqrt{8} = 4 \sqrt{2}$$
which is true, even though the inequality we needed to prove $8 \gt 9$ is false.


UICollectionViewCell constraint error after reloadData

Question: This is my custom UICollectionViewCell code. I am only giving a constraints for the subviews in the configureViews() function.
class CategoryCell: UICollectionViewCell {
  private lazy var nameLabel: UILabel = {
    let label = PaddingLabel()
    label.numberOfLines = 1
    label.adjustsFontForContentSizeCategory = true
    label.font = UIFont.boldSystemFont(ofSize: UIFont.preferredFont(forTextStyle: .subheadline).pointSize)
    label.textAlignment = .center
    let widthConstant = floor((UIScreen.main.bounds.size.width) / 3)
    label.widthAnchor.constraint(equalToConstant: widthConstant).isActive = true
    return label
  }()

  private lazy var bottomLine = UIView()

  override init(frame: CGRect) {
    super.init(frame: frame)
    configureViews()
  }

  required init?(coder: NSCoder) {
    super.init(coder: coder)
    configureViews()
  }

  override func prepareForReuse() {
    super.prepareForReuse()
    nameLabel.text = nil
  }
}

private extension CategoryCell {
  func configureViews() {
    contentView.addSameSizeConstrained(subView: nameLabel)
    contentView.addSubview(bottomLine)

    bottomLine.translatesAutoresizingMaskIntoConstraints = false

    NSLayoutConstraint.activate([
      bottomLine.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
      bottomLine.topAnchor.constraint(equalTo: contentView.bottomAnchor),
      bottomLine.trailingAnchor.constraint(equalTo: contentView.trailingAnchor),
      bottomLine.heightAnchor.constraint(equalToConstant: AppLayoutGuidance.spacingHalf / 4),
    ])
  }
}

When the cell is first rendered, there is no problem, but when I call the collectionView.reloadData() function, a constraint error appears on the console. Do you have any idea?
Edit: Constraint Console Log
"<NSLayoutConstraint:0x600000d01090 App.PaddingLabel:0x13d494320.width == 130   (active)>",
"<NSLayoutConstraint:0x600000d010e0 H:|-(0)-[App.PaddingLabel:0x13d494320]   (active, names: '|':UIView:0x13d467360 )>",
"<NSLayoutConstraint:0x600000d01130 App.PaddingLabel:0x13d494320.trailing == UIView:0x13d467360.trailing   (active)>",
"<NSLayoutConstraint:0x600000d02850 'UIView-Encapsulated-Layout-Width' UIView:0x13d467360.width == 0   (active)>"

Comment: Can you show the cell in its entirety?
Comment: I'm sorry, and can you share the error or warning message in the debugger console? This is such a simple cell, why even use a stack view? Just add the label and the line to the cell's content view using constraints. You can simplify this cell down to something so basic that it's virtually future proof.
Comment: Yes you're right this is simple cell but at the beginning I was planning to add other subviews. I edited my question according to your comment, is that what you wanted to say? By the way, this is still produces a constraint error when the reloadData function triggered. There is no problem in the first rendering.
Comment: And what's the error or warning message in the console?
Comment: I added the console warning to the question.
Answer: I think the addSameSizeConstrained function, as the name suggests, makes the frames of the view added with the contentview the same.So the width of the nameLabel is equal to the contentView.
But when defining the label, you gave the label a width value of floor((UIScreen.main.bounds.size.width) / 3)
UIView-Encapsulated-Layout-Width' UIView:0x13d467360.width == 0 this message is basically give us that information. You have to give priority one of the constraint , these are :

nameLabel width constraint in declaration = floor((UIScreen.main.bounds.size.width) / 3)
nameLabel width constraint in equaled contentView width in addSameSizeConstrained

You can fix this by giving priority to one of the constraints:
let widthConstant = floor((UIScreen.main.bounds.size.width) / 3)
let const = label.widthAnchor.constraint(equalToConstant: widthConstant)
   const.priority = .defaultLow
   const.isActive = true
return label

You are not getting this warning in console for first time load  because your collectinview's estimated size must be Automatic. If you change with None , you will see this warning when you load for the first time.


In American football, where do the officials mark the tackle?

Question: I watch both NFL and CFL, so I might be confusing what each league does, but here is what I think I have noticed:

sometimes a player gets the ball after the snap, they are blocked, and they are pushed several steps back but officials mark the tackle where the player was grabbed, and not where the tackle ended.
contrary to the above, when a tackled player keeps moving forward while falling, it seems like the ball is placed where the fall ended.

This feels incoherent to me. What do the rules say about the placement of the ball after a tackle?
Answer: The game as a whole is made simpler and more coherent if it is only possible to move forward when attacking, and this requires that it not be possible to move forward when defending. To be attacking, a team must have possession, one way or another. The exception is backward movement made as part of the attack, i.e. the snap and any backward passes or runs: the attacking team sacrifices territory now in order to gain territory in several seconds.
Each attempt at moving the ball forward is called a down. A down ends when the player with the ball is tackled (see further definition later) or leaves the field of play, some kind of score occurs, a pass is incomplete, or the player in possession stops making forward progress. Note that

the down ends, the ball is dead, and no further "in play" action can occur from that exact instant, even if it is not known until some time later when precisely the instant was;
the ball is placed for the next down based on its position when the down ends, and not for example when a defender first made contact with the attacker or when the attacker first took possession.

In the case of a player moving backwards, the player stops making forward progress because they have begun doing the opposite.
In the case of a player falling forward, a tackle requires that some part besides the hand or foot of the player in possession has touched the ground (or any part of that player or the ball has touched an object or ground outside the field). Since the player is still making forward progress, every inch of territory gained until the down has actually ended must be counted.
Answer: The rationale here is that when the defense stops the ball carrier, it is preferable that they do not get any benefit from holding the carrier up (so the play would remain live) and just pushing them backward a huge distance instead of tackling.
This concept is in the rule book as "forward progress"

SECTION 13 FORWARD PROGRESS
ARTICLE 1. FORWARD PROGRESS. The Forward Progress of a runner or airborne receiver is the point at which his advance
toward his opponent's goal ends and is the spot at which the ball is declared dead by rule, irrespective of the runner or receiver
being pushed or carried backward by an opponent.

Note in the wording that forward progress is only stopped by the opponent.  If the ball carrier advances and then on their own decides to retreat (presumably to find a better position elsewhere), then they do not have benefit of forward progress.  If they are tackled during the retreat, the ball is marked at that spot.  Not the more forward position that was held earlier.


Pegar a quebra de linha em um arquivo e colocar o conteúdo em uma variável

Question: Eu estou pegando um arquivo em PHP.
$arquivo = file_get_contents($_FILES['arquivo']['tmp_name']);

Eu quero saber como eu faço para pegar este arquivo e colocá-lo em uma array para cada quebra de linha que ele encontrar \n.
por exemplo:
Nome 1
Nome 2
Nome 3
Nome 4

Eu irei pegar estes 4 nomes em um arquivo .txt e coloca-los em um array. O objetivo é colocar todas as informações em um vetor e escreve-las.
Answer: Pode usar a função explode() para isso:
$nomes = explode("\n", $arquivo);

Caso queira somente visualizar os dados, você pode utilizar o nl2br() ou iterar os resultados:
echo nl2br($arquivo);

foreach($nomes as $nome){
    echo $nome;
}

Comment: Como eu faço para escrever as variáveis?
Comment: Com `print_r` ou use um `foreach` para iterar os resultados. Pode também referenciar linha por linha usando o índice do *array* `$nomes[0]`
Answer: Utilize a função file(), ela lê o arquivo selecionado para um array.
$lines = file ('arquivo');

// Percorre o array, mostrando o número da linha que está
foreach ($lines as $line_num => $line) {
    echo "Linha #{$line_num+1} : {$line}
\n";
}


Ubuntu 12.04 stuck on "checking for running unattended upgrades" message while restarting

Question: I'm running Ubuntu 12.04 on my computer, my hard disk is shared by another thin client terminal.
When I try to shut-down or restart my computer I get a black screen with the words halted and nothing else happens.
This is the screen I get:

Thank you in advance.
Comment: This is not a programming question. It belongs on [ubuntu.se] or [su] instead.
Answer: I once faced this problem with Ubuntu 12.04 on a HP x360 and I fixed the problem by adding acpi=noirq to the kernel arguments.
To do this you'll first you'll need to go open the /etc/default/grub file like this:
sudo nano /etc/default/grub

Then you'll need to set the line that starts with GRUB_CMDLINE_LINUX_DEFAULT to this:
GRUB_CMDLINE_LINUX_DEFAULT="acpi=noirq quiet splash"

Save your file using:
ctrl + o

Then exit nano using:
ctrl + x

You must then update grub like this:
sudo update-grub

Good luck and all the best.
Comment: Thank you mango for your help, I tried but this not worked for me. I found  where was the problem, actually when i got this error-> E: Could not get lock /var/lib/dpkg/lock - open (11 Resource temporarily unavailable)
E: Unable to lock the administration directory (/var/lib/dpkg/) is another process using it? so i used following command=>1. sudo rm /var/lib/apt/lists/lock  2.sudo rm /var/cache/apt/archives/lock . so due to this my system was broken. so i reinstalled the ubuntu 12.04 (64bit) and xrdp on it. Now it working and this error is gone..!  Thanks Ones again
Comment: @firefly Anytime. Feel free to up-vote if you think this was a good answer.


JavaScript OnMouseDown Image Hover Effect Help

Question: So here's the thing I made a stopwatch (that you can view here).
However when you try it out you'll see there's some problems, and what I'm trying to achieve is...
When I hover over the start button, it's rollover shows, but when I click down the stop button appears, and when the mouse button is up the stop buttons rollover/hover image appears.
In which it does what I want it to there, but when you hover off the stopwatch when the time is going the start button appears when I want the stop button to remain.
Additionally, when the time is going, and the cursor is still on the stop button, once it's pressed again instead of showing the start button, like I want it still shows the stop button.
Now I know I haft to use the If, and Else If statements with this however I'm unaware on how to get this to work. (I've spent almost 3 hours trying to find the answer, and just having a inner blonde moment today all day)
Can anybody help???
Comment: Your (cross-browser) life will be made a **lot** easier if you use a JS library, such as jQuery, MooTools, Dojo, YUI, Prototype... doesn't really matter which one.
Comment: The problem might be because you are using image which has "start" and "stop" written on it. I'd recommend to use a plain image without any text, and let the text be changed with JavaScript based on user actions. And you can always use CSS3 to stylize overlay text the way you want.
Answer: Try this :

        <A HREF="#" onclick="started = !started;findTIME();"
        onMouseOver = "if(started){document.images['imBut'].src='images/stophover';}else{document.images['imBut'].src='images/starthover.png';}"
        onMouseOut = "if(started){document.images['imBut'].src='images/stop.png';}else{document.images['imBut'].src='images/start.png';}"
        onMouseDown = "document.images['imBut'].src='images/stop.png';"
        onMouseUp = "document.images['imBut'].src='images/stophover.png';"


A doubt on Wald's identity proof.

Question:
Here we've just proved that $S_T$ is integrable.The last text line of the proof, which is missing from the picture, states that «the same computation without the absolute values yields the remaining part of the claim», i.e., the same computation withou abs values yields the equality $E(S_T)=E(T)E(X_1)$. My question is how do we get equality without abs values?
Since, from a theorem in the previous page $E\sum^{\infty}X_i=\sum^{\infty} EX_i$, if $X_i\geq_{a.s.} 0$ for all $i$. Hence, I don't understand why the same computation would be allowed, since without abs values, the r.v. can take negative values (they are real r.v.), and the theorem wouldn't be usable anymore.
So, as an alternative, I was thinking of using the positive and negative part of $S_T$, and then the difference of both (which we can since $S_T$ is integrable). Would this be ok?
Comment: Indeed $E\sum X_k=\sum E(X_k)$ when every $X_k$ is almost surely nonnegative, *and also when* $E\sum|X_k|$ and/or $\sum E|X_k|$ converges (these two conditions being equivalent). The alternative you suggest does not work as such, since there is no reason to expect that $(S_T)^+$ would equal $\sum\limits_{k=1}^T(X_k)^+$.
Comment: @Did, thanks for the comment. I think I wrote something unclear. I had understood the equivalence you state in your 1st sentence. My doubt is how would you show then that we have the equality, using what the author states?
Comment: @Did I've edited the question, to make it clearer.
Comment: Fubini. Has been explained tons of times on the site (never in your questions? and you never met it à propos others' questions?).
Comment: @Did, yes I've heard of it, a long time ago (more than a decade ago), and it didn't stuck. I've trying to learn this by myself, but only now in a more systematic way. Also, the book I'm using, Klenke's Prob Theory isn't so nice in this regard. I'm reading a proof of chapter 5, when the 1st time he talks about Fubini is chapter 14 (I just did a ctrl-f on the pdf).
Comment: I think you can also use the Dominated Convergence Theorem here to plug the gap e.g. it's used at https://en.wikipedia.org/wiki/Wald%27s_equation. But I don't think that's covered in Klenke at all!
Answer: It is an application of the Fubini's theorem. The step in the picture is assuring that
$$ \sum_{n=1}^{\infty} \mathbb{E}\left[ \left| S_n \mathbf{1}_{\{T = n\}} \right| \right] < \infty. $$
So by the Fubini's theorem we have
$$ \mathbb{E}[S_T]
= \mathbb{E}\left[ \sum_{n=1}^{\infty}  S_n \mathbf{1}_{\{T = n\}} \right]
= \sum_{n=1}^{\infty}  \mathbb{E}\left[ S_n \mathbf{1}_{\{T = n\}} \right]
= \mathbb{E}[X_1]\mathbb{E}[T] $$
with the computational detail of the first equality and the third equality being the same as in your picture.
Comment: Many thanks for your answer Sangchul

A doubt on Wald's identity proof.


Problema no acesso à API Json com React

Question: Estou tentando acessar a seguinte variável no Json de uma API:
page[0].infoBloco[0].tabela[0].dados[0].fonte.nome

Estou recebendo o erro:
TypeError: this.state.page[0] is undefined[Learn More] index.jsx:49

O Json que a API retorna é o seguinte:
[
    {
        "infoBloco": [
            {
                "tabela": [
                    {
                        "dados": [
                            {
                                "fonte": {
                                    "url": "http://www.google.com",
                                    "nome": "Site de buscas"
                                }
                            }
                        ]
                    }
                ]
            }
        ]
    },
    {
        "infoBloco": [
            {
                "tabela": [
                    {
                        "dados": [
                            {
                                "fonte": {
                                    "url": "http://www.yahoo.com",
                                    "nome": "Outro site de buscas"
                                }
                            }
                        ]
                    }
                ]
            }
        ]
    }
]

O código da página React é o seguinte:
import React, { Component } from "react"

export default class extends Component {

  constructor(props) {
    super(props)
    this.state = {
      page: [],
    }
  }

  componentDidMount() {
    this.getData()
  }

  getData = async () => {
    await fetch('http://localhost:3003/api')
      .then(resp => resp.json())
      .then(data => this.setState({
        ...this.state,
        page: data,
      }))
  }

  render() {

    console.log(this.state.page[0].infoBloco[0].tabela[0].dados[0].fonte.nome)

    return (

        Exemplo

    )
  }
}

Eu só consigo acessar até page[0], quando tento acessar qualquer elemento mais interno retorna esse mesmo erro. Esse erro seria causado pelo acesso assíncrono à API? Alguém pode me ajudar a corrigir isso?
console.log(this.state.page) retorna o json completo
console.log(this.state.page[0]) retorna o primeiro objeto do json
console.log(this.state.page[0].infoBloco) gera o erro TypeError: this.state.page[0] is undefined[Learn More] index.jsx:49
Comment: Faz só `console.log(page);`, que resultado dá? Não deveria ser `console.log(this.state.page);`?
Comment: `this.state.page` retorna o json completo, a partir de `this.state.page[0].infoBloco` é que aparece o erro `TypeError: this.state.page[0] is undefined`
Answer: Em react, para acederes a objectos/valores que estão no state de um componente, deves usar this.state, no teu caso seria this.state.page
Comment: Podes por um if no `render`, tipo `if (this.state.page.length === 0)`. Também podes mudar o teu `.then` que tem o `setState` e fazer `setState` para colocar no state apenas o que precisas, em vez da raiz do objecto (`pages`). Se não precisas de usar o caminho especifico como tens no exemplo, em que usas só 1 dos items, o melhor é fazer ciclos para listar tudo, se estiverem vazios nada renderiza, mas quando há dados, vai funcionar normalmente.
Comment: Funcionou, estou verificando com if, mostrando uma mensagem de load e quando page está preenchido eu renderizo o componente. Muito Obrigado!
Comment: Realmente eu havia esquecido de colocar o this.state aqui no stackoverflow, mas o código original está como console.log(this.state.page[0].infoBloco[0].tabela[0].dados[0].fonte.nome) e retorna esse mesmo erro. Muito obrigado pela observação!
Comment: E se fizeres `console.log(this.state.page);`? O array está vazio? Ou não é nem um array?
Comment: `this.state.page` retorna um array completo com os dois objetos json.
`this.state.page[0]` retorna o primeiro objeto do array.
`this.state.page[0].infoBloco` retorna o erro `TypeError: this.state.page[0] is undefined`
Comment: Adiciona o output a pergunta de quando fazes `console.log(this.state.page)`, estranho dar erro só quando acessas a uma propriedade do `page[0]`
Comment: Só para constar o recomendado pela documentação é mesmo usar `setState` e não atribuir o estado diretamente. Isso irá fugir a certos casos especificos que podem dar em bugs particulares.
Comment: No código delete, ele tem a chamada ao `setState`, mas o problema pode estar ai sim. Gostava de ver o que tem o `page` para tentar perceber. Pode também ser de ainda não ter recebido a resposta a API quando faz o render, e estar a tentar aceder a índices no array que ainda não existem, mas ai `this.state.page[0]` não devia retornar o objecto que ele está a espera.
Comment: Ok, adicionei um link com o print logo após `console.log(this.state.page)` na pergunta original
Comment: Aparentemente está a fazer log 2 vezes, pelo output da consola. Isso será então o que mencionei no comentário acima, a primeira vez que entra no `render`, o resultado da chamada a API ainda não retornou.
Comment: E como posso fazer para o resultado ser exibido só após ser recebido da api? tenho que usar algum outro código ou middleware?
Answer: Solução fornecida por Leite
import React, { Component } from "react"

export default class extends Component {

  constructor(props) {
    super(props)
    this.state = {
      page: [],
    }
  }

  componentDidMount() {
    this.getData()
  }

  getData = async () => {
    await fetch('http://localhost:3003/api')
      .then(resp => resp.json())
      .then(data => this.setState({
        ...this.state,
        page: data,
      }))
  }

  render() {

    //soluciona o problema do preenchimento da variável page
    if (this.state.page.length === 0) return
Loading, please wait…

    return (

           Exemplo: {this.state.page[0].infoBloco[0].tabela[0].dados[0].fonte.nome}

    )
  }
}

Problema no acesso à API Json com React


node_delete_confirm_submit() and hook_node_delete()

Question: Still getting my head around Drupal 8 after using Drupal 7 for so long. I want to override (alter) the node delete action. Now in Drupal 7 I would have used  node_delete_confirm_submit() and hook_node_delete() or similar such as using hook_form_alter and changing the submit function.
In Drupal 8 this has partly changed. I can still use hook_node_delete(), but there is no node_delete_confirm_submit() which was deprecated in favor of \Drupal\Core\Form\ConfirmFormBase. Rather than try and create a hack I would like to learn the proper way I should be doing this.
I have tried to use ConfirmFormBase. I have a src/Form/DeleteXXXConfirm.php file.
namespace Drupal\XXX\Form;

use Drupal\Core\Form\ConfirmFormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;

class DeleteXXXConfirm extends ConfirmFormBase {

   ... code here for confirm and delete ...

}

Since I want to override node/nid/delete, I assumed the routing file would look something like this.
XXX.delete:
  path: '/node/{id}/delete'
  defaults:
    _form: '\Drupal\XXX\Form\DeleteXXXConfirm'
    _title: 'Confirm Deletion'
  requirements:
    _permission: 'administer site configuration'
    id: ^\d+$

This doesn't appear to work, do I need a Controller? Or am I totally barking up the wrong tree? I am obviously misunderstanding something. Can anyone point me in the right direction?
Comment: No, in Drupal 8 you cannot define in a module a route another module is defining. That is not different from Drupal 8. The difference is that there isn't anymore `hook_menu_alter()`, but there is still a way to alter routes another module is providing.
Comment: @kiamlaluno thanks for the reply. You say **but there is still a way to alter routes another module is providing** but don't say how. So question then is how do you alter entity.node.delete_form ?
Answer: I've found inspecting the routes availble and then working back to the controller to be a super helpful way to understand how to override things.
You will need Drupal console installed.
For example run
drupal router:debug | grep node | grep delete

This will list all routes, and then filter only ones with node in and then filter only ones with delete in.
You should then see the route you are interested in (/node/{node}/delete) is called entity.node.delete_form
Now you can debug just that specific route:
drupal router:debug entity.node.delete_form

This will show you that the form for this route is called node.delete. If however there was a method and a controller for the route is would show you exactly what the callback is.
To change the entity.node.delete_form route to use your own callback you can use the new method of doing menu_alter.
However if you want to keep the same node delete form and just change the submit handler then you can still use hook_form_alter to change this.
Comment: I did not in the post I have used form alter and the changed the submit handler. The issue I have is it seems to get called twice when confirming deletion and looking at what is submitted it is identical on both calls. Wouldn't be an issue but using `drupal_set_message` appears on the confirm page and then again after deletion. Never thought of using drupal console to trace it. Not sure why. Will give it a go and report back. Thank you Felix.
Comment: So not figured out hook_form_alter being called twice. But making progress usin the new Drupal 8 methods work, routing and menu callbacks, etc. Once I have a working sample will put it on here.