Selenium Webdriver with Java: Not able to locate element on the browser popup window

Question:
Go to this URL: https://sports.ladbrokes.com/en-gb/
Click on "JOIN NOW" at the top right of the window
It opens a window pop up, where I need to enter 'First name' and other info

Though the 'First name' input box has the input tag with name attribute in the DOM, I am not able to find it with usual way. Please suggest!
When I say usual way, something straight forward like below is not working:
driver.findElement(By.xpath("//input[@name='firstname']"));
driver.findElement(By.xpath("//input[@placeholder='First name']"))

Comment: Please post the code that you have tried
Comment: you have to switch that window and then use that code
Comment: Check the code it is working for me. let me know if u have any concern
Comment: Learn it from mukesh otwani tutorial on youtube
Answer: First you have to enter into the iframe and then locate the fields. try below code it works for you:
WebDriver driver= new FirefoxDriver();
driver.get("https://sports.ladbrokes.com/en-gb/");

// click on the Join now button
driver.findElement(By.xpath(".//[@id='loginSubmit']/div[3]/button[2]")).click();

//find Locator of  frame
WebElement frampath= driver.findElement(By.xpath(".//iframe[(@class='lightbox-registration-frame')]"));

//switch to frame for operations
driver.switchTo().frame(frampath);
driver.findElement(By.name("firstname")).sendKeys("fdf");
// more operations
//statement1 (operation you want to perform)
//statement2(operation you want to perform)

driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

//Switch to main page
driver.switchTo().defaultContent();

Comment: I am a newbie to Selenium. do let me know if there a place where I can read and practice about complex element recognition. Thanks again!
Comment: I am also a  newbie:)
Answer: It's an iframe which means you have to switch to the iframe first before you can locate elements there.
this is untested but something similar to this
driver.switchTo().frame("lightbox-registration-frame")

driver.findElement(By.xpath("//input[@name='firstname']"));
driver.findElement(By.xpath("//input[@placeholder='First name']"))

driver.switchTo().defaultContent(); // <- important if need to switch back to original window

You may also need to use a wait to allow the iframe to appear/load. I noticed it took a second or 2 to load so if you try to switch immediately you'll end up with an unable to find iframe exception.
Also note that in my example i used "lightbox-registration-frame" to find the iframe which may not necessarily be correct. Generally you want to use the name or id of the iframe which i didn't see so you may need to use an index or some other method to find the iframe.


Gostaria de enviar os dados de um arquivo txt(lido) para uma listbox

Question: Por exemplo:
Leitura do arquivo
string [] linhas = File.ReadAllLines("ip.txt");
Console.ReadLine();

fiz a leitura do arquivo, agora, quero jogar eles em uma ListBox, como fazer?
Comment: Você está usando Formulários?
Comment: sim. windows form, eu consegui ler um arquivo, agora quero enviar ele para a listbox
Comment: o que tem cada linha do arquivo txt?
Comment: IP's 184.108.40.206, vou tentar antes de enviar para listbox, validar se o ip é valido ou não
Comment: cada linha é um IP? como está formatado esse txt?
Comment: cada linha é um ip, existem ips validos e uns não, preciso validar e enviar pra listbox valida ou invalida por exemplo :
126.96.36.199
192.168.1.1
18.104.22.168
2126.96.36.199
85.345.1.2
22.214.171.124
126.96.36.199
192.168.0.256
Comment: Você quer na pergunta uma coisa não tem validação, como está validando?
Comment: vou explicar detalhadamente, preciso ler o arquivo txt, validar se o ip é valido ou não, e enviar pra uma listbox :IPAddress ipAddr;
            string addr = " 188.8.131.52";

            bool res = IPAddress.TryParse(addr, out ipAddr);

            if (res)
                Console.WriteLine("ip valido");

            else
                Console.WriteLine(" ip Invalido");
Answer: Basicamente para ler um arquivo de texto onde cada linha represente um número ip e adicionar em um ListBox é simples:
using (StreamReader str = new StreamReader("ip.txt"))
{
    string item = string.Empty;
    while ((item = str.ReadLine()) != null)
    {
        if (IPAddress.TryParse(item, out _))
        {
            listBox1.Items.Add(item);
        }
    }
}

Nota: a estrutura que está utilizando tem baixo desempenho e como vai precisar iterar em cada linha a melhor forma é essa, fazendo dentro da própria leitura a adição, economiza memória e aumenta desempenho.
Comment: cara, muito obrigado mesmo, deu certo o que pedi, você sabe alguma função que eu possa validar se o ip é valido ou não? são duas listbox, ip valido e ip invalido
Comment: Muito obrigado! c# não é a minha praia. mas outras linguagens, pode ter certeza que irei acompanhar o fórum e tentar ajudar o pessoal, acredito que isso seja a ideia do site.
Comment: @Matheusbatista fiz a alteração com a validação e o descarte onde só precisa do valor texto.
Comment: caraca, mano, muito obrigado mesmo, deu certinho... como posso te recompensar? nunca pensei que alguém conseguiria ajudar tanto assim.
Comment: @Matheusbatista só quando criar uma pergunta coloque todos os detalhes na própria pergunta e seja bem claro, quando você aceita a pergunta e clica na seta pra cima já está ajudando a comunidade.
Comment: Não não @Matheusbatista aqui é para ajudar mesmo ... fica tranquilo


Random Graphs: Examples of their Uses

Question: Just writing a paper at the moment on random / random geometric graphs.
If any of you could perhaps give examples, as broad and interesting as possible, of where these have been used across science? I have plenty of examples, but thought this might be a good place to get some breadth of use.
Cheers!
Answer: Well, the Barabási-Albert model appears in context of social networks, neural networks and power grids. It is good because it reflects some properties that theses networks have, like the degree distribution is a power law. You can see this on the paper of Barabási and Albert:
Emergence of Scaling in random Networks
If you want something more recent, the preferential attachment models with fitness seems to appears in recommendation algorithms. Some comments about it you can find here:
First to Market is not Everything: an Analysis of Preferential Attachment with Fitness
by Borgs, Chayes, Daskalakis and Roch.
This use of random graphs is pretty interesting once the actual advertisement model is based on such algorithms. Google, Netflix, Facebook, Yahoo... All theses big companies are interested in such algorithms.
Hope this can help!
Comment: No problem. If you are interested in applications on the internet you can find them in the book "A Course on the Web Graph" there you can find a better explanation about random graphs and PageRank algorithms, for example.

Random Graphs: Examples of their Uses


Exponential equation - algebra

Question: I'm having trouble solving this type of equations:
$y^{x} = k + x$
Where $x$ is the only unknown variable.
I've tried substituting variables and all kind of things but I can never get to the answer.
The only way I've been able to solve for $x$ is by plotting $y^x$on a graph and plotting $k + x$ on the same graph and seeing where they intersect.
I'm trying to find a way of doing this without the need to draw it on a graph, if anyone has got any idea I'll greatly appreciate it.
Comment: Lambert W function can be applied here. This is a transcendental equation (with no elementary solutions).
Answer: Lambert W function reduces the transcendental equation
$$Xe^X=Y$$
to
$$X=W_n(Y),$$
where $n$ is the $n$th branch of $W$.
We use $W_n(\cdot)$ to solve this equation:
\begin{align*}
y^x&=k+x\\
e^{x\cdot\ln y}&=k+x\\
1&=(k+x)e^{-x\cdot\ln y}\\
-e^{-k}\ln y&=\big(\color{blue}{(-k-x)\ln y}\big)\cdot e^{\color{blue}{(-k-x)\ln y}}\\
W_n(-e^{-k}\ln y)&=\color{blue}{(-k-x)\ln y}\\
x&=-\frac{W_n(-e^{-k}\ln y)}{\ln y}-k.
\end{align*}
Comment:

In line 4, we multiply $-e^{-k}\ln y$ on both sides (so as to transform to the form $Y=Xe^X$, where $X=\color{blue}{(-k-x)\ln y}$).
In line 5, we use the property of $W$ function, i.e.
$$Y=Xe^X\implies W_n(Y)=X.$$
Comment: Do you mind explaining how you went from step 3 to step 4 and from step 4 to step 5, thank you
Comment: @rr1303 answer updated, feel free to ask.
Comment: You can also find some examples [here](https://en.m.wikipedia.org/wiki/Lambert_W_function#Solutions_of_equations)
Comment: Perfectly understood, also thanks for the examples. One last thing, is it possible to find an actual solution(s) or do we simply leave it as a function of W? In Wikipedia that is what they do.
Comment: Yes, we leave $W$ in the answer, like what $\sin$ or $\ln$ do.

Exponential equation - algebra


Raw eigenvectors or standardized eigenvectors for principal component regression?

Question: Thanks to @amoeba, I learned that standardized eigenvectors are sometimes calculated, i.e., eigenvectors are divided by the square root of their eigenvalues.
Now, when I want to do principal component regression (PCR), I first calculate the components that I subsequently use in regression.  There are two procedures that can be used:

I calculate my components once as raw components, that is I do not standardize the eigenvectors.
I calculate my components as components based on standardized eigenvectors.

Now, I do PCR once with the components in situation 1, and once with the components in situation 2.
My questions:

What are the implications (a) for the coefficients, (b) for the interpretation in the two cases?
What are the main differences?
I know that the variance of the components will differ, but how does that change the behaviour in regression, or does it at all?
Is there any recommendation to whether I should use the one but not the other?
Comment: maybe you will want to link to where amoeba has dropped the idea you are starting from? Because your question is unclear without that context.
Comment: PCA eigenvectors can be multiplied (not divided!) by the square roots of the eigenvalues to obtain *loadings*. In principal component regression one uses principal components, i.e. projections on the eigenvectors, and not eigenvectors themselves, so I am not sure what exactly you mean by your approach #2. Perhaps you mean standardized principal components (scaled to unit variance). If so, then notice that any scaling of individual predictors does not influence the regression at all, so the answer to your question is that **it does not matter.**
Comment: I tried to make it clearer. She didn't really drop the idea, rather uncovered my knowledge lacks.
Comment: In one case the components are standardized, in the other not.
Comment: It's common to express eigenvectors as unit vectors. I don't know what dividing each component by its eigenvalue would mean.
Comment: @duffy That would produce a *dual basis* for the eigenbasis.  It's a useful construct.  See https://stats.stackexchange.com/a/444058/919 for some details.
Comment: Thank you for pointing it out.  I was ignorant.
Answer: I'm reviewing this and found a nice paper Parameter Estimation in Factor Analysis: Maximum Likelihood versus Principal Component which makes me think that the eigenvectors are indeed standardized, if only for convenient interpretation. They're operating on a standardized nxp data matrix, $\mathbf{Z}$, where the variance matrix has ones on the diagonal and thus there  are p units of variance (the trace) "to distribute".
For eigenpairs $(\lambda_k, \mathbf{e_k}), k = 1, .., p$, the sum of the eigenvectors is still $p$ and the proportion of the variance is $\lambda_k / p$. To have the nice interpretation of distributing these p units of variance, you'd clearly have to be working with unit eigenvectors (though the paper doesn't specifically say it).
Answer: It might have something to do with whether your predictor variables are standardized or not (centered they must be!). If they are in original form, some eigenvector will be extremely large so standardizing them is a good idea (Why?). I don't see the point in standardizing them if your PCA used standardized (commensurating) variables already.
Comment: -1. That's not really an answer to the question.


