Initialization of vectors in a struct/class and print out

Question: I am actually trying to initialize vectors in constructors of struct/class.
I came up with these, the below content compiles without error, however does not print out the contents in the vector. I will like to know why, help will be definitely appreciated!
struct MyInt
{
friend ostream &operator<<(ostream &printout, const MyInt &Qn)
{
    printout<< Qn.value << endl;
    return printout;
}

     int value;
     MyInt (int value) : value (value) {}
};

struct MyStuff
{
    std::vector<MyInt> values;

MyStuff () : values ()
    {
        values.reserve (10); // Reserve memory not to allocate it 10 times...
    }
};

int main()
{
MyStuff *mystuff1;
MyStuff *mystuff2;

for (int i = 0; i < 10; ++i)
{
        mystuff1->values.push_back (MyInt (i));
}

for (int x = 0; x < 5; ++x)
{
        mystuff2->values.push_back (MyInt (x));
}

vector<MyInt>::iterator VITER;

for (VITER =mystuff1->values.begin(); VITER!=mystuff1->values.end(); ++VITER)
{
    cout<< *VITER;
}

return 0;
}

Answer: Undefined behaviour. Your pointers are invalid. Since you don't need pointers here at all, just go with values:
MyStuff mystuff1, mystuff2;

// ...
mystuff1.push_back(...); // et cetera

Also, if you don't reserve, it still wouldn't allocate 10 times. vector implementations are smart enough to not increase capacity by 1 each time.
Comment: Interesting that this did not crash. Probably the compiler treated the code as unreachable and removed everything?
Comment: @usr: Behaviour is undefined. Maybe it'll crash when the moon is in right position.
Comment: Of course, but why does the implementation behave this way? Interesting.


Music in religious movies

Question: Whenever I listen to The Tallis Fantasia by Ralph Vaughan Williams I am reminded of music scores from classic religious films or religious scenes from other films. What is it about this music that gives it this distinctive, familiar sound?
I also wonder since Vaughan Williams composed that piece before there were films, how is it that the music "found" that perfect fit in the visual genre of films?
Answer:
What is it about this music that gives it this distinctive, familiar sound?

The tune that forms the basis of the piece was written as a hymn tune.  Vaughan Williams used that tune in the English Hymnal in 1906.  He even orchestrated the piece to resemble an organ:

The work is scored for an expanded string orchestra divided into three parts: orchestra I, a full-sized string orchestra; orchestra II, a single desk from each section (ideally placed apart from Orchestra I); and a string quartet. Vaughan Williams made this configuration resemble an organ in sound, with the quartet representing the swell division, orchestra II the choir division, and orchestra I the great division. The score specifies that the second orchestra should be placed apart from the first. This spacing emphasizes, on several occasions, the way that the second orchestra echoes the first orchestra.

It is clear, therefore, that Vaughan Williams intended for the piece to sound religious.
Hymn tunes, especially those written in the renaissance, tend to share certain characteristics.  The melodies tend to follow a similar profile, beginning on the tonic pitch, then rising and eventually falling back to the same pitch.
Notably, renaissance hymn tunes are modal.  This tune is in the Phrygian mode, which is probably the mode least like the modern major and minor modes on account of its lowered second degree.  This contributes to the distinctiveness of the impression it creates.

I also wonder since Vaughan Williams composed that piece before there were films, ...

It was actually composed in 1910, after motion pictures were invented, but before they had sound.

...how is it that the music "found" that perfect fit in the visual genre of films?

Religious-sounding film music sounds religious because it is based on religious music, whether on specific pieces or merely certain stylistic elements.  The Fantasia on a Theme by Thomas Tallis is also based on religious music, both in terms of the specific melody and certain stylistic elements, and it is clear that Vaughan Williams intended for the piece to evoke its religious heritage.  It is therefore not surprising that later film music reminds one of that piece.
Furthermore, many film composers writing music for religious scenes are probably familiar with the piece and in some cases they may be unconsciously influenced by it, or they may even make a conscious effort to emulate it.
In at least one movie, they used it directly.

Music in religious movies


A few questions about $\mathbb{Q}$-models of modular curves (curves given by congruence groups)

Question: I'm just now beginning to learn about descending the curves $X(N)$ to $\mathbb{Q}$, and I have a few questions:

Does $X(N)$ have a $\mathbb{Q}$-point for every $N$?
What is $\operatorname{Aut}(X(N))$? I know that $\operatorname{PSL}_2(\mathbb{F}_p)\leq \operatorname{Aut}(X(p))$ for $p$ prime, but can we say more? (for example, is this an equality for $p$ prime; what can we say if $p$ isn't prime?)
Does the map $X(N)\rightarrow \mathbb{P}^1_{\mathbb{C}}$ together with the Galois action descend to $\mathbb{Q}$? How about without it?
Do the curves $X_0(N)$ (and curves given by congruence groups in general) also descend to $\mathbb{Q}$? If so, I ask the above questions for those as well.
Answer: For $X(N)$, one can give a $\mathbb{Q}$-model, but there's a sense in which doing so is "cheating".
The moduli interpretation of $X(N)$ only makes sense over $\mathbb{Q}(\zeta_N)$; if $R$ is an algebra over this field, then $X(N)$ classifies triples $(E, P_1, P_2)$ where $E$ is an elliptic curve over $R$ and $P_1, P_2$ are $R$-points of $E$ order $N$ which pair to $\zeta_N$ under the Weil pairing.
You can choose a model for $X(N)$ over $\mathbb{Q}$ in various ways, but you lose the moduli interpretation above. The usual way of doing this is such that the rational functions defined over $\mathbb{Q}$ are those whose $q$-expansions at the cusp $\infty$ have coefficients in $\mathbb{Q}$. This is done in, for instance, Stevens' book "Arithmetic on modular curves". With this choice, it is essentially tautological that the cusp $\infty$ is a $\mathbb{Q}$-point, and that the $j$-invariant map $X(N) \to X(1) \cong \mathbf{P}^1$ is defined over $\mathbb{Q}$. But this $\mathbb{Q}$-structure is rather artificial, and doesn't interact well with the moduli interpretation; e.g. sometimes one encounters modular curves $X$ which are quotients of $X(N)$, and which have a natural $\mathbb{Q}$-structure which is compatible with the moduli space interpretation of $X$, but where the map $X(N) \to X$ isn't defined over $\mathbb{Q}$ when we give $X(N)$ the $\mathbb{Q}$-structure described above. (See e.g. Elkies' paper on mod 3 and mod 9 representations of elliptic curves.)
I hope this at least partially answers your questions (1) and (3). I don't know the answer to (2); but for $N < 6$ we have $X(N) \cong \mathbf{P}^1$, so the automorphism group of $X(N)$ is infinite in these cases (in particular it is much larger than $PSL_2(\mathbf{Z} / N)$).
For $X_0(N)$ and $X_1(N)$ life is much easier than $X(N)$: the moduli space interpretations of these curves make sense over $\mathbb{Q}$, and they have rational models compatible with this moduli space structure, and the cusp $\infty$ is always a $\mathbb{Q}$-point.
(EDIT: Actually the last sentence is wrong, sorry! This works for $X_0(N)$ but not for $X_1(N)$. The canonical $\mathbb{Q}$-structure on $X_1(N)$ is the one that makes $\mathbb{Q}$-expansions at the cusp 0, not the cusp $\infty$, rational.)
Comment: Are you saying $X(N)\rightarrow \mathbb{P}^1$ is *always* defined together with the group action over $\mathbb{Q}$? This surprises me. I thought $PSL_2(\mathbb{F}_p)$ is not known (for a general prime $p$) to be realized as a Galois group over $\mathbb{Q}$. I think Shih proved it was just for some of the primes....
Are you sure you didn't mean defined without the group action over $\mathbb{Q}$? That would make more sense.
(P.S. Thanks a lot for the answer)
Comment: I'm not sure I quite understand your question -- what do you mean by "defined without the group action"?
Comment: The cover is defined, but it is not nec. Galois.


How can I interpret infinitesimal/differential notation in involved integrals? E.g. in the Chapman-Kolmogorov condition

Question: In our class on stochastic processes I keep getting confronted with a problem w.r.t. notation. I am a mathematics major and attended all the prerequisite classes on standard analysis.
In those analysis classes we introduced the Lebesgue-Integral as a limit of sums over "simple functions" for example like this (taken from wikipedia)
$$ \int_{\Omega} f \, d\mu := \lim_{n \rightarrow \infty} \int_{\Omega} f_n \, d\mu$$
where the $f_n$ are a sequence of simple functions that converges pointwise and grows monotonously. The integral notation is introduced first for simple functions of the form $\phi := \sum_{i=1}^{n} \alpha_i \mathbb{1}_{A_i}  $ like so
$$ \int_{\Omega} \phi \, d\mu := \sum_{i = 1}^{n} \alpha_i \mu(A_i) $$
I liked this introduction and found it very reasonable and intuitive. What troubles me now is that the $d\mu$ and later similarly the $dx$ have no properly defined meaning outside of the context of this definition. I realize there is another definition when differentiation is introduced, but there too we defined $\frac{df}{dx}$ via a limit and as if it was merely like a name without an intrinsic meaning.
Yet, in our class we use $dy$ e.g. in the following description of the Chapman-Kolmogorov $(*)$ condition for transition functions like this:
$$\forall s \leq t \leq u:  \mu_{s,t}(x,B) = \int_{E} \mu_{s,u}(x,dy) \mu_{u,t}(y,B) $$

For context: For a stochastic process $(X_t)_{t \in T}$ on a state space $E$ the transition function $\mu_{s,t}(x,B)$ gives the probability that $X$ transitions into $B \subset E$ starting from point $x \in E$ within the timeframe $[s,t]$.

Suddenly something that used to be nothing but the indicator for the variable/measure we are integrating over is itself subjected to a function. From context I would say it represents a set (a small ball around $y$ maybe) but I don't know how to deal with it in a rigorous way. I.e. even if I was given specific values for $s,t,u,x $ and $B$, I wouldn't know how to calculate or even properly represent such an integral.
I read some articles on differentials/infinitesimals e.g. from the San José State University or on Wikipedia>Differential but I still feel clueless as to

How to interpret this notation; e.g. what exactly am I summing up, integrating over in $(*)$?
How to calculate with these infinitesimals/differentials in a practical way?
Comment: First, look at Markov kernels: https://en.wikipedia.org/wiki/Markov_kernel
Answer: In your C-K example, it's a matter of sorting out the notation. You are integrating a (measurable) function $f(y):=  \mu_{u,t}(y,B)$ (in which $u,t,B$ are fixed, for the moment) with respect to a measure $\nu$ defined by $\nu(A):=\mu_{s,u}(x,A)$ (in which $s,u,x$ are fixed). This is a Lebesgue integral of the type you learned in analysis and described above.  What may be novel is that the function $f$ and the measure $\nu$ depend on parameters, and in the end so does the integral $\int_E f d\nu$. It can be shown that if $(s,u,x)\mapsto\mu_{s,u}(x,A)$ and $(u,t,y)\mapsto\mu_{u,y}(y,B)$ are suitably measurable, then the end result $(s,t,x)\mapsto\mu_{s,t}(x,A)$ is  measurable in the same sense.


Yamaha tenor recorder

Question: Playing very low notes tend to be an octave too high and I'm blowing very gently. Very new at this and am not sure what the problem is. Can anyone help?
Comment: So what you mean is: _very low notes come out as overblown, despite very gentle blowing_?
Answer: If your low notes are coming out an octave too high, and you are blowing very gently, then the most likely problem is that one or more of the fingerholes is not completely closed.  You must make sure your fingers are not allowing any air to leak at all, which is difficult to do and requires practice.
Answer: I had the exact same experience with my Aulos tenor recorder. You really don't have to blow much harder to get an overblown octave. I also found that the angle of the stream of air is important so make sure the position of the beak in your mouth is right. Also make sure that all your finger holes are properly closed, especially your right ring finger that closes the double hole. If you are having trouble closing it, try adjusting the position of your foot joint so that you can comfortably reach the key and the double hole without any discomfort. Lastly, give yourself time to experiment and you'll figure it out. Practise for very short amounts of time at first because your fingers get tired and it's almost impossible to play then.
It took me about a week to be able to reliably play a bottom C. Hope this helps!
Answer: If you are getting the pitch in the wrong register, the classic mistake is a leak at the thumb hole.  Deliberately leaking the thumb hole is how one gets the upper register, and beginners often have trouble covering it accurately, not least because its on the underside of the instrument where you can't see it, and the thumb is less touch-sensitive than the other finger tips.

Yamaha tenor recorder


Marcar campos duplicados numa tabela

Question: Tenho uma tabela no meu banco de dados e gostaria de marcar as ocorrências onde determinado código se repete. Lembrando que esse campo código não se trata de uma chave primária.
Exemplo:
Data        Código    Repetição   Status    ...
25/2/2014   138863    ok          C96       ...
25/2/2014   387707    ok          C96       ...
25/2/2014   387707    nok         C96       ...
25/2/2014   387707    nok         C96       ...
25/2/2014   387707    nok         C96       ...
25/2/2014   1845141   ok          C96       ...
25/2/2014   1845141   nok         C96       ...
25/2/2014   1845141   nok         C96       ...
25/2/2014   1845141   nok         C96       ...
25/2/2014   1845141   nok         C96       ...
25/2/2014   1845141   nok         C96       ...

