Valgrind reports read error on C code

Question: I'm getting problems trying to find out what I'm doing wrong in my code, because valgrind is telling me that my code generates a read error.
This is the problematic function:
    double func3(double *xp, double *yp, int dims, double *u_b,
        double *array, int nc)
    {
        int i, j, pos;
        double cx, cy, dx, dy, dist, rx, ry, sx, sy, sxy, trxx, tryy, trxy,ans;

        //printf("size of n:", dims);
        sx = sy = sxy = trxy = 0.0;
        for (j = 0; j < dims; j++) {
           rxx = ryy = 0.0;
           for (i = 0; i < dims; i++) {
            if (i != j) {
                dx = (xp[i] - xp[j]);
                dy = (yp[i] - yp[j]);
                dist = calc(dx, dy);
                pos = find(u_b, nc, dist);
                cx = array[pos];
        //printf("i,j: %i , %i\n",i,j);
        //printf("\t xposi = %f\t\t xposj= %f\n",xp[i],xp[j]);
        //printf("\t yposi = %f\t\t yposj= %f\n",yp[i],yp[j]);
        //printf("\t dx = %f\t\t dy= %f\n",dx,dy);
        //printf("\t value of pos: %i value of nc: %i\n", pos, nc);
                /*problematic line*/
                cy = array[pos + nc];
        printf("\t cx: %f\t\t cy: %f\n",cx,cy);
        printf("\n");
            }
            else
                cx = cy = 1.0;
            rx  += cx;
            ry  += cy;
            trxy += cx * cy;
        }
        sx += rx;
        sy += ry;
        sxy += rx * ry;
    }

    trxx = (double) dims - sx / dims;
    tryy = (double) dims - sy / dims;
    trxy += (sx * sy / dims - 2.0 * sxy) / dims;
    ans = trxx * tryy / trxy - 1.0;

    return ans;
}

So the error traceback from valgrind is:
==22457== Invalid read of size 8
==22457==    at 0xFBC3076: func3 (funcs.c:90)
==22457==    by 0xFBC3204: func2 (funcs.c:121)
==22457==    by 0xFBC3335: func1 (funcs.c:11)
==22457==    by 0x485A53: do_dotCode (dotcode.c:1722)
==22457==    by 0x4BACF3: Rf_eval.part.13 (eval.c:651)
==22457==    by 0x4BDC6D: do_set (eval.c:1991)
==22457==    by 0x4BAB5B: Rf_eval.part.13 (eval.c:623)
==22457==    by 0x4BDE93: do_begin (eval.c:1620)
==22457==    by 0x4BAB5B: Rf_eval.part.13 (eval.c:623)
==22457==    by 0x4BF40C: Rf_applyClosure (eval.c:1033)
==22457==    by 0x4BA907: Rf_eval.part.13 (eval.c:670)
==22457==    by 0x4BDC6D: do_set (eval.c:1991)
==22457==  Address 0xd68c758 is 0 bytes after a block of size 248 alloc'd
==22457==    at 0x4A0887C: malloc (vg_replace_malloc.c:270)
==22457==    by 0x4E9750: Rf_allocVector (memory.c:2465)
==22457==    by 0x44790E: do_makevector (builtin.c:756)
==22457==    by 0x4B0595: bcEval (eval.c:4700)
==22457==    by 0x4BA83F: Rf_eval.part.13 (eval.c:554)
==22457==    by 0x4BF40C: Rf_applyClosure (eval.c:1033)
==22457==    by 0x4BA907: Rf_eval.part.13 (eval.c:670)
==22457==    by 0x4BC3E1: Rf_evalList (eval.c:2081)
==22457==    by 0x4BAC0C: Rf_eval.part.13 (eval.c:642)
==22457==    by 0x4BDC6D: do_set (eval.c:1991)
==22457==    by 0x4BAB5B: Rf_eval.part.13 (eval.c:623)
==22457==    by 0x4BDE93: do_begin (eval.c:1620)
==22457==

So the program doesnt seg fault, in fact if I uncomment the "prints" on the code I can see that the error is found at random values for the loop indexes (i,j) and it occurs when the code tries to read from "array[pos+nc]" but it actually reads the correct value at that position!!! (for the corresponding values of pos and nc) a number of times before de valgrind error and after the valgrind error and at the error... so I'm completly lost here.
I check that the arrays "array", "xp" and "yp" were correctly filled at all the required entries, and the other functions were checked as well.
Any help will be much appreciated.
Comment: This looks like an off-by-one error.
Comment: What were the parameters of the run where the error was reported?  valgrind is telling you that the block allocated was only `31` doubles.  Is that really the size you expected your `array[]` to be?
Comment: As I said to Sean... I debug the code and the values of the parameters when the read error is found are pos=8 and nc=10. The problem is that array[18] has been read multiple times before the error and retrieves correctly the value... in fact at the moment of the error also the value retrieves from array is correct
Comment: @wooltar: the sizes are fine, I checked the values on them... the program actually reads the values correctly, but valgrind complains... i dont know why
Comment: `cy = array[pos + nc];` To me it looks like nc is the number of elements in array, in which case `array[pos + nc];` would be off by one, indeed.
Answer: To expound on @H2CO3's comment find() may not be giving you the value you expect or nc is incorrect. Fire up a debugger and inspect the situation.
Comment: Well actually it gives me a value of 8 and the nc parameter is 10 (on the example that I run valgrind on). The weird thing is when valgrind says that it found and error is not the first time that the code read at the position 18... actually is like the tenth time...

Valgrind reports read error on C code


Determining closest key when primary contributing factors are shared among keys