Why can I sometimes find a note, other times not?

Question: I'm doing a bit of choral work in a tiny choir - one each of SATB typically so often there's nobody good to follow!
I'm finding we might have a phrase which goes D3-A3-C4, E4-C4-A3. Up to the £ I can find the notes but then I can't find the C after the E even though I literally just sang it.
What causes this - they're hardly big intervals - and other than just doing interval practice are there any good tricks I can use?
Answer: It probably has to do with the nature of the context. Many times jumping into a dissonance, even if you were just singing the pitch, will cause you to second-guess your concept of what pitch is coming next.
Harmonically, pitches can function differently based on context. B at the top of a e chord is different from B in the middle of a Gchord. Technically, this is because as a chorister you are blending towards a purer sense of tonality than the equal temperament that a piano might provide.
In your context, you're also jumping down to a note you just reached by ascending. Strangely enough, that change of context can cause the ear to misplace pitches too. A study of counterpoint may help you appreciate that a bit more.

So that is descriptive, for prescriptive:

Playing your part on piano or putting it into notation software is clearly a good first step.
I would recommend that you learn someone else's part on the piano and sing one part while playing the other. My general experience (and what I learned when in conservatory) is that it actually doesn't really matter which one you sing so long as you can put both in your ears at the same time.
You should also consider singing your part while holding down the notes you are having difficulty with. So If your are having difficulty with A-C-A, play A and hold it until you get to the second A.
Comment: Good point about practicing singing against a different part, that could be useful once I get it down in isolation. And an interesting answer, thanks.
Answer: What I would suggest is to try it home on your own, using a piano or guitar or some other instrument, so you can clearly hear the note you are singing. If you are trying to sing without some accompaniment, you are bound to get some mistakes at first. Also, when there are many voices singing with you, you might get confused and this might be why you cannot find the note.
Singing along with a piano has helped me a lot. Especially when I first tried to learn how to sing intervals and short melodies, I used a piano and sung what I was playing. I played the melodies or the intervals and sung them. After I got better, I played the first note and sung the rest, then played them to see if I had gotten them right.
This must be happening because you need practice. So,  keep practicing this part with the choir, but also do some homework on your own.
Comment: @Mr.Boy yup; nothing beats repetition in music. Try it again and again and eventually you'll get it right. But if even when you're on your own and you can't find the note, use a piano or guitar
Comment: Yeah, it's much easier on my own but even then I often can sing the A, and the C, but then I can't find the A coming back down. Or similar - especially if I have to go from chest->head voice or vice versa I get totally lost!  You're recommending good old repetition until it becomes engrained?
Answer: Valuable technique:
If you have sheet music for choir, it usually shows you the parts for all four voice sections and for the piano accompaniment. If you have an entrance where you have to hit a certain note and you can't find it in your head, then look through the notes in the two or three bars before your note -- look in the other parts on the other staves. It may be that the piano is playing that particular note a couple of beats before you need to sing it. Or perhaps the altos or tenors are singing that note (in a different octave). If you can find it, then circle your note on your staff, and circle the same note that occurs earlier on another staff, and draw a line between the two.
Then the next time you are rehearsing that section, you can remind yourself to listen for that note to be played or sung by the other parts, fix that note in your head, and then you will be prepared to sing it.
Any time you come across a tricky section where you are making mistakes in your own part, circle it in pencil. Then during breaks, look for other parts in the sheet music that can help you figure out how to sing that particular problematic lick in your part. Make as many annotations (lightly in pencil) on your sheet music as you need.
Also, in rehearsal, during breaks in the action and when you are sure that you are not being disruptive and it is not interfering with the work of the choir director, you can lean over to your fellow musicians, point out a problem area you have circled, and ask them to explain or sing or hum the lick that is giving you trouble. Be careful, though, because a choir contains a lot of people sitting close together, and singing or humming out loud during breaks can be disruptive to others' concentration and thought processes.
Update: Each note depends upon a different context in the music. Finding the note you need to sing is always dependent upon the notes that the other vocal parts are singing at that instant, and the notes that the piano accompaniment is playing. The first time you have a particular note to sing, it might be one note in a chord where your note fits neatly into consonant intervals being sung by the other voices, so it's easy for your ear and your brain to find your note. The next time this note appears, it may be in a dissonant interval against one or more of the other voice parts. That would make it harder for you to sing it, because it might sound "wrong" to your ears even though that's the way the composer wrote the song. Now you don't need to analyze all the chords in detail -- that takes time, schooling and ability. But you can learn to become aware, in general terms, of consonance and dissonance at any given point. Your choir director might point out a certain note and say, "Hey, Basses, that particular note is supposed to clash with the tenor note. Don't be shy about singing it", etc.
Answer: I recommend working through a sight singing book, step by step.  Such books are written in a progressive way, and they show you the tricks you are looking for.  It will take you a few months to work your way through it.  It will be fun.
Comment: @Mr.Boy - I don't have experience with the online resources.  But I do have experience with sight singing books.  I can't recommend them enough for what you want to accomplish.
Comment: These days, would some online resource be better - a set of Youtube lessons for instance or a paid online video course? Wouldn't they offer everything a book does plus more interactivity?


angular 1.5X [ngOptions] for regular array

Question: I'm trying to create a drop down menu from a simple array in Angular using the ngOptions attribute from angular 1.5, however after reading the docs and browsing the web I can't seem to get it to work with a 'simple' array (with objects it works fine).
I got the following Data
 ["Interne Vacatures","Human Resources","Sales"]

I use the following code in my view
<select class="form-control" ng-model="widget.GroupNameSearch" id="widgetselectedGroupName" ng-options="group as widget.GroupNameSearch for group in widget.GroupNameSearch | orderBy:'GroupNameSearch' track by widget.GroupNameSearch">
   <option value="" disabled selected>--- Kies een group ---</option>
   <option value="" ng-if="false"></option>
</select>

However my html creates the following:

I am not sure why it produces these results but if i change my array to a json object I can get it to work. Unfortunetly I don't ant to waste the memory. Below is a working example with JSON:
{"groupName": {
    "groupName":"Group 100",
    "mail":"firstname.lastname@example.com"}
}

  <select class="form-control" ng-model="widget.selectedGroupName.groupName" id="widgetselectedGroupName" ng-options="group as group.groupName for group in widget.GroupNameSearch | orderBy:'groupName' track by group.groupName" >
                    <option value="" disabled selected>--- Kies een group ---</option>
                    <option value="" ng-if="false"></option>
                </select>

Any help would be much appreciated.
Cheers!
Answer: This is happening because of widget.GroupNameSearch in your options.
ng-options="group as widget.GroupNameSearch for group in widget.GroupNameSearch.."
//                   ^^^^^^^^^^^^^^^^^^^^^^ this one

You are trying to reference whole array again as your reference to the current item.
It can be read as value as label for collection. Now, you should't have the whole array itself as label for each item, should you?
Instead, you can have it like this for the array of strings,
ng-options="group as group for group in widget.GroupNameSearch..

Comment: Thanks your answer pointed me in the right direction. Another problem was that the array was of the type string. so i had to recreate the array. Thanks a lot.
Comment: @RodneyWormsbecher glad it helped a little :)
Answer: To continue what tanmay said, make sure your ng-options are like this.
More about that here:
ng-options with simple array init

      <select class="form-control" ng-model="widget.selectedGroupName.groupName" id="widgetselectedGroupName" ng-options="a as a for a in groups">

https://jsfiddle.net/brhardwick/4eatv28b/1/


Need to randomize rank order,

