Detailed proof of $\zeta(s)-1/(s-1)$ extends holomorphically to $\Re(s)>0$

Question: I'm trying to understand the proof of PNT by Don Zagier. But his proof is too simplified so I can't understand it. I got stumped at step II: $\zeta(s)-1/(s-1)$ extends holomorphically to $\Re(s)>0$.
The proof is available here:
http://mathdl.maa.org/images/upload_library/22/Chauvenet/Zagier.pdf
Can anyone post a detailed proof that $\zeta(s)-1/(s-1)$ extends holomorphically to $\Re(s)>0$?
Or please tell me which book has a detailed proof so I can look it up?
edit:
Zagier's proof:
$\displaystyle \zeta(s)-\frac{1}{s-1} = \sum_{n=1}^{\infty} \int_{n}^{n+1} (\frac{1}{n^s}-\frac{1}{x^s}) dx$
$\displaystyle \left|\int_{n}^{n+1} (\frac{1}{n^s}-\frac{1}{x^s}) dx\right| \leq \frac{|s|}{(n^{\Re(s)+1})}$
therefore $\displaystyle \zeta(s)-\frac{1}{s-1}$ extends holomorphically to $\Re(s)>0$
My question: We have a function
(i) $f(s)=\sum_{1}^{\infty} g_n(s) \quad \forall \Re(s)>0$
(ii) $g_n(s) \leq |s|/(n^{\Re(s)+1}) \quad \forall \Re(s)>0$
Is (i) and (ii) the necessary and sufficient condition that $f(s)$ has holomorphic continuation?
Does there exist functions $f$ and $g_n$ that satisfy (i) and (ii), but does not have holomorphic continuation?
Do we need to prove other conditions, for example $g_n$ must be continuous/holomorphic?
Comment: What part *exactly* you don't understand in that proof? It looks to me pretty straightforward...
Comment: @alek: You might notice that I merged the account you used to write the post with the account you wrote the answer/edit. This will let you comment and edit your own question. Best of luck.
Answer: Start with the defining series, convergent for $\Re(s)>1$:
$$
   \sum_{n=1}^\infty \frac{1}{n^s} = \sum_{n=1}^\infty  \frac{1}{\Gamma(s)} \int_0^\infty t^{s-1} \mathrm{e}^{-n t} \mathrm{d} t = \frac{1}{\Gamma(s)} \int_0^\infty t^{s-1} \frac{\mathrm{e}^{-t}}{1- \mathrm{e}^{-t}} \mathrm{d} t
$$
Also notice that, for $\Re(s)>1$,
$$
  \frac{1}{s-1} = \frac{\Gamma(s-1)}{\Gamma(s)} = \frac{1}{\Gamma(s)} \int_0^\infty t^{s-2} \mathrm{e}^{-t} \mathrm{d} t
$$
Now subtracting we have:
$$
  \zeta(s) - \frac{1}{s-1}  = \frac{1}{\Gamma(s)} \int_0^\infty t^{s-1} \mathrm{e}^{-t} \left( \frac{1}{1- \mathrm{e}^{-t}} - \frac{1}{t} \right) \mathrm{d} t
$$
The integral on the right-hand side converges now for $\Re(s)>0$, since at the lower integration bound $\frac{1}{1-\exp(-t)} - \frac{1}{t} = \frac{1}{2} + \mathcal{o}(1)$.
Answer: Trying to address what I think was troubling the OP.
Fix constants $a,b$ such that $0<a<b$. Consider the set $$L(a,b)=\{x+yi\in\mathbb{C}\mid a<x, |x+yi|<b\}.$$ The functions $g_n(z)$ are holomorphic in the set $L(a,b)$. Item $(ii)$ means that for all $z\in L(a,b)$ and all positive integers $n$ we have
$$
|g_n(z)|\le\frac{b}{n^{1+a}}.
$$
Therefore, by Weierstrass' M-test (note that here the lower bound on the exponent, $1+a$, does not depend on $z$, only on the set $L(a,b)$), the series $f(z)=\sum_{n=1}^\infty g_n(z)$ converges uniformly in the set $L(a,b)$ and therefore gives a holomorphic function on $L(a,b)$.
The right half-plane is the union of the sets $L(a,b)$, so $f(z)$ is holomorphic there.
Comment: In other words, use the techniques familiar from proving that a converging power series gives a holomorphic function: Shrink the set in a suitable way such that your estimates prove the convergence to be uniform in that smaller set.


Given area of circle, find the radius of each circle that can fit the area

Question: I have the following given values:

area of the big circle
values ranging from 1 to 100 (it can be more or less)

I need to create a circle for each value, where its size is proportional to its value.  For example, a value of 5 will become a circle that is smaller, while a value of 20 will become a larger circle.
Then, all these circles should fit inside the big circle.
My goal is to find the radius of each circle.
Comment: Not clear to me, but if the values are $A_1,A_2,A_3,\ldots$, and each one is to be interpreted as the area $A_i = \pi r_i^2$ of the $i$-th circle, then $$r_i = \sqrt{\frac{A_i}{\pi}}$$ Is that helpful? ___EDIT:___ Or is this instead a packing problem where you try to pack a bunch of circular discs of different sizes into one big circle? In that case, it is hard to find an optimal packing!
Comment: I think it's straightforward to get the radius of each circle whose area is Ai.  However, I still need to know the area of each circle, which is the Ai of each circle.  This is provided that all these circles will be packed inside a big circle having an area of, say, Abig.  Meaning Abig > A1 + A2 +.... An.
Comment: @iPhoneJavaDev What are you doing this for? Do you need a visualization for $100 = 50 + 25 + 10 + 7 + 5 + 3$ that involves pouring little circles into a big one in a way that visually fills up the big circle? Like Jeppe mentioned, this is a fairly intensive problem and I might suggest not using circles. Maybe stuff flexible bubbles in there? ...
Comment: Yes, I need to display the data into bubble chart.  However, I need them to be circles that merge in the center forming a big circle.  The reason that Abig > A1 + A2 + ... An is that if I pack those circles together, there will be gaps among them to avoid overlapping of circles.  I try to scale the radius of each circle based on their value, however, for some case, they perfectly fit the big area Abig.  For some combinations of data, they overflow.  And for some case, they form into a circle much smaller than Abig.  I need to scale the circles based on their value to somehow fit Abig properly.
Answer: Suppose you have 4 circles of radius $r$ each at the corner of a square having side length =$2r$.
Then the area of this square is $4r^2$. One quarter of each of these 4 circles lies inside the square totaling an area of an entire circle, $\pi r^2$. So for a given square, circles packed in this way  will only cover $\frac{\pi}{4}$ of the area.
Repeat this with a regular triangle and we find the corresponding ratio to be $\frac{\pi}{2\sqrt{3}}$
Each of these processes corresponds to a way of packing circles into an area. However you pack the circles, some gaps will be present and with a signature ratio.
So given a square of side length $L$, how many circles of radius $r$ can fit?
The area of the square that can be occupied by Square Corner packing is $\frac{\pi}{4}L^2$
Divide this by the area of the circle to get $N=\frac{L^2}{4r^2}$. So N circles will fit.
The same principle applies for circles. Suppose you have a big circle with radius $r_1$ and you want to fill it with circles of radius $r_2$.
Then $$N=\frac{(\frac{\pi}{4})\pi r_1^2}{\pi r_2^2}=\frac{\pi r_1^2}{4r_2^2}$$
There are different ways of packing, and radii can be non-uniform, but once you know the packing fractions, you can usually sort things out.


Procurar valores em um data.frame e adicionar em outro (R)

Question: Eu tenho 2 data.frames, o primeiro é um data.frame que contem dados de ações e uma coluna com um identificador único (coluna "ISIN"), conforme exemplo abaixo:
Teste=data.frame(matrix(runif(20), nrow=5, ncol=4))
Teste$ISIN <- c("A1","A2","A3","A4","A5")
colnames(Teste) <- c("AVG_VOLUME","AVG_RETURN","VOL","PRICE","ISIN")

          AVG_VOLUME AVG_RETURN    VOL         PRICE  ISIN
 Stock 1  0.7028197  0.09264265    0.002169411 100    A1
 Stock 2  0.7154557  0.03314615    0.004839466 100    A2
 Stock 3  0.4038030  0.04347487    0.003441471 100    A3
 Stock 4  0.5392530  0.06414982    0.004482528 100    A4
 Stock 5  0.8720084  0.09615865    0.008081017 100    A5

Meu segundo data.frame possui uma coluna "ISIN" porém não são unicos, conforme exemplo abaixo :
Teste2 <- data.frame(matrix(runif(10), nrow=5, ncol=2))
Teste2$ISIN <- c("A1","A1","A3","A2","A2")

  X1        X2          ISIN
1 0.0273074 0.6829592   A1
2 0.1928437 0.3768154   A1
3 0.9693224 0.3331828   A3
4 0.9434274 0.1549707   A2
5 0.6211476 0.3360101   A2

O que eu gostaria de fazer é buscar no data.frame Teste o valor da coluna "AVG_VOLUME" correspondente ao "ISIN"do data.frame Teste2 e adicionar essa informação como uma coluna nova em Teste2, resultando em :
  X1        X2          ISIN  AVG_VOLUME
1 0.0273074 0.6829592   A1    0.7028197
2 0.1928437 0.3768154   A1    0.7028197
3 0.9693224 0.3331828   A3    0.4038030
4 0.9434274 0.1549707   A2    0.7154557
5 0.6211476 0.3360101   A2    0.7154557

Qual a melhor maneira de obter esse resultado, tipo um PROCV no excel ?
Answer: Usando dplyr você pode fazer assim:
> library(dplyr)
> Teste3 <- left_join(Teste2, Teste %>% select(ISIN, AVG_VOLUME))
Joining by: "ISIN"
> Teste3
         X1        X2 ISIN AVG_VOLUME
1 0.5896936 0.1847698   A1  0.3473872
2 0.9254054 0.1172393   A1  0.3473872
3 0.3235616 0.3382006   A3  0.1330457
4 0.8382510 0.6392993   A2  0.9750695
5 0.3537203 0.7187851   A2  0.9750695

Você poderia especificar o argumento by na função left_join se as colunas nos dois data.frames não tivessem o mesmo nome:
Teste3 <- left_join(Teste2, Teste %>% select(ISIN, AVG_VOLUME),
                    by = c("ISIN" = "ISIN"))

Se você quisesse trazer todas as colunas do outro banco, poderia fazer o seguinte:
> Teste3 <- left_join(Teste2, Teste,
+                     by = c("ISIN" = "ISIN"))
> Teste3
         X1        X2 ISIN AVG_VOLUME AVG_RETURN       VOL     PRICE
1 0.5896936 0.1847698   A1  0.3473872  0.1309524 0.6389297 0.3433055
2 0.9254054 0.1172393   A1  0.3473872  0.1309524 0.6389297 0.3433055
3 0.3235616 0.3382006   A3  0.1330457  0.2889567 0.3713113 0.8803770
4 0.8382510 0.6392993   A2  0.9750695  0.1394496 0.5789795 0.7136534
5 0.3537203 0.7187851   A2  0.9750695  0.1394496 0.5789795 0.7136534