Question: Given a construct of intervals as follows:
1,#2,3,4,5,6,b7
(Dominant #2 first position)
For the purpose of general notation, as the #2 is equivalent to a b3 and the 3rd is still present, would this be classified as a major key with the raised second as the accidental since attempting to classify it as a minor would leave you without the second interval? As I understand it, your general key is derived by the root triad at the first tone. However if you have both 3rds present, is it a matter of first 3rd reached in the interval stack that determines key?
Given that I would assume a Dorian b4 is minor even though the b4 falls upon the major interval and using it in any other way effectively negates the 4th.
1,2,b3,b4,5,6,b7
Would the same logic apply for 8 tone Spanish?
1,b2,b3,3,4,b5,b6,b7
Am I incorrect in these assumptions?
Answer: When talking about what composes of a scale, letter name and interval matter. In your first example although the enharmonic equivalent of #2 is a b3, you would not look at it that way in the context of a scale.
If you built the scale off C you would get:

C  D#  E  F  G  A  Bb

Again while D# and Eb are enharmonic equivalents the fact that you are using the D# as the basis of the scale means that you would not think of it as a 3rd of C hence the only third in this would be E.
Same goes for your second example which built on C would be:

C  D  Eb  Fb  G  A  Bb

While Fb and E are enharmonic equivalents the fact that you are using the Fb as the basis of the scale means that you would not think of it as a 3rd of C hence the only third in this scale would be Eb.
The last is a little more complicated. Since we are trying to fit 8 notes into a scale when we typically have 7 there will end up being one note that can be viewed as just a chromatic passing tone  in the scale construction. Let's look at the last scale built in C:

C  Db  Eb E  F  Gb  Ab  Bb

You can see in the Eb, E, F  the E is sandwiched inbetween. This means that in most cases it will be more of a passing tone than anything else thus the minor third will be more prevalent.
Comment: Dom, thank you. Just to flip the script slightly and apply this to a minor key to see if I am approaching this correctly... With an Alt @5 bb7 construct of 1,b2,b3,b4,5,b6,bb7. That is minor as b4 becoming the enharmonic of 3 is 'intent' to modify the 4th where if I stated 1,b2,b3,3,5,b6,bb7 (odd I know, just trying to come up with an example) then I was really going for a major key, dropping the 4th, and adding a passing tone in the use of b3. Correct?
Comment: @ceearrtee not quite as the big difference is you only have 7 notes. The chromatic aspect only applies when there are more than 7 notes. It would sill be viewed as a b4 because you don't have a fourth.


Accuracy in neural network for regression

Question: I want to measure the accuracy in neural network that performs regression. I have two outputs. Is the root-mean-square deviation (
RMS wiki) the right way to go?
From wikipedia

RMSD is a good measure of accuracy[...]

How do I use it? I want to show how the accuracy is changing over epochs.
In classification measuring accuracy is simple.
$$ accuracy = \frac{TP+FN}{TP+FP+TN+FN} $$
Comment: you can set the answer as the correct one...
Answer: There are multiples measures. You need to understand the nature of your data/regression you are using.
For example:
MAPE is a pretty good measure for time series data, but will not work if has zero in the data or in the regression.
The most used RMSE and MSE are used to minimize the error, not necessarily the accuracy. The most close to zero better the measure.
For next step:
It's good to use measures that will automatically compare you model with other models, so you will be able to tell if your model is better than guessing or random walk models.
For instance:
Theil's U

Theil's U statistic is a relative accuracy measure that compares the
forecasted results with the results of forecasting with minimal historical
data. It also squares the deviations to give more weight to large errors and
to exaggerate errors, which can help eliminate methods with large errors.
Comment: @jumalo please mark as correct answer
Comment: Thank you for the MAPE direction. I went for R squared to track how well I fit my data.
Comment: @jumalo  Good! I just updated my answer, with more examples of measures You can look up.
Comment: @jumalo As a heads up, R$^2$ does not have the usual "percent of variation explained" interpretation when the model is nonlinear (neural nets are nonlinear).


Independent, Uniform, Random Variable:

Question: Working on this:

Alice and Bob agree to meet in the Copper Kettle after their Saturday
  lectures. They arrive at times that are independent and uniformly
  distributed between 12:00 and 13:00. Each is prepared to wait s
  minutes before leaving. Find a minimal s such that the probability
  that they meet is at least 25%.

I honestly can't figure out how to approach this one... It seems super simple, but I just can't wrap my head around it right now. Any advice on how to start?
Thank you.
Comment: @gfppaste: I hope you locate it, for a picture really helps, and someone will have drawn one. Let's measure time of wait in **hours**, can go to minutes later. Let $X$ be Alice's arrival time, $Y$ Bob's. We want $P(|X-Y|\le w)\ge 0.25$. The joint density of $X$ and $Y$ is $1$ on the square with corners $(0,0)$, $(1,0)$, $(1,1)$, $(0,1)$. what is the area of the region $|x-y|\le w$? Hint: Draw the line $x-y=w$ and $x-y=-w$.
Comment: This type of question has been asked and solved in great detail repeatedly on this forum.  Look around a bit.
Answer: We can define Alice's arrival time by a and Bob's arrival time by b, with both a and b between uniformly distributed between 0 and 1. We can therefore define a set $C = \{(a,b): |a-b| \le \frac{s}{60}\}$. You should be able to graph this and see that it is a diagonal strip around the graph of y=x. The area outside of this strip is $(1-\frac{s}{60})^2$, so the area inside the strip is $1-(1-\frac{s}{60})^2$. We want this to be at least 0.25. From here, it is relatively straightforward to see what the minimum value of s should be.

Independent, Uniform, Random Variable:


College World Series winners winning a World Series Ring

Question: I remember watching the College World Series in Omaha as a kid in the 1960s, and I remember watching Sal Bando and Rick Monday play for Arizona State.  Are there any MLB players who have played on a College World Series championship team and also won a World Series ring?  Of those, if any, did there happen to be anyone who played in a Little League World Series championship game?
Comment: Hmm. I don't know of a good dataset to query for this. Anecdotal data might turn up a few players, but that's far from a real answer.
Answer: Roger Clemens won 1983 College World Series with the Texas Longhorns and the 1999 and 2000 MLB World Series with the Yankees.
Answer: The second half of your question is actually answered here (very bottom of page):

Did you know that only two Major League players have appeared in a Little League World Series, College World Series, and Major League World Series Series? Those players are Ed Vosberg, who participated in the Little League World Series (Tucson, Arizona, 1973, Runner-Up), College World Series (University of Arizona, Champions, 1980) and the 1997 World Series; and Jason Varitek who participated in the Little League World Series (Altamonte Springs, Florida, 1984), College World Series (Georgia Institute of Technology, Runner-Up, 1994) and both the 2004 World Series & 2007 World Series.

Vosberg is the actual answer here, his LL team played in the championship game and his college and pro teams won it all.
As far as the first half. I suspect there is far more overlap in these two data sets. I'm going to CW this and see if we can build a comprehensive list.

Ed Vosberg (Arizona 1980, Florida 1997)
Roger Clemens (Texas 1983, NYY 1999,2000)


Tratamento de Exceção não funciona quando faz divisão por zero

Question: Preciso ler um conjunto de valores e informar a divisão entre eles, independente de ser positivo ou negativo. O problema fala que se ocorrer uma divisão por zero deve ser exibida uma mensagem dizendo "divisao impossivel".
Eu resolvi fazer essa questão usando o comando try/except, já que é a única alternativa que não retornaria uma mensagem de erro com uma divisão por zero, mas mesmo usando esse comando está sendo retornada uma mensagem de erro e não exibe a mensagem que a questão pede.
N = int(input())

for i in range(0, N):
    try:
       X, Y = input().split(" ")

       X = float(X)
       Y = float(Y)
    except ZeroDivisionError:
       print('divisao impossivel')
    else:
       divisao = X / Y

       print(divisao)

Answer: A divisão deveria estar dentro da tentativa, depois que a tentativa acabou e já tratou o possível erro que não tem como acontecer não adianta fazer a divisão porque ali o erro não será tratado. Seria algo assim:
N = int(input())
for i in range(0, N):
    try:
       X, Y = input().split(" ")
       X = float(X)
       Y = float(Y)
       divisao = X / Y
       print(divisao)
    except ZeroDivisionError:
       print('divisao impossivel')

Mas isso não é correto.
Há outros erros que não foram tratados, e que é complicado tratar sem ser pela exceção.
E acho que um erro que é facilmente detectado deveria fazê-lo em vez de deixar a exceção estourar. Então ao contrário do que está escrito na pergunta capturar a exceção não é a única alternativa para resolver isso.
E se der erro imagino que não deve avançar na contagem de itens como está fazendo.
Não é um erro, mas o pessoal de Python pegou essa maneira triste de pegar os dados em uma linhas só que incentiva digitar coisas erradas. Eu mudaria isso, mas pode ser que o exercício pede assim, o que é uma forma de ensinar fazer coisas confusa, eu repensaria em algo que vai por esse caminho como sendo uma boa referência.
Aí ficaria quase isto;
n = int(input())
i = 0
while i < n:
    try:
        x, y = input().split(" ")
        x = float(x)
        y = float(y)
        if y != 0:
           print(x / y)
           i += 1
        else:
            print('divisao impossivel')
    except ValueError:
       print('formato digitado errado')

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Na verdade ainda pode dar erro quando digita o n, faça o tratamento desse caso.
Comment: Poderia me explicar porque essa maneira de ler os dados em uma única linha não é apropriado? A minha primeira linguagem de programação é o Python.
Comment: Porque é muito fácil digitar errado, a pessoa tem que saber que tem que colocar um espaço.
Answer: Tmb me deparei com esse problema de mensagem de erro do sistema.
A solucão foi colocar "divisao impossivel" antes do comando para dividir:
    print('QUANTOS CASOS VAI DIGITAR? ', end='')
    n = int(input())

    for i in range(n):
        print('entre com o numerador: ', end='')
        num = int(input())
        print('entre com o denominador: ', end='')
        den = int(input())
        if den == 0:
            print("DIVISAO IMPOSSIVEL")

# qndo vc coloca nessa posicao, antes da divisao, o sistema nao da erro

        else:
            div = num / den
            print(f'DIVISAO = {div:.2f}')

# estava posicionando o "divisao impossivel" abaixo do comando de divisao.
# onde o erro do sistema aparecia


Using variables as paths for images in react native

Question:
My Goal
I am trying to create an app with react native, and want to have an image that can change depending on the circumstances. I want to have a list of paths, and then select the image by choosing an item in the list.
What I have tried
I have tried making an image that looks like this:
<Image source={require(icons[iconNum])} />

But whenever I try that, I get an error saying,
Requiring unkown module "./images/exampleImage.png".

I have also tried using a single variable, that isn't a list, and that gives me the same error. How could I use a variable to select the correct image that I want to use?
Comment: instead of putting the string path in the array, why don't you put the whole object, `require("./your/image/path")` on the array?
Answer: require is a javascript keyword with a preload nature, you have to prepare every resources you want to use, simply create a resources file for that. ex:
export var icons = [
  require('./icon/icon1.png'),
  require('./icon/icon2.png'),
  require('./icon/icon3.png'),
  ...
];

Images are pre-bundled into App, provide related path at runtime doesn't mean anything.
You can easily prove it by changing require("./icons/icon.png") to require("./icons/"+"icon.png"). Although they are logically the same, latter one will never works.


A list of tricks for calculating expectations?

Question: Does anyone know of a good resource listing known tricks (with examples?) for calculating closed form expressions from messy expectations? (e.g., moment generating function, law of iterated expectations, change of measure, etc.)
In a different setting, I've found Summary of Rules for Identifying ARIMA Models tremendously helpful. I was hoping a list of rules-of-thumb like this would also exist for calculating expectations...right? Unfortunately, I'm not finding anything.
Comment: calculating expectations almost always involves integration. Unfortunately there are no universal simple rules how to calculate integrals.
Comment: @mpiktas I believe anyone who has taught a freshman calculus course might consider disagreeing a little :-).
Comment: @whuber, the key word here is universal. There are simple rules which can help a lot for a large class of integrals. I just wanted to make a point, that there are no similar rules like rules for differentiation. Rereading the question, I see that I missed the point :)
Answer: Let's build it!
You mentioned:
1 moment generating function
2 law of iterated expectations
3 change of measure
Adding:
4 Decompose random variable as a sum. Usually the sum of indicators of something.
5 Build a reccurence relation for E(X) (or a set of linear equations). Useful in Markov Chains.
6 Stopping time theorem for martingales: $E(X_{T})=E(X_{1})$
6b Wald identity. $E(S_{T})=E(X_{1})E(T)$
7 Kolmogorov forward/backward equation
8 Crofton's method
9 General idea: Symmetry. Especially for "$n$ points are chosen uniformly on the $[0;1]$" problems.
Comment: Right! This is kind of the idea. Maybe should put up a wiki toward which everyone can contribute. (My next project once I'm done with my dissertation :>) Was never aware of Crofton's method btw. Pretty cool!
Answer: If you are just looking to simplify an expression involving expectations, Economists' Mathematical Manual has a nice concise list of identities. You can find a copy online here.
Comment: Definitely a nice reference. Didn't find what I was looking for...but I'll hold onto this. I'm sure it'll come in handy at some point :)
Comment: Link is broken (at least when and how I try it).


Reverse proxy to an authentication server and webserver

Question: For a while my team and I have been working on an API server with a client. We would like to use a separate server as authentication server. Consider the diagram below.
<code>+----------+
|          |
|  Client  |
|          |
+-^------+-+
  |      |
 (6)    (1)
  |      |
  |      |
+-+------v-+            +----------+
|          +----(2)----->          |
|  Proxy   |            |   Auth   |
|          <----(3)-----+          |
+-^------+-+            +----------+
  |      |
 (5)    (4)
  |      |
  |      |