Question: I have a ranking of items, $X = (x_1, \ldots, x_n)$. I want to obtain a random sequence $\hat{X}$, which is a permutation of $x_i$, such that the expected rank-correlation (say, Kendall) between $X$ and $\hat{X}$ is $\tau$, where $\tau$ is a parameter in range $[0, 1]$.
Comment: Of course, but I only need this in expectation, which should be possible I think.
Comment: I think it is not always possible. Rank-based correlations for finite samples are, kind of, "discrete". Not possible to make it equal to some random real number.
Comment: In theory there are myriad ways to do this.  Associated with each permutation $\sigma$ there is a rank correlation $\tau(\sigma)$ determined by $\sigma.$ All solutions consist of $n!$ probabilities $p_\sigma$ (indexed by the symmetric group and summing to unity) for which $$\sum_{\sigma\in\mathfrak{S}_n}p_\sigma \tau(\sigma) = \tau.$$  That's one more linear restriction on the probabilities, whence (generically) there is an $n!-2$ dimensional family of solutions.  To narrow them down, could you explain more about your underlying statistical problem and objectives?
Comment: Thanks for the comment. I need function which would compute (in Touring sense, i.e. I'm writing a program), efficiently, $\hat{X}$ from $X$, such that rank-correlation is $\tau$ in expectation.
Answer: Assuming you have a very large number of items in your rank it should be possible, the precision to which you will be able to match to $\tau$ will be determined by the size of your set.
Knowing that, you will want to work backwards from $\tau$, assuming that you have $n$ observations, we can get the concordant ($c$) discordant ($d$) pair ratio as follows:
$$
\tau =  \dfrac{c-d}{c+d}
$$
We also know that the total number of pairs for $\tau$ can be obtained using the following:
$$
{c+d} = \dfrac{1}{2}n(n+1)
$$
Hence:
$$
{c-d} = \dfrac{1}{2}n(n+1)-2d
$$
And if we plug that into the $\tau$ function:
$$
\tau = \dfrac{\dfrac{1}{2}n(n+1)-2d} {\dfrac{1}{2}n(n+1)} = 1-\dfrac{4d}{n(n+1)}
$$
We can now solve for $d$ which is the variable that will determine the correct permutation necessary:
$$
d = \dfrac{1}{4}n(n+1)(1 - \tau)
$$
This is where my mathematical knowledge reaches its limits, and the permutation will be calculated in python (I'm afraid it's a little convoluted, happy to refactor and add more comments):
<code>#Function to calculate Tau without needing concordant pair number
def tau_from_discordant_and_n(discordant, n):
    return 1-(4*discordant)/(n*(n+1))

#Entrypoint to get the right array for a given tau and input array
def permutation_for_tau(items: list, tau: float):
    desired_discordant_pairs = 1/4*len(items)*(1+len(items))*(1-tau)
    rounded_discordant_pairs = round(desired_discordant_pairs)
    permutation = permutator(items, rounded_discordant_pairs)
    return permutation, tau_from_discordant_and_n(desired_discordant_pairs, len(items))

# This function creates a permutation of the array increasing the number of discordant pairs by
# one at a time, for the array [1,2,3,4] the progression would be as follows:
# [1,2,3,4] => [2,1,3,4] => [3,1,2,4] => [4,1,2,3] => [4,2,1,3] => [4,3,1,2] => [4,3,2,1]
# The "thresholds" mentioned throughout the function indicate the point at which n number of
# digits are fully reversed within the start of the sequence. The adjustment value is the first
# digit after the sequence of fully reversed digits.

def permutator(items, discordant_pairs):
    thresholds = []
    previous_threshold = 0
    for i in range(len(items) - 1):
        current_threshold = len(items) - i - 1 + previous_threshold
        thresholds.append(current_threshold)
        number_of_fully_reversed_digits = i
        if discordant_pairs <= current_threshold:
            adjustment_digit = discordant_pairs - previous_threshold + 1
            break
        previous_threshold = current_threshold

    permutation = []
    for i in range(number_of_fully_reversed_digits):
        permutation.append(len(items) - i)
    if adjustment_digit != 0:
        permutation.append(adjustment_digit)
    missing_digits = list(set(items).difference(set(permutation)))
    permutation+=missing_digits
    return  permutation

array_to_permutate = [1,2,3,4,5,6]
results = [(permutation_for_tau(array_to_permutate, x/10)) for x in range(10, -1, -1)]
[print('Obtained tau of: {} with array: {}'.format(x[1], x[0])) for x in results]
</code>
Output:
<code>Obtained tau of: 1.0 with array: [1, 2, 3, 4, 5, 6]
Obtained tau of: 0.9 with array: [2, 1, 3, 4, 5, 6]
Obtained tau of: 0.8 with array: [3, 1, 2, 4, 5, 6]
Obtained tau of: 0.7 with array: [4, 1, 2, 3, 5, 6]
Obtained tau of: 0.6 with array: [5, 1, 2, 3, 4, 6]
Obtained tau of: 0.5 with array: [6, 1, 2, 3, 4, 5]
Obtained tau of: 0.4 with array: [6, 2, 1, 3, 4, 5]
Obtained tau of: 0.30000000000000004 with array: [6, 3, 1, 2, 4, 5]
Obtained tau of: 0.19999999999999996 with array: [6, 4, 1, 2, 3, 5]
Obtained tau of: 0.09999999999999987 with array: [6, 5, 1, 2, 3, 4]
Obtained tau of: 0.0 with array: [6, 5, 2, 1, 3, 4]
</code>
Let me know if you need any further clarification, hope this helps, I'm sure there are many more efficient ways to do the permutation, but this should be good enough.
Comment: I wrote a [comment to the question](https://stats.stackexchange.com/questions/421933/need-to-randomize-rank-order#comment787314_421933) that characterizes *all* solutions, no matter what $n$ may be.
Comment: I think it should be $n(n-1)$ instead of $n(n+1)$, right?

Need to randomize rank order,


How to get the super user in a functional test?

Question: How can I get the information for the super user (uid 1) in a functional test?
I want to test the external auth logic I have written, and one of the steps is authenticating the Drupal superuser locally instead of in the remote system. I am not seeing a way to get the username/password of that user in order to simulate a login.
Test:
  /**
   * The superuser should not authenticate to Netforum.
   */
  public function testSuperUserUsesDrupalAuthentication() {
    $this->drupalGet('user/login');
    $edit = ['name' => $this->rootUser->getEmail(), 'pass' => $this->rootUser->pass_raw];
    $this->drupalPostForm(NULL, $edit, t('Log in'));

    $user = \Drupal::currentUser();
    $this->assertEquals(1, $user->id());
  }

Comment: Hi @Kevin, did you get a chance to try out my suggestion below?
Answer: Looking into BrowserTestBase I accidentally found $this->rootUser->name and $this->rootUser->pass_raw last week. These are being used in installParameters(). I have not tested it, but I suppose you should be able to use those in other functions as well.
rootUser appears to be a full AccountInterface object, so getName() and other methods should work as well..
Comment: Gotcha, I updated my question with the test after you provided that information. It is returning 0, instead of 1. Am I getting the user wrong?
Comment: I am not sure, I did not dig that deep. You can compare `\Drupal::currentUser()` after `$this->drupalLogin($this->rootUser);`. I'd expect it to be 1 though....
Comment: For some reason drupalLogin fails because it can't find the "User %user successfully logged in." message on the page. So I use drupalPostForm, to simulate a log in
Comment: But if you get user 0... That is the anonymous user. I get the idea your user is not getting logged in. (Bad credentials?) What if you use the name instead of the email address?
Comment: I am enforcing the email address, as that is what the remote system requires. My module has amended the login form to reflect that (but I did not change the form field key of "name"). It works when I do it manually, I just want to automate it.
Comment: Hard to tell. Your test also loads the required modules and configurations etc. for that to work? Can you validate that the form had indeed been altered in your test?
Comment: Yep. I am only requiring user, node, and my custom module. The setUp method configures the connection settings. But even in this case, that wouldn't so much matter, as the UserAuth service has the exemption for user 1 (I do a user lookup and check the password, if true and account id is one, it goes no further).
Comment: I just checked, but `$this->rootUser->id()` returns 1 as expected. If you get 0, I conclude that your login has failed. But I don't see what else I can do to help you with this... Good luck :)
Comment: Even $this->loggedInUser says FALSE. Odd.
Comment: Oh my god. I am overthinking it. I am not even passing a path to drupalPostForm! But I also see that you are supposed to use drupalLogin... I don't think that works in my case.
Answer: The problem occurs because the password is not set to start with.
You can give this a try:
// Load real user object from UserSession object.
$admin_account = User::load($this->rootUser->id());
// The password is empty.
$this->assertFalse($admin_account->pass_raw);
// Set the password and save the User.
$new_password = $this->randomString();
$admin_account->setPassword($new_password);
$admin_account->save();
// Set the pass_raw directly on the User.
$admin_account->pass_raw = $new_password;
$this->drupalLogin($admin_account);

This is for the WebTestBase, if you use the BrowserTestBase, you should use the following (pass_raw ≠ passRaw)
// Load real user object from UserSession object.
$admin_account = User::load($this->rootUser->id());
// The password is empty.
$this->assertFalse($admin_account->passRaw);
// Set the password and save the User.
$new_password = $this->randomString();
$admin_account->setPassword($new_password);
$admin_account->save();
// Set the passRaw directly on the User.
$admin_account->passRaw = $new_password;
$this->drupalLogin($admin_account);

Good luck!
References
The details regarding the passRaw/pass_raw setting on the User object are available here:

https://api.drupal.org/api/drupal/core%21modules%21simpletest%21src%21WebTestBase.php/function/WebTestBase%3A%3AdrupalLogin/8.2.x
https://api.drupal.org/api/drupal/core%21tests%21Drupal%21Tests%21BrowserTestBase.php/function/BrowserTestBase%3A%3AdrupalLogin/8.2.x


How to combine templates with enums in C++?

Question: There are a huge feature collection in C++ programming language that supply a strict control over datatypes. Frequently one would mold his code with template system to achieve the most adequate functionality while guaranteeing within it correct type preservation and flexibility in its manipulation. Less frequently enumerations are used for this purpose, since they permit define an explicit possibilities for the data and have no direct way to verify type correctness.
So what we have are templates that allow functions and classes to operate with generic types without being rewritten for each one; and enums, providing a straight use of the expected types.
Is it possible to define a restricted template architecture for a class using an enum as a model? How can a templatized method use enumed type and when it could be useful?
My final question is: how to conjoin templates and enumeration types and use them together in the abstract data design?
As an example suppose you are trying to create a data container you expect to have types defined in an enum within your class:
template <typename T>
class element
{
public:
  enum type { text_type, widget_type, image_type };

  ...
private:
  type node_type;

};

You also defined each of the types present in class element:
class text;
class widget;
class image;

Creating an element, you want to specify its content type (text, widget or image) so you pass it by template argument.
if (node_type == text_type) do_something();

In Java you have List<? extends T> that implicitly says what type of classes can be used as template parameter. Can it be done in C++ using enums? How to work with enumed types in statements?
Question: I'd like to know how to restrict the behavior of templates by enumed types to ensure only these are being used, and orient the code using traditional way of working with enums.
Comment: @Rizo, you need to clarify your question.  As posted it's far too vague.  Try posting some code to show what you're trying to do
Comment: @Rizo: Please add a potential use-case (in pseudo-code) to your question.
Comment: @Rizo: Are you talking about an equivalent to the Java `List` generics paradigm?
Comment: What do you mean by *"Is it possible to define a restricted template architecture for a class using an enum as a model?"*?
Comment: Is the enum behaviour question cascading out from Java usage ?
Comment: @Oli Charlesworth: Enums may be used to express all the possibilities for a class content; for example, if you are trying to define `class element;`, you may say that this class may have `enum element_type { text_element, widget_element, image_element };` this way you are saying that there exist these types of elements, normally having associated classes. I want to know if there can be done a restriction of template types used within a class with an enum.
Comment: Oli Charlesworth: Yes I think I need something similar!
Answer: If you don't need to use enums, I believe you could employ similar techniques used in the standard library for categorizing iterators.
class text {};
class widget {};
class image {};

struct text_type_tag {};
struct widget_type_tag {};
struct image_type_tag {};

template <class T>
struct element_traits;

template <>
struct element_traits<text>
{
    typedef text_type_tag category;
};

template <>
struct element_traits<widget>
{
    typedef widget_type_tag category;
};

template <>
struct element_traits<image>
{
    typedef image_type_tag category;
};

//add specializations for any other type you want to categorize

//a template that only works with widget types
template <class Widget>
void foo_implementation(Widget w, widget_type_tag);

template <class Widget>
void foo(Widget w)
{
    foo_implementation(w, typename element_traits<Widget>::category());
}

int main()
{
    foo(widget());
    foo(10);  //error, element_traits not specialized for int (incomplete)
    foo(image()); //error, no matching call for foo_implementation(image, image_type_tag);
}

A further possibility with this: overloading foo_implementation for other categories of elements.
Answer: The type traits idiom as @UncleBens illustrates is the usual way of solving this problem.
You can attach information to classes using static const members of integer or enumeration type, as well.
#include <iostream>

enum color { red, green, blue };

struct x {
    static const color c = red;
};

template< color c >
struct thing;

template<>
struct thing< red > {
    thing() { std::cout << "red\n"; }
};

int main() {
    thing< x::c >();
}

Comment: @DarioOO You could certainly arrange for that, but wouldn't `matrix< float, 4, 4 >` be clearer?
Comment: i'm guessing if that could be used to select a template type .
For example using a

    matrix  => result in a 4x4 float matrix,
(and float type is just a enum value)
Comment: sure:) just because in my case using enum makes API much more simple. I have only a limited amount of vector types (float2,float3,ubyte3) etc. so instead of checkin if that type has correct lenght I just provide enum for types I support


linking two plots to one drop down menu in Shiny

Question: I am working on a shiny app and I have two plots that I would like to link to one selectInput. So the user selection will update both graphs.
Is there a way to achieve this?
my code
library(shiny)
library(plotly)
library(dplyr)
library(tidyr)

#ui
shinyUI(
  pageWithSidebar(
    headerPanel("NYC Flights Delays 2013"),
    sidebarPanel(
      selectInput("select", "Select a month",
                  choices = list("2013","January" ,"February",
                                 "March","April",
                                 "May", "June",
                                 "July","August",
                                 "Septemeber","October",
                                 "November","December")
      )),

    mainPanel(
      plotlyOutput("monthlyavg",width="900",height = "400px")
    )
    ))

#server
function(input, output){
  output$monthlyavg<-renderPlotly({
    if (input$select =="January") {
      #calculate avg delay for departures and arrivals each month
        average_delay_month<-flight%>%
        group_by(flight_month)%>%
        summarise(Average_Departure_Delay=mean(dep_delay[dep_delay>0]),Average_Arrival_Delay=mean(arr_delay[arr_delay>0]))
      #filtering according to month
      average_delay_month<-subset(average_delay_month,flight_month=="January")

      #average delay by month(January)
      c<-average_delay_month %>%gather("metrics", "value", -flight_month)%>%
        ggplot(aes(flight_month, value, group= metrics, fill = metrics)) +
        geom_bar(stat = "identity", width=.5, position = "dodge")+
        labs(title="Average Delay by Month", x="Flight Month",y="Average Delay in Minutes")
      print(c)

      #--January--#
      #--All Months Flight count--#
      flight$flight_month<-factor(flight$flight_month, levels=c("January", "February", "March", "April", "May",
                                                                "June","July","August",'September',"October","November","December"))
      #count number of flights per month
      flight_month_count<-setNames(aggregate(year~flight_month,data=flight,FUN=length),
                                   c('Month','Flight_Count'))
      flight_month_count<-subset(flight_month_count,Month=="January")
      #flight month_count_graph
      p<-ggplot(data=flight_month_count)+
        geom_bar(stat="identity",fill="#008080",aes(Month,Flight_Count),width=0.5)+
        labs(title="Total Number of Flights per Month",x="Flight Month",y="Number of Flights")
      print(p)
      }

I tried adding the two graphs (c) and (p) under one renderPlotly but it doesn't seem to do the trick.
Thanks
Answer:
I tried adding the two graphs (c) and (p) under one renderPlotly but it doesn't seem to do the trick.

I would advise against this.
Option 1. Use two renderPlotly calls, with both depending on the same input$select
Option 2: Create a mydata <- reactive({...}) object with your data processing steps within. Then in your two separate renderPlotly calls, reference mydata(). This will be updated anytime a new selection in made.
Comment: I am curious as to why you would advise against it?


Quotient of two geometric Brownian motions

Question: Given $X=X_t$, $Y=Y_t$ and
\begin{align}
      dX_t &= μX_t\,dt +  σX_t\,dB_t,
\\
      dY_t &= σY_t\,dt + μY_t\,dB_t,
\\
      V_t &= \frac{X_t}{Y_t}
\end{align}
How to calculate $dV_t$?
I'm new to SDE and calculus as well, so I'm not sure if I solved it wrong or not...
Please help, thank you so much!
Comment: Welcome to Math SE!  Please take a few minutes to edit your question and use [MathJax](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) to make it more readable.  Also, you mentioned that you're not sure you solved it wrong or not, please include those details as well.
Comment: DMcMor: Ok i will edit now
Comment: Is the Brownian motion the same in both equations?
Comment: @LutzLehmann yes it's the same
Comment: Can you apply Ito's formula?
Answer: It is often more simple to compute the derivative in a product formula instead of in a quotient formula. In the product formula for $X=YV$ you get, in infinitesimal increments,
$$
dX_t=d(V_tY_t)=(V_t+dV_t)(Y_t+dY_t)-V_tY_t=V_t\,dY_t+Y_t\,dV_t+dV_t\,dY_t
$$
While the last term as infinitesimal increment is random, this randomness is vanishingly small around a trend $d\langle V,Y\rangle_t$, which is the quadratic variation or correlation of the two processes. If $dV_t=a(V)dt+b(V)dB_t$, then $d⟨V,Y⟩_t=b(V)μY_t\,dt$. So let's insert all known equations
$$
X_t(μ\,dt+σ\,dB_t)=V_tY_t(σ\,dt+μ\,dBt)+Y_t\,dV_t+b(V)μY_t\,dt\\
V_t(μ-σ)(dt-dB_t)=a(V_t)\,dt+b(V_t)\,dB_t+μb(V)\,dt
$$
Comparing coefficients gives
\begin{align}
a(V_t)+μb(V_t)&=(μ-σ)V_t
\\
b(V_t)&=-(μ-σ)V_t
\\
\implies
a(V_t)&=(μ-σ)(1+μ)V_t
\end{align}

For a formal derivation of these results use the Ito theorem on transformations of stochastic processes which gives the same formula without mucking around with infinitesimals.

One could also use the solution formulas for geometric Brownian motions
$$
X_t=X_0e^{(μ+σ^2/2)t+σB_t}\\
Y_t=Y_0e^{(σ+μ^2/2)t+μB_t}\\
V_t=V_0e^{((μ-σ)-(μ^2-σ^2)/2)t-(μ-σ)B_t}
$$
which directly implies, as again a geometric Brownian motion,
$$
dV_t=[(μ-σ)(1-(μ+σ)/2)-(μ-σ)^2/2]V_t\,dt-(μ-σ)V_t\,dB_t.
$$
Comment: Thank you so much!
Answer: Note\begin{align}
dV &= \frac{dV}{dX}dX+ \frac{dV}{dY}dY
+\frac12 \frac{d^2V}{dX^2}(dX)^2
 +\frac12 \frac{d^2V}{dY^2}(dY)^2
+\frac{d^2V}{dXdY}(dXdY)\\
&= \frac{1}{Y}dX- \frac{X}{Y^2}dY
+\frac12 \cdot0\cdot(dX)^2
 +\frac{X}{Y^3}(dY)^2
- \frac{1}{Y^2}(dXdY)\\
\end{align}
Substitute $dX/X= μdt+  σdB$ and $dY/Y =σdt+ μdB$ into above to obtain
$$dV = V[\mu dt+\sigma dB - \sigma dt-\mu dB
+\mu^2(dB)^2- \mu\sigma (dB)(dB)] \\
= (\mu-\sigma+\mu^2-\mu\sigma)Vdt + (\sigma-\mu)VdB
$$
Comment: Thank you so much!!


Is it possible to save changes in Firebug locally?

Question: What I'm trying to do is to save the changes I make to CSS and HTML on different sites with Firebug.
Just to be clear, I don't expect Firebug to upload the changes to the server via FTP or anything. I just want to save the changes locally, so only I will be able to see them.
For example I've seen a few Firefox/Chrome extensions that add a download button under every video on Youtube, so I know it's possible to do that somehow.
If you have a different way to achieve what I'm trying to do, I'll be glad to hear about it.
(It doesn't have to be with Firebug.)
Thanks in advance!
Comment: Just to clarify, you want to be able to change the page localy and have those changes "persist" when you later load the same page wihtout having to make any changes on the server, like when you use flash or adblocker and tell it to always remove some content from the page whenewer you load it.
Comment: this addon works only on firefox? is there any addon for chrome ?
Comment: cssUpdater, can save changes from css files locally and from FTp also.
[http://www.cssupdater.com](http://www.cssupdater.com)
Answer: If you don't mind using Web Developer Toolbar it's easy to save changes made to the DOM (and CSS).
When you install the toolbar, you'll get a "View Source" menu, click on that and choose "View generated source". Then just copy and paste that into a .html file.
You did not say if you alter your HTML or CSS, if CSS, FireFile is a very good addon for this.
Edit, with some Googling, i found FireDiff, which states that it can export changes made in Firebug, i have not tested it bit it's worth checking out.
Comment: i tried the Web Developer Toolbar, i changed the DOM, but when i refresh the page the changes arent saved...
Comment: No, the changes aren't saved when you reload the page. You need to write those changes to disk manually.
Comment: Oh, then thanks, but this isnt what im looking for. Im looking for an extension that will let me save changes that i made, and only i will be able to see them.
Comment: Alright. Firebug does not provide a way to save the tree. Have you tried FireDiff or FireFile?
Comment: Yea i used FireDiff but its still not what im looking for.
Answer: You could try using Greasemonkey.
It has support for adding custom scripts that are run whenever you load a page (linked to which pages it should load on) and that can make changes to the page dynamically.
https://addons.mozilla.org/en-US/firefox/addon/greasemonkey/
Comment: Wow, thanks! that's pretty much what I was looking for, thanks again mate
Answer: The http://chrispederick.com/work/web-developer/ web developer toolbar will let you add a user style sheet to a site which should achieve your goals.
Answer: This may or may not be exactly what you're asking for, but you can download the extension FireDiff in order to save changes made with FireBug. I made a little tutorial on how to do it here: https://www.youtube.com/watch?v=m4OmZLX2zd4
Answer: I have a somewhat simlar use-case that I solved differently.  I'm not sure if it is what you are looking for or not. I'll describe the behavior and if that is helpful I'll explain exactly how I implemented it.
I changed the code that execute when you click "Run" (or Ctrl+Enter) to check to see if the first line of the code is a hard-coded string <code>//LoadFromFile:<file path></code>. If it is, and the file exists then I pull the file off of the local file system and run it instead of executing the code in the console window. This way I can use an external text editor to write code.


Is it possible to run Drush 8 smoothly on WSL?

Question: Can WSL be used to run Drush 8 smoothly? I am asking because Drush 8/master doesn't run smooth on a Windows machine.
Until now, I ran Drush 8/master on an Ubuntu virtual machine. I wonder if it's possible to run it on Windows 10 using WSL.
With my very basic knowledge of Operating Systems, I can't strictly determine if having Bash and Ubuntu binaries in Windows is actually enough to run Drush or if something extra which hasn't been released is needed.
I don't know also how to integrate WSL with WAMP/Xampp ,as well as with the c:/drush folder, or how to make some environment variable would be enough.
Answer: We haven't tried this yet. Please give it a spin, and report your results in the issue queue.
Note also that if you want the dev branch of Drush 8, you should use the 8.x branch.  The master branch is now Drush 9.


Powershell equivalent of Ctrl+R?

Question: In bash I can do Ctrl+R and start typing a command to have it search my history.
How do I do that in powershell?
Is there a way to bind a key to something like?
function GH($str) {get-history | select-string $str}

But I would need to re-read the string for each char input or removed to output matching commands like Ctrl+R does.
Is this possible?
Comment: Related: For cmd.exe, there is the tool [clink](https://mridgers.github.io/clink/).
Answer: You can fix this by adopting the PSReadLine module.
See an article on the Hey, Scripting Guy! blog regarding this bash inspired readline implementation for PowerShell.
In particular, the usage of Ctrl+Alt+(Shift)+? to show all keybindings.
PS C:\> $PSVersionTable

Name                           Value
----                           -----
PSVersion                      5.0.10240.16384
WSManStackVersion              3.0
SerializationVersion           126.96.36.199
CLRVersion                     4.0.30319.42000
BuildVersion                   10.0.10240.16384
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
PSRemotingProtocolVersion      2.3

Ctrl+R
PS C:\> Get-Module -ListAvailable
bck-i-search: mo_

Ctrl+Alt+(Shift)+S
Key                  Function                 Description
---                  --------                 -----------
Ctrl+r               ReverseSearchHistory     Search history backwards interactively
Ctrl+s               ForwardSearchHistory     Search history forward interactively

In short: either install this module by hand or upgrade to Windows PowerShell v5.
Answer: Type your search term and then press F8, this will search your command history.
There's a very useful list of PowerShell shortcuts here.
Comment: Have you tried that yourself? It never really worked for me or only half the time. For example I type a bunch of get- commands. Then type get- and it only cycles through one or two random commands from my history? I don't know what the hell its doing. For example I just typed get-childitem and ran it then immediately after type get-c and I get nothing. Maybe my session is messed up?
Comment: Works 100% of the time for me, this is with WMF 5 installed
Answer: I don't know when this got added, but on my non-customized, updated, Windows 10, it's built in. Hit ctrl+r for reverse history search, it works great.
Comment: I also work on win10. Ctrl+R works in powershell, but does not work in cmd window.
Comment: Sure, but why would you need to use cmd.exe??
Answer: There's also graphical search under F7 key. When pressed it will show popup which you can scroll to search for command which was executed earlier. Pressing enter while cursor hover the line will reexecute it again.
Answer: You can also start your command by putting a # character in front of the partial search text of the command you are looking for, then press tap afterwards (multiple times if necessary) to search through session history.

Powershell equivalent of Ctrl+R?


Append two para side by side using shell,sed,awk

Question: Hello i have below raw output
Chunk-1
Mod Ports Card Type                              Model              Serial No.
---+-----+--------------------------------------+------------------+-----------
1     8  Sup 8-E 10GE (SFP+), 1000BaseX (SFP)   WS-X45-SUP8-E      CAT1903LAEN
3    48  10/100/1000BaseT Premium POE E Series  WS-X4748-RJ45V+E   CAT1743L2JQ

M MAC addresses                    Hw  Fw           Sw               Status
--+--------------------------------+---+------------+----------------+---------
1 c08c.60ef.f340 to c08c.60ef.f347 1.2 15.1(1r)SG7  03.09.01.E.112   Ok
3 24e9.b335.bfd0 to 24e9.b335.bfff 1.3

Chunk-2
Mod Ports Card Type                              Model              Serial No.
---+-----+--------------------------------------+------------------+-----------
1     8  Sup 8-E 10GE (SFP+), 1000BaseX (SFP)   WS-X45-SUP8-E      CAT1903LAEN
3    48  10/100/1000BaseT Premium POE E Series  WS-X4748-RJ45V+E   CAT1743L2JQ

M MAC addresses                    Hw  Fw           Sw               Status
--+--------------------------------+---+------------+----------------+---------
1 c08c.60ef.f340 to c08c.60ef.f347 1.2 15.1(1r)SG7  03.09.01.E.112   Ok
3 24e9.b335.bfd0 to 24e9.b335.bfff 1.3                               Ok

want to combine and create the single line. and append
expected output
But if i do all at one time, all lines starting with 1 from chunk 2 will also get appended, along with lines from chunk-1.
So wanna process chunk-1 first, and then chunk-2.
Assume this as single line:
Chunk-1 Output
1     8  Sup 8-E 10GE (SFP+), 1000BaseX (SFP)   WS-X45-SUP8-E      CAT1903LAEN 1 c08c.60ef.f340 to c08c.60ef.f347 1.2 15.1(1r)SG7  03.09.01.E.112   Ok

Another line:
3    48  10/100/1000BaseT Premium POE E Series  WS-X4748-RJ45V+E   CAT1743L2JQ 3 24e9.b335.bfd0 to 24e9.b335.bfff 1.3

Similar manner need chunk-2 output as well.
Comment: its in same file.
Answer: You can use this awk:
awk '$1 ~ /^[0-9]/{a[$1]=a[$1]?a[$1] FS $0 : $0} END{for(v in a)print a[v]}' file

Comment: if i have multiple chunk of this in the same file, but wanna process one at a time. what needs to be changed here?
Comment: @user1220402, What do you mean by "process one at a time" ? Post a sample input.
Comment: have edited my question it self, you can check there as its too long for comment.
Comment: @user1220402, You can do it like this : `for f in a1.txt a2.txt; do awk '...' $f $f.out; done`


A dialog has a delay to open, I get an error when navigating to another view before the dialog is generated. How can I make it not be generated?

Question: I am new to flutter.
In my real problem, my client is in places where it is very frequent that the internet is very slow, so sometimes an attempt is made to make a web request and this may take time, so the user leaves the screen before the web request is completed. Sometimes my app after completing a web request generates a dialog. So here is where my problem lies, the user is trying to make a web request and while it is done, they leave the screen and then the dialog is generated.
I am trying to simulate this problem with a delay that later generates the dialog.
I am not thinking of any strategy to end the web request, what I want is to find a way that once I leave the screen, causes the dialog not to be generated something like a dispose
I made an example where I have 2 screens. On the second screen a dialog is generated with a delay of 5 seconds when the button is clicked. If I navigate to another screen before the dialog is opened I get an error. I assume this occurs because the view was destroyed and therefore the dialog cannot be opened.

What can I do to avoid the error when the dialog is generated after being in another view? if I am in another view I DO NOT WANT the dialog to be generated.
import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    print("main");
    return MaterialApp(title: 'Provider Example', initialRoute: '/', routes: {
      '/': (context) => Home(),
      'home': (context) => Home(),
      'dialogpage': (context) => Dialogpage(),
    });
  }
}

class Home extends StatelessWidget {
  Home() {
    print("home");
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: const Text('home'),
        actions: <Widget>[
          IconButton(
            icon: const Icon(Icons.add_alert),
            tooltip: 'Show Snackbar',
            onPressed: () {
              Navigator.pushNamed(context, "dialogpage");
            },
          ),
        ],
      ),
      body: const Center(
        child: Text(
          'home',
          style: TextStyle(fontSize: 24),
        ),
      ),
    );
  }
}

class Dialogpage extends StatelessWidget {
  Dialogpage() {
    print("dialogpage");
  }

  dialog(BuildContext context) {
    Future.delayed(const Duration(seconds: 5), () {
      showDialog(
          context: context,
          barrierDismissible: false,
          builder: (context) {
            return AlertDialog(
              shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(20.0)),
              title: Container(
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.only(
                    topLeft: Radius.circular(19.0),
                    topRight: Radius.circular(19.0),
                  ),
                ),
                padding: EdgeInsets.symmetric(vertical: 10, horizontal: 5),
                child: Text(
                  'Error',
                  style: TextStyle(color: Colors.white),
                ),
              ),
              content: Column(
                mainAxisSize: MainAxisSize.min,
                children: <Widget>[
                  Container(
                    margin: EdgeInsets.only(top: 20.0, bottom: 20.0),
                    child: Icon(
                      Icons.error,
                      size: 50,
                    ),
                  ),
                  Text("dialog"),
                ],
              ),
              titlePadding: EdgeInsets.all(0),
              actions: <Widget>[
                FlatButton(
                    child: Text('Aceptar'),
                    onPressed: () {
                      return Navigator.of(context).pop();
                    }),
              ],
            );
          });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('dialog'),
      ),
      body: Center(
        child: RaisedButton(
            child: Text("show dialog"),
            onPressed: () {
              dialog(context);
            }),
      ),
    );

  }
}

Answer: Instead of Future.delayed, you should use Timer, which can be cancelled in onDispose method.
Working solution:
void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    print("main");
    return MaterialApp(
      title: 'Provider Example',
      initialRoute: '/',
      routes: {
        '/': (context) => Home(),
        'home': (context) => Home(),
        'dialogpage': (context) => Dialogpage(),
      },
    );
  }
}