Acho legal deixar aqui o bechmark das soluções também. A solução usando dplyr é cerca de 2x mais rápida conforme a tabela abaixo:
> microbenchmark::microbenchmark(
+   merge =  merge(Teste, Teste2, by = "ISIN"),
+   left_join = left_join(Teste2, Teste, by = "ISIN")
+ )
Unit: microseconds
      expr     min       lq     mean  median      uq       max neval
     merge 738.565 773.4590 927.1096 792.249 816.673 13732.206   100
 left_join 287.354 307.5555 323.3633 316.747 327.374   671.206   100

Comment: Gostei desse pq já vai para o final do novo data.frame
Comment: Na solução do @carlosfigueira também é possível levar para o final: `Teste3 <- merge(Teste2,Teste[,c("ISIN", "AVG_VOLUME")], by = "ISIN")`
Answer: merge é a função que você está procurando - ela pode unir dois data frames. Como  você só quer uma coluna do primeiro data frame, você pode filtrá-lo para ter apenas ela:
Teste=data.frame(matrix(runif(20), nrow=5, ncol=4))
Teste$ISIN <- c("A1","A2","A3","A4","A5")
colnames(Teste) <- c("AVG_VOLUME","AVG_RETURN","VOL","PRICE","ISIN")

Teste2 <- data.frame(matrix(runif(10), nrow=5, ncol=2))
Teste2$ISIN <- c("A1","A1","A3","A2","A2")

Teste3 <- merge(Teste[,c("ISIN", "AVG_VOLUME")], Teste2, by = "ISIN")

Comment: Boa obrigado !!


Uninitialized constant while trying to include helper module

Question: The module that I am trying to include is located here:
test/unit/helpers/test_helpers.rb
Looks like:
module TestHelpers
end

I am trying to include it in:
test/unit/app/models/abc.rb
class Abc < ActiveSupport::TestCase
include TestHelpers
end

gives the following error:

Error executing test/unit/app/models/abc.rb uninitialized constant
  Abc::TestHelpers

Any ideas why this might be happening?
Comment: the helper isn't included into ruby include tree... include it with `::require`
Answer: To include a module into your class, you need to require that file.

require 'test_helpers'

Add this line at the top of your model class.


In C minor, is Am7b5 a borrowed chord from Dorian?

Question:
Above is actually a thread from reddit, OP asks what Am7b5 is doing in the piece.
(I am actually not sure posting it here is OK in the first place)
https://www.reddit.com/r/musictheory/comments/1boqdi1/whats_the_function_of_a7b5_in_c_minor/
here is the thread URL.
My question is, there are comments saying that Am7b5 is a borrowed chord from Dorian, when some other comments argue that Am7b5 can be explained by melodic minor scale(to which I also agree).
But again someone else says in jazzy 1 6 2 5, Am7b5 is actually Dorian.
Can someone explain why Dorian is brought up for Am7b5's role when melodic minor alone can explain it?
Answer: They're talking about dorian, because the "true" VI chord in C minor would be AbMaj7. One could consider that the A natural comes from melodic minor, but then there's the matter of the previous chord, C-7, which contains a Bb. "True" melodic minor would have a B natural. So, given the presence in the measure (in the harmony, that is) of both A natural and Bb, there is the suggestion of dorian (C-D-Eb-F-G-A-Bb-C). In the chord-scale approach to jazz improvisation, it would make sense to play the C dorian scale over the measure, because the switch to melodic minor (i.e., play B natural) risks an awkward sound — Bb against one chord but B natural against the other.
However, this is a perfectly ordinary variation of i-vi-ii-V that occurs in jazz frequently. Jazz harmony doesn't attempt to adhere strictly to the same conventions as does classical music. Whether the chord is considered to come from dorian or melodic minor really has no bearing except as a purely academic question. Jazz is comfortable interchanging the various minor scales plus dorian and just calling the whole thing "minor".
Comment: Jazz is comfortable interchanging the various minor scales plus dorian and just calling the whole thing "minor". -- so is classical.  Even more so, in fact.
Answer: Am7♭5 contains the same set of notes as F9 (minus root). So playing an F9 chord would work just as well, with the possibility of it having an A as the lowest note - not clear from a lead sheet, unless 'F9/A' was written. Although Cm6 would be an even better exact substitute, in an inversion.
Considering F9, that would then put the chord in question as 'borrowed' from the parallel key, C major. Considering Cm6/A, it stays in minor. And then follows the familiar 2-5-1 change as found in so many jazz arrangements, the Dm7♭5 reverting the key back to Cm.
Comment: How is F9 from C major? FMaj9, yes, but F9?
Answer: As @Aaron pointed out in his answer this chord can be interpreted in all of the ways you mentioned but it is best thought of as a minor version of a 1-6-2-5, which is very often used in jazz. It is also not usually a part of the original harmony but added as a reharmonizarion of standard tunes like this one. In C minor it creates a nice voice leading of Bb-A-Ab-G in the chord progression. It is used by some in other songs like "How Deep is the Ocean", "Yesterdays" and "Summertime" but like I said, it is rarely part of the original harmony of these songs. It is the same harmonically as going from a Im (or Im7) to a Im6 but adds the bass motion to the 6th of the Im6 chord, thus giving you a VIm7b5.
Confirming my point about this usually being a reharmonization, in the recording of "Angel Eyes" by the composer Matt Dennis, he does not use this chord in either bar 3 or bar 6. In bar 3 he plays a full bar of Cm and in bar 6 he plays an Ab7 in place of the Am7b5. He also plays the song in another key, Eb minor but I have transposed the chords to their C minor equivalents.
Answer: There are many questions and other things to address here.

"In C minor, is Am7b5 a borrowed chord from Dorian?"

I can't see any benefit in thinking about borrowing from Dorian, definitely in a tune like this. Who borrows from a mode anyway? Is that even a thing?

"OP asks what Am7b5 is doing in the piece"

What the Am7b5 chord is doing: it's a middle-point between Cm and Ab that provides a "something changed" feeling without actually doing much. Whoever wrote the chords wanted to have a change halfway through the bar, and they could have used, say an F9 chord as well. The Am7-5, which can be written as Cm6/A, gives a clear one-step bass movement to the target Ab.

there are comments saying that Am7b5 is a borrowed chord from Dorian, when some other comments argue that Am7b5 can be explained by melodic minor scale(to which I also agree).

What is this "explaining"? How does a scale "explain" a chord? I don't understand this thinking. Do you mean that the whoever wrote the Am7b5 chord must have been thinking about a certain scale, in order to come up with  Am7b5? No other chain of events is possible?

Can someone explain why Dorian is brought up for Am7b5's role when melodic minor alone can explain it?

I haven't and won't read the Reddit thread, but a C Dorian scale is one possible scale to overlay on top of an Am7b5 chord. C melodic minor is another.
The general idea I feel is mistaken here is that every chord "comes" from exactly one scale. It's weird that perfectly sane, logically thinking people can think so. What actually happens is more like the other way around. A musician sees a chord symbol and thinks: what scales or 7-note chords can I fit over this chord. A common method used by jazz musicians is extending a chord to a full "13th" or 7-note chord, or even an 8-note chord, which they equate to a scale. Diminished scales have 8 notes per octave. And of course you can play a chord with all 12 chromatic notes appearing somewhere.
A chord comes from a scale, if that scale is what the person was thinking about who decided on that chord. But you cannot know what they were thinking.
One important mechanism to see is chromatic alterations. There is no scale which dictates what you may or may not do, it's the other way around. "The scale" or harmonic context, is at your mercy. Whatever chords you play, scales are your humble servants and they adjust according to the chords. If you start in Cm, but then you play an F major chord, the A scale slot is violently forced to move to natural position. Maybe it used to be an A flat, but you played an F major - now your A is natural, no questions asked. The scale came from the chord. Not the other way around.
However, if you want to play modally - and the tune in question is totally and absolutely and completely not modal - then your tonic and the set of notes around it are restricted. You cannot play notes outside the mode, because if you do, the modal feeling is destroyed. If you're supposed to create a C Dorian feeling, and if you play a chord with an Ab note, the mode breaks down and is no more. You ruined the mode. The modal feeling died and it was your fault, you killed it.
But this tune is not modal.


fedora apache/nginx pylons

Question: I'm trying to wrap my head around Pylons and how it works. So far... it's been confusing... I'm using EC2 with Fedora8. Everything is working so far (i.e. I have Pylons/python et al installed and after creating a test app and running paster serve I can access the default page via my domain name).
As the Pylons docs explain and as I understand, the built in paster serve server is not suited for a production environment. What I am not clear on, then, is what to do next... It seems like nginx is a good option, but I am more familiar with Apache (like .0002%). I plan on having virtualhosts (which nginx says can accomodate). However, I am totally unclear on how the big picture is supposed to work.

In order to serve an app, does paster serve need to be running?

Does then nginx/apache basically just act as a proxy to shuttle connections to the paster server?
How do I start it so it doesn't terminate after closing the ssh connection?
If running multiple apps, what do I set as the host/port in development.ini to differentiate the apps? Or if this is not the right way, how do I differentiate beween apps?

I am more familiar with MySQL, but willing to negotiate PostgreSQL if it's a better fit. Is it?
Is virtualenv a prerequisite to running multiple apps on the same machine?