+-+------v-+
|          |
|  Apache  |
|          |
+----------+
</code>
Right now we have Varnish Cache set up as this reverse proxy, it works fine up to one very important problem. To realize the flow above we have to restart the varnish loop after the authentication server has been polled for validity of some provided access token in the headers by the client. The quirk here is that when sending a POST request (that also needs to be authenticated) varnish will omit the POST request body after the restart loop. The API will never receive any POST data (https://www.varnish-cache.org/trac/ticket/652). This is where we're stuck.
The main question is: how do we realize the flow that we're trying to accomplish in the diagram? Ideally we keep using varnish as reverse proxy and caching mechanism, but I don't have any issues if we need to setup a different reverse proxy and let Varnish just be a caching server in between the proxy and the API. Your help is much appreciated!
Comment: We're currently considering building a custom solution ourselves using Node.js.
Answer: As you've noticed, Varnish has (currently) close to no handling of request or response bodies.
However, it it pretty good with headers.
Can you change the application so there is enough information to do the authentication by the headers alone?
POST to an URL with auth tokens embedded in them, or add additional request headers. (X-auth-token: foo)
I'd also recommend using the CURL VMOD to call out to the authentication server instead of using restarts. Makes the VCL much more readable and easy to debug.
Comment: the cURL vmod was mentioned by someone else as well. Also I don't think you quite understood what I meant. The problem is that a POST request is meant for the API to begin with. The access token is already in the headers. The proxy checks a remote auth server for the token in the header and based on that either forwards or bounces the original POST request.


Criando uma animação JS com SVG usando HTML e CSS

Question: Estou começando os estudos com SVG e tentando compreender um exemplo não consigo executá-lo corretamente, foram demonstradas as partes HTML/CSS/JS e eu fiz a conexão dessas partes, porém não funcionou... Se alguém puder me falar o que estou fazendo errado seria de muita ajuda:

    <title>Exemplo Teste</title>

    <svg>
      <circle class="meu-circulo"></circle>
    </svg>

Comment: Mas o que foi que não funcionou??
Comment: Não desenhar o circulo e aplicar o efeito JS de aumentar o raio com o evento de click
Answer: O problema acontece porque quando é chamada a linha:
const circle = document.querySelector('.meu-circulo');

O elemento:
<circle class="meu-circulo"></circle>

Ainda não existe gerando o erro:

cannot read property of undefined

Na linha:
circle.addEventListener('click', () => {

Para resolver o problema coloque o script dentro do evento 'load' do documento ou seja seu script só será acionado depois que página carregar.

  <title>Exemplo Teste</title>

  <svg>
      <circle class="meu-circulo"></circle>
    </svg>


Javascript Relative Url Doesn't include Id

Question: When I make an ajax request using JQuery, the relative url doesn't include the last part of the url. I have the following urls:
/Question/100
/Question/100/AddComment

I am trying to send an ajax request from the first page to the second page. The jquery I am using is:
$.ajax({
    url: 'AddComment',
    type: 'POST'
 });

This ajax request goes to the url
/Question/AddComment

To fix the issue I can just do window.location.href + "/AddComment" However I was wondering why exactly does the relative url not include the Id value? Also is there a way to solve this issue without using window.location.href?
Comment: That's the expected behavior. URLs are relative to the directory, not the filename, to make it easy to refer to documents in the same directory.
Comment: Normally `window.location.href` refers to a file, not a directory, so you wouldn't need to refer to subdirectories of it.
Answer: This has nothing to do with JavaScript or jQuery, it's just how browsers interpret relative URLs.  And for good reason.
The browser doesn't know or care what the "Id" is in the URL.  It just knows that you are requesting a resource (100) at the end of a path (/Question/).  Any URL relative to that resource is going to be requested relative to that same path.  So requesting only AddComment will result in the browser looking for AddComment in the /Question/ path.
Consider what would happen if this wasn't the case.  What if you're on the page index.html and you click on a link to about.html.  Would you expect or want the browser to navigate to /index.html/about.html?  Of course not.
You just need to specify the correct URL.  If you can write the full absolute path, great.  If you can dynamically output it from server-side code (like the @Url.Route helper in ASP.NET MVC, for example), also great.  If you can dynamically build it in JavaScript either based on known base values or from examining the current URL, that's likely just as good as long as you cover any edge cases you might encounter and whatnot.  But ultimately you need to specify the URL.


Linear Regression: Finding t and p-value

Question: all. I'm taking an introductory to applied statistics class and can't figure out how to do a question on my homework. I won't put all of the data up, because I really want to know how to do the problem, not just the answer.
In the problem, I am given a list of schools and the tuition from each school in the years 2000 and 2005. I put the tuition values from 2000 in list one and the values from 2005 in list two. From there, I was able to state the correct least-squares regression line by running LinReg(a+bx) on my ti-83 calculator. However, it also wants to know the p-value and t, and I have no idea how to come up with these values. We are encouraged to use our calculators, so if someone could point me in the right direction, I'd be much obliged. :)
Answer: I don't know the ti-83, I would recommend using a full statistical program rather than a calculator if you can.  But if the calculator will give you the slope and the standard error of the slope then the t-value is just the slope divided by the standard error and then you can look up that value on the t-table (or some calculators may have that built in) to get the p-value.
Comment: The $t$ value and associated $p$ value may be for the $\beta$ coefficient, for the constant $\alpha$, or for Pearson's $r$. Basically, each of these estimated statistics, has an associated Wald-type test associated with it. The OP needs to understand _which_ $t$ and $p$ are being requested.
Answer: On the TI-83, you can get the test statistic and the p-value by choosing
STAT->TESTS->LinRegTTest,
and then enter the required information.


WebDriver does not accept js alert in Chrome

Question: I'm new at webdriver and I learnt how to handle JS alert things from different blogs. I could not find my problem solution. Actually when I am going to accept my js alert in Firefox the same code works fine, but once I changed my browser into Chrome it raises exception even I put to wait driver before and after it not work. What am I doing wrong?
<code>driver.findElement(By.xpath(".//*[xxxxxx]")).click();
wait.until(ExpectedConditions.alertIsPresent());

Alert al = driver.switchTo().alert();
wait.until(ExpectedConditions.alertIsPresent());

String Alert1 = al.getText();

al.accept();

System.out.println(Alert1);

Assert.assertEquals(Alert1, "xxxxxxx");
</code>
Comment: What exception do you see?
Comment: here is exception.
Exception in thread "main" org.openqa.selenium.WebDriverException: unknown error: cannot determine loading status
from unknown error: unhandled inspector error: {"code":-32000,"message":"Internal error: result is not an Object"}
  (Session info: chrome=47.0.2526.106)
  (Driver info: chromedriver=2.20.353145 (343b531d31eeb933ec778dbcf7081628a1396067),platform=Windows NT 10.0 x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 78 milliseconds
Comment: Hi, try with Thread.sleep(3000); its works good in case of alerts in my scripts. any how, here you can also try with javascriptExecutor.
Answer: You might solve the problem by changing the version of ChromeDriver to v2.18.
I encountered the same bug when I tried to deal with the alert appeared in the iframe. I finally change the the version of ChromeDriver to v2.18 and my test passed.
Probably this bug issue for ChromeDriver is related to your problem. https://bugs.chromium.org/p/chromedriver/issues/detail?id=1224&colspec=ID%20Status%20Pri%20Owner%20Summary
This issue was found in ChromeDriver v2.19, v2.20, and v2.21.
Comment: This has been fixed in v.2.22 - see https://bugs.chromium.org/p/chromedriver/issues/detail?id=1224#c18
Answer: Finally i got who is culprit.
Actually this alert executes in Iframe and main window and Iframe URLs are different with each other. Once I go on that page which URL and Iframe (alert) URL are same then chrome is not raising exception and same code works fine.
Answer: Put a small thread sleep before accepting the alert
<code>    Thread.sleep(100);
    driver.switchTo().alert().accept();
</code>


Evaluate limit of a functon at a point

Question: Suppose we want to evaluate the limit of  a function $f(x) = 2x + 3$ at $2$. One way is to to find $f(2)$ and declare it to be the result. Is it a correct step to do since from the definition of limit we know that we are interested in the value when $x$ approaches close to 2 but not exactly at 2. In this sense, replacing $x$ by 2 might not be a correct step.
Comment: A function is continuous at $x_0$ **iff** the above condition holds.
Comment: If $f$ is continuous, then $f(\lim_{x\to x_0} x
) = f(x_0) = \lim_{x\to x_0} f(x)$.
Comment: @AnirbanGhosh Because when taking the limit you only want to find values near $2$, not at $2$ itself. Notice that $\frac{x^2-4}{x-2}=x+2$ if and only if $x \ne 2$, which is fine when you just want to find the limit.
Comment: This is a good question. Technically this function is not defined at $x=2$, so continuity at $x=2$ makes no sense. However, you can extend the function to be defined at $x=2$ (since $x^2-4 = (x-2)(x+2)$) with a value that makes the extended function continuous. But, then you need to show that the resulting function is continuous, and you can't just substitute $x=2$ into the original formula.
Comment: So we can do such things when the function is continuous else not. Correct?
Comment: Thanks. So what about the case of $\frac{x^2-4}{x-2}$ when $x$ approaches 2. Is it correct to reduce to $x+2$ and then say that 4 is the limit. Why this is a correct step to do as the function is not continuous at $x=2$.
Comment: @AnirbanGhosh How do you replace $x$ with $2$ in $\dfrac{x^2-4}{x-2}$?
Comment: @GitGud: I have never seen a definition of continuity like that. If you are talking about extending uniformly continuous functions to the closure of their domain, it makes sense, but otherwise...
Comment: @copper.hat I was confused. Disregard.
Comment: I have one remark here. By definition $f(x)$ is continuous at $x = a$ if $\lim_{x \to a}f(x) = f(a)$. This means that to check continuity we should evaluate limit using some means and compare with value of function at that point. Note that if we use continuity to evaluate this limit then we are following a circular path.
Answer: Let's consider a slightly more interesting (but related) example. Let $$g(x)=\frac{2x^2-x-6}{x-2},$$ defined for all real $x\ne 2.$ It can be shown that for all $x\ne 2,$ we have $g(x)=2x-3.$ Of course, it doesn't make sense to talk about $g(2),$ since it is undefined, there. However, we can still talk about the limit as $x\to 2$. Noting that for all $x\ne 2$ we have $$|g(x)-1|=|(2x-3)-1|=|2x-4|=2|x-2|,$$ then for any $\epsilon>0$ and any $x\in\Bbb R$ such that $0<|x-2|<\frac\epsilon2,$ we have $|g(x)-1|<\epsilon,$ so $\lim_{x\to 2}g(x)=1.$
Answer: I think it is better to stick to the rules of limits.
$\displaystyle \begin{aligned}\lim_{x \to 2}f(x) &= \lim_{x \to 2}(2x + 3)\\
&= \lim_{x \to 2}2x + \lim_{x \to 2}3\\
&= 2\lim_{x \to 2}x + 3\\
&= 2\cdot 2 + 3 = 7\end{aligned}$
We have used the fact that $\lim_{x \to a}x = a$ which can be verified almost trivially using definition of a limit.
I find it totally unnecessary to invoke any higher concepts (other than definition of limits and rules of limits) to evaluate limits. Only when it is not possible to solve a problem using basic definitions and rules I go for the high level techniques like continuity, L'Hospital, series expansion, Stirling formula and what not.
We should try to stick to simple ideas to avoid confusion and learn to understand the powers of these simple rules of limits. Using these rules of limit we can show that limit of any expression consisting of algebraic, trigonometric, logarithmic, exponential functions when $x \to a$ can be evaluated by a direct substitution of $x = a$ in the expression provided that such a substitution does not lead to any undefined expression (like zero in denominator, log of zero etc.)

Evaluate limit of a functon at a point


Proving a specific $min$ function is equivalent to solving $Ax-b$

Question: The homework question asks to prove that
$min_{x\in\mathbb{R}} {f(x) = 1/2<Ax,x>-<b,x>}$
is equivalent to solving a linear system $Ax-b$.
The hint the professor gave is to recite the proposition:
The gradient of the function $f(x)$ is $∇f(x) = Ax − b$.
Moreover,
(i) if A is positive definite, then $f$ admits a unique minimum at $x_{0}$ that is a solution of the linear system $Ax = b$;
(ii) if $A$ is positive indefinite and if $b$ belongs to the range of $A$, then $f$ attains its minimum at all vectors $x_{0}$ that solve the linear system $Ax = b$ and at these vectors only.
I don't understand how using that hint gets me anywhere near the original problem.
Comment: What must be true of the gradient at the minimum?
Comment: that it must be unique?
Answer: Suppose we are solving $Ax = b$ for $x$.  This equation can be written, as you did,
$$
Ax - b = 0.
$$
Now, suppose we start out as a little less optimistic: a solution may not exist.  So, we want an $x$ such that $Ax$ is as close as possible to $b$.  In other words, we are now solving the minimization problem:
$$
\min_{x} \rightarrow |Ax - b|^2.
$$
In other words, we are minimizing the function
$$
f(x) = {1 \over 2} |Ax - b|^2,
$$
where the $1/2$ does not affect the solution space, but makes it more algebraically convenient to compute the gradient of $f$.
(In your problem, you have $x \in \mathbb{R}$, which I suspect is a typo.  If $A$ is a matrix and $x$ and $b$ vectors of appropriate dimension, please interpret my $||$'s as the magnitude that we get from the dot product: $|w|^2 = w \cdot w$.)
Accordingly, we are minimizing
$$
f(x) = {1 \over 2}|Ax - b|^2 = {1 \over 2}(Ax - b) \cdot (Ax - b) = {1 \over 2}|Ax|^2 - (Ax)\cdot b + {1 \over 2}|b|^2.
$$
Since $b$ is a constant vector, however, the minima of
$$
{1 \over 2}|Ax|^2 - (Ax)\cdot b + {1 \over 2 }|b|^2
$$
are the same as the minima of
$$
{1 \over 2}|Ax|^2 - (Ax)\cdot b.
$$


Java ExecutorService: awaitTermination of all recursively created tasks

Question: I use an ExecutorService to execute a task. This task can recursively create other tasks which are submitted to the same ExecutorService and those child tasks can do that, too.
I now have the problem that I want to wait until all the tasks are done (that is, all tasks are finished and they did not submit new ones) before I continue.
I cannot call ExecutorService.shutdown() in the main thread because this prevents new tasks from being accepted by the ExecutorService.
And Calling ExecutorService.awaitTermination() seems to do nothing if shutdown hasn't been called.
So I am kinda stuck here. It can't be that hard for the ExecutorService to see that all workers are idle, can it? The only inelegant solution I could come up with is to directly use a ThreadPoolExecutor and query its getPoolSize() every once in a while. Is there really no better way do do that?
Answer: This really is an ideal candidate for a Phaser.  Java 7 is coming out with this new class. Its a flexible CountdonwLatch/CyclicBarrier.  You can get a stable version at JSR 166 Interest Site.
The way it is a more flexible CountdownLatch/CyclicBarrier is because it is able to not only support an unknown number of parties (threads) but its also reusable (thats where the phase part comes in)
For each task you submit you would register, when that task is completed you arrive.  This can be done recursively.
Phaser phaser = new Phaser();
ExecutorService e = //

Runnable recursiveRunnable = new Runnable(){
   public void run(){
      //do work recursively if you have to

      if(shouldBeRecursive){
           phaser.register();
           e.submit(recursiveRunnable);
      }

      phaser.arrive();
   }
}

public void doWork(){
   int phase = phaser.getPhase();

   phaser.register();
   e.submit(recursiveRunnable);

   phaser.awaitAdvance(phase);
}

Edit: Thanks @depthofreality for pointing out the race condition in my previous example.  I am updating it so that executing thread only awaits advance of the current phase as it blocks for the recursive function to complete.
The phase number won't trip until the number of arrives == registers.  Since prior to each recursive call invokes register a phase increment will happen when all invocations are complete.
Comment: Nice, Phasers seem to be what I need. I want to stick to the current standard Java library but as soon as it's out there I will use those. Thanks for the tip!
Comment: I'm aware it was posted a long time ago. Still I'm wondering if there's race condition here. Can't doWork() complete before recursiveRunnable registers with phaser?
Comment: @depthofreality  That's a great point.  You are right there would certainly be a race here (must have overlooked it as I put this example together quickly).  I'll update it now.
Comment: @JohnVint thanks for clarification and fix. I think there's another issue now. Some parties may arrive without being registered.
Comment: @depthofreality I considered that, but that wouldn't be the case.  The first party to register is done in `doWork`, since the phaser below that doesn't `arriveAndAwaitAdvance` the `recursiveRunnable` needs to arrive (which it does).  Also notice the runnable `register`s before executing to the ExecutorService
Comment: @depthofreality So prior to `awaitAdvance` the phaser is at phase 0 and registered parties 1.  If `shouldBeRecursive` is false, then the runnable would arrive tripping the barrier.  If it isnt false, the phaser would have 2 registered parties and 1 arrived party (until the runnable also arrives then tripping the barrier).
Comment: @JohnVint If `shouldBeRecursive` is false then the party (thread) arrives not registered, right? The Oracle documentation says: __It is a usage error for an unregistered party to invoke this method (arrive, @depthofreality). However, this error may result in an IllegalStateException only upon some subsequent operation on this phaser, if ever.__
Comment: @depthofreality  If there was no `register` then yes, it would be a huge error.  To answer your question, upon entering the runnable the first time, registered parties is 1, that is done in `doWork`.  So base case of `shouldBeRecursive` == false the first entry, since phaser.register is done in `doWork` the register count is 1 and the arrive in this case would trip the barrier.
Comment: I took the registering out of the recursive thread and placed it on the submitting thread.  The arriving is done on the recusrvie thread.  In the end you will always get a state where registered parties == arrived parties.
Comment: @JohnVint, `e.submit()` and `run()` will potentially be executed by different threads. That's the reason I see the issue here.
Comment: @depthofreality It will be executed by other threads, but `phaser.register()` will be executed before the `e.submit()` and `run()` so that the phaser will always be in an incremented state before those two are invoked.  Can you explain the race condition some more as you see it?
Comment: @JohnVint Your code is OK. Sorry, it was my confusion. Phaser doesn't treat parties the same way as it treats threads. It is possible to register party on one thread and call arrive() on the other. After your fix of race condition I don't see any other issue here. Thanks!
Answer: If number of tasks in the tree of recursive tasks is initially unknown, perhaps the easiest way would be to implement your own synchronization primitive, some kind of "inverse semaphore", and share it among your tasks. Before submitting each task you increment a value, when task is completed, it decrements that value, and you wait until the value is 0.
Implementing it as a separate primitive explicitly called from tasks decouples this logic from the thread pool implementation and allows you to submit several independent trees of recursive tasks into the same pool.
Something like this:
public class InverseSemaphore {
    private int value = 0;
    private Object lock = new Object();

    public void beforeSubmit() {
        synchronized(lock) {
            value++;
        }
    }

    public void taskCompleted() {
        synchronized(lock) {
            value--;
            if (value == 0) lock.notifyAll();
        }
    }

    public void awaitCompletion() throws InterruptedException {
        synchronized(lock) {
            while (value > 0) lock.wait();
        }
    }
}

Note that taskCompleted() should be called inside a finally block, to make it immune to possible exceptions.
Also note that beforeSubmit() should be called by the submitting thread before the task is submitted, not by the task itself, to avoid possible "false completion" when old tasks are completed and new ones not started yet.
EDIT: Important problem with usage pattern fixed.
Comment: Was answering something similar - he could get by using an AtomicInteger.
Comment: @dogbane that doesnt help this answer though becauase there would need to be synchronization for the waiting.
Comment: @SB: With AtomicInteger you can't wait for completion without busy waiting.
Comment: There is a typo, you are doing lock-- instead of value--
Comment: @axtavt You can still use AtomicInteger instead of int in your InverseSemaphore. You wouldn't need to synchronise around it then.
Comment: Thanks for the answer! I posted an alternative to your basic AtomicInteger idea. Essentially I hook into the ThreadPoolExecutor to increment/decrement the counter and then use the norma ExecutorService.shutdown() and awaitTermination() mechanism.
Comment: +1 for simple usage of basic object synchronization.  If more people understood this fundamental concept, the world would be a much better place.
Answer: Wow, you guys are quick:)
Thank you for all the suggestions. Futures don't easily integrate with my model because I don't know how many runnables are scheduled beforehand. So if I keep a parent task alive just to wait for it's recursive child tasks to finish I have a lot of garbage laying around.
I solved my problem using the AtomicInteger suggestion. Essentially, I subclassed ThreadPoolExecutor and increment the counter on calls to execute() and decrement on calls to afterExecute(). When the counter gets 0 I call shutdown(). This seems to work for my problems, not sure if that's a generally good way to do that. Especially, I assume that you only use execute() to add Runnables.
As a side node: I first tried to check in afterExecute() the number of Runnables in the queue and the number of workers that are active and shutdown when those are 0; but that didn't work because not all Runnables showed up in the queue and the getActiveCount() didn't do what I expected either.
Anyhow, here's my solution: (if anybody finds serious problems with this, please let me know:)
public class MyThreadPoolExecutor extends ThreadPoolExecutor {

    private final AtomicInteger executing = new AtomicInteger(0);

    public MyThreadPoolExecutor(int coorPoolSize, int maxPoolSize, long keepAliveTime,
        TimeUnit seconds, BlockingQueue<Runnable> queue) {
        super(coorPoolSize, maxPoolSize, keepAliveTime, seconds, queue);
    }

    @Override
    public void execute(Runnable command) {
        //intercepting beforeExecute is too late!
        //execute() is called in the parent thread before it terminates
        executing.incrementAndGet();
        super.execute(command);
    }

    @Override
    protected void afterExecute(Runnable r, Throwable t) {
        super.afterExecute(r, t);
        int count = executing.decrementAndGet();
        if(count == 0) {
            this.shutdown();
        }
    }

}

Comment: While this would work for your specific requirements, it is not a general solution (given the potential race condition after you decrement and then test the value of count == 0.)

The general solution would be to use AbstractQueuedSynchronizer to roll your own 'dynamic' countdown latch.
Comment: You have the problem that the executor doesn't know when you have stop adding tasks.  If at any point all your tasks finish before you have finished adding them, those tasks will be rejected as the pool has shutdown.
Comment: @PeterLawrey Right, but there's a trivial solution: Increment the counter initially and decrement it when done with adding. Or use an "adder task" for adding all the tasks.
Answer: You could create your own thread pool which extends ThreadPoolExecutor.  You want to know when a task has been submitted and when it completes.
public class MyThreadPoolExecutor extends ThreadPoolExecutor {
    private int counter = 0;

    public MyThreadPoolExecutor() {
        super(1, 1, 0, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
    }

    @Override
    public synchronized void execute(Runnable command) {
        counter++;
        super.execute(command);
    }

    @Override
    protected synchronized void afterExecute(Runnable r, Throwable t) {
        super.afterExecute(r, t);
        counter--;
        notifyAll();
    }

    public synchronized void waitForExecuted() throws InterruptedException {
        while (counter == 0)
            wait();
    }
}

Comment: I like this solution better than the one that has a score of 13.  HOWEVER:  the "while (counter == 0)" should be "while (counter > 0)", right??!
Answer: Use a Future for your tasks (instead of submitting Runnable's), a callback updates  it's state when it's completed, so you can use Future.isDone to track the sate of all your tasks.
Comment: When he says callback he means the value you return from the call method
Comment: How do you get a callback on a Future?  Thought you had to call .get on it.
Comment: You do, what I mean is that the 'done' flag is set for you (via a callback). I've rephrased the answer to make this more explicit.
Comment: ok so he still has to poll isDone?  Just want to make sure.  @John V. - the call method on a callable returns the result - waiting for it if needed.  You get a Future back when you submit a Callable.  Maybe our definition of callback differs.
Comment: No you're right SB I miss read your questioning on what he meant.
Comment: This would require me to have a "central place" where I collect all the futures and wait for all of them to complete. This would work but doesn't fit the architecture of my program very well.
Comment: Yes, you would need a central collection of Futures so that you could poll their isDone status.
Answer: Use CountDownLatch.
Pass the CountDownLatch object to each of your tasks and code your tasks something like below.
public void doTask() {
    // do your task
    latch.countDown();
}

Whereas the thread which needs to wait should execute the following code:
public void doWait() {
    latch.await();
}

But ofcourse, this assumes you already know the number of child tasks so that you could initialize the latch's count.
Comment: and what should the latch be intialised to?
Comment: CountDownLatch has a problem in that you can't reset the count once it's been created.  I'm assuming he doesn't know the number of tasks the system will invoke.
Comment: yeah...i know, i assumed that he could know the number of tasks before hand
Comment: Actually, I don't know the number of tasks beforehand:) Thanks anyway!
Answer: (mea culpa: its a 'bit' past my bedtime ;) but here's a first attempt at a dynamic latch):
package oss.alphazero.sto4958330;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;

public class DynamicCountDownLatch {
    @SuppressWarnings("serial")
    private static final class Sync extends AbstractQueuedSynchronizer {
        private final CountDownLatch toplatch;
        public Sync() {
            setState(0);
            this.toplatch = new CountDownLatch(1);
        }

        @Override
        protected int tryAcquireShared(int acquires){
            try {
                toplatch.await();
            }
            catch (InterruptedException e) {
                throw new RuntimeException("Interrupted", e);
            }
            return getState() == 0 ? 1 : -1;
        }
        public boolean tryReleaseShared(int releases) {
            for (;;) {
                int c = getState();
                if (c == 0)
                    return false;
                int nextc = c-1;
                if (compareAndSetState(c, nextc))
                    return nextc == 0;
            }
        }
        public boolean tryExtendState(int acquires) {
            for (;;) {
                int s = getState();
                int exts = s+1;
                if (compareAndSetState(s, exts)) {
                    toplatch.countDown();
                    return exts > 0;
                }
            }
        }
    }
    private final Sync sync;
    public DynamicCountDownLatch(){
        this.sync = new Sync();
    }
    public void await()
        throws InterruptedException
    {
        sync.acquireSharedInterruptibly(1);
    }

    public boolean await(long timeout, TimeUnit   unit)
        throws InterruptedException
    {
        return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout));
    }
    public void countDown() {
        sync.releaseShared(1);
    }
    public void join() {
        sync.tryExtendState(1);
    }
}

This latch introduces a new method join() to the existing (cloned) CountDownLatch API, which is used by tasks to signal their entry into the larger task group.
The latch is pass around from parent Task to child Task. Each task would, per Suraj's pattern, first 'join()' the latch, do its task(), and then countDown().
To address situations where the main thread launches the task group and then immediately awaits() -- before any of the task threads have had a chance to even join() -- the topLatch is used int inner Sync class.  This is a latch that will get counted down on each join(); only the first countdown is of course significant, as all subsequent ones are nops.
The initial implementation above does introduce a semantic wrinkle of sorts since the tryAcquiredShared(int) is not supposed to be throwing an InterruptedException but then we do need to deal with the interrupt on the wait on the topLatch.
Is this an improvement over OP's own solution using Atomic counters? I would say probably not IFF he is insistent upon using Executors, but it is, I believe, an equally valid alternative approach using the AQS in that case, and, is usable with generic threads as well.
Crit away fellow hackers.
Answer: If you want to use JSR166y classes - e.g. Phaser or Fork/Join - either of which might work for you, you can always download the Java 6 backport of them from: http://gee.cs.oswego.edu/dl/concurrency-interest/ and use that as a basis rather than writing a completely homebrew solution. Then when 7 comes out you can just drop the dependency on the backport and change a few package names.
(Full disclosure: We've been using the LinkedTransferQueue in prod for a while now. No issues)
Answer: I must say, that solutions described above of problem with recursive calling task and wait for end suborder tasks doesn't satisfy me. There is my solution inspired by original documentation from Oracle there: CountDownLatch and example there: Human resources CountDownLatch.
The first common thread in process in instance of class HRManagerCompact has waiting latch for two daughter's threads, wich has waiting latches for their subsequent 2 daughter's threads... etc.
Of course, latch can be set on the different value than 2 (in constructor of CountDownLatch), as well as the number of runnable objects can be established in iteration i.e. ArrayList, but it must correspond (number of count downs must be equal the parameter in CountDownLatch constructor).
Be careful, the number of latches increases exponentially according restriction condition:
'level.get() < 2', as well as the number of objects. 1, 2, 4, 8, 16... and latches 0, 1, 2, 4... As you can see, for four levels (level.get() < 4) there will be 15 waiting threads and 7 latches in the time, when peak 16 threads are running.
package processes.countdownlatch.hr;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;

/** Recursively latching running classes to wait for the peak threads
 *
 * @author hariprasad
 */
public class HRManagerCompact extends Thread {
  final int N = 2; // number of daughter's tasks for latch
  CountDownLatch countDownLatch;
  CountDownLatch originCountDownLatch;
  AtomicInteger level = new AtomicInteger(0);
  AtomicLong order = new AtomicLong(0); // id latched thread waiting for

  HRManagerCompact techLead1 = null;
  HRManagerCompact techLead2 = null;
  HRManagerCompact techLead3 = null;

// constructor
public HRManagerCompact(CountDownLatch countDownLatch, String name,
    AtomicInteger level, AtomicLong order){
  super(name);
  this.originCountDownLatch=countDownLatch;
  this.level = level;
  this.order = order;
 }

 private void doIt() {
    countDownLatch = new CountDownLatch(N);
    AtomicInteger leveli = new AtomicInteger(level.get() + 1);
    AtomicLong orderi = new AtomicLong(Thread.currentThread().getId());
    techLead1 = new HRManagerCompact(countDownLatch, "first", leveli, orderi);
    techLead2 = new HRManagerCompact(countDownLatch, "second", leveli, orderi);
    //techLead3 = new HRManagerCompact(countDownLatch, "third", leveli);

    techLead1.start();
    techLead2.start();
    //techLead3.start();

    try {
     synchronized (Thread.currentThread()) { // to prevent print and latch in the same thread
       System.out.println("*** HR Manager waiting for recruitment to complete... " + level + ", " + order + ", " + orderi);
       countDownLatch.await(); // wait actual thread
     }
     System.out.println("*** Distribute Offer Letter, it means finished. " + level + ", " + order + ", " + orderi);
    } catch (InterruptedException e) {
     e.printStackTrace();
    }
  }

 @Override
 public void run() {
  try {
   System.out.println(Thread.currentThread().getName() + ": working... " + level + ", " + order + ", " + Thread.currentThread().getId());
   Thread.sleep(10*level.intValue());
   if (level.get() < 2) doIt();
   Thread.yield();
  }
  catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  /*catch (InterruptedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }*/
  // TODO Auto-generated method stub
  System.out.println("--- " +Thread.currentThread().getName() + ": recruted " + level + ", " + order + ", " + Thread.currentThread().getId());
  originCountDownLatch.countDown(); // count down
 }

 public static void main(String args[]){
  AtomicInteger levelzero = new AtomicInteger(0);
  HRManagerCompact hr = new HRManagerCompact(null, "zero", levelzero, new AtomicLong(levelzero.longValue()));
  hr.doIt();
 }
}

Possible commented output (with some probability):
first: working... 1, 1, 10 // thread 1, first daughter's task (10)
second: working... 1, 1, 11 // thread 1, second daughter's task (11)
first: working... 2, 10, 12 // thread 10, first daughter's task (12)
first: working... 2, 11, 14 // thread 11, first daughter's task (14)
second: working... 2, 11, 15 // thread 11, second daughter's task (15)
second: working... 2, 10, 13 // thread 10, second daughter's task (13)
--- first: recruted 2, 10, 12 // finished 12
--- first: recruted 2, 11, 14 // finished 14
--- second: recruted 2, 10, 13  // finished 13 (now can be opened latch 10)
--- second: recruted 2, 11, 15  // finished 15 (now can be opened latch 11)
*** HR Manager waiting for recruitment to complete... 0, 0, 1
*** HR Manager waiting for recruitment to complete... 1, 1, 10
*** Distribute Offer Letter, it means finished. 1, 1, 10 // latch on 10 opened
--- first: recruted 1, 1, 10 // finished 10
*** HR Manager waiting for recruitment to complete... 1, 1, 11
*** Distribute Offer Letter, it means finished. 1, 1, 11 // latch on 11 opened
--- second: recruted 1, 1, 11  // finished 11 (now can be opened latch 1)
*** Distribute Offer Letter, it means finished. 0, 0, 1  // latch on 1 opened

Answer:
The only inelegant solution I could come up with is to directly use a ThreadPoolExecutor and query its getPoolSize() every once in a while. Is there really no better way do do that?

You have to use shutdown() ,awaitTermination()and  shutdownNow() methods in a proper sequence.
shutdown():  Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted.
awaitTermination():Blocks until all tasks have completed execution after a shutdown request, or the timeout occurs, or the current thread is interrupted, whichever happens first.
shutdownNow(): Attempts to stop all actively executing tasks, halts the processing of waiting tasks, and returns a list of the tasks that were awaiting execution.
Recommended way from oracle documentation page of ExecutorService:
 void shutdownAndAwaitTermination(ExecutorService pool) {
   pool.shutdown(); // Disable new tasks from being submitted
   try {
     // Wait a while for existing tasks to terminate
     if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {
       pool.shutdownNow(); // Cancel currently executing tasks
       // Wait a while for tasks to respond to being cancelled
       if (!pool.awaitTermination(60, TimeUnit.SECONDS))
           System.err.println("Pool did not terminate");
     }
   } catch (InterruptedException ie) {
     // (Re-)Cancel if current thread also interrupted
     pool.shutdownNow();
     // Preserve interrupt status
     Thread.currentThread().interrupt();
   }

You can replace if condition with while condition in case of long duration in completion of tasks as below:
Change
if (!pool.awaitTermination(60, TimeUnit.SECONDS))

To
 while(!pool.awaitTermination(60, TimeUnit.SECONDS)) {
     Thread.sleep(60000);
 }

You can refer to other alternatives (except join(), which can be used with standalone thread ) in :
wait until all threads finish their work in java
Answer: You could use a runner that keeps track of running threads:
Runner runner = Runner.runner(numberOfThreads);

runner.runIn(2, SECONDS, callable);
runner.run(callable);

// blocks until all tasks are finished (or failed)
runner.waitTillDone();

// and reuse it
runner.runRunnableIn(500, MILLISECONDS, runnable);

runner.waitTillDone();

// and then just kill it
runner.shutdownAndAwaitTermination();

to use it you just add a dependency:
compile 'com.github.matejtymes:javafixes:1.3.0'


How does bodybuilding or weightlifting affect singer's voice?

Question: I heard from an instructor that bodybuilding causes you to have hard muscles,which are unnecessary for singing and may even hinder singing, the instructor said, though he could not explain more about the issue. Afterwards, I searched and didn't find an explanation.
How does bodybuilding or weightlifting affect a singer's voice? Does it help or negatively affect professional singing?
Comment: @jjmusicnotes this question is about effects on the voice, the other one is on piano playing
Comment: @jjmusicnotes surely though, that's a duplicate of an answer, not a question.  The same larger point can match multiple questions, but the questions themselves are distinct.
Comment: possible duplicate of [Is it bad for a piano player to work out?](http://music.stackexchange.com/questions/12003/is-it-bad-for-a-piano-player-to-work-out)
Comment: @AlexanderTroup - yes, I was distinctly aware of that.  The larger point is that like the pianist from the other question, weight-lifting doesn't affect your vocal cords, therefore not affecting the voice. With vocal production, what matters more is posture and breath management as opposed to muscle / fat ratio.
Comment: @jjmusicnotes the key muscles for singing totally differ from those vital for playing piano! Besides the physical process of singing is a completely different process from playing piano!
Comment: @Manoochehr - again, I am obviously aware of that fact.  It seems that everyone has misconstrued my point and has misunderstood my response.  Do not worry about weightlifting - just focus on learning absolutely correct fundamental technique, posture, and breath management and you'll be fine.
Comment: "weight-lifting doesn't affect your vocal cords, therefore not affecting the voice": I take it, you aren't a singer?  Right afterwards, you are talking about "posture and breath management", and that's supposed to be independent from weight lifting?
Comment: "How does bodybuilding or weightlifting affect singer's voice?" Are you singing while doing those things?
Answer: Body building, weight lifting etc affect the voice indirectly.  A pretty important factor for voice quality is controlling the breath pressure and airway resonance actively and passively.  "Passively" means "riding" on the breath and its support in the lower body.  When you are training your muscles, you are losing elasticity in your breathing apparatus and consequently your breath supply.
There is also the problem that the body building posturing requires a totally different way of breathing than singing: good singing relies on a "big bag of air" around your waist.  Which is exactly what you are trying to avoid when posturing.
If you want to see an example of "too much of a goodness", take a look at old "Conan the Barbarian" movies from the time where Arnold Schwarzenegger was "Mr. Universe".  And particularly scenes where he is "running".  It's obvious that his running muscles are quite detrimental to actually moving forward speedily.
At any rate, once bodybuilding gets to the stage where it is changing your constitution and metabolism, it will not just cause differences to your breathing but actually affect the voice itself as you have different waste products running through your body (and that's assuming that you stay off steroids).
So there are a lot of things where bodybuilding and voice building are not independent.  And if you look at the faces weightlifters make: that requires serious strength in muscle groups (neck, chest, others) which you don't want to tense while singing.  Making those muscles stronger and habitually tensing them is going to make control of them more tricky.
So it all boils down to an emphatic "depends".
Comment: Very tempting to downvote your (excellent) answer simply for recommending anyone watches  "Conan the Barbarian". "Conan the Librarian" would have been a better singer by the sound of it  ;-)
Answer: On one hand, any type of sport can help a singer's breathing skills, but on another, some sports like body-building and weight-lifting can reduce the flexibility of some muscles. So you should be careful on muscles around your chest and neck.
I think it should be OK if you do workouts that help your muscles' flexibility around your chest and neck and also your stomach.
For assurance you can ask a physiotherapist about your workouts.
Comment: True Mohammad, But I'm looking for a more detailed answer which describes how exactly bodybuilding affects singing, what exactly happens to muscles and does really hurt the singing function? As you see it's totally common among many singers to have ripped muscles!
Comment: many singers you said may have another reason for having ripped muscles here ;) :)) lets take a look at professional and high end singers , maybe folk ones you know Mr. Shajarian , or pop ones like Ebi , Dariush? and maybe non persian singers Adele and so on... ;) its not really matter and I think its just a beauty reason than a technical reason.
Answer: Well if you look at Chris Daughtry, does it affect his voice, obviously not, he's a singing monster and a bodybuilder. The assumption that you will get problems with your vocal technique because of too many muscles in your body sounds a bit strange.
The singing "muscles" in your throat, responsible for larynx control, shortening and lengthening are muscles themselves right:-)
Gaining more control over your muscles in general will help imo to get a better feel for muscles in general right, so you will get more control over your voice intuitevely. On the other hand it's logical to also work on cardiovascular strength and endurance as we need a lot of breathing muscles (here again) to maintain a solid air support from the diaphragm and learn how to expand the rib cage correctly (please don't just stick your belly out it's bad old school technique)
Of course it doesn't make sense to go in absolute Schwarzenegger territory unless you want to become super huge and look like the Rock, but even so, underway you will learn by yourself how to adapt with your voice, I guarantee you with a super strong core you will work way easier with your support than before.


Alterar dinamicamente a cor de texto com base em uma cor de fundo

Question: Galera, tenho esse código em que ele me gera uma especie de tema https://jsfiddle.net/jpcaja7t/18/ e gostaria de aplicar esse outro código nele para que o texto entre em contraste com o bg, Como posso fazer isso pois meu bg e a cor do texto são aleatorios?
Porém gostaria de que o código me desse varias core de contraste e não somente uma.
Código para deixar o texto em contraste
var rgb = $('#content').css('backgroundColor');
var colors = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
var brightness = 1;

var r = colors[1];
var g = colors[2];
var b = colors[3];

var ir = Math.floor((255-r)*brightness);
var ig = Math.floor((255-g)*brightness);
var ib = Math.floor((255-b)*brightness);

$('#content').css('color', 'rgb('+ir+','+ig+','+ib+')');

Answer: Você pode determinar a distância das cores a aplicar um brilho diferente de acordo com a tolerância:

function isNeighborColor(color1, color2, tolerance) {
   // Função tirada da resposta:
   // https://stackoverflow.com/a/11506531/3497987
   // Se foi útil para você vá lá e de um voto a favor.
    if(tolerance == undefined) {
        tolerance = 32;
    }

    return Math.abs(color1.r - color2.r) <= tolerance
        && Math.abs(color1.g - color2.g) <= tolerance
        && Math.abs(color1.b - color2.b) <= tolerance;
}

var color = $('#test').css('backgroundColor');
var colors = color.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);

var rgb = {
    r: colors[1],
    g: colors[2],
    b: colors[3]
}

function GenerateRGB(rgb, brightness){
    var brightness = brightness == undefined ? 1 : brightness;
    var ir = Math.floor((255-rgb.r)*brightness);
    var ig = Math.floor((255-rgb.g)*brightness);
    var ib = Math.floor((255-rgb.b)*brightness);

    return {r: ir, g: ig, b: ib};
}

var nrgb = GenerateRGB(rgb, 1);
console.log(rgb, nrgb, isNeighborColor(rgb, nrgb, 165));

$('#test').css('color', 'rgb('+nrgb.r+','+nrgb.g+','+nrgb.b+')');

if (isNeighborColor(rgb, nrgb, 165))
    nrgb = GenerateRGB(rgb, 1.2);

$('#test2').css('color', 'rgb('+nrgb.r+','+nrgb.g+','+nrgb.b+')');
#test, #test2 {
 background-color: #422DAD;
}