class Home extends StatelessWidget {
  Home() {
    print("home");
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('home'),
        actions: <Widget>[
          IconButton(
            icon: const Icon(Icons.add_alert),
            tooltip: 'Show Snackbar',
            onPressed: () {
              Navigator.pushNamed(context, "dialogpage");
            },
          ),
        ],
      ),
      body: const Center(
        child: Text(
          'home',
          style: TextStyle(fontSize: 24),
        ),
      ),
    );
  }
}

class Dialogpage extends StatefulWidget {
  @override
  _DialogpageState createState() => _DialogpageState();
}

class _DialogpageState extends State<Dialogpage> {
  Timer _timer;

  @override
  void dispose() {
    _timer?.cancel();
    super.dispose();
  }

  dialog(BuildContext context) {
    _timer = Timer(
      const Duration(seconds: 3),
      () {
        showDialog(
          context: context,
          barrierDismissible: false,
          builder: (context) {
            return AlertDialog(
              shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20.0)),
              title: Container(
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.only(
                    topLeft: Radius.circular(19.0),
                    topRight: Radius.circular(19.0),
                  ),
                ),
                padding: EdgeInsets.symmetric(vertical: 10, horizontal: 5),
                child: Text(
                  'Error',
                  style: TextStyle(color: Colors.white),
                ),
              ),
              content: Column(
                mainAxisSize: MainAxisSize.min,
                children: <Widget>[
                  Container(
                    margin: EdgeInsets.only(top: 20.0, bottom: 20.0),
                    child: Icon(
                      Icons.error,
                      size: 50,
                    ),
                  ),
                  Text("dialog"),
                ],
              ),
              titlePadding: EdgeInsets.all(0),
              actions: <Widget>[
                FlatButton(
                  child: Text('Aceptar'),
                  onPressed: () {
                    return Navigator.of(context).pop();
                  },
                ),
              ],
            );
          },
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('dialog'),
      ),
      body: Center(
        child: RaisedButton(
          child: Text("show dialog"),
          onPressed: () {
            dialog(context);
          },
        ),
      ),
    );
  }
}