Alguem tem idéia de como posso criar a coluna repetição com a lógica acima (primeira ocorrência, marcar como ok, nas demais nok) utilizando alguma query?
No momento estou utilizando essa tabela num Banco de Dados em Access.
Comment: Utilize a cláusula GROUP BY e conte a quantidade de repetições. A cláusula HAVING cont(*) > 1 pode ajuda-lo a filtrar apenas as repetições.
Comment: Você pode colocar na pergunta as tabelas de origem?
Answer: É possível com uma subquery que retorna um elemento por código.
Vamos a um exemplo com a estrutura abaixo:
create table teste (
    id int primary key auto_increment,
    codigo int,
    repeticao  varchar(10)
);

A seguinte query retorna um ok apenas uma vez por código:
select
  codigo,
  case
    when id = (
      select min(t2.id)
      from teste t2
      where t2.codigo = teste.codigo
    )
    then 'ok'
    else 'nok'
  end repeticao
from teste

Veja o sqlfiddle

Em forma de update, você pode fazer assim:
UPDATE teste
SET repeticao =
    case
        when id = (
            select min(t2.id)
            from (select * from teste) t2
            where t2.codigo = teste.codigo
        )
        then 'ok'
        else 'nok'
    end;

Note que o MySQL não permite selecionar a própria tabela em um subselect no comando UPDATE, mas o trecho (select * from teste) é um workaround para burlar essa limitação.
Veja o sqlfiddle
Comment: Ótima resposta @utliz. Precisei fazer uma alteração para funcionar no Access pois o mesmo não suporta case.
```SELECT Dados_Exportar.codigo, IIf(id=(select min(d2.id) from Dados_Exportar d2 where d2.codigo = Dados_Exportar.codigo),'ok','nok') AS rep FROM Dados_Exportar;```

Marcar campos duplicados numa tabela


Experiences with BIRD for BGP?

Question: We're currently using Quagga with Debian Linux to run a full table BGP router. The set-up has been dead simple up to now, but we've come to a point where I have to reconfigure the router quite a bit, and want to tighten things up.
I've never really understood Quagga, and always found its documentation to be lacking. It appears to be mimicking Cisco, of which I only have basic understanding.
BIRD has caught my eye recently. The couple of articles / presentations I found promote it as lightweight and more responsive under stress compared to Quagga. And it actually seems to have very decent documentation.
So I'd like to know:

Who's running BIRD right now, and in what kind of set-up?
How is it stability-wise? I've read about it running in a couple of sites in production.
Let's say I don't care at all for a Cisco-feel to configuration. How is configuration, maintainance, monitoring, etc. of BIRD in general?
And any other notable experiences you may have with it.
Answer:
It seems like a few internet exchanges are running bird as route servers in their production network see here for a few examples
I am part of dn42(networking playground of sorts) and so far I had no problems with bird at all(unlike quagga, which burned me a few times, so it's safe to say it should work on an public production environment too.)
If you like editing your configuration with an proper editor or want to generate the configuration from some datasource or so(which I do), then bird is for you. If you prefer to edit your configuration via an command line interface, then not so much.
BIRD requires you to run a seperate daemon for IPv4 and IPv6(unlike quagga), but that's no big loss IMHO, as running IPv4 and IPv6 over the same peering is a PITA in quagga anyway.
Answer: Most of the feedback that I've encountered about BIRD has been in an IX capacity. Meaning that the tests and experiences have been quite specific. Yet, if it has proved stable in such use cases, then you can rest assured that it should be production ready for you as an "end user" so to speak.
Here are two presentations from a recent UKNOF that you should find relevant:

Andy Davidson - Route Server Bake-off
Tim Preston - BIRD at LINX

You might want to also consider OpenBGP as an option, of which I can personally attest to the production quality of. It's setup is also primarily config file based, which I always consider a bonus because it makes for easy driving with Configuration Management and versioning. Likewise it doesn't contain any faux-Cisco nasties. However it does require an OpenBSD install, which you might consider outside you comfort range for OSs.
Either way, take a breath of fresh air and ditch Quagga :)
Comment: The second presentation refers to another presentation which was held at NANOG in February. That is also available online at: http://nanog.org/meetings/nanog48/abstracts.php?pt=MTUxMyZuYW5vZzQ4
Answer: I use bird on a couple of Anycast nodes and the stability and ease of configuration has been excellent.
On our regular routers we use Vyatta and I wish they'd replace the bgp daemon there with bird.  :-)

Experiences with BIRD for BGP?


How to append the contents of NSSet to [NSManagedObject]?

Question: My Code
isFiltering = true
  let appDelegate = UIApplication.shared.delegate as! AppDelegate
  let context = appDelegate.persistentContainer.viewContext
  let words = textInSearchField.components(separatedBy: " ")

  for word in words{

    if (word).count == 0{
      continue
    }

    let firstNamePredicate = NSPredicate(format: "firstName contains[c] %@", word)
    let lastNamePredicate = NSPredicate(format: "lastName contains[c] %@", word)
    let idPredicate = NSPredicate(format: "id contains[c] %@", word)
    let orPredicate = NSCompoundPredicate(type: NSCompoundPredicate.LogicalType.or, subpredicates: [firstNamePredicate, lastNamePredicate, idPredicate])

    clientsEntity.predicate = orPredicate
    clientResults = try! context.fetch(clientsEntity) as! [NSManagedObject]

    let sort:NSSortDescriptor = NSSortDescriptor(key:"dateSorted", ascending: false)

    for (index, ob) in clientResults.enumerated(){

      let relationship = ob.value(forKey: "assessed_by") as! NSSet
      let array = relationship.sortedArray(using: [sort]) as! [NSManagedObject]

      for item in array.enumerated() {
        results.append(item.element)
        print(results)
      }
    }

My data model:

I am using a tableView to display my data which works great, now I have implemented a filter function which allows the user to search based on a Clients first name, last name, id etc using NSCompoundPredicate.
I then sort the resulting [NSManagedObject] by date using NSSortDescriptor, my aim is to set my clientResults variable to contain the SORTED contents of the NSSet. My print statement only outputs that there is one Assessment inside the results variable when in actual fact the NSSet contains two of these NSManagedObjects.
let sort:NSSortDescriptor = NSSortDescriptor(key:"dateSorted", ascending: false)

    for (index, ob) in clientResults.enumerated(){

      let relationship = ob.value(forKey: "assessed_by") as! NSSet
      let array = relationship.sortedArray(using: [sort]) as! [NSManagedObject]

      // MARK - I enumerate the contents of the sorted array.

      for item in array.enumerated() {
        results.append(item.element)
        print(results)
      }
    }

What is the best practice for assigning the contents of the NSSet to a variable of type [NSManagedObject]?
Thank you.
Answer: If you know that elements in NSSet are of type NSManagedObject why not just do
let managedObjectsArray = set.allObjects

or if you want to make sure it is of correct type you can do:
if let managedObjectsArray = set.allObjects as? [NSManagedObject] {
    //do what you want with [NSManagedObject] array
}


Attached/ calculus about local minimum and maximum

Question:
I got couple questions with the same issue, could anyone tell me how to know if it was local minimum, local maximum or neither ? :)
Answer: Theorem. A critical point $x=c$ is a local minimum point of $f$ if there is are intervals $(a,c)$ and $(c,b)$ such that $f'$ is negative on $(a,c)$ and positive on $(c,b)$.
This is sometimes called the First Derivative Test. An analagous result holds for local max's.
The derivative is $6t^{-1/3}+1$. Consider the critical point $t=0$ (it is a critical point because the original function is not differentiable here). The derivative is negative just to the left of $t=0$ and positive to the right, i.e., $t=0$ is a local minimum point.  Try the other critical point $t=-216$ (the root of the derivative) using this method...
Answer: Hint: Evaluate the second derivative of the function at the critical points. If it is negative, it is a local max. Positive, local min. $0$ is indeterminant.
Comment: In the case second derivative is $0$ we could have local max, local min, or neither.
Comment: Why do I need to take the second derivative ? and can't I determine by just checking their signs now ?
Comment: The first derivative tells you the points where the slope of the function is $0$, but it doesn't tell you at that point, if the function is concave up or concave down. The second derivative gives you that information.
Comment: you can just look for the sign of the first derivative on an interval to the right of $x=0$ and on an interval to its left.  For instance the sign combination -,+ would indicate local min.
Comment: @TomCruise So I end up having zero as minimum and -216 as maximum, right ? and how to know if it is neither?
Comment: @TomCruise I think no, because when you try to take numbers on the left of ( -216 )) I will end up having a positive and the left negative. Nevertheless, for the ( zero ) on the left as I said is negative and on the right positive. Am I right?
Comment: @user157908 - Make sure you have the correct critical points. You need to solve for $t$, where $g'(t) = 0$
Comment: @user157908 yes you are right!


How to analyze the asymptotic behaviour of this integral function?

Question: Based on the asymptotic analysis of correlation functions at large distence in Physics, now I get a math question. Let the function $$f(x)=\int_{-1}^{1}\sqrt{1-k^2}e^{ikx}dk.$$
Without working out the explicit form of this function, how do we know the asymptotic behaviour of $f(x)$ at large distence $\left |x  \right |\rightarrow+\infty$?
Comment: Probably you can use this: http://math.stackexchange.com/questions/318804/relation-between-function-discontinuities-and-fourier-transform-at-infinity
Comment: The Maple code $$asympt(int(sqrt(-k^2+1)*exp(I*k*x), k = -1 .. 1), x, 2)  $$ outputs $$ -\sqrt {\pi }\sqrt {2}\cos \left( x+1/4\,\pi  \right)  \left( {x}^{-1}
 \right) ^{3/2}+O \left(  \left( {x}^{-1} \right) ^{5/2} \right)
 .$$ The closed form of the integral is expressed in terms of the Bessel function.
Comment: @ leonbloy Thanks for your good suggestion.
Comment: @ user64494 I can't understand what are you talking about...
Answer: I going to manipulate the integral into a form that I can analyze the method of stationary phase.  Let $k=\cos{\theta}$ and the integral becomes
$$\begin{align}I(x) &= \int_0^{\pi} d\theta \, \sin^2{\theta} \, e^{i x \cos{\theta}}\\ &= \int_0^{\pi} d\theta  \, e^{i x \cos{\theta}} - \int_0^{\pi} d\theta \, \cos^2{\theta} \, e^{i x \cos{\theta}}\\ &= \int_0^{\pi} d\theta  \, e^{i x \cos{\theta}} + \frac{d^2}{dx^2} \int_0^{\pi} d\theta  \, e^{i x \cos{\theta}}\end{align}$$
Now, note that
$$\int_0^{\pi} d\theta  \, e^{i x \cos{\theta}} = \int_0^{\pi/2} d\theta  \, e^{i x \cos{\theta}} + \int_{\pi/2}^{\pi} d\theta  \, e^{i x \cos{\theta}} = 2 \Re{\left [ \int_0^{\pi/2} d\theta  \, e^{i x \cos{\theta}}\right]}$$
Now, we may apply stationary phase.  The stationary point of the integrand is at $\theta=0$; there, we may approximate the argument of the exponential by its Taylor expansion.  Further, because of the oscillatory cancllations, we may simply draw the upper limit of the integral to infinity to first order:
$$\int_0^{\pi/2} d\theta  \, e^{i x \cos{\theta}}  \sim e^{i x} \int_0^{\infty} d\theta \, e^{-(i x/2) \theta^2} = \frac12 e^{i(x-\pi/4)} \sqrt{\frac{2 \pi}{x}} \quad (x\to\infty)$$
Therefore
$$\int_0^{\pi} d\theta  \, e^{i x \cos{\theta}} \sim   \sqrt{\frac{2 \pi}{x}} \cos{\left ( x-\frac{\pi}{4}\right)}\quad (x\to\infty)$$
To get the asymptotic behavior of $I(x)$, it looks like we need to take the second derivative of the above result.  It turns out that
$$\frac{d^2}{dx^2} \left[x^{-1/2} \cos{\left ( x-\frac{\pi}{4}\right)}\right ]= \left (\frac{3}{4} x^{-5/2} - x^{-1/2}\right ) \cos{\left ( x-\frac{\pi}{4}\right)}  + x^{-3/2}\sin{\left ( x-\frac{\pi}{4}\right)}   $$
Note that the $x^{-1/2}$ piece drops out when combined with the original integral, and the $x^{-5/2}$ piece is subdominant.  Thus, the leading asymptotic behavior of the integral $I(x)$ is finally
$$\int_{-1}^1 dk \, \sqrt{1-k^2} \, e^{i k x}  \sim  \sqrt{2 \pi} x^{-3/2} \sin{\left ( x-\frac{\pi}{4}\right)}\quad (x\to\infty)$$
Here is a plot illustrating this behavior against the exact value of the integral (the lower plot is the asymptotic result derived here):