Some text

Some other text

Obsoleto
Conforme essa resposta em inglês fiz o seguinte exemplo:

function CheckColor(c){
  // Código dessa função foi tirado da resposta
  // https://stackoverflow.com/a/12043228/3497987
    var c = c.replace('#', '');  // strip #
    var rgb = parseInt(c, 16);   // convert rrggbb to decimal
    var r = (rgb >> 16) & 0xff;  // extract red
    var g = (rgb >>  8) & 0xff;  // extract green
    var b = (rgb >>  0) & 0xff;  // extract blue

    var luma = 0.2126 * r + 0.7152 * g + 0.0722 * b; // per ITU-R BT.709

  // Fiz alguns testes e identifique que o fator 160 é uma boa referência
  // Altere como desejar
  return (luma < 160);
}

// Função aleatorio e CorAleatoria
// foram usados códigos desse link
// http://www.criarweb.com/artigos/gerar-cor-aleatoria-javascript.html

function aleatorio(inferior,superior){
   numPossibilidades = superior - inferior;
   aleat = Math.random() * numPossibilidades;
   aleat = Math.floor(aleat);
   return parseInt(inferior) + aleat;
}

function CorAleatoria(){
   hexadecimal = new Array("0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F");
   cor_aleatoria = "#";
   for (i=0;i<6;i++){
      posarray = aleatorio(0,hexadecimal.length);
      cor_aleatoria += hexadecimal[posarray];
   }
   return cor_aleatoria ;
}