Answer: use Globalkey in scaffold in then check the context in dialog method is it != null
then run dialog otherwise don't...
  GlobalKey _scafolldKey = GlobalKey<ScaffoldState>();

      @override
      Widget build(BuildContext context) {
        return Scaffold(
        key: _scafolldKey,
        appBar: AppBar(
            title: const Text('dialog'),),
            body: Center(
                child: RaisedButton(
                    child: Text("show dialog"),
                    onPressed: () {
                    dialog(context);
               }),
            ),
         );
       }
    }

    dialog(BuildContext context) {
        Future.delayed(const Duration(seconds: 2), () {
          if(_scafolldKey.currentContext !=null){
          showDialog();
            }
         });
      }

Answer: Try this code
class Dialogpage extends StatelessWidget {
  ...
  Timer t;

  dialog(BuildContext context) {
    t = Timer(Duration(seconds: 5), () {
      showDialog(...);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('dialog'),
        leading: IconButton(
          icon: Icon(Icons.arrow_back, color: Colors.black),
          onPressed: () {
            t?.cancel();
            Navigator.of(context).pop();
          },
        ),
      ),
      body: Center(
        child: RaisedButton(
            child: Text("show dialog"),
            onPressed: () {
              dialog(context);
            }),
      ),
    );
  }
}

Hope it helps.


Disabling the form field on submit

Question: I have a webform where I've used form alter to do some functionality and validation.
Now in my validation I want to disable a field for a purpose. How can I do so? Is it possible in form validation?
Answer: I think what are looking for is hook_node_validate()

Perform node validation before a node is created or updated.
This hook is invoked from node_validate(), after a user has has
  finished editing the node and is previewing or submitting it. It is
  invoked at the end of all the standard validation steps, and after the
  type-specific hook_validate() is invoked.

Disabling the form field on submit


Parameters of a negative binomial don't match the observed moments

Question: I have a dataset which, by the looks of it, closely resembles a negative binomial distribution. It is the number of minutes an event has lasted. Here is the original data:
!Raw Data1
I calculate the mean and variance of my data. Mean = 19.08, Variance = 54.67. I try to find out the parameters with which a negative binomial distribution would have the same mean and variance to see if it looks anything like my sample. I see in the literature people work with different parameters - normally they choose two of the p, r, the mean and the variance. Since I have made an assumption for the mean and the variance I decide to look for p and r. Using the following formulas for the mean and the variance (courtesy of Wikipedia):