ADDENDUM
One objection to the above derivation might be that I neglected the next term in the asymptotic expansion of the first integral of $I(x)$, which we know goes as $A x^{-3/2} \sin{(x-\pi/4)}$.  How could I ignore that?  It turns out $I$ is the sum of this term and its second derivative, and the only term that remains $O(x^{-3/2})$ vanishes because it is a simple sine term, the sum of itself and its second derivative vanishing.  So the derivation of the asymptotic approximation above remains valid.
Comment: @K-boy: my guess is that it has something to do with the branch point singularity at the integration endpoints.  The question I posed was not mean to be anything rigorous but was just more of an observation.  Clearly there is something else going on here involving branch points about which I wasn't ready to speculate.
Comment: @K-boy: the derivative of $g$ also blows up at the points of discontinuity.  Again, I am not claiming to have nailed a provable theorem, so if there is an apparent contradiction from my conjecture (which I could hardly claim to be mine anyway), it means that there are holes in that formulation.
Comment: @K-boy: think about a Gaussian; the FT of a Guassian is a Gaussian.  This would indicate (not prove!) that functions having all continuous derivatives die faster than any polynomial (e.g., exponential).
Comment: @ Ron Gordon Thanks for your excellent demonstration and detailed answer.
Comment: @ Ron Gordon I just read your question http://math.stackexchange.com/questions/318804/relation-between-function-discontinuities-and-fourier-transform-at-infinity, and I'm confused that according to the conclusion in it, the decaying power here should be $x^{-2}$ which contradicts $x^{-3/2}$?? Thanks a lot.
Comment: @ Ron Gordon Since we can define a function $g(k)=\sqrt{1-k^2}$ for $k\in[-1,1]$ and $g(k)=0$ otherwise. Then $f(x)$ is the Fourier transform of $g(k)$, and the first derivative of $g(k)$ has discontinuities at $k=-1,1$, which means that $m=1$ in http://math.stackexchange.com/questions/318804/relation-between-function-discontinuities-and-fourier-transform-at-infinity.
Comment: @ Ron Gordon Thanks. Anyway, is the asymptotic behaviour of $f(x)$ at large distance dominated by the singularities of $g(k)$? And if $g(k)$ has no singularities, i.e., any order of its derivative is continuous, then what about the asymptotic behaviour of $f(x)$ at large distance ?
Comment: @ Ron Gordon Thank you very much.
Comment: What is the justification for "it looks like we need to take the second derivative of the above result"? The derivative of an asymptotics may not be the asymptotics of a derivative. It calls for extra justification. Can you just use the stationary phase method directly?


Balão que traz as informações sobre a página

Question: Possuo o seguinte código.

  ..texto..