// Conversão para Hexadecimal
// https://stackoverflow.com/a/1740716/3497987
var hexDigits = new Array
        ("0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f");

//Function to convert hex format to a rgb color
function rgb2hex(rgb) {
 rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
 return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
}

function hex(x) {
  return isNaN(x) ? "00" : hexDigits[(x - x % 16) / 16] + hexDigits[x % 16];
 }

// Aplica cor aleatória
var cor = CorAleatoria();
document.body.style.backgroundColor = cor;

// Verifica a cor de fundo e aplica cor da fonte
var corAleatoria = rgb2hex( document.body.style.backgroundColor );

document.body.style.color = CheckColor(corAleatoria) ? '#fff' : '#000' ;

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Debitis cupiditate adipisci reprehenderit ea iure laborum voluptate deserunt rerum ad placeat recusandae delectus nulla veritatis iste maxime ipsa odio sit vel.

Execute o código várias vezes para testar diversas cores.
Comment: Então mas o que eu quero é que a cor da fonte mude de acordo com o contraste do fundo, o bg do que passei ele funciona normal, só não quero que em um bg vermelho caia uma font rosa por exemplo.
Comment: eu tirei por base nesse código onde o texto entra em contraste com o bg http://jsfiddle.net/2VTnZ/2/
Comment: não entendi o atualize a resposta, e como que eu consigo implementar o código que me passou no meu tema aleatório? pq esse é o grande problema, em todos os modelos eles funcionam porém no que eu fiz que gera aleatório o tema não funciona
Comment: No trecho da cor onde é gerada a segunda cor você compara a tolerância `if (isNeighborColor(rgb, nrgb, 165))` e a tolerância for menor que `165` você gera novamente `nrgb = GenerateRGB(rgb, 1.2);` esse é a regra que precisa implementar no seu gerador de cor @VictorSaul
Comment: e com esse código como que eu faço para ele ler as cores que eu botei e não só preto e branco?
Answer: Usando uma biblioteca muito boa para tratamento de cor chamado chroma.js você pode facilmente manipular a cor do background do dom e aplicá-lo na estilo da color do texto.
Segue uma função que retorna no padrão rgba o valor da cor do background
function GetBG(e) {
    var v = null;
    if (document.defaultView && document.defaultView.getComputedStyle) {
        var cs = document.defaultView.getComputedStyle(e, null);
        if (cs && cs.getPropertyValue) v = cs.getPropertyValue('background-color');
    }
    if (!v && e.currentStyle) v = e.currentStyle['backgroundColor'];
    return v;
};