... I arrive at p = 0.65 & r = 10.23. If I understand correctly r that is not an integer is perhaps not very logical but computationally possible. Then I calculate the pmf for the single values of X and compare with my sample. To my surprise the negative binomial distribution I have simulated looks nothing like my sample:

I decide to start playing around with the parameters and with certain values I get pretty close to what I observe. For example, for p = 0.375 and r = 11 it looks like this:

Now that looks pretty much like the distribution of my sample. However, using the Wiki formulas from above, those p and r values lead to a mean = 6.6! It is obvious from the diagram alone that that doesn't make sense. The graph peaks around 17, and is a bit skewed to the left, so the mean should be somewhat bigger than that. Now I am confused.
So my question is, why do the p and r values that match my observed mean and variance lead to an entirely different distribution? Or the other way around, why do the p and r values that produce a distribution matching the observed one, lead to a mean that is obviously very wrong? What am I doing wrong here?
Note: All the calculation are done in Excel. Using the Excel formula for a pmf of a negative binomial and calculating it "manually" leads to the same result. As you see it is a very layman's task and I don't aim at the most acurate estimation of the parameters but want to understand where is the mistake in my reasoning and why am I so far off.
Thanks in advance to anyone willing to help!
Answer: I ran into a similar problem a couple weeks ago.  On Wikipedia, the definition has $r$ as the number of failures, and the random variable is the number of successes.  But everywhere else, $r$ is the number of successes, and the random variable is the number of failures.
Defined in the usual way, the mean of a negative binomial RV is $\mu = \frac{r(1 - p)}{p}$ and the variance is $\sigma^2 = \frac{r(1 - p)}{p^2}$.
Using these with the $r$ and $p$ you found, you get $\mu = 18.33$ and $\sigma^2 = 48.88$, which looks to be more in line with what you're seeing.
I'm not sure why Wikipedia has a different definition than the typical one.
Comment: That's it! Thank you!


Relation Question on Partial order

Question: Let S be a set of positive integers and define a relation ρ on S as follows: ∀a, b ∈ S, aρb if and only if a ≤ b and a and b have the same number of positive divisors.
(a) Let S = {1,2,3,4,5,6,7,8}. Draw an arrow diagram of ρ on the set S.
(b) Let S = Z+. Prove that (S, ρ) is a partial order.
I am stuck on part a) i am not to sure on how to draw an arrow diagram of ρ
while for part b), May i know how do i prove a statement to be a partial order.
Comment: For (a) write the numbers down. The numbers $1,2,3,5,7$ are have the same number of divisors and are linearly ordered in the usual order. Therefore $\rho$ orders them in that same order. Draw arrows from smaller to larger with respect to $\rho$. The numbers $6\leq8$ have the same number of divisors. Therefore $6\rho8$. Finally $4$ is lonely.
Comment: $1\to2\to3\to5\to7$, $6\to8$ and $4$. That would be the diagram. (b) follows from this, since $\rho$ is the disjoint union of those three linearly ordered sets.
Answer: a) For this part you should draw an arrow from $i$ to $j$ if and only if $a \rho b$. As an example, you draw an arrow from $3$ to $5$ as $3 \leq 5$ and they have the same number of positive divisors.
b) You need to prove the axioms of partial order:
   i) reflexivity $a \rho a$. This is clear as $a \leq a$ and they have the same number of positive divisors.
ii) antisymmetry If $a \rho b$ and $ b \rho a$, then $a=b$. This follows easy $ a \rho b$ and $b \rho a$ implies $a \leq b$ and $b \leq a$ respectively, so $a=b$.
iii) transitivity If $a \rho b$ and $ b \rho c$, then $a \rho c$. I will this as an exercise.
Comment: does that mean to prove a statement is partial order i have to prove that its is AntiSymmetric and also the relations is Transitivity? Thank You!
Comment: The axioms of partial order are i) reflexivity, ii) antisymmetry and iii) transitivity as described in the Wikipedia article: https://en.wikipedia.org/wiki/Partially_ordered_set

Relation Question on Partial order


Commutating Matrices, a question

Question: RE-EDITED:
I've come to conclusion that $e^{At}e^{Bt}=e^{Bt}e^{At}$ if:
$\sum_{k=0}^{\infty}\sum_{j=0}^{\infty}\frac{t^{k+j}}{k!j!}A^kB^j=\sum_{j=0}^{\infty}\sum_{k=0}^{\infty}\frac{t^{k+j}}{k!j!}B^jA^k$
Does anyone have any idea how I can verify that it only is true if $AB=BA$?
Comment: Yes, just apply $AB=BA$ repeatedly in $A^xB^y$, you will get $B^yA^x$. An example $A^2B^2=A(AB)B=A(BA)B=(AB)(AB)=(BA)(BA)=B(AB)A=B(BA)A=B^2A^2.$
Answer: We have
\begin{align}
A^x B^y &= \underbrace{A\cdots (A}_{x \text{ times}}\underbrace{B)\cdots B}_{y \text{ times}}\\
&= \underbrace{A\cdots (B}_{x \text{ times}}\underbrace{A)\cdots B}_{y \text{ times}}\\
&= \underbrace{A\cdots (A}_{x-1 \text{ times}}B)A\underbrace{B\cdots B}_{y-1 \text{ times}}\\
&= \underbrace{A\cdots (A}_{x-2 \text{ times}}B)AA\underbrace{B\cdots B}_{y-1 \text{ times}}\\
&= \ldots\\
&=B\underbrace{A\cdots A}_{x \text{ times}}\underbrace{B\cdots B}_{y-1 \text{ times}}\\ &= BA^xB^{y-1}.
\end{align}
Now repeat this $y-1$ more times.
Comment: Thank you for your explanation.
Answer: Using induction we have $AB=BA$. Also if $A^mB^n=B^nA^m$ we obtain$$A^{m+1}B^n=A.A^mB^n=AB^nA^m=B^nA^{m+1}$$similarly$$A^mB^{n+1}=B^{n+1}A^m$$and $$A^{m+1}B^{n+1}=B^{n+1}A^{m+1}$$which means that for all natural $l,k$ we have $$A^lB^k=B^kA^l$$
Comment: Thank you for your explanation. This made it possible to finish a proof I've been working on for the last 5 hours...
Comment: I'm happy for you. Wish you luck!!!

Commutating Matrices, a question


Django - TypeError at feeds() missing 1 required positional argument: 'id'

Question: I'm trying to add comments to my project and I've got this error: feeds() missing 1 required positional argument: 'id'. Here is my code.
views.py
@login_required
def feeds(request, id):
    feeds_list = Feed.objects.all()
    feed = get_object_or_404(Feed, id=id)
    users = User.objects.filter(is_active=True)

    if request.method == 'POST':
        # Komentarz został opublikowany.
        feed_form = FeedForm(request.POST)
        if feed_form.is_valid():
            # Utworzenie obiektu Comment, ale jeszcze nie zapisujemy go w bazie danych.
            new_feed = feed_form.save(commit=False)
            new_feed.user = request.user
            new_feed.date = timezone.now
            # Zapisanie komentarza w bazie danych.
            new_feed.save()
    else:
        feed_form = FeedForm()

    context = {'section': feeds,
               'users': users,
               'feeds_list': feeds_list,
               'feed_form': feed_form}
    return render(request, 'feed/list.html', context)

I think that's here is problem: feed = get_object_or_404(Feed, id=id), but I don't know how to solve it.
Thanks for help.
Edit:
urls.py
from django.contrib.auth.urls import url
from . import views

app_name = 'feedApp'
urlpatterns = [
    url(r'^$', views.feeds, name='feeds'),
    url(r'^feed/new$', views.post_new, name='post_new'),
    url(r'^feed/(?P<id>[0-9]+)/$', views.feed, name='post_detail'),
    # url(r'^feed/(?P<id>[0-9]+)/comment$',
    #     views.comment_feed,
    #     name='comment_feed'),
    url(r'^feed/(?P<id>[0-9]+)/delete/$',
        views.feed_delete,
        name='feed_delete'),
]

Comment: paste `urls.py`
Comment: The view `feeds` expects `id` to be present in urls. Your endpoint should be like this -
localhost:8000/
Comment: if there is error post full error trace
Answer: as per your urls you need to add the required argument id to it.
edit your url to :
url(r'^(?P<id>[0-9]+)$', views.feeds, name='feeds'),

Answer: You have not used 'id' as keyword args in views.feeds url.
Add url(r'^feed/(?P<id>[0-9]+)/$', views.feeds,),
Comment: the url in your answer is for some other function `views.feed`. And it already has `id` argument in the url.


Halmos: Inverse image implies function $X \to Y$

Question: In the beginning of the Chapter on "Inverses and Composites," Halmos says: "A necessary and sufficient condition that $f$ map X onto Y is that the inverse image under $f$ of each non-empty subset of Y be a non-empty subset of X." and invites a proof.
I can see how the "necessary" part is true.  If there exists some $f$ where $\forall x \in X (f(x) \in Y)$, then there cannot exist some $B \subseteq Y$ where $f^{-1}(B)=\emptyset$ or, by definition, there would exist some $x$ where $f(x) \notin Y$.
But I'm struggling a little with the "sufficient" part.  How can you prove that just because every non-empty subset of Y has an inverse image, there isn't some $x \in X$ that doesn't map onto a $y \in Y$.
I realize I must be missing something pretty simple but I can't see what it is.  Can someone show me this part of the proof?
Comment: I don't understand your argument for the necessitiy part. Anyway, if $f:X \to Y$ is onto and $B\subseteq Y$ is not empty there is $y\in B$ and, by the surjectivity, there is $x\in X$ with $f(x)=y\in B$ so that $x\in f^{-1}(B)$. Vice versa, for every $y\in Y$, the singleton $B=\{y\}$ is not empty and every $x\in f^{-1}(\{y\})$ satisfies $f(x)=y$ so that $f$ is onto.
Comment: It's a function:  every point in the domain must go to *some* point in the codomain.
Comment: No. The definition of a function $f:X\to Y$ implies that *every* $x\in X$ is mapped to a unique value $f(x)$ *belonging to* $ Y$.
Comment: @jochen, This may betray a deeper misunderstanding on my part, but why does the fact that every $x \in f^{-1}(\{y\})$ satisfies $f(x)=y$, establish that $f$ is onto.  Couldn't there still be some $x \in X$ where $f(x)$ is undefined or not a member of Y?
Comment: @Jochen, right, but isn't the existence of $f$ what you have to prove to establish the "sufficient" part of Halmos's statement?  I.e., doesn't the "sufficient" part mean that you can prove that $f:X->Y$ must exist from the fact that the inverse map of any $B \subseteq Y$ is a non-empty subset of X?
Comment: Is what I'm missing simply that the existence of the inverse image, i.e. $f^{-1}(\{y\})$, implies the existence of $f(x)$ with dom $X$ that is to $Y$?  And so the only question is whether that function is "onto", which your proof establishes.
Comment: The map $f:X\to Y$ is given from the outset.
Answer: If $f:X\to Y$ is a surjection (i.e $X$ onto $Y$), for every $y\in Y$ there must exist a $x\in X$ such that $f(x)=y$. That is,
$$
\forall y\in Y, \exists x\in X, f(x)=y
$$
Now, let us assume that $f: X\to Y$ is a function such that $B\subseteq Y$ implies $f^{-1}(B)\neq \varnothing$.
Necessary part:
If there exists a subset $B\subseteq Y$ such that $f^{-1}(B)= \varnothing$, every $y\in B\in Y$ would not be in the range of $f$ because no $f(x)$ maps to it.
Sufficient part:
If the inverse image $f^{-1}(B)$ of any subset $B$ is indeed nonempty, then we could just consider $\{y\}$ for every $y\in Y$ because then $\{y\}\subseteq Y$: For every $\{y\}$ there exists a nonempty subset $f^{-1}(\{y\})$ of $X$ containing the elements that map to $y$. Since $f^{-1}(\{y\})$ is nonempty, we can simply obtain an element from the set, which surely maps to $y$ by virtue of it being contained in $f^{-1}(\{y\})$.
Therefore, as long as the inverse image $f^{-1}(B)$ of every subset $B\subseteq Y$ is nonempty, $f$ is a surjection.