Thanks in advance for any tips.
Answer: apache2/mod_wsgi -> pylons
or
nginx/uwsgi (don't use their mod_wsgi) -> pylons
Why you don't want to use nginx and their mod_wsgi
Virtualenv keeps your dependencies tied with your own sandboxed version of python and the installed packages.  If you are running multiple sites, it would be advised to use virtualenvs for each.
You can proxy to paster, but, I prefer mod_wsgi. As to the debate with apache2 versus nginx, nginx will use less memory and provide faster static file serving.  Configuring nginx to handle mod_rewrite type functionality is a little different, but, not impossible.  With either mod_wsgi or uwsgi, as long as the webserver is running, your application will start when a request is made.  You might find it easier to start with apache/mod_wsgi and migrate to nginx later.  The number of people that understand apache is far greater than those that understand nginx and most projects are documented assuming apache is going to be used.
If your webserver starts when your ECS instance starts, either wsgi method will start on the first request.
When running multiple apps, you'll have separate wsgi config files or separate .wsgi scripts.
Philosophical debate to choose MySQL versus PostreSQL.  SQLAlchemy supports both in Pylons.
Comment: So essentially with mod_wsgi/uwsgi, when a request for a page is made, the respective module will handle the "paster serve" command? Am I understanding that right?

Thanks for the very informative answer!
Comment: It doesn't call paster, pylons runs using the wsgi interface.  Paster is just a simple wsgi web server.
Comment: I think I'm starting to get it...  I've successfully completed the "Verify wsgi is installed correctly" section of the pylons+wsgi docs http://docs.pythonweb.org/pages/viewpage.action?pageId=5439610#id4, but the information beyond that isn't really clear to a newb like me. I need a pylons+wsgi+apache for dummies :/

Thanks again!

fedora apache/nginx pylons


Can Sublime Text 3 support project-specific snippets?

Question: I'm working on a front-end web app that has a bunch of reused components, and I would like to make snippets in order to decrease hand-typed code. The problem is that I don't want those snippets to appear in other projects, with different components.
I've set up my folder to be a sublime project (having the *.sublime-project file in the root)
Is there any straightforward way to do this?
Comment: There was a feature request some time ago:
https://sublimetext.userecho.com/topic/23900-project-based-snippets/
Comment: Not very straightforward, but you could make a plugin which has a `Project Snippets` sub-directory that users populate with `ProjectName/SnippetName.sublime-snippet`.  When they run the command, ST3 shows a searchable QuickPanel listing all found snippets for the current project, end executes them when the user presses enter.
Answer: As of writing, ST build 3120, there is no way to do this.
A quick workaround: (requires Package Control)
Put the snippets inside a folder inside the packages directory.
Menu > Preferences > Browse Packages....
This folder/package can then be enabled/disabled very quickly via the Command Palette, Ctrl+shift+P then type to find the enable/disable command, using Package Control.


Play framework 1.x on Tomcat - httpOnly cookies

Question: I'm setting application.session.httpOnly=true in the application.conf and generating a war file and deploying on tomcat.
I still see the cookie generated as HttpOnly=No and it is editable.
This is an issue with play 1.x running on tomcat 6 (i.e. servlet api 2.x). Apparently, http only flag for cookies was only introduced in servlet 3.0 and so is only available in tomcat 7+
has anybody identified a workaround for this so far (so I could have http only cookies for play 1.x on tomcat 6.x ) ? the httpOnly flag on context in tomcat only works for tomcat's jsessionid cookie...
also, can I run a play 1.x app on servlet 3.0 ?
PS: This was also posted on the play framework's google groups but we did not receive a response and so posting on SO.
Answer: You should be able to run the app in tomcat 7. The reason is that although you'll deploy a War file, Play is not using any Servlet API, so that shouldn't be a problem. That said, the problem could be the addon that generates the War file, I'm afraid I don't have experience with it.
On workarounds, the only one would be to use the integrated server available with Play. If you run in Tomcat, Tomcat sets the rules so no HttpOnly for you. If you use the integrated Netty then you'll have that.
Comment: not quite the answer I was hoping for, but I'll accept the reality :-)


Single log in for multiple moodle installation

Question: I have installed three instances of moodle in the local site for the three different courses for three diffirent languages
localhost/netstudy/english/
localhost/netstudy/marathi/
localhost/netstudy/hindi/
I want to have a single login page containing the dropdown for the selection course language. How to bypass the moodle login so that depending on the course language selection respective course moodle shoo

<form name="form1" method="post" action="http://localhost/netstudy/english/login/index.php">

Member Login

Username
:
<input name="myusername" type="text" id="myusername">

Password
:
<input name="mypassword" type="text" id="mypassword">

<input type="submit" name="Submit" value="Login">

</form>

I am new to the moodle please help me out with this.
Comment: 3 installations is a bit of an overkill... You can specify the language for the course in the course settings. I would have a single instance with 3 categories, one for each language, with the course in each category
Comment: Those three courses are totally different and have the pratice test conducted in that so is it possible somehow to use single login page so that i can login to any of the three different moodles installed.  by using the above code i am able to bypass only single moodle installation because directly i have specified the action for single course . But how to do when i have drop down for language  selection to go to respective moodle.
Answer: Well, Okay. First, you need to know that what you're building is a bit silly - 3 installation is very, very over-the-top. You can instead have a single site and  a single course with 3 language settings.
And if the content is different like you said in your comment above, you can still configure the course to have 3 different content catalogues using conditional access (All in the same installation).
Having 3 instances of Moodle running simultaneously will significantly impede any low/mid-range server.

Ranting aside, if you really want to do this, you can add a dropdown box in your login form which enables users to select the language/site they would like to log into. You can then post this data onwards in a PHP script.
A bunch of if-statements should do the job.
Pseudo code:
HTML:
<input type="select" name="lingo"/>

    <option value="1">English</option>
    <option value="2">Marathi</option>
    <option value="3">Hindi</option>
</select>
<input type="text" name="username"/>

<input type="text" name="password"/>

<button to submit goes here>

PHP:
If lingo == 1{
    post username and passwords to English_login.php;
}
elseif lingo == 2{
    post username and passwords to Marathi_login.php;
}
else{
    post username and passwords to Hindi_login.php;
}

That should give you an idea of how to go about having a single login page, but I must reiterate that this is probably a bad idea.
Good luck with your project all the same. :)


Does proper contraction on Hilbert space necessarily lead to convergence in norm to zero?

Question: I was asked this in functional analysis class:

Let $ \mathbb{H} $ be a Hilbert space and we are given an operator T satisfying:
$ || Th || < ||h|| $ for all $ h \in H $. We are asked if the following is necessarily true: for all $ h \in \mathbb{H} $ does one have the convergence to zero $ T^nh \to 0 $ in the Hilbert space norm? How about the other direction?

Intuitively it seems to me it is untrue as the Supremum of the operator norm might be one and the inequality given here seems weaker than the conclusion given, but I have no counterexample. For the other direction I got no real idea. Could someone be so kind as to please point me to the way? Thank you.
Answer: Let $\{a_n\}$ be a sequence of positive real numbers that increases to $1$, with the property that the sequence of products
$$ a_1,\ a_1a_2,\ a_1a_2a_3,\ a_1a_2a_3a_4,\ \ldots$$
converges to a positive value. It's not hard to write down a specific example.
Let $\cal H = \ell^2(\mathbf R)$ and define $T : \cal H \to \cal H$ by $$T(x_1,x_2,x_3,\ldots) = (0, a_1x_1,a_2x_2,a_3x_3,\ldots).$$
Clearly $T$ is linear and bounded, and $\|Th\| < \|h\|$ for all (nonzero) $h$.  Let $h = (1,0,0,0,0,\ldots)$.
What is $\|T^nh\|$ equal to?
Comment: Are you sure about that definition for $T$?
Comment: @user251257 term-by-term the absolute values of the entries of $Th$ are less than those of $h$. The inequality is strict at the first non-zero entry.
Comment: @UmbertoP. Oh yeah. I am blind. Thx.
Comment: If your definition is correct, then why the comment about the product $\Pi_{j=1}^{\infty}a_j$? How would that come up?
Comment: The point of the definition is to show that $T^n h \not\to 0$ is possible.
Comment: Isn't $T^n h = a_1^n h$ for your $h$?
Comment: Ack! Silly typo on my part. Thanks for reading it carefully!
Comment: You're welcome. +1 :)


How can I make that an object of the same class become the return value of initializer?

Question: I have this function:
extension UIImage {

    static func from(layer: CALayer) -> UIImage? {
        UIGraphicsBeginImageContext(layer.frame.size)
        layer.render(in: UIGraphicsGetCurrentContext()!)
        let outputImage: UIImage? = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return outputImage
    }

}

How can I change it into like this?
extension UIImage {

    convenience init(layer: CALayer) {
        self.init();
        UIGraphicsBeginImageContext(layer.frame.size)
        layer.render(in: UIGraphicsGetCurrentContext()!)
        let outputImage: UIImage? = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        self = outputImage; // Error: cannot assign to self: self is immutable
    }

}

I want that the result of UIGraphicsGetImageFromCurrentImageContext() becomes the initiated "self". But the result is already a UIImage. I don't suppose I should use "mutating" in this function?
Comment: What was wrong with what you had to start with? A static factory method is _exactly_ the way to do this.
Comment: I think you can't; see this answer: https://stackoverflow.com/a/37612406/433373
Comment: @matt I do not want to create a factory method. I want to create an initializer, which works slightly looks like a "type cast" sort of matter. I do not _produce_ an image. My intent is to _convert_ a type of image from one type to another, which is why the form of factory is not exactly communicating my intent.
Comment: @NicolasMiari yeah I kinda guess that, but I just curious whether if we have some workaround with this limitation.
Answer: As the error states UIImage is immutable. What you can do is to get a CGImage from your outputImage and use UIImage init(cgImage: CGImage) initializer to initialize a new image from it:
extension UIImage {
    convenience init?(layer: CALayer) {
        UIGraphicsBeginImageContextWithOptions(layer.frame.size, false, 0)
        defer { UIGraphicsEndImageContext() }
        guard let context = UIGraphicsGetCurrentContext() else {
            return nil
        }
        layer.render(in: context)
        guard let outputImage = UIGraphicsGetImageFromCurrentImageContext()?.cgImage else {
            return nil
        }
        self.init(cgImage: outputImage)
    }
}

Comment: Very clever indeed! :-)
Comment: Ooh, I never thought of using the `cgImage` initializer. Thanks!


Show that $p_1p_2 \cdots p_t<4^n$

Question:
Let $n$ be an integer greater than $1$ and let $p_1,p_2,\ldots,p_t$ be the primes not exceeding $n$. Show that $p_1p_2 \cdots p_t<4^n$.

We only need to consider $n$ to be of the form $n = p_i$ for every prime $p_i$. Therefore we have to prove that $$p_1p_2 \cdots p_i < 4^{p_i}.$$
Comment: This is used in the proof of Chebychev theorem and Betrand's postulate. See [this](https://en.wikipedia.org/wiki/Proof_of_Bertrand%27s_postulate) and [that](https://www3.nd.edu/~dgalvin1/pdf/bertrand.pdf)
Comment: Observation: For up to $p_100$ it suffices to use $(2.62)^n$ in place of $4^n$.
Answer: Every prime in the range $[n+1,2n]$ is a divisor of
$$\binom{2n}{n} = \frac{2n\cdot(2n-1)\cdot\ldots(n+2)(n+1)}{n!} \tag{1}$$
and
$$\binom{2n}{n} < \sum_{k=0}^{2n}\binom{2n}{k} = 4^n \tag{2}$$
it follows that
$$ \prod_{p\in [n+1,2n]}p < 4^n \tag{3} $$
and by iterating the same argument over the intervals $\left[\frac{n}{2}+1,n\right],\left[\frac{n}{4}+1,\frac{n}{2}\right]$ and so on we get
$$ \prod_{p\in[1,2n]}p < 4^{2n}.\tag{4}$$
Comment: Yes,  problem has $<4^{p_i}$, not $<4^{2n}$, but of course $p_i < 2n$.
Comment: @MarkFischler: yes. I considered the product of the primes in the interval $[1,2n]$ and got that it is $<4^{2n}$, hence the product of the primes in the interval $[1,n]$ is less than $4^n$ as wanted.
Comment: Ah, I see now.  My earlier comment missed your point.  This proof is, IMHO, correct and should be given a check by the OP.  BTW, the bound can surely be tightened; does anybody know how far?  I would bet heavily it is always less than $3^n$ as well.
Comment: @MarkFischler: it can be tightened for sure. In the original Chebyshev's proof (https://integermiscellany.wordpress.com/2012/12/10/notes-on-the-chebyshev-theorem/) the constant $4$ is replaced by something close to $3.03$.