Com o dado da cor do background você pode manipulá-la facilmente:
function calculaBG(dom) {
    var $o = chroma(GetBG(dom));
    if ($o.luminance() < 0.5) return $o.brighten(2);
    else return $o.darken(2);
}

Função que calcula a cor, luminance varia entre 0 para preto e 1 para branco, no caso acima se a luminância for menor que 50% aplica um clarear (brighten) em relação a cor do background, se for maior que 50% ele aplica escurecer (darken) a cor do background.
Segue exemplo no JSfiddle
Comment: Sim vc tem que adicionar o script que pode ser baixado no endereço [aqui](https://gka.github.io/chroma.js/vendor/chroma-js/chroma.min.js), sobre a segunda pergunta, faça uma nova pergunta detalhando o que vc quer, pois, responder por aqui é muito complicado.
Comment: vlw cara é quase isso, só gostaria de que o contraste fosse se o fundo for escuro a font fique clara e vice-versa
Comment: Mas qual cor? se for a cor do background o `if ($o.luminance() < 0.5) return $o.brighten(2) else return $o.darken(2)` já faz isso, vc pode aumentar de 2 pra 3 (`$o.brighten(3)` e `$o.darken(2)`) pra ficar mais claro e mais escuro.
Comment: Desculpe minha ignorância mas copiei seu código para o meu local e não esta funcionando, como eu deveria colocar, em uma tag
Comment: Ah e mais uma coisa @Leandro Amorim sabe se teria como fazer esse resultado do contraste porém com cores aleatórias como era o meu arquivo?
Comment: percebi olhando que no código do chroma.js ele tem uma variedade de cores hexa, porém ele só retorna uma cor para cada fundo, teria como ele retornar mais de uma cor usando a base dele?
Comment: @VictorSaul partindo das ideias que recebeste nas respostas tens de "brincar" com o código, testar e adaptar para fazer o que precisas. Lembra-te que se tiveres dúvidas novas o melhor é colocar noutra pergunta. Quanto mais isolares o problema em cada pergunta mais fácil será encontrares resposta ao problema colocado.


Fragment dentro de ViewPager não chama nenhum método

Question: Tenho uma atividade (MainActivity) que contém um PagerFragment que possui um ViewPager. No pager eu tenho 4 tabs diferentes.
Dentro de cada tab eu possuo um Fragment 1 que pode se substituir usando o FragmentManager.replace() e o adiciono à backStack (addToBackStack())
Tudo funciona normalmente, mas eu notei um problema que eu não consegui achar em nenhum lugar:
Quando esse Fragment 1 , dentro do ViewPager, chama o replace(new Fragment2() ).addToBackStack(null), o meu fragment é substituído corretamente.
Porém, quando eu aperto o back button, Fragment2 é destruído corretamente, mas o Fragment1 que estava na backstack, não chama o seu onCreateView, ou onResume.
Outra coisa que eu notei, é que quando eu chamo o replace, o onDestroy do Fragment1 não é chamado.
O que está errado?
EDIT
Conversando com o @Wakim, chegamos a conclusão de que estou substituindo os Fragments de forma errada:
No onCreateView do Fragment1:
mView = inflater.inflate(R.layout.fragment_lists, container, false);
E no onClickListener de um botão responsável pelo replace:
FragmentManager fragmentManager = mContext.getSupportFragmentManager();
                fragmentManager.beginTransaction()
                        .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
                        .replace(R.id.view_lists_fragment, new CreateListFragment())
                        .addToBackStack(null)
                        .commit();

O R.id.view_lists_fragment é o container do layout do meu Fragment1
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/white"
android:id="@+id/view_lists_fragment"
tools:context="com.kayan.letsapp.Fragments.ListsFragment">
....
</RelativeLayout>

Comment: O que você chama de "fragmento pai"? O `Fragment` que hospeda o `ViewPager` ou o `Fragment` anterior dentro do `ViewPager`?
Comment: Kayan, está usando o `FragmentPagerAdapter` para fazer essa gerência ou está adicionando os `Fragments` por conta própria?
Comment: Hmmm, acho que o problema esta nesse `replace`. O ideal é que não interfira na gerência que o `FragmentStatePagerAdapter` faz, pode ser que ele esteja se perdendo... O que você quer é trocar um determinado `Fragment` dentro de uma posição por outro e depois poder voltar?
Comment: Consegue ver se o `onDestroyView` e o `onCreateView` estão sendo chamados? Por mim esses dois deveriam estar sendo chamados por causa do `replace` e do `backStack`.
Comment: Acho que isso está certo, mas só que você precisaria adicionar um `Fragment` dentro do `onCreateView` do `Fragment1` para poder ser removido. Acredito que você esteja fazendo isso certo (vou chama-lo de **RootFragment**)? Se for isso, no `onCreateView` do `Fragment1` você adicionaria o `RootFragment` no `view_lists_fragment` e depois faria o replace dele pelo `CreateListFragment`. Nesse caso quando você voltar, é o `onCreateView` e `onResume` do `RootFragment` que será chamado. O `Fragment1` sempre ficou visível/ativo então o ciclo de vida dele não é alterado.
Comment: Isso, exatamente. Dẽ uma olhada na resposta para ver se deixei isso claro hehe
Comment: Pergunta editada, @Wakim
Comment: Estou usando o `FragmentStatePagerAdapter` pra retornar os 4 Fragmentos diferentes nas tabs.
E aí cada Fragmento faz suas transactions, via `replace`...
Estou dando uma olhada nesse projeto agora:
https://github.com/danilao/fragments-viewpager-example/blob/master/src/com/pineappslab/frcontainer/RootFragment.java
E parece que ele cria um RootFragment, acho que não estou substituindo os fragmentos corretamente dentro do view pager
Comment: Isso, só que ao voltar, o Fragment que estava antes deveria chamar o onResume, ou o onCreate, pra eu poder atualizar certas coisas. Preciso que pelo menos alguma coisa seja chamada pelo `Fragment1`!
Comment: `onDestroyView` não está sendo chamado, com certeza estou fazendo esse replace errado! Acho que estou usando o `id` errado!
Comment: @Wakim, Editei minha pergunta, se puder ajudar um amigo de eng. de computação da ufrj, eu seria eternamente grato ;D
Comment: @Wakim, Eu entendi, O correto então é ter um Fragment dummy que contenha Fragments, porque esse Fragment Dummy, por estar no ViewPager, não é destruído, certo?
Answer: Seguindo o código fonte do projeto, o que eu entendi que tem que ser feito é o seguinte:
1 - Criação do Fragment principal
FragmentStatePagerAdapter chama o getItem, logo você deve retornar o Fragment principal daquela posição, esse cara que chamo de RootFragment (Acredito que no seu caso seria o Fragment1, mas vou usar outra nomenclatura, seguindo o projeto que você citou).
O RootFragment adiciona o Fragment1 que está inicialmente visível. O Fragment1 é o filho inicial.
Acho que seria até melhor usar o getChildFragmentManager, mas não sei se é necessário.
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.root_fragment, container, false);

    FragmentTransaction transaction = getFragmentManager().beginTransaction();
    transaction.add(R.id.root_frame, new Fragment1());
    transaction.commit();

    return view;
}