Gostaria que ao clicar no texto dessa td subisse um balão sobre a página e me mostrasse todo conteúdo que essa td possui, algo em JS.
Por exemplo imagem abaixo:
Comment: o nome disso é ToolTip, pesquisa aqui no SOPT que ira achar varias maneiras, ou aguarde que certeza que alguém responde  :)
Comment: Da uma olhada nesse [link](https://www.w3schools.com/howto/howto_css_tooltip.asp), aprendi com ele e uso ele até hoje, o bom è que não precisa usar livrarias para fazer isso. E è muito simples e super funcional... sua imaginação terminar o processo.
Comment: [Bootstratp](http://getbootstrap.com/) ou [Foundation](http://foundation.zurb.com/) Se quiser algo mais específico: [JQuery UI](https://jqueryui.com/)
Answer: Um exemplo que pode usar para um tooltip e o JavaScript Tooltip

var tooltipOptions=
{
    showDelay: 20,
    hideDelay: 300,
    effect: "fade",
    duration: 300,
    relativeTo: "element",
    position: 2,
    smartPosition: true,
    offsetX: 0,
    offsetY: 0,
    maxWidth: 600,
    calloutSize: 18,
    calloutPosition: 0.5,
    cssClass: "",
    sticky: false,
    overlay: false,
    license: "241l9"
};

/* JavaScript Tooltip v2016.12.12. Copyright www.menucool.com */
var tooltip=function(v){"use strict";var f="length",Cb="addEventListener",kb,mc,fb=function(a,c,b){if(a[Cb])a[Cb](c,b,false);else a.attachEvent&&a.attachEvent("on"+c,b)},a={},Y=function(a){if(a&&a.stopPropagation)a.stopPropagation();else if(window.event)window.event.cancelBubble=true},jc=function(b){var a=b?b:window.event;if(a.preventDefault)a.preventDefault();else if(a)a.returnValue=false},Xb=function(d){var a=d.childNodes,c=[];if(a)for(var b=0,e=a[f];b<e;b++)a[b].nodeType==1&&c.push(a[b]);return c},bb={a:0,b:0},g=null,ec=function(a){if(!a)a=window.event;bb.a=a.clientX;bb.b=a.clientY},bc=function(a){if(window.getComputedStyle)var b=window.getComputedStyle(a,null);else if(a.currentStyle)b=a.currentStyle;else b=a[e];return b},G="offsetLeft",H="offsetTop",pb="clientWidth",ob="clientHeight",z="appendChild",Jb="display",nc="border",r="opacity",U=0,O="createElement",cb="getElementsByTagName",B="parentNode",M="calloutSize",S="position",Db="calloutPosition",D=Math.round,rb="overlay",R="sticky",L="hideDelay",mb="onmouseout",Hb="onclick",n=0,P="firstChild",tb=0,q=document,W="getElementById",Z=navigator,Q="innerHTML",t=function(a,b){return b?q[a](b):q[a]},C={},vb=!!Z.msMaxTouchPoints,V=!!("ontouchstart"in window||window.DocumentTouch&&document instanceof DocumentTouch),Fb=(Z.msPointerEnabled||Z.pointerEnabled)&&vb;if(Fb)var Ub=Z.msPointerEnabled?"onmspointerout":"onpointerOut";var Nb=function(a){return a.pointerType==a.MSPOINTER_TYPE_MOUSE||a.pointerType=="mouse"},lc="marginTop",ic="marginLeft",w="offsetWidth",m="offsetHeight",sb="documentElement",kc="borderColor",gb="nextSibling",e="style",y="width",o="left",p="top",I="height",gc=["$1$2$3","$1$2$3","$1$24","$1$23","$1$22"],x,lb,A=function(c,a,b){return setTimeout(c,a?a.showDelay:b)},eb=function(a){clearTimeout(a);return null},nb=function(){for(var e=[c,b,h,d,d?d[gb]:0],a=0;a<e[f];a++)if(e[a]&&e[a].o)e[a].o=eb(e[a].o)},Lb=function(c,a,b){Gb(c,a[0][0],a[0][1],b);a[f]==2&&Gb(c,a[1][0],a[1][1],b)},Gb=function(a,b,d,c){clearInterval(a["t"+b]);a["t"+b]=setInterval(function(){cc(a,b,d,c)},15)},cc=function(a,d,c,g){var f=0;if(d==r){if(c&&a.op>=1||!c&&a.op<=0)f++}else{var b=parseInt(a[e][d]);if(Math.abs(b-c)<2)f++}if(f){clearInterval(a["t"+d]);g&&g()}else if(d==r)X(a,a.op+(c?.06:-.06));else{b=b+(c-b)/3;if(Math.abs(b-c)<4)b=c;a[e][d]=b+"px"}},l=function(b,a,c){if(n){var d=k?k.duration:v.duration;b[e][n]="all "+d+"ms"}else{b!=h&&Lb(b,a,c);return}b[e][a[0][0]]=a[0][1]+(a[0][0]==r?"":"px");if(a[f]===2)b[e][a[1][0]]=a[1][1]+(a[1][0]==r?"":"px");if(c)if(n){clearTimeout(b.o);b.o=setTimeout(c,d)}else setTimeout(c,6)},J=function(b,a){if(n)b[e][n]="none";b[e][a[0][0]]=a[0][1]+"px";if(a[f]===2)b[e][a[1][0]]=a[1][1]+"px";b[m]},fc=[/(?:.*\.)?(\w)([\w\-])[^.]*(\w)\.[^.]+$/,/.*([\w\-])\.(\w)(\w)\.[^.]+$/,/^(?:.*\.)?(\w)(\w)\.[^.]+$/,/.*([\w\-])([\w\-])\.com\.[^.]+$/,/^(\w)[^.]*(\w)$/],ib=function(d,a){var c=[];if(tb)return tb;for(var b=0;b<d[f];b++)c[c[f]]=String.fromCharCode(d.charCodeAt(b)-(a&&a>7?a:3));return c.join("")},Kb=function(a){return a.replace(/(?:.*\.)?(\w)([\w\-])?[^.]*(\w)\.[^.]*$/,"$1$3$2")},Qb=function(e,c){var d=function(a){for(var c=a.substr(0,a[f]-1),e=a.substr(a[f]-1,1),d="",b=0;b<c[f];b++)d+=c.charCodeAt(b)-e;return unescape(d)},a=Kb(q.domain)+Math.random(),b=d(a);lb="%66%75%6E%63%74%69%6F%6E%20%71%51%28%73%2C%6B%29%7B%76%61%72%20%72%3D%27%27%3B%66%6F%72%28%76%61%72%20%69%";if(b[f]==39)try{a=(new Function("$","_",ib(lb))).apply(this,[b,c]);lb=a}catch(g){}},dc=function(c,a){var b=function(b){var a=b.charCodeAt(0).toString();return a.substring(a[f]-1)};return c+b(a[parseInt(ib("4"))])+a[2]+b(a[0])},c,b,d,ab,h,j,T=0,hc=1,k,E=null,F=function(){if(E!=null)E=eb(E)},X=function(a,b){if(a){a.op=b;if(a[e][r]!==undefined)a[e][r]=b;else a[e].filter="alpha(opacity="+b*100+")"}},Mb=function(a,c,b,d,g,e,h,f){var j=b>=a,l=d>=c,m=j?b-a<g:a-b<h,n=l?d-c<e:c-d<f,i=m?b-a:j?g:-h,k=n?d-c:l?e:-f;if(m&&n)if(Math.abs(i)>Math.abs(k))i=j?g:-h;else k=l?e:-f;return[i,k]},ac=function(r,j,q){db(b,1);var a=t(O,"div");a[e][y]=r+"px";d=t(O,"div");d.className="mcTooltipInner";if(q==1){d[Q]=j;var g=1}else{var c=t(W,j);if(c[B].w)d=c[B];else{d.w=c[B];d[z](c);g=1}}if(!n){var k=d[cb]("select"),l=k[f];while(l--)k[l][mb]=Y}a[z](d);b[z](a);if(d[w]<20){var i=b.className;b.className=""}var h=d[cb]("img");h&&h[f]&&h[0][m];d[e][y]=d[w]+(g?.3:0)+"px";d[e][I]=d[m]+(g?.3:0)+"px";d[e][o]=d[e][p]="auto";d=b.insertBefore(d,b[P]);d[e][S]="absolute";a=b.removeChild(a);a=null;if(i)b.className=i;return d},Ob=function(a){if(a.w){a.w[z](a);X(a,1)}else{a=a[B].removeChild(a);a=null}},db=function(b,c){for(var a=c;a<b.childNodes[f];a++)Ob(b.childNodes[a])},i=function(b,a){b[e][Jb]=a?"block":"none"},Tb=function(){c.v=U=0;i(ab,0);i(c,0);i(h,0);i(T,0);db(b,0)},Sb=function(){if(document.styleSheets&&document.styleSheets.length){var c=document.styleSheets[0];if(typeof b.style.animationName!="undefined")var a="";if(typeof b.style.webkitAnimationName!="undefined")a="-webkit-";else return;var d="@"+a+"keyframes mcttSpinner {from{transform:rotate(0deg);} to{transform:rotate(360deg);}}";c.insertRule(d,0);var e="#tooltipAjaxSpin {margin:30px;font-size:0;width:20px;height:20px;border-width:3px;border-color:rgba(255,255,255,.8);border-style:solid;border-top-color:black;border-right-color:rgba(0,0,0,.8);border-radius:50%;"+a+"animation:mcttSpinner .6s linear infinite;}";c.insertRule(e,0)}},s=null,Wb={a:function(d,b,a){var e=null,h=null,i=null,c="html";if(a){h=a.success||null;c=a.responseType||"html";e=a.context&&h?a.context:null;i=a.fail||null}s=this.b();s.onreadystatechange=function(){if(s&&s.readyState===4){if(s.status===200){if(k==d){var j=c.toLowerCase()=="xml"?s.responseXML:s.responseText,l=j;if(c.toLowerCase()=="json")l=eval("("+j+")");if(c=="html"){var o=b.match(/.+#([^?]+)/);if(o){var r=function(e,b){var d=null;if(b.id==e)return b;for(var c=b[cb]("*"),a=0,g=c[f];a<g;a++)if(c[a].id==e){d=c[a];break}return d},n=q[O]("div");n[Q]=j;var m=r(o[1],n);if(m)j=l=m[Q];n=null}if(!m){var p=j.split(/<\/?body[^>]*>/i);if(p[f]>1)j=l=p[1]}}if(h)j=a.success(l,e);g.f(d,j,1)}}else if(i)g.f(d,i(e),1);else g.f(d,"Failed to get data.",1);s=null}};if(b.indexOf("#")!=-1&&Z.userAgent.indexOf("MSIE ")!=-1)b=b.replace("#","?#");s.open("GET",b,true);s.send(null)},b:function(){var a;try{if(window.XMLHttpRequest)a=new XMLHttpRequest;else a=new ActiveXObject("Microsoft.XMLHTTP")}catch(b){throw new Error("AJAX not supported.");}return a}},Ib=function(){c=t(O,"div");c.id="mcTooltipWrapper";c[Q]='

';x=q.body;j=x;j[z](c);a.a=v.license||"4321";if(typeof c[e].transition!=="undefined")n="transition";if(navigator.userAgent.indexOf("Chrome")==-1&&navigator.userAgent.indexOf("Safari")!=-1)n="webkitTransition";if(!n)c.op=.1;b=c[P];c.b=c.c=c.v=0;Qb(c,a.a);ab=c.lastChild;h=b[gb];i(c,1);this.m(v,1);i(c,0);var f=this.k();kb=function(a){F();f.i();Y(a)};ab[Hb]=kb;this.l();b[mb]=function(){!k[R]&&f.a(k[L])};b[Hb]=Y;fb(b,"touchstart",Y);var d=function(a){if(k&&c.v!==0&&a.target!=k&&k[R]!==1)E=A(function(a){kb(a)},0,k[L]+99);V&&c.v===0&&a.target==k&&k.dispatchEvent(new MouseEvent("mouseover"))};fb(q,"click",d);fb(q,"touchstart",d);X(c,0);c[e].visibility="visible";Pb()},Yb=function(){var b=q.getElementsByTagName("head");if(b[f]){var a=q.createElement("style");b[0].appendChild(a);return a.sheet?a.sheet:a.styleSheet}else return 0},Zb=function(){if(typeof b.style.transform!="undefined")a="";else if(typeof b.style.webkitTransform!="undefined")var a="-webkit-";else if(typeof b.style.msTransform!="undefined")var a="-ms-";else a=0;return a},Bb=function(a){a=a.replace("__",C.prefix);C.a.insertRule(a,0)},Pb=function(){C.prefix=Zb();C.a=Yb();if(C.a){var a="#mcttCloseButton",b="position:absolute;left:auto;cursor:pointer;top:"+v[M]+"px;right:"+v[M]+"px;";if("insertRule"in C.a){Bb(a+"{"+b+"}");Bb("#mcttCloseButton::after{content:'+';display:block;position:absolute;__transform:rotate(45deg);}")}else{C.a.addRule(a,b,0);C.a.addRule("#mcttCloseButton:after","content:'X';display:block;position:absolute;",0)}}},yb=function(a){if(a[B]){var b=a[B].nodeName.toLowerCase();return b!="form"&&b!="body"?yb(a[B]):a[B]}else return x},u=function(c,b){var a=c.getBoundingClientRect();return b?a[p]:a[o]},K=function(b){return b?q[sb][ob]:q[sb][pb]},Vb=function(){var a=q[sb];return[window.pageXOffset||a.scrollLeft,window.pageYOffset||a.scrollTop]},hb=function(c,b,d,f,g){h[e][c?y:I]=a.f*1.55+"px";b[e].webkitTransform=b[e].transform="translate("+f+"px,"+g+"px) rotate("+d+"deg)"},Rb=function(h,g,c,d){var f=K(0),e=K(1),a=0,b=0;if(j!=x){a=u(j,0)-j[G];b=u(j,1)-j[H]}if(c+a+h>f)c=f-h-a;if(c+a<0)c=-a;if(d+b+g>e)d=e-g-b;if(d+b<0)d=-b;return{l:c,t:d}};Ib.prototype={j:function(){if(typeof h[e].transform=="undefined"&&typeof h[e].webkitTransform=="undefined"){h[e][y]="0";return}var b=h[P];h[e][y]=h[e][I]=b[e][y]=b[e][I]=a.f+"px";b[e].borderLeft=b[e].borderTop=a.b+"px solid "+a.d;b[e].backgroundColor=a.c;switch(a.e){case 0:hb(1,b,-135,a.f/4,-a.f/2);break;case 2:hb(1,b,45,a.f/4,a.f/2);break;case 3:hb(0,b,135,-a.f/2,a.f/4);break;default:hb(0,b,-45,a.f/2,a.f/4)}},d:function(a,d,b){F();E=A(function(){(U!=1||a!=c.v)&&g.f(a,d,b)},a)},e:function(a,c,b){F();E=A(function(){g.g(a,c,b)},a)},f:function(f,z,x){i(c,1);U=1;F();nb();i(T,f[rb]);i(ab,f[R]);V&&i(ab,1);var e=this.n(f,z,x);if(c.v){l(c,[[o,e.l],[p,e.t]]);l(b,[[y,b.tw],[I,b.th]]);l(h,[[o,e.x],[p,e.y]])}else if(a.e==4){var A=u(f,0),B=u(f,1);J(c,[[o,A],[p,B]]);l(c,[[o,e.l],[p,e.t]]);l(b,[[y,b.tw],[I,b.th]])}else{J(c,[[p,e.t],[o,e.l]]);J(b,[[y,b.tw],[I,b.th]]);J(h,[[o,e.x],[p,e.y]])}if(f.effect=="slide"){var g,j;if(!c.v&&a.e<4){switch(a.e){case 0:g=0;j=1;break;case 1:g=-1;j=0;break;case 2:g=0;j=-1;break;case 3:g=1;j=0}var k=[g*d[w],j*d[m]]}else{if(!c.v&&a.e>3){g=f[G];j=f[H]}else{g=c[G];j=c[H];if(a.e>3){g+=c.v[G]-f[G];j+=c.v[H]-f[H]}}var t=a.l+a.b+a.b,v=a.m+a.b+a.b;k=Mb(g,j,e.l,e.t,b.b+t,b.c+v,b.tw+t,b.th+v)}var q=a.l/2,s=a.m/2;J(d,[[o,k[0]+q],[p,k[1]+s]]);l(d,[[o,q],[p,s]]);var n=d[gb];if(n){J(n,[[o,q],[p,s]]);l(n,[[o,-k[0]+q],[p,-k[1]+s]],function(){db(b,1)})}X(d,1)}else{l(d,[[r,1]],function(){db(b,1)});var n=d[gb];n&&l(n,[[r,0]])}l(c,[[r,1]]);c.v=f},g:function(a,c,b){s=null;F();!V&&g.f(a,'

',1);Wb.a(a,c,b)},a:function(a){F();E=A(function(){g.i()},0,a)},i:function(){U=-1;nb();l(c,[[r,0]],Tb)},l:function(){if(t(W,"mcOverlay")==null){T=t(O,"div");T.id="mcOverlay";x[z](T);T[e][S]="fixed"}},m:function(f,g){var j=0;if(g||a.e!=f[S]||a.f!=f[M]){a.e=f[S];a.f=f[M];c[e].padding=a.f+"px";j=1}if(g||b.className!=f.cssClass){b.className=f.cssClass?f.cssClass.replace(/^\s+|\s+$/g,""):"";if(d){d[e][n]="none";d[m]}b[e][n]="none";b[m];var k=bc(b),l=Math.ceil(parseFloat(k.borderLeftWidth)),p=k.backgroundColor,o=k.borderLeftColor;if(g||a.b!=l||a.c!=p||a.d!=o){a.b=l;a.c=p;a.d=o;j=1}a.l=g?b[pb]-b[P][w]:d[G]*2;a.m=g?b[ob]-b[P][m]:d[H]*2}if(j)if(a.e<4)this.j();else i(h,0)},k:function(){return(new Function("a","b","c","d","e","f","g","h","i",function(e){var d=[];b.onmouseover=function(a){if(!k[R]){F();if(U==-1){nb();l(c,[[r,1]])}}Y(a)};for(var a=0,g=e[f];a<g;a++)d[d[f]]=String.fromCharCode(e.charCodeAt(a)-4);return d.join("")}("zev$pAi,k,g,+kvthpu+0405--\u0080\u0080+6+-?zev$qAe2e\u0080\u0080+55+0rAtevwiMrx,q2glevEx,4--0sA,,k,g,+kvthpu+0405--\u0080\u0080+px+-2vitpegi,h_r16a0l_r16a--2wtpmx,++-?mj,e2e%Aj,r/+8+0s--qAQexl_g,+yhukvt+-a,-?mj,q@259-wixXmqisyx,jyrgxmsr,-m,40g,+Ch'oylmD.o{{wA66~~~5tlu|jvvs5jvt6.E[vvs{pw'W|yjohzl'YltpuklyC6hE+-0tswmxmsr>:\u0081-?\u008106444-?\u0081\u0081vixyvr$xlmw?"))).apply(this,[a,P,ib,fc,Kb,dc,t,gc,jb])},n:function(k,C,u){var q=x;if(u==2){var D=t(W,C),B=D[cb]("*"),E=B[f];while(E--)if(B[E].type=="submit")q=yb(D)}if(j!=q){j=q;j[z](c)}b.b=b[pb]-a.l;b.c=b[ob]-a.m;d=ac(k.maxWidth,C,u);this.m(k,0);if(!n)d[e].backgroundColor=a.c;b.tw=d[w];b.th=d[m];k.effect=="fade"&&X(d,0);var s=b.tw+a.l+a.b+a.b,r=b.th+a.m+a.b+a.b,o=this.p(k,s,r);if(k.smartPosition)var g=Rb(s+a.f,r+a.f,o.x,o.y);else g={l:o.x,t:o.y};var l=k[S],p=this.u(l,k[Db],s,r);if(k.smartPosition&&l<4){var y=g.l-o.x,A=g.t-o.y;if(l==0||l==2)p[0]-=y;else y&&i(h,0);if(l==1||l==3)p[1]-=A;else A&&i(h,0)}if(j==x){var v=Vb();g.l=g.l+v[0];g.t=g.t+v[1]}g.x=p[0];g.y=p[1];return g},p:function(b,t,s){var c,d,h,g,p=b[S],n=b[Db];if(p<4)if(b.nodeType!=1)c=d=h=g=0;else if(b.relativeTo=="mouse"){c=bb.a;d=bb.b;if(bb.a==null){c=u(b,0)+D(b[w]/2);d=u(b,1)+D(b[m]/2)}h=0;g=0}else{var i=b,e=Xb(b);if(e[f]){e=e[0];if(e[w]>=b[w]||e[m]>=b[m])i=e}c=u(i,0);d=u(i,1);h=i[w];g=i[m]}var o=20,l=t+2*b[M],k=s+2*b[M];switch(p){case 0:c+=D(h/2-l*n);d-=k+o;break;case 2:c+=D(h/2-l*n);d+=g+o;break;case 3:c-=l+o;d+=D(g/2-k*n);break;case 4:c=D((K(0)-l)/2);d=D((K(1)-k)/2);break;case 5:c=d=0;break;case 6:c=K(0)-l-Math.ceil(a.l/2);d=K(1)-k-Math.ceil(a.m/2);break;case 1:default:c+=h+o;d+=D(g/2-k*n)}var q=0,r=0;if(j!=x){q=j[G]-u(j,0);r=j[H]-u(j,1)}return{x:c+q+b.offsetX,y:d+r+b.offsetY}},u:function(f,c,e,d){i(h,f<4);var b=[0,0];switch(f){case 0:b=[e*c,d+a.f-a.b-1];break;case 1:b=[a.b+.5,d*c];break;case 2:b=[e*c,a.b];break;case 3:b=[e+a.f-a.b-1,d*c]}return b}};var zb=function(){if(g==null){if(typeof console!=="undefined"&&typeof console.log==="function"){var a=console.log;console.log=function(){a.call(this,++tb,arguments)}}g=new Ib;if(a)console.log=a;Sb()}if(k&&k.m&&c[Q].indexOf(ib("kdvh#Uh"))!=-1)g.i=function(){};return g},ub=function(d,c,b){b=b||{};var a;for(a in c)d[a]=b[a]!==undefined?b[a]:c[a]},qb=0,N,Eb=function(a){if(!a){a=t(O,"div");a.m=1;a[e][Jb]="none";x[z](a)}if(typeof a==="string")a=t(W,a);k=a;return a},wb=function(a,b){ub(a,v,b);if(vb||V){a.showDelay=1;a[L]=30}if(a[rb])a[R]=a[rb];if(!a[R])if(Fb)a[Ub]=function(a){Nb(a)&&g.a(this[L])};else a[mb]=function(){E=A(function(){g.a(a[L])},0,V?400:a[L]+200)};if(a.relativeTo=="mouse")a.onmousemove=ec;a.set=1},jb=function(a,c,h){a=Eb(a);var b=0;if(c.charAt(0)=="#"){if(c[f]>2&&c.charAt(1)=="#")b=2;else b=1;var d=c.substring(b),e=t(W,d);if(e){if(b==2)c=e[Q]}else b=-1}if(!a||!g||b==-1){if(++qb<40)N=A(function(){jb(a,c,h)},0,90)}else{N=eb(N);!a.set&&wb(a,h);if(b==1)g.d(a,d,2);else g.d(a,c,1)}},xb=function(a,d,b,c){a=Eb(a);if(!a||!g){if(++qb<40)N=A(function(){xb(a,d,b,c)},0,90)}else{N=eb(N);!a.set&&wb(a,c);g.e(a,d,b)}};fb(window,"load",zb);var Ab=function(a){if(++qb<20)if(!g)A(function(){Ab(a)},0,90);else{ub(v,v,a);i(c,1);g.m(v,0);i(c,0)}};return{changeOptions:function(L_options){Ab(L_options)},pop:function(L_sender,L_text,L_options){jb(L_sender,L_text,L_options)},ajax:function(L_sender,L_url,L_ajaxSettings,L_options){xb(L_sender,L_url,L_ajaxSettings,L_options)},hide:function(){var a=zb();a.i()}}}(tooltipOptions)
/* www.menucool.com/tooltip/javascript-tooltip */

/*For tooltip target element that has set class="tooltip" */
.tooltip {text-decoration: none; border-bottom:1px dotted #36c;color: #36c; outline:none; }

/*For tooltip box*/
#mcTooltip
{
    line-height:16px;
    border: 1px solid #333;
    color:#000;
    padding:20px;
    font-size: 12px;
    font-family: Verdana, Arial;
    border-radius:1px;
    background-color:white;
}

#mcTooltip, #mcttCo b {
    box-shadow: 0 1px 4px rgba(0,0,0,0.5);
}

/* For hyperlink within tooltip */
#mcTooltip a { color:#36c; }

/*Close button. Available when sticky or overlay has been set to true, or is on touch-enabled devices. */
#mcttCloseButton
{
    width:18px;
    height:18px;
    margin-right:4px;
    margin-top:4px;
}
/*Close button X symbol*/
#mcttCloseButton:after {
    font:normal 38px/18px arial, sans-serif;
    color:black;
    top:0;left:-2px;
}

/*Give the close button a bigger size on smaller devices*/
@media only screen and (max-width: 736px) {
    #mcttCloseButton {
        width:28px;
        height:28px;
    }
    #mcttCloseButton:after {
        font-size:48px;
        line-height:28px;
    }
}

/* Useful when overlay has been set to true or 1 in JS */
#mcOverlay
{
    background-color: rgba(255,255,255,0.8);
    display:none;top:0;left:0;width:100%;height: 100%;overflow:visible;z-index:4;
}
#mcTooltip img {border:0;vertical-align:middle;}

/*The settings below should remain unchanged*/
#mcTooltipWrapper {position:absolute;visibility:hidden;overflow:visible;z-index:9999999999;top:-2000px;}
#mcTooltip {float:left;border-style:solid;position:relative;overflow:hidden;}
.mcTooltipInner {float:left;position:relative;width:auto;height:auto;}
#mcttCo,  #mcttCo b{position:absolute;overflow:hidden;}

/*compatible with bootstrap*/
#mcTooltip, #mcTooltip div {box-sizing:content-box;}
<span class="tooltip" onmouseover="tooltip.pop(this, 'Nome Nome Nome  Descrição

Qualque conteudo html
', {position:0})">
    Passe o mouse aqui

Answer: Pode usar jQuery e o Bootstrap JS Modal, que é um "plugin" do Bootstrap.

$(document).ready(function() {
  $('.abrir-modal').on('click', AbrirModal);

  function AbrirModal() {
    var codigo = $(this).data('codigo');

    $('#myModal').modal();
    $('#myModal .modal-title').html('Código selecionado: ' + codigo);
  };
});

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">

    Primeiro
    Link

    Segundo
    Link

        <button type="button" class="close" data-dismiss="modal">×</button>

Some text in the modal.

        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

Comment: Com foundation não teria nada ?
Comment: Nunca usei o Foundation. Mas com certeza deve ter algo, só dar uma procurada.
Answer:
O Bootstrap tem algumas coisas em relação à tooltips e popovers.
Você disse que quer que o usuário clique para aparecer, veja:
<button type="button" class="btn btn-lg btn-danger" data-toggle="popover" title="Título do popover" data-content="Conteúdo do popover">Clique</button>

Pode ver ler mais sobre os popovers aqui. Além do popover tem as tooltips, que já comentaram acima.
Answer: O script abaixo em JS puro e sem uso de bibliotecas faz o mesmo efeito.
Funcionamento simples: clique numa célula da
 e abrirá o box com o texto da célula clicada (e fechar o box de outra célula caso esteja aberta). Clique fora da tabela para fechar o box.

tds = document.getElementsByTagName("td");
for(x=0;x<tds.length;x++){
 tds[x].addEventListener("click", function(e){
  if(!this.getElementsByTagName("span")[0]){
   escondeTudo();
   this.setAttribute("style", "position: relative;");
   td_texto = this.innerHTML;
   seta = document.createElement('span');
   seta.setAttribute("style", "position: absolute;bottom: 80%;left: 50%;margin-left: -8px;width: 0;height: 0;border-top: 8px solid #bbb;border-right: 8px solid transparent;border-left: 8px solid transparent;");
   seta.setAttribute("class", "pops");
   this.appendChild(seta);
   ptexto = document.createElement('p');
   ptexto.innerHTML = td_texto;
   ptexto.setAttribute("style", "position: absolute;bottom: 52%;-webkit-transform:translate(-50%,0);-moz-transform:translate(-50%,0);transform:translate(-50%,0);left:50%; max-width: 200px; display: inline-block; padding: 5px; background: #fff; border: 1px solid #ddd; text-align:center;border-radius:10px;-webkit-box-shadow: 2px 2px 2px 0px rgba(0,0,0,0.48);-moz-box-shadow: 2px 2px 2px 0px rgba(0,0,0,0.48);box-shadow: 2px 2px 2px 0px rgba(0,0,0,0.48);");
   ptexto.setAttribute("class", "pops");
   this.appendChild(ptexto);
  }

  e.stopPropagation();return false;

 });
}

function escondeTudo(){
 apaga_pops = document.getElementsByClassName("pops");
 while(apaga_pops[0]){
  apaga_pops[0].parentNode.removeChild(apaga_pops[0]);
 }
}

document.addEventListener("click",function(){
 escondeTudo();
});

  ..texto1..
  Latest compiled and minified JavaScript
  ..texto3..


Transform a non-stationary time series to perform ARIMA

Question: I have a time series (TS) of daily Particulate Matter (PM) data for 6 years. My PM data are not normally distributed. The result of the KPSS test returns p-value of 0.01 and t-statistic of 1.53 therefore failing the H0 of trend stationarity. The result of ADF however rejects the H0 and infers (diffrence?)stationarity.
The result of the decomposition (using slt) shows clear seasonality (please see attached image).

I used The nsdiffs and ndiffs from the R forecast package to calculate the number of seasonal differencing and regular differencing respectively to make the time series stationary. The output returned null for seasonality and 1 for regular diffrencing. Please correct me if I have done wrong so far!
forecast::ndiffs(TS[,6])
1 1
forecast::nsdiffs(TS[,6])
1 0
My question is why I get null for removing the seasonal removal if there is clear seasonality in my timeseries?
Please excuse me if my question is naive as I am new to time series analysis.
I appreciate your advise.
Comment: https://stats.stackexchange.com/questions/405099/ar-and-ma-signatures-in-these-autocorrelation-and-partial-autocorrelation-plots/405372#405372 may be of interest . Please post tour data and I will try and help you further. You don't want to transform you want to incorporate arima into a causal model.
Comment: @IrishStat Thank you for your reply.  By transformation I meant  to de-seasonalize and de-trend my time series. Sorry, I think I chose the wrong term. The original data set is protected but I managed to get another data-set that shows similar trend and seasonality to the original data-set and returns the similar results for nsdiffs and ndiffs. I am not sure how to post the data as it is daily measurements of six years (2011-2016).
Comment: After reviewing some curious results suggest illogical day-of-the-week ,,, I closely investigated your data AND it appears you omitted some days ...e.g. 02/26/2011  . Time series analysis requires that each and very period have an observation. Please closely examine and send a corrected data set .
Answer: Took your 2193 daily values and introduced them to AUTOBOX which detected both a significant persistent day-of-the-week pattern :day 1 & day2 (Saturday & Sunday) ... both negative and a significant very explicable month of the year pattern (months 4-8 ... all positive and summer months BUT different) and an arima structure (1,0,0) with value .427 ALONG with a number (90) of pulses or one-time anomalies.
Other than adjust for some anomalies .... that was all that was needed to characterize it.
Your series is non-stationary that is a symptom  . There are many possible causes that can lead to this symptom. One possible remedy is to adjust for two days of the week and 4 months of the year and anomalous data points. That is your remedy.
Your current "procedures" to test for and to remedy non-stationarity might have assumptions regarding remedies.
From https://en.wikipedia.org/wiki/Stationary_process .... a stationary process is a stochastic process whose unconditional joint probability distribution does not change when shifted in time. Consequently, parameters such as mean and variance also do not change over time. Your series has a mean which changes over time due to day-of-the=week and month-of-the-year thus remedial action (model structure ) is required.
The series does not have to be otherwise different to obtain a stationary set. You should also know that if you difference a stationary series you CREATE a non-stationary series.
Here is the Actual, Fit and Forecast

with forecasts for the next 365 days here:

The model is (partially) shown here:

and also here:

&

The plot of the residuals is here:

with acf here:

Finally, the Actual & Cleansed graph highlights the anomalies which might be worth pursuing in order to identify (user)

omitted causal variables.
Hope this helps you.
Comment: so AUTOBOX correctly identified the 4 monthly factors. Isn't that interesting !. The problem you are having is that weekly indicators (17-32)  are correlated with the four monthly indicators this creating CONFUSION. It is very interesting to that AUTOBOX identified 2 days of the week as being exceptional BUT you didn't advertently inject that in your simulation ... perhaps inadvertently ? I don't know how to answer your questions as tbats is not AUTOBOX ..
Comment: In your second paragraph: "Your series is non-stationary that is a symptom." both adf and KPSS test indicated stationary timeseries:
Dickey-Fuller = -26.928, Lag order = 0,
p-value = 0.01 KPSS Trend = 0.097148, Truncation lag
parameter = 8, p-value = 0.1
Comment: Since I had found that there was non-stationarity  BUT YOUR TESTS FAILED TO DO SO as the don't consider a level shift in a daily effect or a monthly effect to "prove non-stationarity. In other words both the tests that you used are INSUFFICIENT to detect non-stationarity as proven by this analysis. Closely read from https://en.wikipedia.org/wiki/Stationary_process          "your  unconditional joint probability distribution DOES  change when shifted in time due to day-of-the-week , month-of-the-year and the 1 level shift down..
Comment: did the conclusions surprise you ... the saturday/sunday effect ... the May-Aug factors ?
Comment: In my initial data exploration I used the Kruskal-Wallis H test to check for differences between day of the weeks and also months. The difference were significant. I noticed the seasonality factor in winter months (in southern Hemisphere) as I mentioned in my email. That is why I was confused, that even though the decomposition of my time-series shows seasonality, the "nsdf" returns null.
Comment: I create the time series to accommodate two seasonalities (weekly and 4 months):
     TS <- msts(TS,seasonal.periods = c(7,120),start = decimal_date(as.Date("2011-01-01")))
 then performed multiple season decomposition to get a seasonality adjusted time series using tbats:       tbats <- tbats(TS[])                                                   my question is if I can adjust for seasonality but removing the two seasonal components?


Can I use bass pick as guitar pick?

Question: First of all, I don't really know about the difference between both picks, but as far as I know, the bass pick is slightly wider.
Can I use it (the bass pick) as a guitar pick (for guitar, of course)? Will it make different tone? (Yes, I know, but what kind of tone, is it thick, thin, or anything?).
Comment: Thicker picks dont strumm as nice though.
Answer: There is absolutely no rule for this, and it depends entirely on the sound you want. A thicker pick allows for more precision because it does not bend (as much) when you pick a string. This goes very far; Brian May is known for sometimes using coins as guitar pick.
A bass pick is also 'wider', with a larger surface than a normal pick. This gives you more leverage, which is nice on a bass's thick strings, but I can imagine that it is not that handy when playing the guitar. If anything, using a bass pick on a guitar would feel a bit clumsy.
Comment: Brian May would use [a sixpence](http://www.brianmaycentral.net/sounds.html#Sixpence), not a dollar of course!
Answer: Anything you use to pluck a guitar/bass string will affect the sound. A thick pick will give a thicker sound than a thin one. Fingers and finger nails will give different sounds again. Really, you need to try it. It certainly won't hurt either instrument, but personally I can't think of a reason for using a pick with bass. Slapping and popping become impossible, and there's hardly any variety in tone that one gets using one's fingers and thumb.
A felt pick was (is?) available for bass playing, but I imagine it would sound awful on guitar. Wooden picks are supposed to make a guitar sound different, and there was a certain player who used a coin...
Comment: Felt picks are available (often marketed as ukulele picks) -- I have not found them useful on guitar;  they tend to "grab" on the thinner guitar strings and just produce a dull, muffled tone.
Answer: There are sooooo many different picks to choose from and every thickness and size will make a different sound. For me, I play bass and I prefer sharp guitar picks: for some reason these are the most comfortable for me and I like the sound.
A bass pick will generally be louder (well, you'll notice when playing acoustically) and have more attack on your strings and a higher gain from your guitar signal, but if its more comfortable then there are actually thin-medium sized bass picks (like just the fender ones) that will give you a very similar tone to guitar.
I think in general, the tone will change based on the thickness of the pick and sharpness of the edge. I haven't seen sharp bass picks, they tend to be the normal rounded edges. So if you pick a similar thickness, just in bass pick size, I can't imagine you're messing with tone too much.
Picks are an easy thing to experiment with to find your best comfort zone while playing and your best tone (though it is not by far the defining tone factor) that are really cheap. If you think a big pick would be more comfortable for your playing, go for it! Try em out.
Answer: I remember trying that out myself. There wasn't so much difference in the sound, but it was kind of harder to play with a bass pick on a guitar.
That is mainly because a bass pick is wider (since the bass strings are bigger) and the guitar strings are small.
But the simplest thing you can do is to try it out. Picks are almost free, so getting a bass one and trying it on guitar won't hurt your budget.
Answer: You can use anything as a pick if it's comfortable for you. I'm not a guitarist but I tried coins, wood picks, metal picks, bass rubber picks, plastic picks of different sizes and a lot more. I even tried a violin "pick" (whatever it's called) and a glass pick and also different possible variants. My friend a guitarist made himself some bone picks and a silver pick even and they both sound great.
Indeed every pick can create a different tone and of course some are good for strumming like 0.2 to 0.7 sizes and others are good for solo. The shape and extra attributes like bumps or holes male them either less comfortable or more.

Can I use bass pick as guitar pick?


how to count 16th note triplets

Question: When you count in 4/4 time, to get 16th notes you normally say something like:
1 ee and ah two ee and ah 3 ee and ah 4 ee and ah
When you count 8th note triplets you normally say something like
1 and ah 2 and ah 3 and ah 4 and ah
But what about when I want to count 16th note triplets? Is there some kind of way to say that rythmically?
Answer: In the 1 and ah system, your best option is to subdivide. For example, a piece in 4/4 you would count as though it were 8/8.
X:0
K:C
M:4/4
L:16
"1"c2y"2"yy"3"c(3"4"c/2"&"c/2"a"c/2 "5"c"6"c "7"c`"8"c

However, there is an alternative system devised by Richard Hoffman that covers sixteenth-note triplets quite well. His mnemonic for a full sextuplet is Ta va ki di da ma. You would extract the appropriate three syllables depending on where in the beat the triplet falls. So, for example:
X: 1
L: 1/16
K: C
M: none
(6"ta"c"va"c"ki"c"di"c"da"c"ma"c | (3"ta"c"va"c"ki"c "di"c2 | "ta"c2 (3"di"c"da"c"ma"c

Richard Hoffman. 2009. The Rhythm Book 2nd ed. Franklin, TN: Harpeth River Publishing.
http://www.takadimi.net/
The Takadimi system is nicely explained on Wikipedia.
Answer: I count triplets '1-trip-let, 2-trip-let' etc. The fact that semis are faster than quavers doesn't matter. They can be counted at whatever speed you want. Chances are if going through something tricky, it'll be slower than it should eventually be, so count as normal.

how to count 16th note triplets


I need to pass errors back from the model to the controller when a csv file is uploaded

Question: Model:
  def self.import(csv_file)
    order = Order.new
    if order.valid? == false
      nil
    else
      CSV.foreach(csv_file, headers: true) do |row|
        Order.create! row.to_hash
      end
    end
  end

Controller:
  def import
    Order.import(params[:csv_file].tempfile)
    if nil
      redirect_to '/orders/upload_page', flash[:error] = "#{@order.errors.full_messages.to_sentence}"
    else
      redirect_to '/orders/upload_page', flash[:notice] = "upload successful"
    end
  end

form partial:
<%= form_tag import_orders_path, multipart: true do %>

  <%= file_field_tag :csv_file, accept: 'csv', :class => 'btn btn-xs btn-info' %>
  <%= submit_tag "Upload Orders", :class => 'btn btn-xs btn-success' %>

<% end %>

render page:

Orders CSV Upload

  <%= render partial: 'upload_form' %>

What I need to somehow do is ideally two things: 1. I need to supply a notice for errors or success and 2. either supply a notice with the errors OR return a csv file with the rows that contain errors, both would be like cake with a spoon.  I am not entirely sure how to create a tempfile where the errored data would be spit into and then returned as I am processing the csv file from tempfile as it is.
There is only one validation in the model that the csv uploader currently has to pass and it is validates_uniqueness_of :batch, :scope => :projectid
As you can see I have tried flash[:error] to no effect; it does nothing.  I can see in the console that when I insert data I know is purposely trying to violate the validation that it doesn't get uploaded and passes back a Order Exists from the active record.
I am also working on making the submit button available only when there is a file selected.  If there is any advice on that I would love to hear it.
Answer: Let's write some example code on how we would like to access the errors in the controller.
#controller
def import
  @import = Order.import(params[:csv_file].tempfile)

  if @import.successful?
    flash[:notice] = "#{@import.success_count} orders successfully imported"
  else
    flash[:error] = "Import failed with #{@import.error_count} errors"
  end

  # access all orders with errors in the view using @import.failed_records
  redirect_to '/orders/upload_page'
end

This implies that import needs to return an object which responds to success_count, error_count, failed_records and successful?.
class OrderImporter
  def initialize(file)
    @file = file
    @success_count = 0
    @failed_records = []
  end

  def call
    CSV.foreach(@file, headers: true) do |row|
      order = Order.new(row.to_hash)
      save_and_report(order)
    end

    self #ensure that this object is returned upon call
  end

  def success_count
    # default to 0 at start
    @success_count
  end

  def failed_records
    @failed_records
  end

  def error_count
    failed_records.count
  end

  def successful?
    failed_records.empty? && success_count > 0
  end

  private

  def save_and_report(order)
    # avoid the bang version (save!) as we don't need to handle exceptions here.
    if order.save
      @success_count += 1
    else
      @failed_records << order
    end
  end
end

We can call the OrderImporter from Order.import.
class Order < ActiveRecord::Base
  def self.import(file)
    importer = OrderImporter.new(file).call
  end
end

Or, we can bypass Order and directly use the OrderImporter in the controller:
@import = OrderImporter.new(params[:csv_file].tempfile).call
This gives you full access to the results of the upload in the controller. I'll leave it up to you to populate the flash or create a CSV for download.
Comment: Yea you're using a separate controller for handling the import.  I originally was going to go this way.  I can still probably do that; it will take a while to re-work my site to do it that way.
Comment: This way is bypassing the model validation.  It imported an order that should not have been able to be imported due to the validation.  if I try and use @import = OrderImporter.new(params[:csv_file].tempfile).call
Comment: if I do it with just @import = Order.import(params[:csv_file].tempfile) I get the expected, but it says with 0 errors.
Comment: Actually, I am even more wrong; it is just failing to import anything.
Comment: @user2867882: Are the order records being created as expected?
Comment: @user2867882: Is it returning the records in `errors` then?
Comment: I have tried different variations of this code now; the only time it actually imports orders is when I don't use the model.  The problem is then it also skips the validation and imports orders that violate the validation.
Answer: I don't actually have a full answer, but here is where I am at right now; still need some help.
Model
  def self.import(csv_file)
    CSV.foreach(csv_file, headers: true) do |row|
      order = Order.find_or_initialize_by(projectid: row["projectid"], batch: row["batch"])
      order.assign_attributes(row.to_hash)
      if order.valid?
        order.save!
        return true
      else
        order.errors
        return false
      end
    end
  end

Controller
  def import
    if params[:csv_file].present?
      result = Order.import(params[:csv_file].tempfile)
      if result == true
        flash[:notice] = "upload successful"
      elsif result == false
        flash[:error] = "Error uploading"
      end
    else
      flash[:notice] = "Please choose a file"
    end

    redirect_to '/orders/upload_page'
  end

form
<%= form_tag import_orders_path, multipart: true do %>

  <% flash.each do |type, msg| %>

<%= msg.humanize %>

  <% end %>
  <%= file_field_tag :csv_file, accept: 'csv', :class => 'btn btn-xs btn-info' %>
  <%= submit_tag "Upload Orders", :class => 'btn btn-xs btn-success' %>

<% end %>

I can get the initial upload to work, but it always tells me error uploading; nothing I do changes that.  That might have to do with how I am trying to do the messages on the form since I also get other error messages on the form that shouldn't be there.  I am somewhat less concerned with the messages being displayed, though getting that working would be good too.  I am more concerned with the failure to function on update.
The other thing that is not working is the record is not updating.  If I enter a record that already exists I thought that this should update the record.  It's not updating.
Comment: I am fairly certain that the issue is with the form
Comment: Okay, the flash messages are working mostly now.  I still get flashes from other methods if I go straight back to the upload page; very strange and I think that it has to do with the form flash code.

The model code still won't allow updating; I am not sure why.


How to hide group header in grid style View?

Question: How can I hide the headers of the groups in views (Art, Society and Culture) ?

this is a grid style view of taxonomy grouped by parent term (Drupal 7)
Answer: Several options :

hide the relevant elements with CSS.
override the relevant template to prevent the output of the field.
depending on the view, tick the checkbox to not display the field in the field properties.
Answer: you must go to this location: \sites\all\modules\views\theme\views-view-grid.tpl and delete
<?php if (!empty($title)) : ?>

<?php print $title; ?>

<?php endif; ?>

or
go to \sites\all\modules\views\theme\views-view-grouping.tpl and delete

<?php print $title; ?>

Comment: You should never hack contrib module files. This breaks the upgrade path. The Drupal theme system should allow you to override these templates for your specific view in your theme.
Comment: I agree with Nick. Override the tpl file, never, *ever* edit core or contrib like this. Read here https://www.drupal.org/node/173880 for more specifics.


python - for loop in range continues populating data instead of exiting the loop

Question: In the following code,
no_of_sheet_b = 6
row_count_b = 39

I would expect that when j = 7 (i.e. for the final "Sheet 7), the data from rows 37, 38, 39 of dataframe "df_s" will be copied to columns 10, 14, 18, respectively, of worksheet_for_b.cell (which will be saved as "Sheet 7" in this last iteration), and the columns 22, 26, and 30 would be empty (this is what I want). But loop i is completing the iteration even if row_index > row_count_b, and populating columns 22, 26, 30 of "Sheet 7" with data from cols 22, 26, 30 from the previous sheet ("Sheet 6"). How can I make i loop completely stop populating columns when row_index > row_count_b?
row_index = 0
location_value = df_s.at[row_index, "Column 1"]
sample_no_value = df_s.at[row_index, "Column 2"]
top_depth_value = df_s.at[row_index, "Column 3"]

# Iterate over the rows of df_s
for j in range(1, no_of_sheet_b + 1, 1):
    for i in range(10, 31, 4):
        # Check if row_index is within the valid range
        if row_index < row_count_b:
            # Copy the data to the appropriate cells in worksheet_for_b
            worksheet_for_b.cell(row=9, column=i).value = location_value
            worksheet_for_b.cell(row=12, column=i).value = sample_no_value
            worksheet_for_b.cell(row=15, column=i).value = top_depth_value

            worksheet_for_b.cell(row=7, column=4, value=f'{date_assigned}')
            worksheet_for_b.cell(row=7, column=12, value=f'{project_name}')
            worksheet_for_b.cell(row=7, column=24, value=f'{job_no}')

            # jump to next row
            row_index += 1
            if row_index < row_count_b:
                location_value = df_s.at[row_index, "Column 1"]
                sample_no_value = df_s.at[row_index, "Column 2"]
                top_depth_value = df_s.at[row_index, "Column 3"]
       workbook_for_b.save(f"results_folder\\Sheet {j}.xlsx")

Comment: _I would expect that when j = 7_ In that loop, j will **never** be 7.  `range()` loops stop **before** they reach the end limit.  So your expectation makes no sense.
Answer: Using a simple approach you can add a condition to break out of the loop when row_index >= row_count_b. That is you can edit the following couple lines in your code:
            # jump to next row
            row_index += 1
            if row_index < row_count_b:
                location_value = df_s.at[row_index, "Column 1"]
                sample_no_value = df_s.at[row_index, "Column 2"]
                top_depth_value = df_s.at[row_index, "Column 3"]
       else:
            break

       workbook_for_b.save(f"results_folder\\Sheet {j}.xlsx")


Complex Variables Series Coefficient proof.

Question: I was studying for my Complex Analysis(an elementary undergraduate Complex Analysis course) exam and came across this question in the textbook.  I know that in order for there to be a pole of some order, the limit of f(z) would have to go to infinity.  I also know that if f(z) has a removable singularity then it is bounded.  Thus, I am not sure how if two functions, each with poles of different orders, has a product with a removable singularity.  Any advice, tips, and suggestions would be much welcomed.  I have attached this question as an image.  Please note, that this is for an elementary Complex Analysis course, so please nothing too advanced, I am really trying to understand the concepts.
Comment: Read again: $f$ has a *zero*, $g$  has a pole.
Answer: Since $f$ has a zero of order $m$ at $z_0$, its Taylor series in the disk $|z - z_0 | < R$ looks like:
$$ f(z) = a_m(z - z_0)^m + a_{m+1} (z - z_0)^{m+1} + a_{m+2}(z - z_0)^{m + 2} + \dots $$
Therefore, you can write
$$ f(z) = (z - z_0)^m p(z),$$
where
$$ p(z) = a_m + a_{m+1}(z - z_0) + a_{m+2}(z - z_0)^2 + \dots$$
Since $p(z)$ is given by a power series, and since all power series are holomorphic within their disk of convergence, it follows that $p(z)$ is holomorphic on the disk $| z - z_0 | < R$.
Similarly, since $g$ has a pole of order $l$ at $z_0$, its Laurent series on the punctured disk $0 < | z - z_0 | < R$ looks like:
$$ g(z) = b_{-l}(z - z_0)^{-l} + b_{-l+1}(z - z_0)^{-l+1} + b_{-l+2}(z - z_0)^{-l+2} + \dots.$$
So you can write
$$ g(z) = (z - z_0)^{-l}q(z),$$
where
$$ q(z) = b_{-l} + b_{-l+1}(z - z_0) + b_{-l+2}(z - z_0)^2 + \dots$$
Since $q(z)$ is given as a power series, $q(z)$ is holomorphic on the disk $| z - z_0 | < R$; in particular, it is well-defined and holomorphic at the point $z = z_0$.
Finally,
$$ f(z)g(z) = (z - z_0)^{m-l} p(z) q(z).$$
Since $m - l \geq 0$, and since $p(z)$ and $q(z)$ are both holomorphic on $| z - z_0 | < R$ (including at the point $z = z_0$), we see that the right-hand side is holomorphic on the disk $|z - z_0| < R$ (including at the point $z = z_0$). Thus we have succeeded in extending $f(z)g(z)$ to a holomorphic function on $| z - z_0 | < R$ (including at the point $z = z_0$), which proves that $f(z)g(z)$ has a removable singularity at $z = z_0$.


Python list mathematical operation

Question: I have list named money and I am trying to find the total amount. Is there a way to do it like that as shown in the expected output:
money = [
    ("+", 0,0,0,0),
    ("1", 0,0,0,1),
    ("2", 0,0,1,0),
    ("/", 0,0,1,1),
    ("4", 0,1,0,0)]

my_money= [[0, 0, 1, 0], [0, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 1], [0, 0, 0, 1]]

expected output:
total = 2+4/1
total = 6

Comment: It would be a lot easier if `money` was a dict... Do you have control over it (i.e. change it)?
Comment: I don't quite understand how the `money` list relates to the expected output. How do you get from `+ 1 2 / 4` to `2+4/1`? What is the meaning of the 0s and 1s? What is `my_money`?
Comment: yes, i have .  but not over my_money
Comment: Please clarify your post. It's not clear what the relation is between your data and the result.
Answer: It seems that my_money's elements are binary encoding of the money list's elements' indexes. So it seems that the other values in the money list are redundant and the elements can be indexed directly with binary encoding:
for l in my_money:
    index = int(''.join(str(x) for x in l), 2)
    print(money[index][0], end=' ')

Gives:
2 + 4 / 1

If you have control over money and can change its structure it would help you alot. Anyway, you can pre-process the current money to a more appropriate structure - a dict:
money_dict = {t[1:]: t[0] for t in money}

Now money_dict looks like this:
money_dict = {
    (0,0,0,0): '+',
    (0,0,0,1): '1',
    (0,0,1,0): '2',
    (0,0,1,1): '/',
    (0,1,0,0): '4'}

So now the task is much easier:
my_money= [[0, 0, 1, 0], [0, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 1], [0, 0, 0, 1]]
print(*(money_dict[tuple(l)] for l in my_money))

which gives:
2 + 4 / 1

The above is O(n) where n = len(my_money). You can still do it with the original money but the best you can do is O(n*m) where m = len(money):
for l in my_money:
    for t in money:
        if t[1:] == tuple(l):
            print(t[0], end=' ')
            break

Python list mathematical operation


php - upload multi imagens para mesmo campo

Question: Boa Noite,
Tenho uma dúvida e uma questão...
Eu quero fazer upload de múltiplas imagens, mas na minha base de dados tenho la 2 campos:
 Imagem_1 e Imagem_2.

Mas não sei como separo as imagens, visto ser tudo do mesmo array $_POST['imagens']
Alguma dica?
Comment: Essa resposta pode te ajudar: [Como tratar muilt upload da forma certa](https://pt.stackoverflow.com/questions/220116/multi-upload-com-variados-formatos-php-e-mysql/220191)
Answer: Acredito que a questão não é o código em si, por isso vou focar somente na lógica.
Quando tu for percorrer a variável das imagens com o foreach, tu compara a posição delas com a variavel $key. Então no if que compara se $key == 0, vai o código que faz a inserção no banco e move para a pasta a primeira imagem, e no else, vai fazer o mesmo com a segunda imagem
foreach($_FILES['imagem'] as $key => $imagem) {
  if($key == 0) {
    // Codigo que vai salvar na coluna imagem_1 e mover para a pasta
  } else {
    // Codigo que vai salvar na coluna imagem_2 e mover para a pasta
  }
}

Comment: ok mas exemplo... EU tenho dado para inserir tambem, nao vou inserir-los 2x... como faço para inserir os dados juntamente com essas imagens?
Comment: Posso usar tipo... $_FILES['imagem'][0], e $_FILES['imagem'][1] ?
Comment: Faz dois inserts, um para as imagens e outro para os dados.
Answer: Você pode criar um input com o atributo name como um array:
<form action='' method='post'>
    <input name='imgs[]' type='file' multiple>
</form>

E no PHP:
var_dump($_POST["imgs"]);

O resultado vai ser algo assim:
array(2) { [0]=> string(8) "img1.png" [1]=> string(8) "img2.png" }

Então é só fazer um loop e converter as imagens para o tipo blob, mover para uma pasta ou apenas salvar o nome do arquivo


D7 - db_select: order by most recent, commented status

Question: I'm writing my custom module.
I use the modules Statuses and 'fbss_comments' (part of the Statuses module). Comments are used to comment on statuses.
Using the following code I get a list of results:
 $query = db_select("statuses", "thread")->distinct();
        $query->join("fbss_comments", "comment", "comment.sid = thread.sid");
        $query->fields("thread", array("sid", "sender", "created", "message"));
        $query->fields("comment", array("created"));
        $query->orderBy("comment.created", "DESC");
        $result = $query->execute();

Now the list of results will be sorted by the most recent posted status. I want to achieve the following: sort the result list by statuses with the most recent comments
Some clarification: normally status(100) will be shown above status(30). When I comment on status(30), status(30) should be shown above status(100). On top of this, when I create a new status(101), this status should be shown on top of the result list.
I hope my goal is clear to you, sadly, I have no idea how to achieve this.
Any advice or help is much appreciated
edit: I've managed to order the results by the most recent commented statuses, however, if a status has 9 comments, the status is shown 9 times. Any advice why/how this happens?
edit 2: I probably should use ->distinct(), I've added it after the db select statement, but  this doesn't work (probably because I select two tables)
Comment: It's hard to answer your question without seeing the new code, you created. If you create SQL fiddle with test data and your request, it will be very helpful.
Comment: "if a status has 9 comments, the status is shown 9 times. Any advice why/how this happens?" It happens, because you created a query, fetching the data from 2 related tables. And it returns all the corresponding rows from both tables.
Comment: Why are you fetching `sid` field twice: once from the 1-st table, then from the 2-nd table?
Comment: good question, now I only select 'created' from the fbss_comments table. Doesn't make any visual difference though. If distinct the right approach to make sure a status is only shown once? thanks for your help so far btw.
Answer: You have a classical case, that requires using 'HAVING' SQL operator. Suppose, we have 2 related tables:
| table1 |
|--------|
|   id   |
|--------|
|    1   |
|    2   |
|--------|

table2.f_id is the FK for table1.id
|         table2        |
|--------+------+-------|
|     id | f_id | order |
|--------+------+-------|
|      1 |    1 |     1 |
|      2 |    1 |     2 |
|      3 |    2 |     3 |
|      4 |    2 |     4 |
|--------+------+-------|

And you want to get all the records from table1 with MAX of the related table2.order. And sort them by table2.order. You must use this SQL to get the data:
SELECT
  table1.id AS id1,
  table2.id AS id2,
  table2.order
FROM
    table1
INNER JOIN
    table2
ON
    table1.id=table2.f_id
GROUP BY
    table1.id
HAVING
    MAX(table2.order)
ORDER BY
    table2.order DESC

And you will get:
| id | id1 | order |
|----+-----+-------|
|  2 |   3 |     3 |
|  1 |   1 |     1 |
|----+-----+-------|

Fiddle
Converting this SQL to Drupal, we'll get this:
$query = db_select("table1");
$query->innerJoin("table2", NULL, "table1.id=table2.f_id");
$query->addField("table1", "id", "id1");
$query->addField("table2", "id", "id2");
$query->addField("table2", "order", "order_field");

$query->groupBy("table1.id");
$query->having("MAX(table2.order)");
$query->orderBy("table2.order", "DESC");
$result = $query->execute();
while($row = $result->fetchAssoc())
{
      var_dump($row);
}

So, for your case, this query must work:
$query = db_select("statuses", "thread");
$query->innerJoin("fbss_comments", "comment", "comment.sid = thread.sid");
$query->fields("thread", array("sid", "sender", "created", "message"));
$query->fields("comment", array("created"));

$query->groupBy("thread.sid");
$query->having("MAX(comment.created)");
$query->orderBy("comment.created", "DESC");
$result = $query->execute();

Comment: @MaartenHartman IF you still can't fix it, I can come to char for a while.
Comment: thanks a lot for your extensive answer, I'll test it within a few hours and report back.
Comment: hmm sorry but it's not correct, now I only get statuses with comments (of course, join..). I need to show all statuses, and sort by most recent comments on statuses + most recent status. So either the latest status is on top or the status with the latest comment. this is really hard.. :( shouldn't we use outer join / union?
Comment: @MaartenHartman It's hard to answer without seeing, what is the data and what result does the request produce. Plz, create a fiddle.
Comment: thank you so much for your help mate. I've decided to solve this in a much easier way: I will just update the timestamp of the status when a comment has been posted to it. In this way I will achieve the same result in a very simple way :) thanks again.
Comment: what shall I do with this question? delete or just leave it open?
Comment: @MaartenHartman Leave it open. I think my answer is good and could be useful for others.


Find B elementarily equivalent to A such that $\phi(B)$ is uncountable.

Question: Suppose A infinite L structure, such that $\phi(\overline{x})$ is a formula such that $\phi(A)$ - the set defined by $\phi$ is denumerable. Find B $\equiv$ A such that $\phi(B)$ uncountable.
heres my idea:
in the $\overline{x} = x$ (ie 1 tuple case), this is a standard compactness argument. augment L with uncounably many fresh constants; create $\Sigma$ = union of original theory and $\phi(c)$ for all new constants and statements saying the new constants are not equal. then use the fact that $\phi(A)$ infinite to show that any finite subset has a model. by compactness, done.
all other cases "reduce" to the 1 tuple case, for example suppose
$\phi (a_1, a_2, a_3), \phi (a_1, a_2, a_5), \phi (a_7, a_2, a_5),...$ all hold.
claim: at least one of the (set of projections of) tuple components must contain infinitely many different variables. for suppose otherwise. then each component only contains finitely many different variable, so finitely many different tuples for which $\phi$ holds. but this is a contradiction.
so we can just make the set {$\phi(\hat{a_1}, \hat{a_2}, W)$} where $\hat{k}$ denotes intoa set of fresh constants meant to interpreted as elements in A, and W ranges over the uncountable many fresh constants added. we only add in $\phi(\hat{a_1}, \hat{a_2}, W)$ if there is some corresponding tuple $\phi(a_1,a_2,a_3)$ that holds and the third compent is the column that contains infinitely many fresh variables. the argument then proceeds essentially as above.
Does this work? Is there a cleaner way to do this?
Answer: The way you expressed your argument is not so clear, so I can't say for sure if it works. But yes, there's a cleaner way.
Let's say $\varphi(\overline{x})$ has $n$ free variables $x_1,\dots,x_n$. Let $\theta_=(\overline{x},\overline{y})$ be the formula $\bigwedge_{i=1}^n x_i=y_i$. Note that $\theta_=(\overline{a},\overline{b})$ is true if and only if $\overline{a}$ and $\overline{b}$ are equal as $n$-tuples.
Now introduce uncountably many new $n$-tuples of constants: $(\overline{a}_\alpha)_{\alpha<\kappa}$ for an uncountable cardinal $\kappa$, where $\overline{a}_\alpha = (a^1_\alpha,\dots,a^n_\alpha)$. By the same compactness argument you described, the theory $$\Sigma\cup \{\varphi(\overline{a}_\alpha)\mid \alpha<\kappa\}\cup \{\lnot \theta_=(\overline{a}_\alpha,\overline{a}_\beta)\mid \alpha<\beta<\kappa\}$$ is consistent, and we're done.
Comment: much cleaner, thx!


If I drop a PG table with an index, does the index still exist?

Question: If I'm dropping and re-creating a Postgres table that is indexed, will the index still exist?
Do I need to drop and re-index the table after re-creating it or do I just need to re-create the index on the new table and leave the cleaning up of the old index to Postgres?
Comment: Why didn't you try it out? The index gets dropped when the table is dropped. Automatically generated indexes (e.g. primary key, unique) will be re-created when the table is re-created, manually created indexes won't. You cannot have an index without an associated table.
Answer: Drop table will delete all related constraints, & index, no need for you to do any kind of cleanup. Postgres will handle that.


Finding maximum score in a "bubble pop" game

Question: Consider the following game: there is a n×n field, where each cell is randomly coloured in one of m colours. Let a group of cells be a set of same-coloured cells s.t. every cell in a group has at least one common edge with another same-coloured cell. A group of s$\geq$k cells can be "popped" i.e. removed from the field and a player is assigned a score for it. When a group is removed, the remaining cells are displaced s.t. no cell has an empty cell underneath it (basically, remaining cells "fall down"). If a column vanishes as a result of popping, every non-empty column to the left of it is displaced one cell to the right. The game ends when there are no groups left on the field. The score is a function of s, and in the end a cumulative score is calculated. The aim of the game is to get maximum cumulative score.
The question is if there is an algorithm that allows to calculate maximum possible end score for a given starting arrangement of cells? I suspect it has something to do with graph searching, but I have little experience with such things. Can anyone please suggest how can one approach such kind of a problem? I have also thought about doing something with cellular automata, but I really doubt this approach (however fun it might be).
Comment: Maybe try StackExchange for algorithms stuff?
Answer: This often goes by the name 'Clickomania' or, apparently, 'Same Game'; I'm not sure how much people have studied the optimization version you list, but it's known that determining whether a grid can be completely solved or not is NP-complete as soon as you get to sufficient amounts of colors and columns.  See Eric Demaine's page at http://erikdemaine.org/clickomania/ for more details of the result, including a link to the original paper proving the NP-Completeness result and a few basic results on optimization in the $n\times 1$ grid case; alternately, you can find the paper on the arXiv.
Comment: Cheers, will look into it.


add External javascript file - Syntax issue

Question: When i use the following syntax, the inline script is not executed. In Firebug not able to debug the code.

but if i change the external file add script, it works fine. no issues at all.

Answer: You must close

script is html pair tag. You have to close it
BTW there's no reason to use https
Answer: Your are closing the script tag too early. Remove the last slash from the first row.
Answer: the browser inserts the content from the url provided in the src attribute into the   tag. so if there is only a emtpy tag you can't insert anything


Adding points on an elliptic curve

Question: I'm trying to work out a problem from a previous exam in Cryptography regarding elliptic curves. I can add points on an EC using the formulas given, but the suggested solution to this exam problem I cannot understand.
The EC is given by $E:Y^{2} = X^{3} + X + 46$ over $\mathbb{F}_{101}$, and I'm given three points, $P = (2,37)$,  $Q = (54,2)$ and $R = (64,19)$ I'm supposed to show that $$6P + 2Q + R = \infty$$ $$2P + Q + 2R = \infty$$
$\infty$ being the identity or zero/neutral element of the corresponding group. I tried to compute the addition of the points to itself and see if some inverses turned up, but I might have made a mistake because I couldn't find such a property. The suggested solution however talks about doublings and addition, and the cost of these operations. I don't really understand how that plays a part, and nowhere in the solution do they compute anything so I'm really unsure how they arrive at the correct conclusion. Some help would be appreciated.
EDIT: Someone asked to see the suggested solution, but I couldn't figure out how to format it correctly, so I'll give a link to it. It's the answer to problem 3b).
https://wiki.math.ntnu.no/_media/tma4160/losning2013.pdf
Comment: One would need the curve itself for the computation, I suppose?
Comment: Oops, I'll make an edit
Comment: It might help to know the curve :p. Anyway given that it shouldn't be too hard to show that $6P + 2Q = -R$ and $2P+2R = -Q$.
Comment: Can you give the "suggested solution"? As it is, I don't see any way to show it other than to just compute, which is probably not what is expected. (It is true, by the way.)
Comment: That's funny, the suggested solution doesn't even answer the question. It tells how to answer it in the most **efficient** manner (this is why they are talking about the cost of doubling, etc), but doesn't show the steps in answering.
Comment: I see. I spent a good hour yesterday computing all of those doublings and additions (crypto by hand sux),  and did in fact show that they were inverses. i was just thrown off by the solution.
Answer: I was disposed to solve your question but the point $R=(63,19)$ does not belong to the curve $E$ so have no sense neither, the addition with $R$ nor the duplication point $2R$.
If you edit your post, I could give an answer maybe. I wonder a related problem could be find the point $R=(x,y)$ in order to have your relations (not forgetting that $ nP $ is given by a polynomial formula of degree $ n ^ 2 $). It would be convenient, if you edit, say that your $\infty$ is assumed to be the zero of the corresponding group.
NOTE.- I hope, anyway, not to be wrong saying $R\notin E$
<code>              **********************
</code>
ADDENDUM.-This question only requires calculations with formulas defining the law of the group $E$, calculations in the finite field $\mathbb F_{101}$ which may be somewhat laborious task. It seems to me that AT LEAST ONE OF THE TWO GIVEN RELATIONS IS WRONG! because  calculating $-Q = 2 (P + R)$ and $2P = 3R$ (this last relation implicated by elimination of $Q$) not give me the correct verification in both cases. I give here the calculation of $2(P+Q)$ which results distinct of $-Q$. If I am wrong in this calculation (with some frequency it happens to me) I think what is important  is to see clearly the way this kind of problems in the realm of elliptic curves is solved.
<code>                              ********************************
</code>
Then $R=(64,19), P=(2,37), Q=(54,2)$, so $-Q=(54,-2)$ lie in the curve $E: Y^2=X^3+X+46$ and it is asked to verified the relations $$6P+2Q+R=0….(1)$$ and $$2P+Q+2R=0….(2)$$
I have to use the formulas defining the group $E: y^2=x^3+Ax+B$.
If $P_i=(x_i,y_i); i=1,2$ then $P_1+P_2=(x_3,y_3)$
with $$x_3=m^2-x_1-x_2$$ and $$y_3=m(x_1-x_3)-y_1$$ where
$$m=\frac{y_2-y_1}{x_2-x_1}\text{ when}\space\space P_1\ne P_2$$ and $$m=\frac{3x_1+A}{2y_1}\text{ when}\space\space P_1=P_2$$.
<code>                               ********************************
</code>
We calculate in detail with
$\boxed{2P+Q+2R=0\iff –Q=2(P+R)}$
►$P+R=(x,y)=?$
$m=\frac{19-37}{64-2}=\frac{-9}{31}$ then $$x=(\frac{-9}{31})^2-64-2=\frac{81-66\cdot(31)^2}{(31)^2}=\frac{-63345}{961}=\frac{-(627\cdot101+18)}{9\cdot101+52}=\frac{-18}{52}=\frac{-9}{26}=-9\cdot35=-315=-12$$
$$y=(\frac{-9}{31})(2-(-12))-37=\frac{-9\cdot14-31\cdot37}{31}=\frac{-1273}{31}=\frac{-(12\cdot101+61)}{31}=\frac{-61}{31}=-61\cdot88=-61(-13)=793=7\cdot101+86=86=-15$$
Thus $P+R=(-12,-15)$
►$2(P+R)=2(-12,-15)=(x,y)=?$
$m=\frac{3(-12)+1}{2(-15)}=\frac{-35}{-30}=\frac76$ then
 $$x=(\frac76)^2-2(-12)=\frac{49+36\cdot24}{36}=\frac{913}{36}=913\cdot87=4(-14)=-56=45$$
$$y=\frac76(-12-45)-(-15)=\frac{7(-57)+6\cdot15}{6}=\frac{-309}{6}=-\frac{309}{6}=\frac{-6}{6}=-1$$
Thus $2(P+R)=(45,-1)\ne(54,-2)=-Q$ which would imply that the relation (2) is false (If none error in this calculation).
Comment: You are correct, $(63,19)$ doesn't lie on the curve, but $(64,19)$ does. I copied the wrong point, but for my own computations I've used the correct one.

Adding points on an elliptic curve


Convergence of $\lim_{R \rightarrow \infty} \int_\Gamma \frac{e^\lambda}{|\lambda|}d\lambda$ on $\Gamma=Re^{i\theta}$

Question: The book I am studying claims that some arguments are valid because the following integral converges:
$$\lim_{R \rightarrow \infty} \int_\Gamma \frac{e^\lambda}{|\lambda|}d\lambda$$
where $\Gamma=Re^{i\theta}$, $\theta \in [-\phi,\phi]$ and $\frac{\pi}{2} < \phi < \pi$.
However, when I try integrating, I get:
$$\int_\Gamma \frac{e^\lambda}{|\lambda|}d\lambda =
\int_{-\phi}^{\phi} \frac{e^{Re^{i\theta}}}{R}iRe^{i\theta}d\theta =
\int_{-\phi}^{\phi} \frac{1}{R}\frac{d}{d\theta}\big(e^{Re^{i\theta}}\big)d\theta =
\frac{1}{R}\big(e^{Re^{i\phi}}-e^{Re^{-i\phi}}\big)$$
If we take $z=Re^{i\phi}$, then:
$$\frac{1}{R}\big(e^{Re^{i\phi}}-e^{Re^{-i\phi}}\big) =
\frac{1}{|z|}\big(e^{z}-e^{\bar z}\big) =
\frac{e^z}{|z|}\big(1-e^{-|z|^2}\big),$$
which diverges when $|z|=R \rightarrow \infty$. Have I done something wrong?
In case someone is interested, I am studying Pazy's "Semigroups of Linear Operators and Applications to Partial Differential Equations", Theorem 1.7.7 (I know I probably should not be struggling with that at this level).
Answer: Everything is alright until you think the quantity diverges.
$$|e^z|=|e^{R\cos\phi}e^{iR\sin\phi}|=e^{R\cos\phi}$$
Note that for $\pi/2<\phi<\pi$, $\cos\phi<0$, thus $e^{R\cos\phi}\to0$ in the limit.
Therefore, we can conclude $e^z\to 0$ as $R\to\infty$.


How do i derive the joint probability distribution table of X and Y?

Question: If there is a bag with 3 red balls, 2 blue balls and 1 white ball. Two balls are drawn without replacement. Let X be number of red balls drawn and Y be number of blue balls drawn.
Comment: Hi, welcome to the site. This seems to be a homework/self-study problem. Please add the self-study tag and follow the instructions in http://stats.stackexchange.com/tags/self-study/info
Answer: Step 1: Determine the sample space.
When you draw a sample of two balls from this bag

all of the 15 following results are equally likely:

To assure that this figure is complete and contains no redundancies, the samples are drawn systematically, beginning with all those containing ball $A$, then all additional samples containing $B$ (but not $A$), then all additional samples containing $C$ (but not $A$ or $B$), etc.
Step 2: Label the elements of the sample space with the values of the random variables.
Next to each sample, by counting the number of red balls and the number of blue balls, I have drawn the values of $X$ and $Y$ in the form $X,Y$.
Step 3: Summarize the probabilities.
We can total the probabilities of each possible value of $(X,Y)$ and present these totals in a table.  For instance, two of the samples have $(X,Y) = (0,1)$, giving a probability of $2/15$ for this value of the (bivariate) random variable $(X,Y)$, which is entered in the column $X=0$ and the row $Y=1$.
$$\begin{array}{cccc}
  & X=0 & X=1 & X=2 \\
 Y=2 & \frac{1}{15} & 0 & 0 \\
 Y=1 & \frac{2}{15} & \frac{6}{15} & 0 \\
 Y=0 & 0 & \frac{3}{15} & \frac{3}{15} \\
\end{array}$$
Answer: To find the joint distribution of X and Y, think about all the possible values that X and Y can take.  Then, the joint distribution is just the probability that X and Y simultaneously take two of their possible values.


I want to join two array elements and print their values. The output value I am receiving is garbage value

Question:     System.out.println("The ip address is in class: ");
    System.out.println("Class C");
    System.out.println("The masked Ip address is:");
    System.out.println(arr[0] + arr[1] + arr[2] + ".0");

The above code is working but it is giving me garbage value. I want to print all the elements in the array.
Comment: how does the output look like and what is the data type of the array?
Answer: You can print them using for loop like this:
for(int i = 0 ; i < 3 ; i++){
    System.out.print(arr[i]);
}
System.out.println(".0");

Or, using stream:
Arrays.stream(arr).forEach(System.out::print);

Comment: Thanks  for the help
Answer: Always print arrays/collections using iterator or loops. Hardcoded array access can lead to errors.
StringBuilder sb=new StringBuilder();
for(String s:arr){
sb.append(s);
}
System.out.println(sb.toString() + ".0");

Answer: I guess if the IP is 192.168.1.0
Then you are seeing result as: 1921681.0
If yes, then you have to print it like this:
System.out.println(arr[0] + "." +arr[1] + "." + arr[2] + ".0");