Show that $p_1p_2 \cdots p_t<4^n$


Loop com array + string

Question: Estou tentando fazer algo como:
a = {move1="oi", move2="oi2"}
for x=1, #a do
print(a.move..x)
end

Não sei explicar muito bem, mas o que estou tentando é isso:
print(a.move..x)

ficando print(a.move1) e no próximo print(a.move2), como posso fazer isso?
Answer: Vou colocar duas soluções para você.
A primeira é baseada em resposta que eu já lhe forneci. Preste muita atenção ao comentário do lhf, o criador da linguagem.
function table.map_length(t)
    local c = 0
    for k, v in pairs(t) do
         c = c + 1
    end
    return c
end

a =  { move1 = "oi", move2 = "oi2"}

for x=1, table.map_length(a) do
    print(a["move" .. x])
end

Para ajudar entender saiba que a tabela que você escreveu é a mesma coisa que escrever:
a =  { ["move1"] = "oi", ["move2"] = "oi2"}

A sintaxe de a.move1 é o mesmo que a["move1"]. Aí você consegue o que você quer.
A segunda é o jeito correto de fazer o que você quer.
a =  { move1 = "oi", move2 = "oi2"}

for k, v in pairs(a) do
    print(v)
end

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.

Uma observação importante: em todos os seus códigos você ignora a indentação em todas as linguagens que você está tentando. Isso dificulta a sua leitura e principalmente das outras pessoas. Pode parecer bobo, mas os melhores programadores do mundo têm dificuldade para ler códigos não indentados. Existe uma dificuldade cognitiva no jeito como você escreve. E não é só isto, espaçamentos em geral ajudam a leitura. Veja a diferença como eu escrevi.
Comment: Vou começar a me preocupar mais com isso. Quanto a resposta, está perfeita.

Loop com array + string


Accuracy of deep neural network

Question: I have implemented a deep neural network which performs the classification task and obtained accuracy for each epoch as follows

In graph, X-axis is number of epochs and Y-axis is accuracy obtained
According to graph highest accuracy obtained is 90%, lowest is 0% and average is nearly 40% But now what will be the overall performance(accuracy) of the model
How to choose best hyper parameters according to the performance of the model
Answer: Plotting error/accuracy against number of epochs is a way to see how fast is your neural network approaching a minima. Usually, one would observe a low accuracy for a small number of epochs. With an increasing number of epochs, accuracy should increase. Hence, your plot is rather weird! Are you sure it's correct?

But now what will be the overall performance(accuracy) of the model?

To estimate accuracy you should be looking at the performance for a high number of epochs. Moreover, you need to split your data into a train and test set and have an idea of whether your model suffers from under-/overfitting.

How to choose best hyper parameters according to the performance of the model?

Split your data into train and test set. Compute training and test error/accuracy and see whether your model suffers from under- and/or overfitting. Based on such diagnosis change some of the hyperparameters accordingly. In particular, when your model is underfitting you can try bigger networks, bigger hidden layers, or run the optimisation for more iterations. If your model suffers from overfitting you can try regularisation. Hyperparamter tuning is a topic in itself. There is a vast amount of literature on this. I would suggest Andrew NG's courses on Machine Learning for detailed info.
Comment: you mean increasing number of epochs always increases accuracy
Comment: Well, yes. If everything is going alright you should observe an increasing accuracy with an increasing number of epochs.
However, the smoothness of the accuracy-number of epochs curve is related to the optimisation method you are using. If you are using gradient descent (update weights after passing the whole dataset) the improved accuracy should be smooth. If you use batch gradient descent accuracy should also increase but in a less smooth manner. In general, the higher the batch size is, the smoother the curve.

Accuracy of deep neural network


Spectrum of normal elements in C*-algebras

Question: Let $\mathcal{A}$ be a C*-algebra and $x \in \mathcal{A}$ a normal element. Can you show that $\left\{ \phi(x) : \phi \text{ is a state on } \mathcal{A} \right\}$ is the closed convex hull of the spectrum of $x$?
If you want you can use the result above for sef-adjoint elements in C*-algebras. That is,
if $a \in \mathcal{A}$ is a self-adjoint element, then $[a,b]=\left\{ \phi(x) : \phi \text{ is a state on } \mathcal{A} \right\}$, where $a=\min{\sigma(a)}$ e $b=\max{\sigma(a)}$. One proof of this fact can be found in Proposition 7.8 of Conway, for example.
Answer: Since the spectrum does not depend on the (C$^*$) algebra, we can assume that $\mathcal A=C^*(x)$. Using the Gelfand transform, we can identify $C^*(x)$ with $C(\sigma(x))$, with $x$ mapped to the function $z\mapsto z$.
The point evaluation states $f\mapsto f(t)$ are precisely the pure states The pure states are the extremal points of the set of states of $\mathcal A$. So any state $\phi$ is a limit of convex combinations of points evaluations, which means that $\phi(x)$ is a limit of convex combinations of points in $\sigma(x)$.
As Jonas rightfully mentions, one needs to check that the set does not depend on the algebra. This is verified by checking that every state on $C^*(x)$ extends to a state on $\mathcal A$. So
$$
\{\phi(x):\ \phi\ \text{ is a state on }\mathcal A\}=\{\phi(x):\ \phi\ \text{ is a state on }C^*(x)\}.
$$
Comment: Perhaps it is worth mentioning that the set $\{\phi(x):\phi\text{ is a state on }A\}$ is also not affected by passing to a subalgebra (because states on the subalgebra extend to states on $A$).
Comment: Good point, Jonas. I have edited accordingly.


WS02 G-REG new metadata type

Question: We're testing G-Reg for use of a SOA repository. The default types are Services, WSDL's, Schemas and WS Policies, we're triying to add a new type (Persons for example).
Once added, we want to create a xml to specify the fields that needs to be filled to upload a new resource of the "Persons" type, (like the Services type actual funcionality).
We've followed the guide on http://docs.wso2.org/wiki/display/Governance411/Configurable+Governance+Artifacts, but with no success of creating the example named "Events", because there exists contradictory information, the path "/_system/governance/repository/components/org.wso2.carbon.governance/types", doesn't exists on GREG 4.1.1, so where is supposed the content to be uploaded?
And, the guide explains about a "registry extension file" and a "content", which is the difference between them?, they need a name?, content.xml and extfile.xml perhaps?
Any orientation will be greatly appreciated
Thanks,
Gabriel.
Answer: Here is a sample server.rxt file I have created.
<artifactType type="application/vnd.wso2-server+xml" shortName="server" singularLabel="Server" pluralLabel="Servers" hasNamespace="false" iconSet="5">
    <storagePath>/servers/@{overview_name}/</storagePath>
    <ui>
        <list>
            <column name="Name">
                <data type="path" value="overview_name" href="@{storagePath}"/>
            </column>
        </list>
    </ui>
    <content>
    <table name="Overview">
        <field type="text" required="true">
            <name label="name">Name</name>
        </field>
        <field type="text" required="true">
            <name label="url">url</name>
        </field>
        <field type="text" required="true">
            <name label="username">username</name>
        </field>
        <field type="text" required="true">
            <name label="password">password</name>
        </field>
    </table>
    </content>
</artifactType>
you need to save this under the directory you have mentioned.
/_system/governance/repository/components/org.wso2.carbon.governance/types
this location is not exits. But you need to create this directory and save.
After restart you should see the new type under meta data list

WS02 G-REG new metadata type


How to interpret Lasso shrinking all coefficients to 0?

Question: I've got a dataset with 338 predictors and 570 instances (can't upload unfortunately) on which I'm using the Lasso to perform feature selection. In particular, I'm using the cv.glmnet function from glmnet as follows, where mydata_matrix is a 570 x 339 binary matrix and the output is binary too:
library(glmnet)
x_dat <- mydata_matrix[, -ncol(mydata_matrix)]
y <- mydata_matrix[, ncol(mydata_matrix)]
cvfit <- cv.glmnet(x_dat, y, family='binomial')

This plot shows that the lowest deviance occurs when all variables have been removed from the model. Is this really saying that just using the intercept is more predictive of the outcome than using even a single predictor, or have I made a mistake, possibly in the data or in the function call?
This is similar to a previous question, but that didn't get any responses.
plot(cvfit)

Comment: @Dhiraj Significant is a technical term related to null hypothesis significance testing.  It is not appropriate here.
Comment: I think this link can flesh out some of the details. In essence, it may mean that many (if not all) your predictors are not very significant. The thread below explains this in some more detail. https://stats.stackexchange.com/questions/182595/how-to-interpret-all-zero-coefficients-in-the-results-of-cv-glmnet
Answer: I don't think you have made a mistake in the code.  This is a matter of interpreting the output.
The Lasso doesn't indicate which individual regressors are "more predictive" than others.  It simply has a built-in tendency to estimate coefficients as zero.  The larger the penalty coefficient $\log(\lambda)$ is, the greater is that tendency.
Your cross-validation plot shows that as more and more coefficients are forced to zero, the model does a better and better job of predicting subsets of values that have been randomly removed from the dataset.  When the best cross-validated prediction errors (measured as the "Binomial Deviance" here) are achieved when all coefficients are zero, you should suspect that no linear combination of any subset of the regressors may be useful for predicting the outcomes.
You can verify this by generating random responses that are independent of all the regressors and applying your fitting procedure to them.  Here's a quick way to emulate your dataset:
n <- 570
k <- 338
set.seed(17)
X <- data.frame(matrix(floor(runif(n*(k+1), 0, 2)), nrow=n,
                       dimnames=list(1:n, c("y", paste0("x", 1:k)))))