2 - Replace do Fragment1 pelo CreateListFragment.
Delegaria ao RootFragment essa responsabilidade:
public void replaceFragment() {
    FragmentTransaction transaction = getFragmentManager().beginTransaction();

    transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
    transaction.replace(R.id.root_frame, new CreateListFragment());
    transaction.addToBackStack(null);

    transaction.commit();
}

No final você teria algo como:

FragmentStatePagerAdapter -> add RootFragment
RootFragment -> add Fragment1
RootFragment -> replace Fragment1 to CreateListFragment

3 - Remoção do CreateListFragment
Quando você fizer FragmentManager.popBackStack() o CreateListFragment será destruído (onDestroView e onDestroy será chamado).
E o Fragment1 será restaurado (onResume e onCreateView será chamado).
Lembrando que não tenho tanta certeza do funcionamento disso, porque nunca tive que implementar algo assim. Mas acho que deve funcionar
Comment: Em que momento? Depois de adicionar o `CreateListFragment`?
Comment: Não, o `AdminPagerAdapter` precisa ter o `getFragmentManager` e não o `getChildFragmentManager`. O conceito de `nested Fragments` só se aplica ao `RootFragment` e não ao `ViewPager`. Acho então que o melhor é o usar o `FragmentManager` nos dois casos, porque pelo que estou entendendo o `BackStack` não é "compartilhado" e quando você aperta o **Back Button**, ele verifica apenas o `BackStack` do `FragmentManager` de mais alto nível e não dos `FragmentManager's` dos filhos.
Comment: Vou implementar isso aqui e já digo, de qualquer forma já foi de uma ajuda absurda! Obrigado mesmo!
Comment: Estranho... Mesmo sendo sem o `onChildFragmentManager()`, quando aperto o back, ele destrói a atividade que possui o `ViewPager`, mesmo colocando na backStack
Comment: Sim, o mais estranho é isso aqui:
Mudando o FragmentManager na hora de inicializar meu adapter, o código funciona!
`AdminPagerAdapter(getFragmentManager());`
Sabe me explicar o porquê? Está funcionando, mas pra mim o ViewPager deveria ter um ChildFragmentManager, já que são nested fragments, certo? Agora embolou tudo!
Comment: sobre a sua pergunta, ele adiciona corretamente o `CreateListFragment`, mas quando aperto back, ele destrói o `Fragment` que contém o `ViewPager` inteiro.
Comment: Ultima pergunta: Em que situação faria sentido o `ViewPagerAdapter` usar o `ChildFragmentAdapter`?
Comment: Acho que talvez, se você tivesse a seguinte situação: `Activity -> Fragment -> ViewPager (Fragment's)`. Nunca usei de fato esse `FragmentManager`, mas acho que isso seria um caso.
Comment: Pior que eu acho que é exatamente a minha situação, mas está funcionando perfeitamente agora! Muito Obrigado, @Wakin!


Is it true that $(1+o(1))^\frac{1}{2} = (1 + o(1))?$

Question: I think its true that $(1+o(1))^\frac{1}{2} = (1 + o(1))$ but I'm not sure if my argument is correct.
I would appreciate if someone told me if my argument is correct, or if someone provided a different argument of the same result (if its true).
We can assume (I think?) that $|o(1)| < 1$ and so we can apply the binomial theorem. I'm a little hesitant about this step, since typically the binomial theorem is applied to something like $(1+x)^n$ for concrete $x$ but $o(1)$ seems more mysterious and less concrete.
But anyway, applying the binomial theorem:
$(1 + o(1))^\frac{1}{2} = 1 + \frac{1}{2}o(1) + \frac{1}{2}\frac{-1}{2}\frac{o(1)^2}{2!} + \frac{1}{2}\frac{-1}{2}\frac{-3}{2}\frac{o(1)^3}{3!} + \dots$
Observe the series is absolutely convergent since the absolute value of the degree $k$ term is at most $o(1)^k$.
Hence $(1 + o(1))^\frac{1}{2} \leq 1 + o(1) + o(1)^2 + o(1)^3 + \dots = 1 + \frac{o(1)}{1 - o(1)} = 1 + o(1)\frac{1}{1 - o(1)} = 1 + o(1)$ since we can assume $o(1) \leq \frac{1}{2}$ and so we can assume that $\frac{1}{1 - o(1)} \leq 2$.
I think my main difficulty with this is being uncomfortable performing algebraic manipulations or applying binomial formula with expression like $o(1)$. Can I justify those things by treating it like a number that is as small as I like?
Comment: "[I'm] uncomfortable performing algebraic manipulations... with expression[s] like $o(1)$" General tip: then make your notation more explicit. Example for this problem: if $f\in o(1)$ then, for constant $q\ne0$, prove $(1+f)^q-1\in o(1)$ (hint: first prove $\frac{(1+f)^q-1}{f}\sim q$).
Answer: If $a_n \to 0$ then $\sqrt {1+a_n}-1=\frac {a_n} {\sqrt {1+a_n}+1}\to \frac 0 {1+1}=0$, so the answer is YES.
Answer: Since the $o$-notations with equal symbols sometimes are confusing, I think it would be better to state the equation more explicitly.
Specifically, $(1+o(1))^\frac{1}{2} = (1 + o(1))$ means

Given $f(n): \mathbb{N} \rightarrow \mathbb{R}$, if for any $c > 0$, there exists $N_0$ s.t. $n > N_0 \Rightarrow 1 - c \leq f(n) \leq 1 + c$, then $g(n) = f^{1/2}(n)$ satisfies that for any $c > 0$, there exists $N_1$ s.t. $n > N_1 \Rightarrow 1 - c \leq g(n) \leq 1 + c$.