Maximum potential speed for serial port rs232

Question: What is the potential maximum speed for rs232 serial port on a modern PC? I know that the specification says it is 115200 bps. But i believe it can be faster. What influences the speed of the rs232 port? I believe it is quartz resonator but i am not sure.
Answer: This goes back to the original IBM PC.  The engineers that designed it needed a cheap way to generate a stable frequency.  And turned to crystals that were widely in use at the time, used in any color TV in the USA.  A crystal made to run an oscillator circuit at the color burst frequency in the NTSC television standard.  Which is 315/88 = 3.579545 megahertz.  From there, it first went through a programmable divider, the one you change to set the baudrate.  The UART itself then divides it by 16 to generate the sub-sampling clock for the data line.
So the highest baudrate you can get is by setting the divider to the smallest value, 2.  Which produces 3579545 / 2 / 16 = 111861 baud.  A 2.3% error from the ideal baudrate.  But close enough, the clock rate doesn't have to be exact.  The point of asynchronous signalling, the A in UART, the start bit always re-synchronizes the receiver.
Getting real RS-232 hardware running at 115200 baud reliably is a significant challenge.  The electrical standard is very sensitive to noise, there is no attempt at canceling induced noise and no attempt at creating an impedance-matched transmission line.  The maximum recommended cable length at 9600 baud is only 50 feet.  At 115200 only very short cables will do in practice.  To go further you need a different approach, like RS-422's differential signals.
This is all ancient history and doesn't exactly apply to modern hardware anymore.  True serial hardware based on a UART chip like 16550 have been disappearing rapidly and replaced by USB emulators.  Which have a custom driver to emulate a serial port.  They do accept a baudrate selection but just ignore it for the USB bus itself, it only applies to the last half-inch in the dongle you plug in the device.  Whether or not the driver accepts 115200 as the maximum value is a driver implementation detail, they usually accept higher values.
Answer: The maximum speed is limited by the specs of the UART hardware.
I believe the "classical" PC UART (the 16550) in modern implementations can handle at least 1.5 Mbps. If you use a USB-based serial adapter, there's no 16550 involved and the limit is instead set by the specific chip(s) used in the adapter, of course.
I regularly use a RS232 link running at 460,800 bps, with a USB-based adapter.
In response to the comment about clocking (with a caveat: I'm a software guy): asynchronous serial communication doesn't transmit the clock (that's the asynchronous part right there) along with the data. Instead, transmitter and receiver are supposed to agree beforehand about which bitrate to use.
A start bit on the data line signals the start of each "character" (typically a byte, but with start/stop/parity bits framing it). The receiver then starts sampling the data line in order to determine if its a 0 or a 1. This sampling is typically done at least 16 times faster than the actual bit rate, to make sure it's stable. So for a UART communicating at 460,800 bps like I mentioned above, the receiver will be sampling the RX signal at around 7.4 MHz. This means that even if you clock the actual UART with a raw frequency f, you can't expect it to reliably receive data at that rate. There is overhead.
Comment: So if the maximum speed is 1.5Mbps, is it possible to setup rs232 port to perform at higher speed. I guess bios chip performs division of frequency. SuperIO chip usually has a 48Mhz quartz, but the frequency is divided so that UART gets only 1.843 Mhz. Can i somehow configure the hardware so that UART gets more than 1.843Mhz?
Comment: I'm pretty sure the clocking in UART is: the receiver measures the pulse time of a bit and "synchronizes" to it. So while there's no "clock" signal sent in another line, it _is_ self-syncing. The very first bit is a throwaway used to measure the rate.   There is no "negotiation" phase like there is in modems. The receiver either can, or can't, recognize the start bit. (too fast or too noisy to start a "lock", see "phase-locked loop"). The sender has no way to tell if the send data is accepted, unlike a modem which negotiates a two-day communication starting at the lowest speed and working up.
Comment: @KatasticVoyage Please provide a reference to an actual hardware UART implementation that works like that, I haven't seen any. All embedded UARTs I'm familiar with require the receiver to have the expected baud rate programmed into it before reception begins. There is no requirement that the first data bit is different from the start bit, so using the start bit as a synchronization device seems very difficult.
Answer: Yes it is possible to run at higher speeds but the major limitation is the environment, in a noisy environment there will be more corrupt data limitating the speed. Another limitation is the length of the cable between the devices, you may need to add a repeater or some other device to strengthen the signal.


Javascript PrintScreen

Question: Javascript from client side.
That is the window.clipBoard in javascript i got some documents where text copied to clipboard is got and shown.
I want the to implement the "PrintScreen" functionality over a web application.
Any help would be appreciated.
Answer: After a quick google search to check, no you cannot make screenshots with javascript. You will need to use a different language and if you want to put in a webpage then the user will be prompted for extra privilages. Additionally, window.clipBoardData only works in ie.
Answer: window.print()  ??

Javascript PrintScreen


Can't use facebook to authenticate: undefined method 'web_server' for OAuth2?

Question: Trying to let users sign in / sign up with Twitter and Facebook. Twitter works no problem but the strategy is different for Facebook.
undefined method `web_server' for #<OAuth2::Client:0x00000005211d58>

Trace shows
oa-oauth (0.0.1) lib/omniauth/strategies/oauth2.rb:18:in `request_phase'
oa-oauth (0.0.1) lib/omniauth/strategies/facebook.rb:28:in `request_phase'
oa-core (0.0.5) lib/omniauth/strategy.rb:25:in `call!'
oa-core (0.0.5) lib/omniauth/strategy.rb:19:in `call'
oa-core (0.0.5) lib/omniauth/builder.rb:22:in `call'
warden (1.0.5) lib/warden/manager.rb:35:in `block in call'
warden (1.0.5) lib/warden/manager.rb:34:in `catch'
warden (1.0.5) lib/warden/manager.rb:34:in `call'

Anybody else experienced this?
ps. I'm using the following gems:
gem 'oa-oauth', :require => 'omniauth/oauth'
gem 'oauth2'

I'm not using the full omniauth gem as its addressable dependencies conflict with other gems.
Comment: What version of oauth2 are you using? As far as I can tell, it is updated quite rapidly due to how fast the oauth2 specification changes. I am getting the same problem as you when I use the sorcery gem which attempts to use oauth2 version 0.5.0
Comment: I'm presently using Oauth2 0.4.1
Answer: I ran into the same problem when trying to use facebook_oauth (https://github.com/moomerman/facebook_oauth) on my rails app. After spending an hour or so trying to change its code, i realized it might be easier just to use oauth2 directly. I solved the problem and now there's no need for that intermediate library. Here's how:
In Gemfile add
gem 'oauth2'

Then run
bundle update
Then, in your login_via_facebook method you either construct the dialog uri manually or use the oauth client something along these lines:
oauth_client = OAuth2::Client.new(APPLICATION_ID, APPLICATION_SECRET, {
    :authorize_url => 'https://www.facebook.com/dialog/oauth'
})

redirect_to oauth_client.authorize_url({
    :client_id => APPLICATION_ID,
    :redirect_uri => YOUR_REDIRECT_URL
})

If you need to request additional permissions, specify scope param in the authorize_url call:
redirect_to oauth_client.authorize_url({
    :client_id => APPLICATION_ID,
    :redirect_uri => YOUR_REDIRECT_URL,
    :scope => 'offline_access,email'
})

Then, in the method that handles YOUR_REDIRECT_URL (i call mine login_via_facebook_callback), do something like this:
oauth_client = OAuth2::Client.new(APPLICATION_ID, APPLICATION_SECRET, {
    :site => 'https://graph.facebook.com',
    :token_url => '/oauth/access_token'
})

begin

  access_token = oauth_client.get_token({
      :client_id => APPLICATION_ID,
      :client_secret => APPLICATION_SECRET,
      :redirect_uri => YOUR_REDIRECT_URL,
      :code => params[:code],
      :parse => :query
  })

  access_token.options[:mode] = :query
  access_token.options[:param_name] = :access_token
  facebook_user_info = access_token.get('/me', {:parse => :json}).parsed

rescue Error => e

  # You will need this error during development to make progress :)
  #logger.error(e)

end

Now facebook_user_info has the basic user info!
Answer: I had a similar issue, you should try two things:

I also had conflicting gem issues/dependencies issues and resolved them by adding this in my gemfile:

gem 'omniauth', :git => 'git://github.com/intridea/omniauth.git'

Try using a rails application template which works remarkably well for starting a Twitter/Facebook app in no time, run this command in your terminal:

rails new APP_NAME -m https://github.com/RailsApps/rails3-application-templates/raw/master/rails3-mongoid-omniauth-template.rb -T

You can read more about it here:
https://github.com/RailsApps/rails3-mongoid-omniauth/wiki/Tutorial
Answer: here i came across an example app that demonstrates the use of omniauth along with authlogic
https://github.com/madhums/omniauth-authlogic-demo
hope it helps


Limited fields at registration time and full profile after logged in

Question: I want to display limited fields at registration time say username email and password
And when user get registered then he can edit his profile with rest of the fields like Phone no., Address, Date of birth etc.

I tried adding field in admin/config/people
But that fields are visible at the time of registration.
How can I do that any help....
I am using drupal 7
Answer: You can do this without installing another module. It's good practice to avoid installing additional modules if you don't have to.
1) Go to the Manage Fields screen for user accounts at admin/config/people/accounts/fields
2) Edit the fields you want to hide/display from the user registration form. There is a setting at the top of the form called "Display on User Registration Form". View the attached screenshot for example.
3) If a field is marked as "required", it has to be displayed on the user registration form.
Certain form fields on the user registration form are not managed through the "Manage Fields" screen. So they can't be changed without getting in to modules. These include username, password, and a few others depending on your set up. But fields that you add yourself, like phone number, address, etc., can be edited.
Answer: You can use https://drupal.org/project/profile2 module for this. Once you get installed this module, go to admin/structure/profiles/add
AS shown in screenshot, don't enabled this option. Show during user account registration.
Now you can give any name to your profile and can add all other fields that you want to fill from user after registration. One more thing if in future you want to show these all fields at the time of registration, just enable Show during user account registration. option.


How to identify colour of an icon of presence

Question: I am new to espresso .My test scenario involves to check the colour of the icon during the presence.For example if person X in available there is small green icon next to his name, if he is busy icon change to red
I am not quit sure how I can test colour of the specific icon R.id.presence
I do understand I need to use drawable but not sure how
Answer: You can try something like this. Try to find the element(probably R.id.presence in your case) and then try to get the background color of the element. Now compare it with the expected color.
Sample code for a button where green as background color is being verified.
<code>Button btn = (Button) findViewById(R.id.my_button);
Drawable buttonBackground = btn.getBackground();

ColorDrawable btn_color = (ColorDrawable) btn.getBackground();

int color = btn_color.getColor();
if (color == R.color.green) {
    log("color is green");
}
</code>
Hope it helps :)


Use of xi:include in Orbeon

Question: I created a form using Orbeon form builder, and i included in its form instance the content of an xml file using :
<xi:include href="oxf:/path/file.xml" xxi:omit-xml-base="true" />

When i save the form in form builder and edit it, i get a new form, and when i publish it and run it in form runner i get a blank page.
Can you tell me please what's wrong with the xi:include ?
Answer:
If you want to include the whole content of an external file as the instance, use:
<xforms:instance id="main-model-instance" src="oxf:/path/file.xml"/>

Here we have the model instance xml in external file at /path/file.xml and we are using this file into our form and have named the model instance as id="main-model-instance"
If you need to add part of the instance from external file, then insert that piece dynamically during xforms-model-construct-done event, e.g.:
<xforms:action ev:event="xforms-model-construct-done">

    <xforms:insert context="instance('fr-form-instance')"
         origin="doc('oxf:/path/file.xml')/root-element/some-section" />
</xforms:action>

Comment: ok, if thats the case, then insert that piece into main model instance at model-construct-done event. See my answer, i have add this update.
Comment: @KaipaMSarma Exactly. I just edited your answer to fix a typo in the name of the event (it is `xforms-model-construct-done`). Also, instead of using a separate instance, you can directly use `doc('oxf:/path/to/file.xml')` in the `origin` attribute.
Comment: but the content of file.xml is not the whole main instance, it's only a part of it, the rest is hardcoded.
Comment: Ok good, that works fine, I just added something in your example:'

' therefore, the instance is inserted only when creating a new form.
Comment: @avernet: Thanks for edit. Its good to know about doc() used in origin attribute.
Comment: @trin86: Good to see this is helpful. Please upvote or accept the answer so that it helps others
Comment: @KaipaMSarma You're welcome; and thank you for the initial response! I also change the example a bit in an attempt to make it clearer that doc() returns the document node, not the root element, unlike instance().

Use of xi:include in Orbeon


The number of summands $\phi(n)$

Question: If $n$ is a positive integer such that the sum of all positive integers $a$ satisfying $1\leq a\leq n$ and $\gcd(a,n)=1$ is equal to $240n$ then the number of summands namely $\phi(n)$ is

120
124
240
480

My attempt:
If $n $= $p_1^{q_1}p_2^{q_2}...p_k^{q_k}$ where $p_1, p_2,...p_k$ are primes.
$240 n = \frac{n(n+1)}{2} - \frac{p_1^{q_1+1}-1}{p_1 -1}\frac{p_2^{q_2+1}-1}{p_2 -1}... \frac{p_k^{q_k+1}-1}{p_k -1}  +1 $
From here, I was not able to proceed. Guesswork tells me that the number has to be 480 because the sum is $240n$.
Answer: Note that $a$ and $n$ are relatively prime if and only if $n-a$
and $n$ are relatively prime.
Call such a pair $\{a,n-a\}$, where $a$ is relatively prime to $n$,  a couple. The sum of the numbers in a couple is $n$.
If $n\gt 2$, there are $\frac{\varphi(n)}{2}$ couples. For every $a$ relatively prime to $n$ gets coupled with someone other than herself.
It follows that our sum is $n\cdot\frac{\varphi(n)}{2}$. If this is $240n$, then $\varphi(n)=480$.

The number of summands $\phi(n)$


Possible Converse to a Corollary to the Artin-Wedderburn Theorem

Question: Let $\mathsf{K}$ be a field, and $A$ a finite dimensional associative $\mathsf{K}$-algebra, and suppose that $\mathcal{L}$ is a complete collection of representatives of the isomorphism classes of irreducible left $A$-modules. If $A$ is semisimple, then a corollary to the Artin-Wedderburn theorem states that
$$
\dim_{\mathsf{K}} A = \sum_{L \in \mathcal{L}} (\dim_{\mathsf{K}}L)^{2}.
$$
I am interested in whether this corollary has a converse. That is, if this equality holds can we say that $A$ is semisimple? If the answer is yes is there a simple (semisimple?) argument that I'm missing here, or if it is false can you provide a counter-example? If it is false, are there extra suppositions that we can apply to $A$ or $\mathsf{K}$ to make the statement hold? (Perhaps characteristic zero or algebraically closed?)
Comment: Well, that is true (the proof is immediate; see my answer below).
Comment: I'm confused about the corollary of Artin-Wedderburn that you mention at the beginning: presumably you should assume $K$ is algebraically closed (or that $A$ is *split* semisimple)? For instance if $K=\mathbf{R}$ and $A=\mathbf{C}$ then the left-hand side is $2$ but the right hand side is $4$ (there being one irreducible $A$-module, namely $A$, of dimension $2$ over $K=\mathbf{R}$).
Comment: Ah yes, I think the extra condition that I actually want is that the modules L are absolutely irreducible (which of course is satisfied if $\mathsf{K}$ is algebraically closed), but I need the result in a case where $\mathsf{K}$ is not algebraically closed, for instance $\mathsf{K} = \mathbb{Q}(t)$. Of course this is needed because the proof of the Artin-Wedderburn theorem uses that $\operatorname{End}_{A}(S) \cong \mathsf{K}$ for any irreducible $A$-module $S$, which is only true is $\mathsf{K}$ is algebraically closed (or $S$ is absolutely irreducible)
Comment: Well, the most general (and also the most widely cited) version of Artin-Wedderburn does not in fact assume that the algebra is split (that it, that every irreducible is absolutely irreducible), and the conclusion is that a semi-simple algebra is a direct sum of matrix rings over division algebras over $K$. In any case, the result you are wondering about is false without some additional hypothesis (see below). I guess it is true if $A$ is split, though.
Comment: Sure. I understand that that is the statement of Artin-Wedderburn. I am not looking for a strict converse to Artin-Wedderburn, but rather to the corollary to Artin-Wedderburn that if $\mathsf{K}$ is algebraically closed (or I suppose that all irreducible $A$-modules are absolutely irreducible), then this dimension formula holds. I suppose what I'm looking for is a result like "Suppose that $A$ is a finite dimensional algebra over a field $K$ whose irreducible modules are absolutely irreducible, and such that this dimension formula holds, then $A$ is semisimple.
Comment: Thank you! That was precisely the sort of argument I was looking for
Answer: No: consider $A=\mathbf{C}[t]/(t^2)$ and $K=\mathbf{R}$. $A$ has one irrep, namely $\mathbf{C}$, of dimension $2$ over $\mathbf{R}$, and the dimension of $A$ over $\mathbf{R}$ is $4=2^2$, but $A$ is not semi-simple.
The issue is that there are two competing forces at work here: $A$ is not semi-simple, which tends to decrease the number of irreducibles relative to the semi-simple case, but also not split, which tends to increase the dimensions of the irreducibles.
If you assume that every irreducible representation is absolutely irreducible, then the result it true: the right-hand side is in this case the dimension of the semi-simplification $A/\mathrm{Jrad}(A)$ of $A$ (here $\mathrm{Jrad}(A)$ is the Jacobson radical of $A$); if this is equal to the dimension of $A$ then $\mathrm{Jrad}(A)=0$ as desired.
Comment: If I could upvote this answer twice then I would!
Comment: @AdamHiggins Thanks, glad I could help!


unknown JS error in IE8

Question: I am using js function to changes class and text of li in my html document. Its working fine in every browser except IE8 and IE7. I dont what is the response. It is just a simple function . I am not getting any clue where to google it.
In group parameter I pass javascript object like:
var group = {
    0: {
        class: "classname1",
        text: "mytext"
    },
    2: {
        removeClass: "classname2",
        text: 'mytext2'
    },
    remove: [4, 5]
}

if (!Array.isArray) {
        Array.isArray = function (vArg) {
            return Object.prototype.toString.call(vArg) === "[object Array]";
        };
    }
function xyz(group, parent) {
    $.each(group, function (key, val) {
        if (Array.isArray(val)) {
            var $lis = $(parent).find("li");
            for (var i = $lis.length - 1; i >= 0; i--) {
                if (val.indexOf(i) > -1) $lis.eq(i).remove();
            }
        } else {
            $(parent).find('li').eq(key).removeClass(val.removeClass).addClass(val.class).text(val.text)
        }
    })
}

Answer: Array.isArray is only supported in IE9 and above.
Put this in front of your code in order to support older versions of IE:
if(!Array.isArray) {
  Array.isArray = function (vArg) {
    return Object.prototype.toString.call(vArg) === "[object Array]";
  };
}

Source: MDN
Comment: any alternative for Array.isArray
Comment: @amit Make sure the polyfill occurs in the code before calling the `xyz` function otherwise, the polyfill will not have loaded when `Array.isArray` is called.
Comment: @amit please put your code on jsFiddle so we can look further into it.
Comment: @amit the problem is in `.addClass(val.class)`. `class` is a reserved property name for Internet Explorer - you cannot use it. Rename the property to something else, like `val.cssClass`.
Answer: From Microsoft, Array.isArray() is not supported until IE9+.
Reference:  http://msdn.microsoft.com/en-us/library/ie/ff848265(v=vs.94).aspx

unknown JS error in IE8


Unsure why I can't find a limit of PDF using CASIO Classpad with Piecewise function

Question: I am trying to find the value of 'd' using the CASIO Classpad. I have been given a hybrid (piecewise) function and, having defined it on the calculator, I need to know the value of 'd' which will give Pr(T>=d)=0.35388..
However, this just doesn't seem to want to work.
Does anyone know where I am going wrong?
Here is a screenshot of the calculation. The limits of each function are between 20<=x<45 and 45<=x<=70 respectively.

Thanks in advance
PS. I'm fairly new to using the Classpad so apologies if this seems a basic question to ask.
Answer: Observe that $\int_{45}^{70}f(x)dx=0.5>0.35388$ and that $f(x)\geq 0$ for $20\leq x\leq 45$ so that $\int_d^{70}f(x)dx>0.35388$ for $d\leq 45$. Thus You can assume that $d>45$ and solve
$$F(70)-F(d)=0,35388$$
where $F(x)=\frac{1}{625}(70x-\frac{1}{2}x²)$, which leads to a simple quadratic equation and even all this is overkill since the functions involved are linear and You just need to know the formula $A=\frac{ab}{2}$ where $A$ is the area of a right angled triangle with catheti $a$ and $b$. Then for example You can compute $\int_{45}^{70}f(x)dx=\underbrace{f(45)}_{=a}\underbrace{(70-45)}_{=b}\frac{1}{2}=\frac{1}{2}$ and similary $\int_{d}^{70}f(x)dx=f(d)(70-d)\frac{1}{2}=0.35388$
which of course leads You to the same quadratic equation that You should solve by completing the square as an exercise.