The data frame X has one random binary column named "y" and 338 other binary columns (whose names don't matter).  I used your approach to regress "y" against those variables, but--just to be careful--I made sure the response vector y and model matrix x match up (which they might not do in case there are any missing values in the data):
f <- y ~ . - 1            # cv.glmnet will include its own intercept
M <- model.frame(f, X)
x <- model.matrix(f, M)
y <- model.extract(M, "response")
fit <- cv.glmnet(x, y, family="binomial")

The result is remarkably like yours:
plot(fit)

Indeed, with these completely random data the Lasso still returns nine nonzero coefficient estimates (even though we know, by construction, that the correct values are all zero).  But we shouldn't expect perfection.  Moreover, because the fitting is based on randomly removing subsets of the data for cross-validation, you typically won't get the same output from one run to the next.  In this example, a second call to cv.glmnet produces a fit with only one nonzero coefficient.  For this reason, if you have the time, it's always a good idea to re-run the fitting procedure several times and keep track of which coefficient estimates are consistently nonzero.  For these data--with hundreds of regressors--this will take a couple of minutes to repeat nine more times.
sim <- cbind(as.numeric(coef(fit)),
             replicate(9, as.numeric(coef(cv.glmnet(x, y, family="binomial")))))
plot(1:k, rowMeans(sim[-1,] != 0) + runif(k, -0.025, 0.025),
     xlab="Coefficient Index", ylab="Frequency not zero (jittered)",
     main="Results of Repeated Cross-Validated Lasso Fits")

Eight of these regressors have nonzero estimates in about half of the fits; the rest of them never have nonzero estimates.  This shows to what extent the Lasso will still include nonzero coefficient estimates even when the coefficients themselves are truly zero.
Comment: It looks like the model is still performing well even with zero coefficients. What does this say about using cross validation to estimate performance? Mainly referring to this question here: https://stats.stackexchange.com/questions/475502/how-can-a-glmnet-model-with-no-coefficients-have-perfect-performance
Comment: Really insightful answer. "(...)when all coefficients are zero, you should suspect that no linear combination of any subset of the regressors may be useful for predicting the outcomes". Would glmfit not find the best individual predictor nervertheless?
Comment: @Emmanuel This would depend on what "best" might mean and--not to sound too nit-picking--what "find" even means! In the posited situation we should suspect that the data are insufficient for determining reliably which regressors may truly be useful.  That is, there may be a relatively large chance that `glmfit` will identify the *wrong* regressors.
Answer: If you want to obtain more informations can use the function
fit1<-glmnet(x_dat, y, family='binomial', alpha= x)

plot(fit1, xvar = "lambda", label = TRUE)

The graph should be similar to

The labels allow to identify the effect of lambda for the regressors.
Can you use differents value of x ( in the model is called alpha factor) to 0 (ridge regression) to 1 (LASSO Regression). The value [0,1] are the elastic net regression
Comment: Decreasing alpha to 0.5 has helped to include more variables, thanks for the tip.
Answer: It's possible but a little surprising. LASSO can do weird things when you have collinearity, in which case you should probably set alpha<1 so you're fitting elastic net instead. You can choose alpha by cross-validation but make sure you're using the same folds for each value of alpha.
Answer: The answer that there are no linear combinations of variables that are useful in predicting outcomes is true in some but not all cases.
I had a plot like the one above which was caused by multicollinearity in my data.  Reducing the correlations allowed Lasso to work but it also removed useful information about the outcomes.  Better sets of variables were obtained by using random forest importance to screen variables and then using Lasso.
Answer: One possible reason is that the classes are imbalanced in your train and val datasets. Try stratifed sampling to split the whole dataset into train and val subsets. That is, make the event ratios same between train and val.


Android Studio - Button Click Crash (Simple)

Question: I'm brand new to Android Studio and for whatever reason am experiencing really weird errors if I could please get some help.
I have very basic code that is supposed to, on button click change the text of my button from "button" to "clicked!". However everytime I press the button, the app crashes and I get "Appname has stopped" on the emulator.
What is incredibly weird is that in my activity_main.xml Design view, the onClick dropdown shows two functions of the same name (https://puu.sh/t2h5I/42ad4379d6.png)
H owever the code only works when the bottom one is selected. AND each time I run the app, it deselects the bottom one and reselects the top, only to stop working.
Here is my MainActivity:
package com.example.john.ameladay;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    public Button melButtonCode;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void buttonPress(View v){
        melButtonCode = (Button) v;
        ((Button) v).setText("Has been clicked!");

    }
}

Here is my activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.john.ameladay.MainActivity">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/mainText"
    android:id="@+id/textView" />

<ImageView
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:src="@drawable/mela"
    android:id="@+id/melPhoto" />

<Button
    android:text="Button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_toRightOf="@+id/textView"
    android:layout_toEndOf="@+id/textView"
    android:layout_marginLeft="32dp"
    android:layout_marginStart="32dp"
    android:layout_marginBottom="43dp"
    android:id="@+id/button"
    android:onClick="buttonPress (MainActivity)" />

Any help would be greatly appreciated!!
Comment: Please Share Crash report
Comment: Where are you calling buttonPress function?
Comment: use onclicklistner instead of onclick and show toast or anything on your button click like this:
Comment: and first find the id of your button
Comment: melButtonCode = (Button) findviewbyid(R.id.button);
Comment: Do you know accepting an answer...? You can accept one helpful answer. For more information, see help center
Answer: Simple. You should write:
android:onClick="buttonPress"

Why happened
If you wrote buttonPress (MainActivity), Android tries to find buttonPress (MainActivity) method (not MainActivity.buttonPress()), but MainActivity doesn't have buttonPress (MainActivity) method. So the error happened.
Answer: Simply replace this Tag in button
Remove this
android:onClick="buttonPress (MainActivity)"

And Paste This
android:onClick="buttonPress"

Answer: A better way to do it is, get a reference to the button in your Java code using findViewById() method and set an OnClickListener to the button.
For your current problem, use
android:onClick="buttonPress"

instead of
android:onClick="buttonPress (MainActivity)"

Answer: According to me this is the better way to set click on button
public class MainActivity extends AppCompatActivity {

    public Button melButtonCode;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        melButtonCode = (Button).findViewById(R.id.button);//find button by Id
        melButtonCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                melButtonCode.setText("Has been clicked!");
            }
        });
    }
}

For your problem
replace it
android:onClick="buttonPress (MainActivity)"

With
android:onClick="buttonPress"

Answer: Make the method public - protected works when you are in instantrun mode, but not when not. No idea why!
Comment: _Which_ method should be made public?
Comment: Consider adding some code describing which method to make public.


MapKit Annotations Disappearing

Question: I have an array of latitudes and another array of longitudes that I add to an array of type CLLocationCoordinate2D. I then use the new array to annotate multiple points on the map. Some, or most, or maybe even all of the annotations are displaying on the map but as I zoom in (yes, zoom IN), some of the annotations disappear, then come back, or dont.  Any ideas on how to keep them all visible?  This is behavior I would expect while zooming out, not in.
Here is the code i'm using for what i've described above.
import UIKit
import MapKit
import CoreLocation

class MultiMapVC: UIViewController, CLLocationManagerDelegate {

@IBOutlet weak var multiEventMap: MKMapView!

var latDouble = Double()
var longDouble = Double()
let manager = CLLocationManager()
var receivedArrayOfLats = [Double]()
var receivedArrayOfLongs = [Double]()
var locations = [CLLocationCoordinate2D]()

func locationManager(_ manager: CLLocationManager, didUpdateLocations uLocation: [CLLocation]) {
    let userLocation = uLocation[0]
    let span:MKCoordinateSpan = MKCoordinateSpanMake(0.3, 0.3)
    let usersLocation = userLocation.coordinate
    let region:MKCoordinateRegion = MKCoordinateRegionMake(usersLocation, span)
    multiEventMap.setRegion(region, animated: true)
    manager.distanceFilter = 1000
    self.multiEventMap.showsUserLocation = true
}

func multiPoint() {

    var coordinateArray: [CLLocationCoordinate2D] = []
    print ("Received Longitude Count = \(receivedArrayOfLongs.count)")
    print ("Received Latitude Count = \(receivedArrayOfLats.count)")
    if receivedArrayOfLats.count == receivedArrayOfLongs.count {
        for i in 0 ..< receivedArrayOfLats.count {
            let eventLocation = CLLocationCoordinate2DMake(receivedArrayOfLats[i], receivedArrayOfLongs[i])
            coordinateArray.append(eventLocation)
            print (coordinateArray.count)
        }
    }

    for events in coordinateArray {
        let annotation = MKPointAnnotation()
        annotation.coordinate = CLLocationCoordinate2D(latitude: events.latitude, longitude: events.longitude)
        multiEventMap.addAnnotation(annotation)
        }
}

override func viewDidLoad() {
    super.viewDidLoad()
    manager.delegate = self
    manager.desiredAccuracy = kCLLocationAccuracyBest
    manager.requestWhenInUseAuthorization()
    manager.startUpdatingLocation()
    multiPoint()
        }

override func viewDidDisappear(_ animated: Bool) {
    super.viewDidDisappear(animated)
    multiEventMap.removeFromSuperview()
    self.multiEventMap = nil

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

}
Comment: I am experiencing the same issue, it appears to be only present in iOS 11.
Comment: Please share your code of viewFor annotation method
Comment: I updated to include all the code from my VC..  I don't have a viewForAnnotation method though.
Comment: It is still happens on iOS 13.
Answer: NiltiakSivad's solution works but it reverts to the old iOS 10 look. If you want to keep the new iOS 11 balloon markers for iOS 11 and use the old pin look only for older iOS versions then you can implement the delegate method as below:
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
    let reuseIdentifier = "annotationView"
    var view = mapView.dequeueReusableAnnotationView(withIdentifier: reuseIdentifier)
    if #available(iOS 11.0, *) {
        if view == nil {
            view = MKMarkerAnnotationView(annotation: annotation, reuseIdentifier: reuseIdentifier)
        }
        view?.displayPriority = .required
    } else {
        if view == nil {
            view = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseIdentifier)
        }
    }
    view?.annotation = annotation
    view?.canShowCallout = true
    return view
}

Comment: (BTW you should not refer to another answer as "above" or "below", as their order changes depending on their ratings. Instead, you should write "NiltiakSivad's solution". I'll edit your answer accordingly.)
Comment: It's actually probably a bug from Apple, as the default display priority should be `.required` (but it's apparently not!)
Answer: The accepted answer from Leszek Szary is correct.
But there is some fineprint. Sometimes MKMarkerAnnotationViews are not rendered, even if
view.displayPriority = .required

is set.
What you are seeing is a combination of different rules.

MKAnnotationViews are rendered from top to bottom of the map. (It doesn't matter where north is).
If MapKit decides to draw overlapping MKAnnotationViews, then the MKAnnotationView nearer to the bottom is drawn on top (because it's drawn later)
Not only MKAnnotationViews, also titles rendered below MKMArkerAnnotationViews need space. The rendering of those titles is influenced by markerView.titleVisibility. If markerView.titleVisibility is set to .visible (instead of the default .adaptive), then this title is stronger than a MarkerAnnotationView that is rendered later, even if the later MarkerAnnotationView has a displayPriority = .required. The MarkerAnnotationView nearer to the bottom is not rendered.
This even happens if the MarkerAnnotationView nearer to the top has a low displayPriority. So a MarkerAnnotationView with low displayPriority and .titleVisibility = .visible can make a MarkerAnnotationView nearer to the bottom with displayPriority = .required disappear.

I am not aware of a documentation of this behaviour. This is the result of my experiments with iOS 12. My description is sipmplified.
Answer: I was setting annotationView.displayPriority = .required only when the MKMarkAnnotationView was first allocated. Normally thats all you should need to do, but setting it each time the cell was reused fixed the issue for me.
Answer: I was experiencing a similar issue. My best guess is that it has something to do with how iOS 11 detects pin collisions. Implementing a custom annotation view or reverting to use the iOS 10 pin fixed the problem for me.
For example, implementing the following should fix your code:
class MultiMapVC: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {
   override func viewDidLoad() {
       super.viewDidLoad()
       mapView.delegate = self
    }

    func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
       guard let annotation = annotation as? MKPointAnnotation else { return nil }

       let identifier = "pin-marker"
       var view: MKAnnotationView

       if let dequeuedView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier) as? MKPinAnnotationView {
           dequeuedView.annotation = annotation
           view = dequeuedView
       } else {
           view = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier)
       }
       return view
   }
}