And it is true since $N_1(c) = N_0(c)$ suffices.


inner join inside extension method (linq)

Question: I am trying to write an extention method for a repository. The repository has a method IQueryable<parent> GetAll(). I want to create an extention method FilterByChildId(int childId) so that I can write:
List<parent> data = from d in repository.getAll().FilterByChildId(33).ToList()

Not sure how to do the join on the parent and child inside the extension method.
I thoudht it would be something like:
public static IQueryable<parent> FilterByChildId(
  this IQueryable<parent> query,
  int id)
{
  return from data in query where data.child.id == id select data
}

but not a chance. I tried all sorts of variations using join, groupjoin but not clicking.
Any help would be appreciated.
Comment: how is the relationship between parent and child defined?
Answer: I would essentially write the same as you did.
public static IQueryable<Parent> FilterByChildId(
   this IQueryable<Parent> parents, Int32 id)
{
   return parents.Where(p => p.Child.Id == id);
}

Just checked it with one of my Entity Framework models and it works. I assumed a simple many (parent) to one (child) relationship as your code indicates. Note that this is a bit confusing - many parents for one child. Could it be that you have a many to many relationship? One parent might have many childs and one child might have multiple parents? Then the proeprty Childs (child in your code) would be a collection and the code must be changed as follows.
public static IQueryable<Parent> FilterByChildId(
   this IQueryable<Parent> parents, Int32 id)
{
   return parents.Where(p => p.Childs.Any(c => c.Id == id));
}

The third posibility is one parent with many childs. The second method will work for this case but always return at most one parent assuming the child ids are unique.


Views insert current page node id to image link url

Question: I want to create a block view of some content's image field. I am trying to insert current page node id to paths of image links. Because linked page is a entity form and I try to prepopulate node id in one of the field of the entity form.
How can write to current node id to URL with views rewrite results?
URL pattern like that. example.com/form?edit[field_whatisrefferaelid][und][0][value]=[currentpagenodeid]
Actually I am seraching for current node id token avaible in views block.
Answer: If you have a Contextual Filter in place for Content: Nid that is pulling in the nid from the currently viewed page, can

Add a field for your image
Choose Image for the formatter.  Configure the image style that you want.
Link image to Nothing
In Rewrite Results, check Output this field as a link
In the link path, use form?edit[field_whatisrefferaelid][und][0][value]=!1
Check Use absolute path

The !1 is the replacement pattern for the first contextual filter.  It should be listed in the list of replacement patterns in the popup you do the configuration from.
That shuld
Comment: but these image are link to a form page and URL pattern like that. example.com/form?edit[field_whatisrefferaelid][und][0][value]=[currentpagenodeid]. In every page last part of url [currentpagenodeid] must be different
Comment: @mtin-nong Sorry, misinterpreted what you needed.  Try the new version.
Comment: I think the solition is close but with !1 nor "Output this field as a link" neither "Rewrite the output of this field" options render node id. Also in "Output this field as a link" options square brackets renders as like that %5B
Comment: The %5B is the bracket encoded. !1 worked in the view I tested with.
Comment: !1 works only if images comes from current node and provide default value>content id from url is selected. These images will be use every content in selected content type and must be shown if images are not their node.
Answer: You can simply follow below steps:

Add ID field in your view, hide the display of it and drag it above the image field .
In you image field, link the image to nothing and rewrite the result as below using the {{ nid }} as replacement pattern:

{{ your image }}

If the image is not part of current node, you can simply use {{ url('<current>')| split('/') | last }} in you view rewrite result as:
<a href='/form?edit[field_whatisrefferaelid][und][0][value]='{{ url('<current>')| split('/') | last }}>{{ your image }}


Temporal analysis with linear regression, with some years sampled more than once

Question: I am examining a temporal dataset of contaminant concentrations from individual specimens over a 100 year time span, comparing mercury (THg) concentrations over time (in years). For some of the years, I have single samples, whereas for others I have over 10 samples in a given year. How best could I control for the differences in sampling effort among years?
Answer: This is one of the benefits of using a multilevel or mixed model. By specifying a random intercept for specimen, the model gives greater weight to specimens with more measurements and less weight to those with fewer. In the case of a specimen with a single measurement, the model would likely predict that such a specimen would have a value on the outcome that is essentially equivalent to the mean outcome across all specimens over time.
In lme4, an example of this model with a single predictor (time) would be the following:
m <- lmer(y ~ 1 + x + (1|specimen), data=df)
You can use ranef(m) to see exactly what the model predicts for each of your specimens. For those specimens with very few observations or just 1 observation, the prediction would be 0, which is understood relative to the (Intercept) from the summary of your model. A positive prediction means that for that specimen, the model predicts their outcome value to be higher than the intercept and vice-versa for a negative prediction.
You can further plot these using dotplot(ranef(m,condVar=TRUE)) to see the distribution of predictions.
Edit:
Based on the comments to the post, I'm adding a bit more information. The model I suggested above, m, treats the effect of time (x) on y as linear and as "fixed," meaning the trend is the same across all specimens. This is an assumption and it can easily be relaxed, allowing for unique linear trends for each specimen (i.e., a random slope on x) and tested as follows:
m1 <- lmer(y ~ 1 + x + (x|specimen), data=df)
anova(m, m1) #likelihood ratio test comparing fixed time effect to random time effect

If the $\chi^2$ test is significant, then the random effect model is preferred; the increased complexity of m1 is a better fit to the data. It may be worth exploring different functional forms of x given the long measurement period here. That can be done with, e.g.:
m2 <- lmer(y ~ 1 + poly(x, 2) + (x|specimen), data=df) #fixed only
m3 <- lmer(y ~ 1 + poly(x, 2) + (poly(x, 2)|specimen), data=df) #fixed + random

These models can again be likelihood ratio tested against simpler models. Note that if all you are doing is changing a fixed effect predictor and want to run a likelihood ratio test, you should be using full maximum likelihood (REML=FALSE in your lmer model). The anova command will do this automatically.
Because of the unique nature of your data, it may be worth exploring generalized additive mixed models to allow for the most flexible modeling of the effect of time on the outcome. This has an introduction to GAMs and then some specific information on the mixed version of GAMs.
Comment: nice answer (+1)
Comment: Nice answer!  Does x stand for time in your suggested model? If so, how is x expressed? One possibility would be to have x expressed as a decimal date (e.g., x = 2009.11 if the first sample in 2009 was collected on 2009-02-10).
Comment: @IsabellaGhement not necessarily, although it could. It wasn't clear from the original post whether or how the author wanted to model the effect of time. `x` could be a time-varying predictor that was measured contemporaneously as when the concentrations were measured or could be time-invariant characteristics of the specimen (e.g., climate zone).
Comment: @Erik Ruzek. Thanks for your answer, it was most helpful! Just to clarify x is year, and the analysis was to look at mercury trends over time (in years). But, I do have information from the museum samples collected on month and date, so decimal date is a possibility.
Comment: @emmy, thanks for the clarification. If you use IsabellaGhement's coding scheme for year, you have lots of possibilities for modeling. I added to my original post to illustrate some of these.
Comment: @ErikRuzek: Great edit to your original answer, Eric! Thank you!
Comment: @Erik Ruzek Quick question. Suppose I only had individual specimens for all the data, but I wanted to control for the fact that some years had more specimens than others. Could year, as only predictor, be included as both a fixed and random factor with levels? eg. m <- lmer(Hg ~ 1 + Year + (1|Year), data=df)
Comment: @emmy, you would typically have year as either a fixed or random factor/intercept in such a model unless you wanted to allow year to have a linear or non-linear effect on Hg, which would be the models I discussed in my post. Why is `(1|specimen)` not in your model? You get data from multiple individual specimens, correct?
Comment: @ErikRuzek Yes I do have data from individual specimens (1 sample per specimen), but when I run the model, `m1 <- lmer(Hg ~ 1 + Year + (1|Sample), data=Hg)`, I get :
`Error: number of levels of each grouping factor must be < number of observations`
Comment: @emmy I am confused. You say here that you have 1 sample per specimen, but in your original post you say, "For some of the years, I have single samples, whereas for others I have over 10 samples in a given year." This suggests that some speciments only have 1 sample/year while others have 10+/year. Can you explain?
Answer: Here is a description from The Analysis Factor article on Approaches to Repeated Measures Data: Repeated Measures ANOVA, Marginal, and Mixed Models by Karen Grace-MAartin.  To quote some comments:

In a marginal model (AKA, the population averaged model), the model equation is written just like any linear model.  There is a single response and a single residual.  The difference between the marginal model and a linear model is that the residuals are not assumed to be independent with constant variance.
In a marginal model, we can directly estimate the correlations among each individual's residuals.  (We do assume the residuals across different individuals are independent of each other). We can specify that they are equally correlated, as in the RM ANOVA, but we're not limited to that assumption.  Each correlation can be unique, or measurements closer in time can have higher correlations than those farther away.  There are a number of common patterns that the residuals tend to take.

And, with respect to the option of employing a Linear Mixed Model:

It too controls for non-independence among the repeated observations for each individual, but it does so in a conceptually different way.  Rather than just estimate the correlation among an individual's repeated observations, it actually adds one or more random effects for Individuals to the model.
The model equation therefore includes extra parameters to include any random effects.  They take the form of additional residual terms, each of which has its own variance to be estimated.
This literally means the model is controlling for the effects of individual.  The simplest mixed model, the random intercept model, controls for the fact that some individuals always have higher values than others.  By controlling for this variation, we've taken it out of the original residual.
Individual growth curve models are a specific type of mixed model that uniquely models each individual's value of the outcome over time.  They are particularly useful when the research question is about how covariates affect not only the value of the dependent variable, but its change over time.
The biggest advantage of mixed models is their incredible flexibility.  They can handle clustered individuals as well as repeated measures (even in the same model).  They can handle crossed random effects, where there are repeated measures not only on an individual, but also on each stimulus.
Time can easily be considered continuous or categorical, and covariates can be measured just once per individual or repeatedly at each observation.  Unbalanced data are no problem, and even if some outcomes are missing for some individuals, they won't be dropped from the model.
The biggest disadvantage of mixed models, at least for someone new to them, is their incredible flexibility. It's easy to mis-specify a mixed model, and this is a place where a little knowledge is definitely dangerous.

In the case that your data contains individuals with say measurements of heavy metals in their blood over time, but not necessarily the same individuals (given that is a 100 years of data), I suspect that with the simplest mixed model, namely the random intercept model, one may have a model specification issue. For example, in measuring blood levels of say Lead which actually relates to water and air exposure to all individuals over time in a particular locale, the process for controlling the effects of the individual (who happen to change over time), there could be a misstatement in the individual effect (the intercept). The latter may actually be part of the time trend (from say, mining activity and associated pollution over years with a corresponding impact on the general population). In such a case, working with the marginal model may be better.
Bottom line, more clarity on what is being modeled (like pollution related to a particular locale) and is the selected model appropriate and likely could provide the best fit for a time trend (or forecast, which may be of interest).
On the last comment, to quote from a prior thread: "However, the problem is that so far in my experience population-level predictions based on mixed models are significantly worse than predictions based on standard regression models with fixed effects only." Supplied answers seem to suggest, it depends (hence, my call for clarity).