If this doesn't work, there is a displayPriority property that is worth looking into as it is responsible for helping to determine when pins should be hidden/shown at different zoom levels. More info at https://developer.apple.com/documentation/mapkit/mkannotationview/2867298-displaypriority
Hope this helps.
Comment: This works!  One thing I noticed is that these pins aren't selectable.
Answer: I was seeing a similar problem with Xcode 10, and iOS 12+ as my deployment target. A post from an Apple staffer (https://forums.developer.apple.com/thread/92839) recommends toggling the .isHidden property on the dequeued marker. That has improved things but has not completely solved the problem.
result?.isHidden = true
result?.isHidden = false
return result

MapKit Annotations Disappearing


eliminar jquery

Question: Como consigo o mesmo efeito em typescript/angular sem utilizar jquery.
$('#divPublicar').mouseenter(function() {
  this.isOnDiv = true;
});

$('#divPublicar').mouseleave(function() {
  this.isOnDiv = false;
});

Answer: Você pode criar uma diretiva, segue exemplo pra deixar o elemento mais escuro quando o mouse estiver sobre ele:
import { Directive, ElementRef, HostListener, Renderer, Input } from '@angular/core';

@Directive({
    selector: '[apDarkenOnHover]'
})
export class DarkenOnHoverDirective {

    @Input() brightness = '70%';

    constructor(
        private el: ElementRef,
        private render: Renderer
    ) {}

    @HostListener('mouseover')
    darkenOn() {
        // aqui você vai colocar o comportamento que você desejar quando mouse estiver em cima do elemento
        this.render.setElementStyle(this.el.nativeElement, 'filter', `brightness(${this.brightness})`);
    }

    @HostListener('mouseleave')
    darkenOff() {
        // aqui você vai colocar o comportamento que desejar quando o mouse deixar o elemento
        this.render.setElementStyle(this.el.nativeElement, 'filter', 'brightness(100%)');
    }
}

Para adicionar a diretiva no elemento basta adicionar o nome dado à diretiva como se fosse um atributo da tag:

Lembrando que é uma boa prática o uso de diretivas para aprimoramento de elementos, segue links de apoio:
Angular Style Guide
O que são diretivas e como usar
Espero ter ajudado.
Answer: Vou deixar um exemplo de como pode ser feito, sendo que existem várias formas de se fazer isto e mostrarei talvez a mais fácil, agora aconselho dar uma estudada antes no Angular e ver como ele funciona, como ele acessa e manipula o DOM, pq isto é o básico, se não está conseguindo fazer esta funcionalidade com Typescript é pq ainda não assimilou os conceitos que precisa para mexer com o framework:
HTML

TS
public isOnDiv: boolean;

Enter() {
   this.isOnDiv = true;
   console.log('ENTROU NA DIV');
}

Out() {
   this.isOnDiv = false;
   console.log('SAIU DA DIV');
}

Pode ver o exemplo funcionado aqui

eliminar jquery


How to calculate that a value falls within a range given another value historically

Question: I have a forecasts for a specific variable and historical actual and forecast values for the same variable.
Let's say that my forecast for the next time period is X, what method can I use to calculate the probability that the actual value will fall within a range of 10% of X given historic performance?
Answer: If you have the probability distribution of $x_t$ given past observations, i.e. $p(x_t|x_{t-1}...x_0)$ you can calculate the probability that $x_t$ is between $0.9X$ and $1.1X$, i.e. within %10 of $X$. In most situations, this isn't readily available, and we estimate it along with some assumptions. There is no single method to do this, and the method of choice doesn't give any guarantees because your data is unique and nobody really knows its underlying distribution unless it's been artificially generated. Markov chains of some order is one simple method to achieve this. But, your forecast method may (not always) also give confidence intervals for your estimates.


Java unmarshalling complex xml into Object

Question:  I tried to unmarshall following xml file.

<ns2:Triggermessage xmlns="http://www.asd.com/messaging" xmlns:ns2="http://www.asd.com/messaging/closing/trigger">

    <creationTimeStamp>2017-05-23T12:11:46.950+00:00</creationTimeStamp>
    <businessDate>2017-05-23</businessDate>
    <messageId>20170523-22:30:00_Calypso Rpt 7_444_0</messageId>
    <conversationId>7397dbd3-5177-40ff-acb5-1b2ba8d0d1f6</conversationId>
    <numberOfRecords>1</numberOfRecords>
    <sentBy>ABCDE</sentBy>
    <sendto>Camplico</sendto>
    <processingCycle>ACD</processingCycle>

  <ns2:Request>
    <ns2:ProcessingCircle>EOD</ns2:ProcessingCircle>
  </ns2:Request>
</ns2:Triggermessage>

Here I created classes in this way.(not all the classes are mentioned here)

**TriggerMessage.java**
 @XmlRootElement(name = "TriggerMessage", namespace="http://www.asd.com/messaging/closing/trigger")
    public class TriggerMessage {

        private Header header;
        private Request request;

        @XmlElement(name = "Header")
        public Header getHeader() {
            return header;
        }
        public void setHeader(Header header) {
            this.header = header;
        }

        @XmlElement(name = "Request")
        public Request getRequest() {
            return request;
        }
        public void setRequest(Request request) {
            this.request = request;
        }
    }

**Header.java**
private CreationTimeStamp creationTimeStamp;
    private BusinessDate businessDate;
    private MessageId messageId;
    private ConversationId conversationId;
    private SentBy sentBy;
    private SendTo sendTo;
    private ProcessingCycle processingCycle;
    private NumberOfRecords numberOfRecords;
@XmlElement(name = "creationTimeStamp")
public CreationTimeStamp getCreationTimeStamp() {
    return creationTimeStamp;
}
public void setCreationTimeStamp(CreationTimeStamp creationTimeStamp) {
    this.creationTimeStamp = creationTimeStamp;
}

@XmlElement(name = "businessDate")
public BusinessDate getBusinessDate() {
    return businessDate;
}
public void setBusinessDate(BusinessDate businessDate) {
    this.businessDate = businessDate;
}

@XmlElement(name = "conversationId")
public ConversationId getConversationId() {
    return conversationId;
}
public void setConversationId(ConversationId conversationId) {
    this.conversationId = conversationId;
}

@XmlElement(name = "messageId")
public MessageId getMessageId() {
    return messageId;
}
public void setMessageId(MessageId messageId) {
    this.messageId = messageId;

 }
-
-
-}

**CreationTimeStamp.java**

 public class CreationTimeStamp {

        private String value;

        @XmlMixed
        public String getValue() {
            return value;
        }
        public void setValue(String value) {
            this.value = value;
        }
    }

  **Request.java**

@XmlType(namespace="http://www.asd.com/messaging/closing/trigger")
public class Request {

    private ProcessingCircle processingCircle;

    @XmlElement(name = "processingCircle")
    public ProcessingCircle getProcessingCircle() {
        return processingCircle;
    }
    public void setProcessingCircle(ProcessingCircle processingCircle) {
        this.processingCircle = processingCircle;
    }
}

and got the object as followsenter image description here
could anyone can mention how I need to create java class correctly to get all the value unmarshall correctly.please note I didn't use package-info.java file here.
This is the code I used for unmarshalling
private List<Object> unMarshalMessages(List<String> messages) {
        List<Object> messageObjects = new ArrayList<Object>();
        JAXBContext context = null;
        try {
            context = JAXBContext.newInstance(Class.forName("com.msgs.calpico.TriggerMessage"));
            Unmarshaller m = context.createUnmarshaller();
            StringReader reader = null;
            for (String message : messages) {
                reader = new StringReader(message);
            messageObjects.add(((com.msgs.calpico.TriggerMessage) m.unmarshal(reader)));
            }

        } catch (JAXBException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        LOGGER.info("After unmarshal the output messages size: " + messageObjects.size());
        return messageObjects;
    }

Answer: Convert the xml into xsd.
After that using eclipse, create jaxb project and point to xsd. java files will be generated based on the xsd file.
Once java schema files are generated, you can use marshall and unmarsahll code.
private static JAXBContext _jaxbContext;
static
{
    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    try
    {
        Thread.currentThread().setContextClassLoader(Connection.class.getClassLoader()); //NOPMD.

        StringBuffer sb = new StringBuffer();
        sb.append("com.microsoft.schemas.windowsazurerm"); //schema package name
        _jaxbContext = JAXBContext.newInstance(sb.toString());
    }
    catch (Exception e)
    {
        logger.error(e);
    }
    finally
    {
        Thread.currentThread().setContextClassLoader(cl);
    }
}

Unmarshaller unmarshaller;
        Object object = null;
        try
        {
            unmarshaller = context.createUnmarshaller();
            object = unmarshaller.unmarshal(new StreamSource(new StringReader(xml)));
        }
Comment: I have edited original post with add the code which I used for unmarshalling.could you please check with it.
Comment: i am unable to find  for (String message : messages)  messages object from where your getting. you can use this code :  Unmarshaller unmarshaller;
        Object object = null;
        try
        {
            unmarshaller = _jaxbContext.createUnmarshaller();
            object = unmarshaller.unmarshal(new StreamSource(new StringReader(xml)));
        }


Ring polynomial kernel generators

Question: This is the textbook question:
Q: Find generators for the kernels of the following maps:

$\mathbb{R}[x,y] \to \mathbb{R}$ defined by $f(x,y) \mapsto f(0,0)$
$\mathbb{R}[x] \to \mathbb{C}$ defined by $f(x) \mapsto f(2+ i)$
$\mathbb{Z}[x] \to \mathbb{R}$ defined by $f(x) \mapsto f(1+\sqrt{2})$

My work:

Any polynomial that satisfies $f(0,0)=0$ will be in the kernel. That includes $f(x,y)=x, f(x,y)=y,f(x,y)=x+y,f(x,y)=x^7y^3 + xy^5$. I'm not sure what polynomial generates this.
The generator of the kernel is $f(x) = x-2-i$. This seems too simple. Is this right?
The generator of the kernel is $f(x) = x-1-\sqrt{2}$. This seems too simple. Is this right?
Answer:
The number of generators can be more than one. Try to convince yourself that in this case the generators are $x$ and $y$.
Not Correct: $x-2-i$ is not an element of $\mathbb{R}[x]$!
Not correct! Observe that the generator must be an element of $\mathbb{Z}[x]$ and $x - 1 -\sqrt{2}$ certainly is not.

Ring polynomial kernel generators


Xgboost cv evaluation metric - unbalanced data

Question: I'm using Xgboost for some binary classification and so it makes sense for me to use log loss as my evaluation metric within cross validation.
My data is highly unbalanced though. Would log loss still be relevant? Is there a better metric for unbalanced data?
Comment: Log loss measures the compatability of estimated probabilities against the true outcomes. Since it is probabilistic, it does not suffer from class imbalance.
Answer: I would recommend using the AUC metric, since you are using xgboost. Also, you can try F1 metric, however it's a custom metric:
<code>def xg_f1(y,t):
    true = t.get_label()
    y_bin = [1 if y_cont > 0.5 else 0 for y_cont in y]
    return 'f1',f1_score(true,y_bin)
</code>
Comment: Since you recommend using the AUC, I assume you believe log loss is not relevant for highly unbalanced data. Is that correct? (Note that that is the OP's question.) Can you explain why unbalanced data makes log loss irrelevelant & how using the AUC addresses that problem? At present, it isn't clear that this is actually an answer to the stated question (I suspect it might be, but it isn't clear).


Concordance vs. Sensitivity

Question: I am confused between these two terms: sensitivity and concordance. What I understand about these two terms:
Concordance: the number of pairs where actual 1s have higher predicted probability of becoming 1s than 0s divided by total number of pairs.
Sensitivity: percentage of 1s correctly predicted as 1.
By their definitions, both seems to be the same.
I have read somewhere that concordance = (true positive  + true negative) / sample size.
I have tried to calculate concordance using this formula. But it seems to be incorrect.
First, I have run logistic regression in SAS using PROC LOGISTIC with the CTABLE PPROB=0.5 options. Then I have calculated true positive pairs from (sensitivity percentage $\times$ number of 1s) and true negative pairs from (specificity percentage $\times$ number of 0s). I added them up and divided by total responses. This is not matching up with concordance score.
Answer: I have always found the Wikipedia article on sensitivity and specificity to quite well summarize the various measures. The formula for concordance you mention above is the same that the Wikipedia article calls accuracy. This is not the same as concordance, which also goes with names c-statistic or area under the receiver operating characteristic curve (AUC). Concordance is also different from specificity. Your formula for the specificity seems to be correct, but the formula for concordance is not.
The difference between accuracy and AUC is that accuracy is measured at a certain cut-off point that was used for dicotomizing the probability distribution given by logistic model whereas AUC measures overall accuracy over a range of cutoff points, so to say.
There's a well written article on concordance in Austin, P. C. and Steyerberg, E. W. (2012). Interpreting the concordance statistic of a logistic regression model: relation to the variance and odds ratio of a continuous explanatory variable. BMC Medical Research Methodology, 12(82):1–8.. The second paragraph of the Background gives several definitions for concordance. There's also some information specifically on the SAS implementation and how to invoke the ROC curve and to produce an AUC value in SAS.

Concordance vs. Sensitivity


In an Angular template, is there a way to throw an error if a variable is undefined?

Question: In Angular templates, if there is an undefined variable in a template, it will fail silently.
Some sample code below:
The controller:
angular.module('app').controller('MyCtrl', function($scope) {
  //nothing here
});

And the view:

{{ data }}

  <input type="text" ng-modal="input">

None of the variables get interpolated because they don't exist on $scope. The mistyped ng-modal (not ng-model) attribute will fail silently. This is undesirable behavior in development.
Is there a way to change that so that errors are thrown? I'd be okay with a monkey-patch solution to Angular for this.
Comment: The answer address the case where `data` is missing. However there is no way to detect that you wrote `ng-modal` other than creating such `ngModal` directive or running some dictionnary based error detector like (with jQuery) `$('[ng-modal]').each( ... )`
Comment: I dont think there is anyway to handle spelling error..If you spell the arribute wrong , you wont see the result. This is only the way
Comment: the real solution now is to just use Angular 2+ :P
Answer: You can make sure a value is selected, by using || in the template. When using || to assign a variable, the first truthy variable will be returned. So in your example:

{{ data || "Data is not defined" }}

  <input type="text" ng-modal="input">

This will have the message change from "Data is not defined" to $scope.data whenever data becomes defined. If you want an error, use the same approach but instead of a string, use a function.

{{ data || handleEmptyData(data) || "Data is not defined and handleEmptyData() also returned undefined" }}

  <input type="text" ng-modal="input">

$scope.handleEmptyData = function(data){
    if(!data){ alert("Error, data was " + JSON.stringify(data)); } };


Basis of the localization of a free module is the localization of its basis?

Question: Let $R$ be a ring and $M$ a free $R$-module with basis $B$. If $P$ is a prime ideal of $R$, is $B_P$ a basis for the $R_P$-module $M_P$?
Comment: A localization can be seen as a tensor product and tensor products behave well wrt free modules...
Comment: Do you know about tensor products?
Comment: @Quimey yes I do!
Comment: @Quimey As in $M_P = M \otimes _ R R_P$?
Comment: yes! That was what I meant
Comment: @Quimey Thanks! that point of view is actually super helpful for me!
Comment: What is a basis of a non-free module? You mean a set of generators or a projective basis or what?
Comment: @QiaochuYuan Woops! I wrote finitely generated when I meant free - thanks!
Answer: Let $f : R \to S$ be an arbitrary homomorphism of rings and let $M$ be a free $R$-module. Then $M \otimes_R S$ is a free $S$-module, and any basis of $M$ is a basis of $M \otimes_R S$. This follows more or less by the universal property of the tensor product together with the universal property of free modules.
Comment: Do you not need $f$ to be injective here?  I understand your claim if $R$ is a subring of $S$, but maybe it is more general as you say.
Comment: @spietro: nope.


Getting error while creating new Angular 2 project

Question: I install AngularJs using the command npm install -g angular-cli and afterwards, when I was trying to create new project, I get the following error,
Cannot find module 'reflect-metadata'

What should I for resolve the error ?
Comment: Make sure you are using npm v3. Have you tried `npm install -g reflect-metadata`? Also take a look at this issue: https://github.com/angular/angular-cli/issues/2431
Answer: I had to reintall nodeJS from their website and install reflect-metadata and portfinder using the following commands while being as superuser,
sudo npm install -g reflect-metadata
sudo npm install -g portfinder

Afterwards, I can create new project using the command,
ng new myProject

Answer: Upgrade npm by npm install -g npm.
If problem still exists try:
npm i -g reflect-metadata
Comment: Try `curl -L https://npmjs.org/install.sh | sudo sh` it will reinstall npm
Comment: After running the command  npm install -g npm, I get the follwoing error,
-bash: npm: command not found
Answer: Re-installing node.js worked for me.


Covariance in system with lagged reverse causality

Question: Is there an easy way to find the covariance between $x_t$ and $\epsilon_t^1$ in a system like
$$y_{t} = \beta x_{t} + \epsilon^1_{t}$$
$$x_{t} = \alpha y_{t-1} + \epsilon^2_{t},$$
potentially under the assumption that $\epsilon_t^1$ and $\epsilon_t^2$ have 0 covariance and each variance 1?
Comment: How do you define $\beta$? Is $\beta:=\mathbb{E}(y_t|x_t)$ or $\beta:=\mathbb{E}(y_t|\text{do} \ x_t)$ or ...? I guess the answer may depend on that.
Comment: I do not understand $\beta:=\mathbb E[y_t \lvert x_t]$ did you mean $x_t\beta:=\mathbb E[y_t \lvert x_t]$ or perhaps $\beta:=\partial \mathbb E[y_t \lvert x_t]/\partial x_t$.  I am not super familiar with Judea Pearl style do-operator.
Comment: What I wrote was simply wrong. I guess I meant $\beta \ \text{such that} \ x_t\beta=\mathbb{E}(y_t|x_t)$. In that case $\epsilon^1\bot x$ by definition and their covariance is 0, is it not? I am also not very familiar with $\text{do}$, so even that part may be wrong. Should I perhaps have written $\beta \ \text{such that} \ x_t\beta=\mathbb{E}(y_t|\text{do}\ x_t)$? But the question is, what $\beta$ are you interested in?
Comment: Yes it follows from $\mathbb E[y_t \lvert x_t] = x_t \beta$ that $\mathbb cov[x_t\epsilon_t]=0$. I think I need to think more and then maybe update the question.
Answer: If you assume zero covariance between $\epsilon^1_t$ and $\epsilon^2_t$ as well as between $y_{t-1}$ and $\epsilon^2_t$, then $\beta$ is identified by a regression of $y_t$ on $x_t$ and $y_{t-1}$. This then identifies $cov(x_t, \epsilon^1_t) = cov(x_t, y_t - \beta x_t) = cov(x_t, y_t) - \beta var(x_t)$.
If you assume zero covariance between $\epsilon^1_t$ and $\epsilon^2_t$ as well as between $y_{t-1}$ and $\epsilon^1_t$, then $cov(x_t, e^1_t) = cov(\alpha y_{t-1} + \epsilon^2_{t}, \epsilon^1_t) = 0$.


Executar 2 `SUM` em um `UPDATE`

Question: Bom estou tentando fazer o SUM de dois campos diferente e dar um UPDATE em uma outra tabela.
Estou fazendo assim:
 UPDATE
        pedidos a
    SET
        custo = (
            SELECT
                case when SUM((b.qtd - b.qtd_devolucao) * b.custo) is null then '0' else SUM((b.qtd - b.qtd_devolucao) * b.custo) end  AS total
            FROM
                produtos_pedidos b
            WHERE
                b.id_pedido = a.id
            )
        valor = (
            SELECT
                case when SUM((b.qtd - b.qtd_devolucao) * b.valor) is null then '0' else SUM((b.qtd - b.qtd_devolucao) * b.valor) end  AS total
            FROM
                produtos_pedidos b
            WHERE
                b.id_pedido = a.id
            )
    where
        id = '2'

Porém o mysql me retorna um erro de sintaxe no segundo SUM.
Se eu fazer as query separadas elas funcionam, exemplo:
    UPDATE
        pedidos a
    SET
        custo = (
            SELECT
                case when SUM((b.qtd - b.qtd_devolucao) * b.custo) is null then '0' else SUM((b.qtd - b.qtd_devolucao) * b.custo) end  AS total
            FROM
                produtos_pedidos b
            WHERE
                b.id_pedido = a.id
            )
    where
        id = '2'

    UPDATE
        pedidos a
    SET
        valor = (
            SELECT
                case when SUM((b.qtd - b.qtd_devolucao) * b.valor) is null then '0' else SUM((b.qtd - b.qtd_devolucao) * b.valor) end  AS total
            FROM
                produtos_pedidos b
            WHERE
                b.id_pedido = a.id
            )
    where
        id = '2'

Bom acho que para ficar mais eficiente fica melhor eu juntar as query, é possível fazer isso?
Answer: Faltou uma vírgula ,, após o fechamento dos parenteses do select do campo custo:
    UPDATE
        pedidos a
    SET
        custo = (
            SELECT
                case when SUM((b.qtd - b.qtd_devolucao) * b.custo) is null then '0' else SUM((b.qtd - b.qtd_devolucao) * b.custo) end  AS total
            FROM
                produtos_pedidos b
            WHERE
                b.id_pedido = a.id
            ),
        valor = (
            SELECT
                case when SUM((b.qtd - b.qtd_devolucao) * b.valor) is null then '0' else SUM((b.qtd - b.qtd_devolucao) * b.valor) end  AS total
            FROM
                produtos_pedidos b
            WHERE
                b.id_pedido = a.id
            )
    where
        id = '2'

Comment: Hahahah e mesmo, obrigado.

Executar 2 `SUM` em um `UPDATE`


How to express a sentence having two for all?

Question: I want to write a sentence in a journal but the sentence has two 'for all's.
For example,

The variable $x$ is the smallest number such that $f(\zeta x) \le g(a)$ for all $\zeta\in[0,10]$ and for every $a\in A$.

Is it fine if I write like the above?
Another cases are

The variable $x$ is the smallest number such that $f(\zeta x) \le g(a)$ for all $\zeta\in[0,10]$ and $a\in A$.
The variable $x$ is the smallest number such that, for all $\zeta\in[0,10]$, $f(\zeta x) \le g(a)$ for every $a\in A$.

What is the best expression among them?
If you know better expression, please let me know. Thank you.
Comment: Why wouldn't it be fine? All are understandable. I like the second best as it's the shortest and clearest; the last one confuses me. This question is opinion based (although I suspect most people will tend to like the second version best).
Comment: @k.stm I am worried whether or not the second one implicitly expresses that the constraints are satisfied FOR EVERY $a$ in a set $A$.
Comment: I would definitely read it thay way. Otherwise, I'd expect to see "and *some* $a ∈ A$". To make that explicit, you could also write "for all $ζ ∈ [0..10]$ and all $a ∈ A$", which is still very short.
Comment: @k.stm I got it. Thank you
Answer: The key to good writing is clarity and simplicity. One way to achieve this is to group things together. Consider the following format:
"... such that [list of statements] for every [list of definitions]."
As we naturally like to group things, using this format which groups definitions and statements together makes it easy for us to understand what it is conveying.
To answer the above questions, All three expressions are clear and okay to use. Of the three expressions above, the second one is the easiest to understand.
Comment: Thank you for answering. I usually group things together. In this case, however, I do not want to group them since their characteristics are too different. I will use the second one. Thank you.
Answer: Your second sentence is not so good as it is more asymmetric and will make people thing that the status of $\zeta$ and $a$ differ. The first is fine.
If you want to stress dependency on two variables, you can also write

The variable $x$ is the smallest number such that $f(\zeta x) \le g(a)$ for all $\zeta$ and $a$, subject to $\zeta\in[0,10]$ and $a\in A$.
Answer: Are you sure you really mean this? If we are talking only about nonnegative $x$ here then the smallest $x$ satisfying your condition (if there is such an $x$ at all) is $0$.
You could save one "for all" by writing "Let $x_*$ be the smallest (?) $x\geq0$ satisfying
$$f(\zeta x)\leq \inf_{a\in A} g(a)$$
for all $\zeta\in[0,10]$."


Instance level access on AWS?

Question: I want to give full access on AWS EC2 instance for a single instance, and deny any action on other instances.
Can it be done ?
Thanks.
Comment: SSH access, or AWS Console access?
Answer: Based on the edited question, the answer is yes.
You restrict access to the AWS console using IAM. If gives you detailed control on what individual users or groups can do. For example you can say "John can restart all instances tagged production but only between the hours of 8pm and 5pm". You can control access to individual resources or groups of resources, services, functions within services, etc.
You can also federate users with existing directories, and give temporary credentials. I'm not going to give more detail on that because it's an advanced topic and your question is fairly simplistic.
If you want to control ssh access to an EC2 instance, create users on that instance using standard Unix mechanisms, ideally requiring certificate authentication. Don't give out the certificate for the ec2-user that AWS creates for you, create new users and new certificates. A tutorial like this will walk you through it.
Comment: It's also worth mentioning that any user on the server will also have access to any IAM instance roles that the machine is provisioned with, unless steps are taken to specifically deny that network traffic.
Comment: ok, how can I achieve giving full access for instances with a certain tag only, and prevent it for the rest.
Comment: Example here http://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_examples.html#iam-policy-example-ec2-tag-permissions  . Note that AWS documentation is extensive, Google is a very effective way to work most things AWS out.

Instance level access on AWS?


How to make this more compact? JQuery image slideshow on hover (video thumbnail preview)

Question: I made this video preview slideshow function.
Im new to jquery so i was wondering if there was a better way to do this, it feels clumsy to just have a separate "timers" for each frame and would mean that the number of frames couldnt be changed.
Or is this fine?
Tequila bottles for the sake of demonstration.

$(document).ready(function() {
    var delay=1500, setTimeoutConst;
    $('.image').hover(function(){
            var id = '#' + this.id;
     setTimeoutConst = setTimeout(function(){
            $(id).addClass('hover');
            $(id).attr('src', 'https://cdn8.bigcommerce.com/s-u9ww3di/images/stencil/1280x1280/products/6589/10932/adictivo-botella-anejo-750ml-40alcvol-hd-medal-transparent__55529.1522775464.png');
        }, delay);
   },function(){
 clearTimeout(setTimeoutConst );
   });

    var delay2=3000, setTimeoutConst2;
    $('.image').hover(function(){
        var id = '#' + this.id;
     setTimeoutConst2 = setTimeout(function(){
            $(id).attr('src', 'https://products1.imgix.drizly.com/ci-hornitos-reposado-tequila-73ca9c69a1974b3b.jpeg');
        }, delay2);
   },function(){
 clearTimeout(setTimeoutConst2 );
   });

    var delay3=4500, setTimeoutConst3;
    $('.image').hover(function(){
        var id = '#' + this.id;
     setTimeoutConst3 = setTimeout(function(){

            $(id).attr('src', 'https://www.wallywine.com/media/catalog/product/cache/1/image/1800x/9df78eab33525d08d6e5fb8d27136e95/1/2/12183.jpg');
        }, delay3);
   },function(){
 clearTimeout(setTimeoutConst3 );
   }),

    $('.image').mouseleave(function(){
            $(this).removeClass('hover');
            $(this).attr('src', 'http://www.hellowcost.fr/4806-large_default/tiscaz-gold-tequila-35-70-cl.jpg');
    });
});
.image {
    height:100px;
}

  <title>Page Title</title>

Answer: I've modified your example code and trimmed out some unnecessary bits, and reduced it to one timer so it's cleaner and easier to modify (which I guess was your point).
Firstly it initialises a few variables.  One to store the interval ID (rather than multiple timeouts), an image index so the function knows which image to show next, and then an array of image urls.
The hover function creates the interval and then saves the image's src attribute as a data attribute of that image (so you can set it back to the original image later).
The interval adds 1 to slideshowIndex, and sets it back to 0 if it reaches the length of the image array.  This means you can add images to the array (or remove them) and it will always loop correctly.  You'll never have to change the interval function when you change the list of images in the array (which I assume may be dynamic).
All that's left is to handle the hover off function, which clears the interval and sets the image back to its original src.
I left the add & remove hover class code there in case you use it, but it does nothing in this example.

$(document).ready(function() {
    var slideshowIntervalId = 0;
    var slideshowIndex = 0;
    var slideshowImages = [
        "https://cdn8.bigcommerce.com/s-u9ww3di/images/stencil/1280x1280/products/6589/10932/adictivo-botella-anejo-750ml-40alcvol-hd-medal-transparent__55529.1522775464.png",
        "https://products1.imgix.drizly.com/ci-hornitos-reposado-tequila-73ca9c69a1974b3b.jpeg",
        "https://www.wallywine.com/media/catalog/product/cache/1/image/1800x/9df78eab33525d08d6e5fb8d27136e95/1/2/12183.jpg"
    ];

    $(".image").hover(function() {
        var $image = $(this);
        $image.addClass("hover");
        $image.data("original-src", this.src);
        slideshowIntervalId = setInterval(function() {
            slideshowIndex = ++slideshowIndex % slideshowImages.length;
            $image.attr("src", slideshowImages[slideshowIndex]);
        }, 1500);
    },
    function() {
        $(this).removeClass("hover");
        this.src = $(this).data("original-src");
        clearInterval(slideshowIntervalId);
    });

});
.image {
    height:100px;
}

  <title>Page Title</title>

Comment: Thanks - glad you like it.  It does raise some questions for me, like how you're planning on actually using it.  If there's more than one instance of this on a page then it will need changing to suit that, for example.  It all depends on the final use case, which I don't know so I've just answered the question as asked.
Comment: I also just noticed I'd left some unnecessary code in there, so I've removed it.
Comment: Oh if youre still wondering, i edited it a bit so i could use it with multiple sets of images on different instances.                                                                                `$(".thumbnail").hover(function() {
     var id = "http://mywebsite.com/thumbnails/" + this.id;
     var slideshowImages = [
      id + "_1.jpg",
      id + "_2.jpg",
      id + "_3.jpg",
      id + "_4.jpg",
      id + "_5.jpg",
      id + "_6.jpg"
     ];`


Accessing a variable outside of class

Question: Suppose I have two classes built of constructor method. Can I access the variables of those classes by defining a function outside? Example:
class MyCat1():
    def __init__(self, weight1, speed1):
    self.weight1 = ...
    self.speed1 = ...

class MyCat2():
    def __init__(self, weight2, speed2):
    self.weight2 = ...
    self.speed2 = ...

def run(self, weight1, weight2, speed1, speed2):
    self.sum = weight1.speed1+ weight2.speed2
    x = self.sum
    return x

Comment: No, you access *instance attributes* via *an instance of the class*. What exactly are you actually trying to do?
Comment: This doesn't really answer your question, but there's not much point in writing two individual classes that are identical except for attribute names. Why not have a single `MyCat` class that has `weight` and `speed` attributes, no numbers required? You can make more than one instance of a single class, of course.
Comment: That's just an example. My question is can I define two classes for two separate objects and define a function which will have attributes from both classes and that is outside of both classes?
Answer: I think this is closer to what you're shooting for. You just need to define your class one time, then you can make as many instances of it as you'd like.
class MyCat():
    def __init__(self, weight, speed):
        self.weight = weight
        self.speed = speed

This is a free function, and therefore has no self, so you can just pass in instances of MyCat to work with. You can call the attributes weight and speed off the instances.
def run(cat1, cat2):
    return cat1.weight * cat1.speed + cat2.weight * cat2.speed

For example
>>> cat1 = MyCat(5, 10)
>>> cat2 = MyCat(3, 5)
>>> run(cat1, cat2)
65

Answer: I would make a single Cat class and keep the method in the class and pass the instances to the method:
class Cat(object):
    def __init__(self, weight, speed):
        self.weight = weight
        self.speed = speed

    def run(self,other):
        return self.weight * other.weight + self.speed * other.speed

cat1 = Cat(2, 2)
cat2 = Cat(3, 3)

print(cat1.run(cat2))
12

There is no point creating pretty much identical classes and it would get quite arduous if you decide to have 100 cats.

Accessing a variable outside of class