What are the advantages of learning to play on your own versus learning from a teacher?

Question: Ok, as a new learner I have started by watching Learn and Master Guitar lessons, using other web tutorials, and whatever other resources I can find on the internet.
Do you believe that this way is OK for someone who wants to learn guitar? Or do I have to go to a local guitar teacher? What are the advantages of learning from a teacher, as opposed to learning on your own?
Comment: -1 WAY too subjective.  See http://blog.stackoverflow.com/2010/09/good-subjective-bad-subjective/
Comment: grab a guitar and start playing
Comment: This would be a great question, but the OP has used 'best'.
Comment: An excellent question! Im also doing the same. Btw thanks for allowing this question guys.
Comment: Legacy's course is the best alternative to having a GOOD teacher to go to.
Advantages of self training: you set the pace, you determine what to do
Disadvantages of self training: you set the pace, you determine what to do

And yes, both can be both advantage and disadvantage
Comment: I can't imagine not having a real-life teacher for this. Still be best way to come into a lesson is to be hungry for more.
Comment: In my opinion the biggest advantage to having a teacher is in the very beginning stages of learning proper technique.  Picking up bad habits from teaching yourself the wrong way can limit your potential in the long run- bad habits are pretty hard to un-learn once you have been playing a while. So if you don't get a teacher, just make sure you pay close attention to the physical aspects- how you hold the guitar, how you fret/strum, etc. It might help to ask some advice from any experienced players you know. Once you get the proper technique down, you can teach yourself the more advanced stuff.
Answer: It depends on the route you want to go. Some people say a guitar teacher is necessary... I would say not. Plenty of the most well known guitar players in the world on not trained by a teacher.
Think about the music you want to play.
Almost anything in the blues/rock world can be self-taught. There is not a right way to play the blues, no matter what the elitists tell you. And rock (sometimes) is a natural extension of blues.
Now if you want to break into classical or metal, you will need to learn some classical techniques. Know your scales, chords, and how to improvise in a technical setting. There are, however, parts of the metal world where unconventional playing is welcome, and even encouraged. Such as funk metal.
My advice is this:
If you plan to go into a technical music genre, get yourself a teacher and learn to do things the "right" way, so that you can play with others freely when you get good enough.
If you want to play by yourself, or are going to stick to less classically influenced music types, just head over to youtube!
I learned guitar for about 3 years on nothing but youtube videos and a chord book. There was a particular guitar player that I admired at the time and I just watched live videos of him and imitated what I saw. Overtime, I became proficient with the guitar and started writing my own songs. I believe this is a very creative and enjoyable route if you're willing to not be taken seriously by more technical bands and guitarists.
Regardless of what you choose. Make sure you spend time learning the songs you love as early as possible. Nothing kills the learning motivation like playing stuff that does not interest you.
Comment: I think that you don't need a teacher to learn the "right" way, you need a teacher to learn not to do the "wrong" way.
It helps to prevent bad habits and to learn easier ways to play. I learned much more in 1 year with a teacher than 3 years alone.
Comment: @Kayle How much time did you practice? Do you have a blog where you kept track of your progress?
Comment: @Mugen - Unfortunately, I was not "intentionally" learning guitar at first, so I didn't think of blogging the journey. Would have been cool though. I practiced roughly 2 hours a day at first... 1 hour, twice per day. Not strictly, that's just how it worked out.

After my fingers toughened up, I started playing 3 hours a day, usually. It becomes very very fun after you get past the initial playing barrier.
Comment: @Kayle Wow I wish I had that kind of dedication. I started with what must have been 1-2 hours a day but after a few months got bored of my slow progress. I finally sat down one day and played the songs I always wanted to play on guitar - it was very slow and didn't sound perfect. I guess that was the last I ever played, hehe.
Comment: Just wanted to underline the last sentence in Kayle's excellent answer. Practicing stuff you like or WANT to get to grips with is paramount to retain your enthusiasm !
Comment: I disagree with your penultimate paragraph. Self taught musicians can indeed be taken seriously. Pink Floyd's keyboardist was self taught. You didn't say that no one would not be taken seriously, but I do not agree that being self taught means that you have to be willing to not be taken seriously. Other than that, I agree with you.
Answer: Like many other people here, I am self-taught (on the banjo, about to self-teach on guitar). However, I used to take piano lessons. Things to consider:

A teacher knows what you might spend hours trying to learn from the internet. Think about the time you'll spend hunting down that information vs. the time you spend to earn the money to pay the teacher. Which "costs" more? Time is money.
A teacher can point out details you would likely never notice yourself, such as how you hold your hand/fingers. Many of these seemingly minute details become very useful later at a higher level of skill.
Taking lessons or not, practice will be the main thing that makes your skill. No teacher can change that.

Lastly, keep in mind that you don't have to take weekly lessons. It's perfectly OK to self-teach for a month, then book a 1 hour lesson to get pointers on your technique, areas for improvement, and suggestions on exercises.
Answer: Take lessons with a teacher. End of story. You will learn so many bad habits and progress very slowly on your own. If you are serious about learning to play at all, take lessons. Once you reach a certain level (depending on age, practice, etc), you could teach yourself. But there's so much to learn in the beginning, a good teacher will really be worth your money.
Comment: @holms - It sounds to me like you haven't met any good teachers. I learned piano from a teacher who was inflexible, and I ended up teaching myself to play. However, several years later, I learned guitar from two excellent teachers.
Comment: not very argumented answer, can your teacher teach you to play better then him? Can't he teach you how to learn guitar by your self instead of someones fantasies? My best friend was my first guitar teacher, you know what? I'm playing 100x better then him now =), NOw that's what I call a good teacher. He teached me to LEARN GUITAR BY MYSELF. That's how you become a pro of your bussiness.. what's the poing of taking all experience from one man? You will be a clone of that man, that's it.. where's you personality in guitar =)? This won't born because of good teacher belive me=)
Comment: no man thnx. Teachers sux. I'm playing better then all teachers I know, just because I learned my self. All things that they learn, most of them are gained my experience and there fantasies... I have my own story and experience. I had few teachers just to grab the best there invented methods. Just for that, by definitely not for LEARNING basics, I would never play like that in my life, I i'd be learning for what they say. Every guitar player has it's own way to go ALONE!
Comment: Too many bad teachers out there... If you find a good one, you're better off than with (solely) self training books/videos. If not (and for most people that's the reality) you're better off on your own.
Comment: big +1. Learning music is a human interaction and the odds are much more in your favor if you have a real teacher.
Comment: Sorry but I just don't agree with this answer. Do you think all great guitarists had lessons? probably not. I'd also draw on my own experience and many other guitarists I know:  Never had a lesson. I do ok ;-) I agree that having lessons will speed things up but "Take lessons with a teacher end of story" doens't sit well with me at all. I think by finding your own way it leaves more room for finding your own style. I also have seen that guitarists taught at the same school all sound very similar.
Comment: Never had lessons - but I've been playing 20 years and I'm still not all that good. I'm certain if I'd had a teacher I'd have improved 10 times faster.
Answer: The only way to get better at something is practice! Don't get discouraged if you feel as if you're not making much progress - practising every day (not necessarily for hours and hours at a time) will help you improve enormously.
Comment: Not enormously, but just a little everyday ;) a little times 365 times X years = enormous ;)
Answer: The best thing I have ever done on my own is buy The Amazing Slow Downer. It lets you slow down a song you want to learn, and play along at a much slower place. I was playing along to Metallica in my first month.
I do think a local teacher is key. It gets you to the next level, because you can't even tell what mistakes you're making.
Comment: "Best practice" does the same and it's free : http://www.xs4all.nl/~mp2004/bp/
Comment: If you have an iPhone or iPad, [Capo](http://itunes.apple.com/us/app/capo/id386963803?mt=8) is a good alternative to The Amazing Slow Downer.
Answer: Learning by yourself is fun, and I did that for many years, but you can easily become stuck in a rut and just keep going over the same old stuff because it is comfortable for you.
I have recently approached a teacher after many years of being self taught, and it has really helped to 'push' me to the next level.  A good teacher will take you out of your comfort zone and stretch you to become a better player.  For example, I was always very familiar with the actual notes on the fretboard on all strings within the first 5 frets, but never bothered to become intimately familiar with the notes from the 6th to the 12th frets.
At my very first lesson, my teacher pushed me to learn those well in preparation for upcoming lessons where I will be breaking out of my pentatonic box habits and learning triads.
It certainly wasn't easy for me, but I pushed myself, and now have a much better familiarity with the fretboard than I have had in 20 years of playing.  I couldn't believe that I hadn't committed myself to learning that information before.
Answer: A pretty decent video method to learn how to play guitar I've been recommended is the Metal Method
Don't let the looks of the guy or name of the method think it's all for Metal learning, it's a general, down to the basics kind of method that so far has brought a few of my friends to a pretty decent level in no time.
Comment: I am a casualty of the Metal Method dating back to the late 1980s. The course offers little in the way of counting time. I learned great tricks and licks, but cannot play with a band to this day.
Answer: Study both music and the guitar at the same time.
I found playing the keyboard and a couple of youtube videos by Andrew Furmanczyk particularly helpful to learning about music theory and chords while I was learning.
Answer: To answer the question:  the biggest advantage to learning by yourself is the time-freedom and independence of thought.  You are the master of yourself.  You set the exercises and practice.  You set your own goals.  You judge yourself.
This ultimately means you must be 100% critical of your practise / performance.  It is not enough simply perform an exercise and complete it.  You must be critical of every nuance of your physical being as well as judge with your ears to listen to your performance.
Recording yourself is a great way to develop this.  Don't ask your family to judge you!  You have to develop your own personal Simon Cowell critic in your brain.
Ultimately, this leads back to the BALANCE between learning by yourself and having a COACH or TEACHER.   Personally, I see a big difference between the two.  When I think of a TEACHER, this usually is a person who is INSTRUCTING YOU on something that you do not yet master.  They are able to give you pointers as to correct execution and give you a level to strive towards in terms of execution and delivery.
A COACH can provide the same thing, but I believe that a COACH should be helping you discover more about yourself and your own limitations.  This doesn't necessarily have to be an airy-fairy/fuzzy/soft subject:   It can be physical/technical limitations, it can be mental/emotional limitations and any combination within.  These are things that are much better dealing with someone who can coach you towards higher levels of skill as well as higher levels of self.
The beauty of this is that the best coach to begin with is yourself - if you know how.
It's best to start with the premise that no one can motivate you to be better than the best coach in the world - yourself!
Answer: I'm a professional guitarist, and I've been teaching guitar for the past 41 years.
Advantages of learning on your own

It's cheaper
it's not a fixed time commitment (you don't have to be there every Thursday or whatever)
You'll only be playing music you like

Disadvantages of learning on your own

You don't know what you don't know.  It's easy to do something intuitively that will hamstring you later on in terms of posture, finger position and hand placement, pick grip,etc - and bad habits can be hard to break.
Because you don't know what you don't know, you'll probably not be giving enough attention to some of the fundamentals of music.

Advantages of learning with a teacher

The teacher will (or at least should) develop a plan to get you from point A to point B.  Skills will be sequenced, because they do build on each other.
A teacher will expose you to concepts and music that you might not discover on your own.
Many teachers can give you a new perspective on things you find daunting.  I experienced more than a few "AHA!" moments with my teachers.

Disadvantages of learning with a teacher

There are more than a few teachers out there who don't know what they're doing.  Teaching is an art that combines knowledge, communication skills, and motivation.  I had a couple or three teachers in my life that in retrospect were a waste of time, and in one case probably set me back a bit.
Answer: In the past, utltimately virtuoso ethnic musicians learned directly from each other by ear - and more often than not couldn't read a single note. Today, their descendants short-cut this process, learning from slowed-down recordings. This is the basis of much learning amongst, for example, Irish session or Balkan dance musicians. Often, and though having a repertoire of thousands of tunes, they will be unable to tell you the name of the one they are playing.
Music notation may have it's uses, but shoves a massive cognitive load between you and your passion. Learn to distinguish between learning music and learning how to RTFM..
Instead, trust your memory. Learning by ear, your fingers will find a way of playing that simply works. You will remember how to play a piece the instant you (re)hear it.
Become active in a playing musical community (session/jam/dance), and above all, play with others. Good players will provide simple, ongoing correction. The rest will look after itself.
Answer: It depends, for me what I did was I learned guitar on my own through youtube videos, and if it is fast enough I tried to download it using Video Surgeon, it is also economical to learn on your own, guitar teachers also do like this, so might as well learn from self.
Answer: While teachers are certainly helpful for learning at first, you are the person that knows yourself the best. Learning on your own may create bad habits that can affect your playing in the long run, but teachers can correct things like that.
However, certain teachers may stifle your potential by assigning you pieces that do nothing to address the problems that you have, or by moving too quickly or slowly. But teachers may also help you to get out of your comfort zone and learn things you wouldn't have done on your own.
In the end, it really depends on how you learn as opposed to how your teacher teaches.


routing traffic from production server to honeypot

Question: I'm trying to direct malicious traffic intended for my production server to my honeypot. I have 3 VMs for now : A router running with Snort in inline mode, a Production server(debian) and my kippo honeypot. I'm very new to this and I'm looking for ways to filter out bad UDP traffic and then route it to my honeypot. Any help will be appreciated! Thanks in advance.
Comment: Have you considered configuring port forwarding at your NAT so that ports you are offering are directed to the legit server and everything else is forwarded to the honeypot?
Comment: @DavidHoelzer thank you for replying. I'm not sure if what I'm thinking is correct, but isn't an attack also possible on the ports that I'm offering?Is there a way to first filter out the traffic on those ports and then route the illegitimate traffic to the honeypot? I'm particulary interested in DoS/DDoS attacks.
Comment: Sure it is... but it will be more difficult to dynamically route that traffic to the honeypot.
Comment: @DavidHoelzer what are the possible options? Is it possible any way by using snort (using it on a VM that I created which acts as a router)?
Answer: I'm not aware of a current project that does this, but "baitnswitch" is a much older project that sought to accomplish it.  You could certainly do something like the following, however:

Snort runs (either inline or not), generating alerts
A log analysis process watches for particular alerts or high priority alerts
When a high priority alert is seen, an iptables rule is inserted that dynamically NATs the inbound packets from that source to your honeypot

None of this would be difficult.  The only warning that I will give you is that when your iptables firewall gets several thousand rules in it, your kernel will start to explode randomly.  It's a super good idea to periodically flush these rules out to prevent this from happening.
Comment: Thank you so much for your answer! I did try my hands on baitnswitch, it somehow did not work for me. I got some errors and since it was an older project I had no way of asking my doubts from anyone. Being very new in this field means I am not always sure how things work, so I read and try to implement. I would definitely take up your advice and would read into how can I implement this in my project. Really appreciate your help!
Comment: Upvotes are appreciated. :) If you run into specific issues implementing this, feel free to add a comment here as that's the most likely way to attract my attention; I don't look at the [snort] tag often.
Comment: Hey @DavidHoelzer , I was wondering if we can add custom iptable rules in fwsnort and psad? I know they can accept and reject packets when they match the ruleset but can it also forward packets to a honeypot?


Bias in bagged decision tree estimates of probability (classification)

Question: As far as I understand it, random forests are as biased as any tree in the forest.  Bagging a non-random forest (using all available variables at any given split) is unbiased -- bias in random forests comes from sampling the independent variables.
However, is
$$
\widehat{pr}(y)_{bagging} = N^{-1}\displaystyle\sum_{trees}vote(y=1)
$$
a unbiased measure of the probability of $y=1$?
The following suggests not:
par(mfrow=c(1,1))
    N=3000
    x = rnorm(N)
    yt = pnorm(x+rnorm(N))
    y = as.factor(yt>.5)
    m = randomForest(y=y,x = cbind(x),mtry=1)
    yhat = predict(m,type='prob')[,2]
plot(yt,yhat)
abline(lm(yhat~yt),col='red',lwd=2)

Am I missing something?  I ask because I've recently heard some loose talk about bagging replacing nonparametric regression in contexts where causality is important.
Comment: Can you please add the plot you obtained with your code?
Answer: [Edited] Oh very important detail. I guess you intend to verify that the a RF estimate produce similar probabilistic predictions as an unbiased normal distribution estimate. But you define $y_t$ = pnorm(x + rnorm(N)), instead of $y_t$ = pnorm(x). Then the unbiased normal distribtion estimate is 'over fitted'.
Your RF model is also overfitted. The single trees of your ensemble are fully grown and overfitted (of course). To ensure the ensemble is not also overfitted, RF algorithm make use of both bootstrapping and random variable subspace to grow decorrelated trees. In this rather special case (1 feature + 50% noise component), it is difficult to grow adequately decorrelated trees. Then, default random forest hyper parameters are not favorable. You can either grow more robust trees by increasing terminal nodesizes or by decorrelating trees further by bootstrapping fewer observations for each tree.
Bias (understood as lack-of-fit) in random forest certainly also comes the trees themselves, if the data structure contains a curvature which is difficult for trees to fit (e.g. saddle points or spherical class borders in feature space).
library(randomForest)
par(mfrow=c(1,1))
#make data
N=3000
x = rnorm(N)
y.value = x + rnorm(N) #training and raw variable
yt = pnorm(x)
y = as.factor(y.value>0)

#tune sampsize
sampsizes = c(2,2*c(2:25)^2,1500,2000,2500)
oob.prob.cor.sampsize = sapply(sampsizes,function(i) {
  m = randomForest(y=y,x = cbind(x),mtry=1,sampsize = i)
  plot(x=yt,y=predict(m,type="prob")[,2],main=paste("sampsize=",i),xlab="yt",ylab="yhat") #movie time
  cor(y.value,predict(m,type="prob")[,2])
})
plot(sampsizes,oob.prob.cor.sampsize,log="x",type="p",main="sampsize")

#...or tune nodesize
nodesizes = c(1:5,6,8,10,15,20,25,50,100,250,500)
oob.prob.cor = sapply(nodesizes, function(i) {
  m =randomForest(y=y,x = cbind(x),nodesize=i)
  plot(x=yt,y=predict(m,type="prob")[,2],main=paste("sampsize=",i),xlab="yt",ylab="yhat") #movie time
  cor(y.value,predict(m,type="prob")[,2])
})
plot(nodesizes,oob.prob.cor,log="x",type="p",main="optimal nodesize")

.
Comment: Thanks for the answer.  Eyeballing your plot of yt vs yhat.samp, it appears that you can approach closer to an unbiased estimate.  But it doesn't appear that $E(\hat{y}_{samp}) = y_t$ (or does it?).  I wonder if there are any conditions under which the estimator can be made consistent, if it can't be made unbiased?
Comment: @generic_user  I updated the answer. Now, RF can produce a very similar estimate.
Comment: That's interesting.  I wonder if there is something general here.


Methods for evaluating partial autocorrelation for identification of ARIMA models

Question: I am trying to programmatically identify an ARIMA model for a series of data and forecast values.
Currently the problem i am facing is to find a way to evaluate partial autocorrelation. I have been looking for methods to calculate PACF for quite a long time now but in vain.
Please provide some online resources which can help me in this matter.
Thank you.
Answer: Use the Durbin-Levinson algorithm. It will be explained in any good time series book such as Brockwell and Davis. Here are some online explanations:

http://www.stat.ufl.edu/~berg/sta4853/files/sta4853-4.pdf
http://amath.colorado.edu/courses/4540/2008Spr/HandOuts/DurbinLevinson.pdf
Answer: You may also be interested in the 'auto.arima' function in the forecast package for r as an example of a way to programmatically identify ARIMA models.  It probably doesn't find the model in the exact same way you would, but some of the code/ideas might be useful to you.


How to solve an equation with the sum of minima numerically?

Question: The equation is given by
$$ \sum_{n=1}^N \min(\gamma, \beta a_n)=N$$
where $\beta$ is the variable with $\beta\in[0,\sqrt\gamma/\min(a_n\mid a_n>0)]$, $ \gamma   $ is a constant with $1\le\gamma\le N$, and $a_n$ is an nonnegative constant.
I know that the function $f(\beta)=\sum_{n=1}^N \min(\gamma, \beta a_n)-N$ is strictly increasing. Also, $f(0)<0 $ and $ f(\sqrt\gamma/\min(a_n\mid a_n > 0 )) > 0$. Thus, there must exist an unique solution for the above equation. How can I find the solution numerically? e.g. using matlab. Increasing $ \beta$ slowly works, but it is not accurate.
Comment: have you tried with bi-section algorithm ?
Comment: useful: https://en.wikipedia.org/wiki/Root-finding_algorithm
Comment: I don't understand why is there $\sqrt{\gamma}$ in the upper bound. $\frac{1}{\min a_n}$ should work as well.
Comment: @uranix I got this equation from an optimization problem. Yes, without  $\sqrt\gamma$ is ok of course. Sorry for not simplifying the equation.
Comment: @Cardinal : Yes, I think bi-section is a good choice now. It is simple and relatively efficient.
Answer: The fastest generic (read: linear convergence) algorithm given a continuous function and an interval $[a,b]$ with $f(a) < 0$ and $f(b) > 0$ is called bisection (sometimes binary search):

Look at the sign $s$ of $f(\frac{a+b}2)$

If $s = 0$, we are done with the exact solution $\frac{a+b}2$.
If $s = 1$, we know the root is in $[a, \frac{a+b}2]$, so set $b = \frac{a+b}2$ and repeat until the interval length $b-a$ is less than $2\epsilon$
If $s = -1$, we know the root is in $[\frac{a+b}2, b]$, so set $a=\frac{a+b}2$ and repeat until the interval length $b-a$ is less than $2\epsilon$

If $b-a<2\epsilon$, return $\frac{a+b}2$. We know that the actual root is wihin $\epsilon$ of this value.

The guaranteed accuracy ($\frac{b-a}2$) is halved in each iteration, so we converge linearly to the solution. In other words we need linear time if the accuracy is given in digits. This algorithm is optimal and always converges as long as $f$ is continuous.
A slight modification to prevent numerical problems if a root is on an interval boundary (i.e. found exactly), but the value returned isn't exactly $0$ would be to also return if $|f(\frac{a+b}2)| < \delta$ for some tolerance $\delta > 0$.
Comment: @uranix I did. Good catch for that. (+1 btw) I'll leave this inaccuracy for the moment as I don't have time now.
Comment: That's not an exponential convergence. It's a linear convergence (slowest). I.e.
$$
\epsilon_{k+1} \leq 0.5 \epsilon_k.
$$
Quadratic convergence can be achieved by Newton's method, and that would be
$$
\epsilon_{k+1} \leq C \epsilon_k^2.
$$
Exponential convergence is convergence for every $p$
$$
\epsilon_{k+1} \leq C_p \epsilon^p, \quad \forall p \exists C_p
$$
and I don't know such iterative methods.
Comment: @uranix How is that slow convergence? Also AFAIK the convergence is measured globally as $$\epsilon \le 2^{-k} |x - x_0|\le 2^{-k-1} (b-a)$$ Newton also only converges quadratically if the function is at least $C^1$, wich this one is not.
Comment: What you wrote is called linear convergence. For iterative methods, linear convergence is not the same that linear convergence for ODE, for example. Newton method I've gave only as an example of method with quadratic convergence. Actually there's no need in iterative method for this problem, you might look at my answer, no tolerance $\delta$ at all.
Comment: @uranix Fixed it now. Thanks again :)
Answer: Your function is piecewise linear. I suggest finding all the points where it's slope changes, seem to be $\beta_n = \frac{\gamma}{a_n}$ (If some $a_n$ are zero, simply kick them out of sum), sort them by value and find the interval $[\beta_k, \beta_{k+1}]$ where the root is (binary search, $O(\log n)$ complexity). On that interval, the root can be found by solving a linear equation.
Here's MATLAB code for that
<code>N = 20;
gamma = 3;
a = .1 + 3 * rand(N, 1);

mina = min(a);

x = linspace(0, gamma / mina, 1000);

f = @(beta) sum(min(gamma, a * beta(:)')) - N;

corners = gamma ./ a;
corners = [corners; 0; gamma / mina];
values = f(corners);
[values, reorder] = sort(values);
corners = corners(reorder);

low = 1;
upp = length(corners);

iters = 0;
while upp - low > 1
    iters = iters + 1;
    mid = floor((upp + low) / 2 + 0.1);
    % low < mid < upp
    if values(mid) > N
        upp = mid;
    else
        low = mid;
    end
end

fprintf('Binary search in %d iters, N at [%f, %f]\n', ...
    iters, corners(low), corners(upp));

root = corners(low) + ...
    (corners(upp) - corners(low)) / (values(upp) - values(low)) * ...
    (N - values(low));

fprintf('The root is %f\n', root);

plot(x, f(x), '-', corners, values, 'r.', ...
    x, N, 'k-', [root], [N], 'g*');
</code>


Confusing thing about $\lim_{n\to\infty} nq^n$

Question: So we have :
$$\lim_{n\to\infty} nq^n , |q| < 1$$
Now lets transform this to:  $$\lim_{n\to\infty} \frac{n}{(\frac{1}{q})^n}$$
Then it says that $\lim$ is equal to $0$ because $(\frac{1}{q})^n$ is >> n, thats what confuses me, how can this be much greater than n, when 1/q is fraction and it goes to $0$ as it gets powered by n.
Thanks in advance.
Comment: If you divide by a very small number, is the result very small or very big?
Comment: If $\vert q \vert < 1$, then $\frac{1}{q}$ is still a fraction, but its modulo now greater than 1.
Comment: Ofcourse... Thanks alot i guess i am tired :)
Answer: If $|q|<1$, clearly $|\frac{1}{q}|>1$. That to power n therefore blows up to infinity, and much faster than n.
Answer: Well there is no need to use the $1/q$ thing. We have two ingredients here in the sequence $a_{n} = nq^{n}$. First is $n$ which is tending to $\infty$ and second is $q^{n}$ which tends to $0$ as $n \to \infty$ (because $|q| < 1$). In order to show that the sequence $a_{n} \to 0$ it is necessary to show that $q^{n}$ tends to $0$ much faster than $n$ tends to $\infty$ so that their product eventually tends to $0$.
To understand this we consider the ratio $$\left|\frac{a_{n + 1}}{a_{n}}\right| = \frac{n + 1}{n}\cdot |q| \to |q|\text{ as }n \to \infty$$ Let $r$ be a number such that $|q| < r < 1$. Then from the above limit we know that given any $\epsilon > 0$ there is a positive integer $m_{\epsilon}$ such that $$\left|\left|\frac{a_{n + 1}}{a_{n}}\right| - |q|\right| < \epsilon$$ whenever $n \geq m_{\epsilon}$. Now we choose $\epsilon = r - |q| > 0$. And then we get a positive integer $m = m_{\epsilon}$ such that $$\left|\frac{a_{n + 1}}{a_{n}}\right| < r$$ for $n \geq m$. Putting $n = m, m + 1, \dots, m + p - 1$ and multiplying the equations we get $$\left|\frac{a_{m + p}}{a_{m}}\right| < r^{p}$$ or $$|a_{m + p}| < |a_{m}|r^{p}$$ Since $0 < r < 1$ therefore $r^{p} \to 0$ as $p \to \infty$ and hence it follows that $$\lim_{p \to \infty}|a_{m + p}| = 0$$ which in turn means that $$\lim_{p \to \infty}a_{m + p} = 0$$ and therefore $a_{n} \to 0$ as $n \to \infty$.
In fact we have proved a general result that
If $a_{n}$ is a sequence such that $\dfrac{a_{n + 1}}{a_{n}} \to L$ and $|L| < 1$ then $a_{n} \to 0$.


Problemas Comunicação Socket Server Delphi Client CSharp

Question: Tenho a necessidade de implementar uma comunicação via socket com server em delphi e um Client em csharp.
Criei um exemplo e o mesmo faz a comunicação porém por algum motivo o server em delphi quando vai dar o retorno pro csharp trava a requisição e quando encerro a App csharp no delphi ele continua com a Requisição, esse exemplo é uma string que envio um XML somente para multiplicar o valor e retornar o dobro do mesmo.
Server - Delphi 7 utilizando TcpServer
procedure TForm1.TcpServerAccept(Sender: TObject; ClientSocket: TCustomIpClient);
  var
    rValor: Real;
    sRequisicao: String;

begin
  try
    try
      CoInitialize(nil);
      sRequisicao := ClientSocket.Receiveln;
      memStatus.Lines.Add(sRequisicao);
      XMLDocument1.XML.Text := sRequisicao;
      XMLDocument1.Active := True;

      rValor := StrToFloat(XMLDocument1.ChildNodes.FindNode('reserva').ChildValues['valor']);
      rValor := Self.Multiplicar(rValor);

      XMLDocument1.ChildNodes.FindNode('reserva').ChildValues['valor'] := rValor;
      sRequisicao := XMLDocument1.XML.GetText;
      ClientSocket.Sendln(StringReplace(sRequisicao, sLineBreak, '', [rfReplaceAll]));
    except on e: Exception do
    begin
      memStatus.Lines.Add('Erro: ' + e.Message);
      ClientSocket.Sendln('Erro: ' + e.Message);
    end;
  end;
  finally
     CoUninitialize;
  end;
end;

Client - CSharp - Exemplo tirado da MSDN
static void Send()
{
    byte[] bytes = new byte[1024];

    try
    {
        IPAddress ipAddress = IPAddress.Parse("192.168.1.164");
        IPEndPoint remoteEP = new IPEndPoint(ipAddress, 6500);
        Socket sender = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

        try
        {
            sender.Connect(remoteEP);
            Console.WriteLine("Socket connected to {0}",
                sender.RemoteEndPoint.ToString());
            byte[] msg = Encoding.ASCII.GetBytes("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><reserva><valor>1</valor></reserva>");
            int bytesSent = sender.Send(msg);
            int bytesRec = sender.Receive(bytes);
            Console.WriteLine("Echoed test = {0}",
                Encoding.ASCII.GetString(bytes, 0, bytesRec));
            sender.Shutdown(SocketShutdown.Both);
            sender.Close();

        }
        catch (ArgumentNullException ane)
        {
            Console.WriteLine("ArgumentNullException : {0}", ane.ToString());
        }
        catch (SocketException se)
        {
            Console.WriteLine("SocketException : {0}", se.ToString());
        }
        catch (Exception e)
        {
            Console.WriteLine("Unexpected exception : {0}", e.ToString());
        }
    }
    catch(Exception e)
    {
        Console.WriteLine(e.ToString());
    }
}

No Csharp quando executo e chega na Linha:
int bytesRec = sender.Receive(bytes);

Ele aciona o server no Delphi e fica preso na linha:
sRequisicao := ClientSocket.Receiveln;

Obs: tenho um Client em Delphi 7 e um Server em Csharp, entre as mesmas linguagens, se comunicam corretamente.
Answer: Descobri que o problema estava no componente que eu estava utilizando no delphi para criar o server, troquei o Componente TcpServer para o SocketServer ambos da paleta Internet, o código ficou praticamente o mesmo, só mudou as linhas
sRequisicao := Socket.ReceiveText;
Socket.SendText(sRequisicao);

E na parte do csharp para facilitar utilizei o pacote Socket que ficou mais simples a utilização.
using (var socket = new ConnectedSocket("127.0.0.1", 6500))
{
     socket.Send("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><reserva><valor>10</valor></reserva>");
     var data = socket.Receive();
     Console.WriteLine(data);
}


Is there a formula for finding the centers of the faces of a platonic solid?

Question: Is there a formula for finding the centers of the faces of a platonic solid given the center of the first (origin) face to be $P_0(x_0,y_0,z_0)$?
Comment: Given just the centrer of one face we cannot tell 1) which way it's turned and 2) how large it is.
Answer: you can find the formula(coxeter) for the radius of the inner sphere of regular solids. the contact point of the plane of the face and the inner sphere is the center of that face.


Display my website statistics with Google Analytics API

Question: I want to display my statistics. I know how to use basicaly the Google Analytics API.

The user will authentificate with google
The user will see HIS statistics from his account.

But what I want is to show my statistics. I really don't understand the goal of the API f I can't display the statistics from my account to other users.
Answer: If you want to integrate the Google Analytics API with your application, you must have a Google API console project and enable Analytics API. For more details Google Analytics API Integration & Example


What is the basis for adjusting critical values in multiple t-tests?

Question: Let's say I have three samples: control, A, and B. (I am assuming basic things about sampling like no bias, no confounding factors, and independence in selecting samples.)
I want to see if there is a significant difference between all three samples. I determine significant difference by hypothesis testing using the t-test.
I perform a t-test on each combination of the three samples using the same cutoff $\alpha$. The null hypothesis is that there is no significant difference between the two samples. For sake of argument, in all three tests, all null hypotheses are rejected.
Based on this scenario, I assert:

The probability of the null hypothesis being rejected in any of the three tests is $3 \cdot \alpha$.
The probability of the null hypothesis being rejected in all three tests is $\alpha^3$.

Are these assertions correct?
If so, is the basis for doing something like Bonferroni or Holm adjustments of $\alpha$ applies only if the original question is: "Will the null hypothesis be rejected for any of the tests"? If that's the case, are adjustments to $\alpha$ irrelevant if the question is: "Will the null hypothesis be rejected for all of the tests"?
Comment: Not a direct answer to your question, but an alternative method for your particular study: If you're interested in comparing your treatment groups to your control, you could also use a [Dunnett's test](http://www.jstor.org/pss/2281208). (Basically, it can be used after an ANOVA came up significant, that is at least one pair of means has been shown to be significantly different.)
Answer:
The probability of the null hypothesis being rejected in any of the
  three tests is 3⋅α.

The probability of any doing a type-I error in at least one of the the three tests is actually:
$1-(1-\alpha)^3$
with a little log() algebra you can get:
$\alpha_{real} = e^{log(1-\alpha_{test})/tests}$ (same as Šidàk's $1-(1-\alpha)^{1/tests}$)
Hope this gives a little clarity on the issue.
UPDATE
Sorry, read your question a little too fast. As I understand it the Holm-Bonferroni method is a stepwise method where you walk through a ranked list of p-values rejecting the null hypothesis as you go, stopping on the first value not fullfilling the criteria. In your case it should be:

Lowest p-value $\le \frac{\alpha}{3}$
Intermed p-value $\le \frac{\alpha}{2}$
Highest p-value $\le \frac{\alpha}{1}$

The chance of all three rejecting the null hypothesis should then be $\frac{\alpha}{3}*\frac{\alpha}{2}*\frac{\alpha}{1}=\frac{\alpha^3}{6}$
The chance of any of the tests being rejected is equal to the first being rejected since you would otherwise not go on testing the next hypothesis, ie  $\frac{\alpha}{3}$
The difference in value of a $\alpha/3$ and an $\alpha_{real}$ as I suggested is really small which makes sense since the probability rules should be similar. The Bonferroni method is an old method and I would suggest you use the Šidàk method since it's more precise and if you have a primary outcome you could also try to allocate some probability space to that hypothesis leaving the other to share the rest.
As I understand it the Bonferroni correction is splitting the $\alpha$ for all the tests, this is a cruder method than the Šidàk developed when it was har to calculate $(1-\alpha)^{1/tests}$. If your question is only the Bonferroni method the answer is $\frac{\alpha^3}{9}$ for all three tests and in any of the tests $(1-\frac{\alpha}{3})^3$
If you have all three tests with p-value of $\alpha$ your chance of that should be $\alpha^3$ which probably is $\le\frac{\alpha}{3}$. You also have to reflect about the meaning of it, and I would interpret that as at least one of the tests isn't a type I error, that's not the same as saying that all of them are true.
I also guess your three test hypothesis isn't a-priori and then you probably should do a Bonferroni correction - it sounds to me a little risky to do this post-hoc. The chance that none of the values matches the start-criteria $\le\frac{\alpha}{3}$ seems also somewhat unlikely... I'm not sure I can help you that much more, you can have a look at Holm's original article and see if he mentions your special case.
Comment: I don't believe you've answered my original question: "...[I]s the basis for doing something like Bonferroni or Holm adjustments of $\alpha$ applies only if the original question is: 'Will the null hypothesis be rejected for any of the tests'? If that's the case, are adjustments to $\alpha$ irrelevant if the question is: 'Will the null hypothesis be rejected for all of the tests'?"


Fieldgroup accordion does not open to first field of group

Question: I am using the accordion group and item via the Field Groups module. If I open an accordion group, scroll to the bottom of the group and then click on the next one to open, the new group opens in the same place in the browser as I was left at. But the new group header goes to the top of the page. So I'm left in the middle or at the end of the group I'm trying to access, rather than at the top of the new group.
Very confusing to describe!
Comment: Sounds like a bug.  Post an issue in the module's issue queue.
Answer: This is the solution I ended up using. I got it from I got it here: https://stackoverflow.com/questions/3621161/jquery-accordion-will-it-scroll-to-the-top-of-the-open-item.
I tested it at modules/contrib/field_group/field_group.js file at line 66. We then created a patch for it.
Not sure if this is the best solution, but it worked for us, so I thought I'd share the info.
<code>activate: function( event, ui ) {
                    if(!$.isEmptyObject(ui.newHeader.offset())) {
                        $('html:not(:animated), body:not(:animated)').animate({ scrollTop: ui.newHeader.offset().top -150}, 'slow');
                    }
                }
</code>


Finding the minimum possible size of the edge cut of a complete graph.

Question: I want to find the minimum size of edge cut that separates $K_{3n}$ into three components. I am thinking for the three components after separation, they will all be complete, with orders $x,y$ and $z$. The relations are $x+y+z=3n$, and finding the $\max ((x-1)x/2+(y-1)y/2+(z-1)z/2)$ will lead to the answer. But I am stuck with finding the maximum.
What should I do to continue? Or am I in a wrong direction.
Comment: Have you already solved the $2$-component version?
Comment: Yes. The method is using calculus and finding the minimum of a parabola
Answer: If you have done the two-component version, then you have seen that the minimum edge cut there separates a $1$-vertex component from an $n-1$ vertex component using $n-1$ edges. So it makes sense to conjecture that the optimal solution here will have two $1$-vertex components and an $(n-2)$-vertex component.
This has $2n-3$ edges, which is pretty low. Can we do better?
Well, it takes $k(n-k)$ edges to separate a component of order $k$ from the rest of the graph. This is already more than $2n-3$, unless $k \in \{1, 2, n-2, n-1\}$. (You can check this part with calculus, if you like.) So each of our components must have one of these orders.
The only way to get three components of these orders to add up to $n$ is to take $1$, $1$, and $n-2$, provided that $n > 6$.
Comment: Thanks! It does make sense! I assume that here n represents 3n in the question right?
Comment: Yes, sorry; I forgot that you were dividing $K_{3n}$ and not $K_n$.


$R$-module structure of tensor product of $R$-algebras (Atiyah-Macdonald)

Question: I am (re-)reading the section on tensor products of $R$-algebras in Atiyah-Macdonald, where $R$ is a commutative ring, and I am not sure about the given definition of the $R$-module structure on the tensor product.
Let $R$ be a commutative ring, and let $(S,f)$ and $(T,g)$ be $R$-algebras. Then, it is claimed that the tensor product $V = S \otimes_R T$ has an $R$-algebra structure due to the homomorphism:
$$R \to V, \;\; r \mapsto f(r)\otimes g(r)$$
However, I don't see how the canonical map $\psi :S \times T \to S \otimes T$ can be bilinear if this is right.
Let $r \in R, (s,t) \in S \times T$. Then, on the one hand:
$$\psi(r*s,t) = \psi(f(r)s,t)=f(r)s\otimes t$$
But on the other:
$$r * \psi(s,t) = r * (s \otimes t) = (f(r) \otimes g(r)) (s \otimes t) = (f(r)s \otimes g(r) t)$$
Therefore, if $\psi$ is bilinear, we must have that:
$$f(r)s\otimes t \stackrel{?}{=} (f(r)s \otimes g(r) t)$$
which does not seem correct to me.
Have I misunderstood something, or is there an error here? If there is, please could I know the true $R$-module structure on $V$?
Comment: @MarianoSuárez-Álvarez Great -- I expected so, but I wanted to double-check. I also thought it would be worthwhile to post this question for other people reading the book. Thanks!
Answer: As mentioned by Mariano in the comments, this is an error in Atiyah-MacDonald, which you can verify because this map is not linear, and the correct map is $r \mapsto f(r) \otimes 1 = 1 \otimes g(r)$.
This confusion could have been avoided by taking a different definition of an $R$-algebra. Instead of defining it as a ring $A$ equipped with a unit map $R \to Z(A)$, which I've always thought of as sort of inelegant, you can define it to be an $R$-module equipped with an $R$-bilinear multiplication making it a ring. The unit map comes from multiplying the unit by scalars in $R$. If $A, B$ are two $R$-algebras then the tensor product $A \otimes_R B$ inherits an $R$-algebra structure simply because it is a tensor product of two $R$-modules so inherits an $R$-module structure, and the natural multiplication on $A \otimes_R B$ is $R$-bilinear.
Since the unit of $A \otimes_R B$ is the tensor product $1 \otimes 1$, we recover the unit map by multiplying the unit by scalars in $R$, and by bilinearity this gives $r(1 \otimes 1) = r \otimes 1 = 1 \otimes r$ as expected.
Abstractly the significance of this definition is that it's a special case of the much more general notion of a monoid object in a monoidal category, in this case the monoidal category of $R$-modules with respect to tensor product. This general definition explains, among other things, why we don't have a (straightforward) notion of $R$-algebra if $R$ is noncommutative: it's because if $R$ is noncommutative the category of (left or right) $R$-modules no longer possesses a tensor product.
Comment: Thanks for the answer. I believe that Atiyah-Macdonald does discuss both viewpoints for $R$-algebras, but it only gives the map $R \to V$ to define the structure for the tensor product. I agree that the definition you describe is generally more convenient.


show $\lim_{n\rightarrow\infty}\int_X|f_n-f|d\mu=0$

Question: I want to show $\lim_{n\rightarrow\infty}\int_X|f_n-f|d\mu=0$ for integrable functions $f_n,f:X\rightarrow [0,\infty)$, $f_n\rightarrow f$ pointwise a.e. and $\int_Xf_nd\mu\rightarrow \int_Xfd\mu$.
This is what our tutor did:
Define $g_n(x):= f_n(x)+f(x)-|f_n(x)-f(x)|$ and so $|g_n(x)|\le 2f(x)$ and therefor $g_n$ is integrable.
 Now $g_n(x)\rightarrow 2f(x)$ and with Fatou we get
$$
2\int_X fd\mu=\int_X\liminf_{n\rightarrow\infty} g_nd\mu\leq\liminf_{n\rightarrow\infty}\int_X g_nd\mu\leq2\int_X fd\mu-\limsup_{n\to\infty}\int_X |f_n-f|d\mu
$$
which immediately implies our claim.
My question: How do you get $\liminf_{n\rightarrow\infty}\int_X g_nd\mu\leq2\int_X fd\mu-\limsup_{n\to\infty}\int_X |f_n-f|d\mu$ ?
Answer: Hint: Let $(a_n)_{n \in \mathbb{N}}$, $(b_n)_{n \in \mathbb{N}} \subseteq \mathbb{R}$ be sequences. Then

$$\liminf_{n \to \infty} (a_n+b_n) = \lim_{n \to \infty} a_n + \liminf_{n \to \infty} b_n$$
whenever the limit $\lim_{n \to \infty} a_n$ exists.
$$\liminf_{n \to \infty} (-a_n) = - \limsup_{n \to \infty} a_n.$$
Comment: thanks, I've thought about 1 but couldn't prove it. I will try again ;) this solved my problem!
Comment: @psipi You are welcome.


Usando variaveis de outras forms (C#)

Question: Estou aprendendo programação com C#,usando o visual studio 2013.
Nesse programa tenho 2 janelas.
Na primeira janela tenho uma caixa de texto e um botão que grava o texto numa string e abre a segunda janela.
Na segunda janela tenho apenas uma caixa de texto .
Como eu faço para escrever na caixa de texto da janela 2 o que esta dentro a string da janela 1 ?
Obs.: Tentei tornar a string public mas não consigo acessar a string do mesmo jeito.
Comment: Poste o seu código, assim vamos poder te ajudar
Answer: Uma forma possível é declarar um construtor, na classe da segunda janela, que receba uma string:
public partial class Form2 : Form
{
    private string texto;

    public Form2(string texto)
    {
        InitializeComponent();
        this.texto = texto;

        //utilize a variável texto para "setar" a sua caixa de texto
        textBox1.Text = texto;
    }
    .....
    .....
}

Para abrir a segunda janela use esse construtor:
private void button1_Click(object sender, EventArgs e)
{

    Form2 form2 = new Form2(textBox1.Text);
    form2.Show();
}

Usando variaveis de outras forms (C#)


2 x Netgear GS724T (Dual GBIC) trunking issue

Question: I have the following:

Netgear GS724T (Firmware Version V1.0.3_35, Protocol Version - 2.001.002)
4 x Indineon ISFP GBR/FC

Settings

STP Function - Enabled
Fast Link - Enabled
Trunking port 23,24, (21,22 - RJ45 cables, but not connected.)

I have connected both switches via 2 fiber cables and want to use trunking.
The problem I am having.

Sometimes I get a an issue when none of the switches cannot talk with each other, nor the devices, sometime they can.
The problem is irregular and no patten can be determined
The statistics shows that when the switches does not work, they have RX errors

If I remove one to the GBIC connections, then everything works as normal.]
Question

Does anyone have a solution for this please?

Thanks
Comment: From what I can find, those switches do not support Etherchannel/LACP.  If I were you I'd just stick with a single trunk.  Ref this link: http://forum1.netgear.com/showthread.php?t=53402
Comment: Not up on Netgear but for a Cisco device you would setup the dual trunks as an Etherchannel connection.  STP should take care of any loops but I think you'll be better off with Etherchannel.
Comment: Hi, I do not think and I cannot find a Etherchannel on the netgear GS724T
Answer: From my experience, there hardly is a series of switches that sucks more than the NetGear "Smart Managed" one. I have indeed seen similar interoperability issues with trunking a GS724T and an Allied Telesis L2 switch, the technical support was less than helpful and in the end I decided to replace the device (the Netgear end) with a different make which cleared my problems.
After a couple of further unpleasant experiences, I decided not to touch Netgear "smart managed" again. Ever*. So if you really need the trunk I strongly suggest you think about alternative devices. Otherwise you might consider just using STP on two independent links - this would at least give you fault-tolerance unless you're fed up well enough to throw the switches into the next trash bin.
* Not that other devices from the "cheapo Chinese-stamped" category are that much better. If you need predictability with your networking gear, stay with the "big" names.


nginx www.domain.com vs domain.com virtualhost

Question: I have an http block where I include virtual hosts for the different domains hosted on the same server. For each virtual host I do:
listen domain.com:80;

Now, domain2.com works fine. However, when I do www.domain2.com it shows the page for domain1.com!
How to properly configure nginx? Does this have something to do whether www is a CNAME or an A record?
Answer: server {
 listen WHATEVER_IP:80;
 server_name domain2.com;
 ... rest of config for domain2.com goes here
}

server {
 listen WHATEVER_IP:80;
 server_name www.domain2.com;
 ... rest of config for www.domain2.com goes here
}

This will work whether the two IPs are the same or not. You can just use listen 80; if you don't need different servers on different IPs and everything is name-based.
Comment: Two server blocks for the same configuration?
Comment: You can also merge them and use one server block for each different configuration.
Answer: It looks like you can do the following in a server block:
listen 80;
server_name domain.com www.domain.com;


Android app not receiving location updates

Question: I'm trying to run an app that updates and centers the location from the device on the map fragment displayed on screen.
The blue dot on the map is displayed on the correct position, and the gps location is locked, but it seems that the onLocationChanged function is never called.
EDIT: Things are getting even weirder now. I left the app running for a while (around 10 minutes) and it did updated it's location a couple of times at random. and it suddenly stopped again. At least i know the functions are correct. But now where should i look?
Below is the relevant code.
public class MapaActivity extends FragmentActivity implements LocationListener{

public static GoogleMap mMap;

@Override
protected void onCreate(Bundle savedInstanceState) {

    setUpMapIfNeeded();

    mMap.setMyLocationEnabled(true);

}

public boolean setUpMapIfNeeded() {

    if (mMap == null) {

        mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();

        if (mMap == null) {

            setUpMap();

        }
    }
    return true;
}

private void setUpMap() {

    mMap.setMyLocationEnabled(true);

    LocationManager locationManager;

    locationManager = (LocationManager)getSystemService(LOCATION_SERVICE);

    Criteria criteria = new Criteria();

    String provider = locationManager.getBestProvider(criteria, true);

    Location location = locationManager.getLastKnownLocation(provider);

    locationManager.requestLocationUpdates(provider, 1000, 0  , this);

}

@Override
public void onLocationChanged(Location location) {

    //do some stuff

}

Comment: the return type for `setUpMapIfNeeded` must be void.
Comment: I actualyy use the information returned from the setup map function in order to check if it is already set, before doing some other assignments to the map frame
Comment: But you are not doing it.
Comment: It's on an omited function.
Comment: Things are getting even weirder now. It did updated it's location a couple of times at random. and it suddenly stopped again. At least i know the functions are correct. But now where should i look?
Answer: Because you are not correctly registering for location udpates.
I dont know why you are checking mMap == null but try this:
if (mMap != null) {

            setUpMap();

        }

Comment: I try to get the mMap using the fragment for it. If it's still null after the attempt, it calls for the setUpMap function.
Comment: That is not correct, you should continue if the map is not null try the answer.
Comment: It didn't fixed my problem. But shouldn't the logic be "If null, try to get from here, if it's still null, setup again"?
Comment: I mean, it's inside setUpMap() that i define the mMap. Shouldn't it be called only if mMap is null?
Comment: but you have already instantiated it before the above condition.
Comment: I'ts because I haven't posted the complete code. The setUpMapIfNeeded() is called inside the onResume() - and onCreate - to make sure the map fragment is not null before proceeding with the rest of the code.
It checks if the mMap is already instanciated, if positive it returns true. If not, it tries to retrieve the map from the fragment, if it fails and mMap still is null, it then calls for the setUpMap(), where it's recreated.


Is there any difference with using only location vs using window.location across browsers

Question: I find myself always writing:
console.log(window.location.href);

without even thinking about it. The majority of answers on SO also write it this way. Is there any reason why I can't just write:
location.href

since location is an object at window level? Are there any cross-browser compatibility issues with this?
To Clarify: I know there is document.location - that is NOT what this question is about. This is about if there is any difference with using only location vs using window.location across browsers.
Comment: Do you even read? It's not a duplicate of `location` vs `location.href`, but about `x` vs `window.x`
Comment: @NikhilAgrawal Nope. You need to read the question again. Or the comment above yours. Both will explain why it is explicitly not about an object vs a property, but the scope of a particular object.
Comment: People are getting way too close-happy. This question isn't even close to being related to the question it's supposedly a duplicate of.
Comment: @Tmdean: it's still a duplicate regardless, for example the first question in the "related" list. http://stackoverflow.com/questions/4709037/window-location-versus-just-location?rq=1
Comment: @Qantas94Heavy The question you linked to is not the first linked one in the related list. None of those in the related list have anything to do with my question. Yours is completely valid but I searched for a long time and came up with nothing
Comment: @RGraham: that's weird, that's what it shows up for me. Anyway, you're right -- the duplicates are incorrect.
Answer: There are some differences.
In global scope, there is absolutely no difference between them, but in other cases you might get in trouble:
function () {
  var location = { 'href' : '123' } ;
  console.log(window.location.href) // actual url
  console.log(location.href) // '123'
}

This stems from the fact that if you write location without prefixing it with window, it will go up through every scope to find a variable named location. Eventually it will find it in window, unless another scope declared one as well. Obviously the reverse is true as well:
function () {
  var window = { 'location' : { 'href': '123' } };
  console.log(window.location.href) // '123'
  console.log(location.href) // actual url
}

I for one prefer to prefix the global variables with window because that way i immediately know they are global and also because when i find a global variable that is not prefixed with window, i know it is a typo missing a var, but that is purely personal preference.
Comment: Well, window is just a namespace, you just need to use it consistently and carefully. Often, people use `document.getElementById`, but somebody could also do `var document = 'Hello!'`, which does not have that function. However, window is sort of a keyword that you cannot override. So using `window.document.getElementById` you should be guaranteed to get the native javascript code. You could prefix this in your local scope with `var win=window,doc=win.document;`. Especially when using 3rd party code, and you care about safety, then this is the way to go imo (don't know if this is common).


Nginx: Can I cache a URL matching a pattern at a different URL?

Question: I have a site with some URLs that look like this: /prefix/ID, where /prefix is static and ID is unique. Using Nginx as a reverse proxy, I'd like to cache these pages at the /ID portion only, omitting the prefix.
Can I configure Nginx so that a request for the original URL is cached at the shortened URL?
I tried this (I'm omitting some irrelevant parts) but obviously it's not the correct solution:
http {
    map $request_uri $page_id {
        default $request_uri;
        ~^/prefix/(?<id>.+)$ $id;
    }

    location / {
        proxy_cache_key $page_id
    }
}

Comment: _"obviously it's not the correct solution"_ But why?
Comment: ...or I wouldn't need to ask :) Not sure what's happening under the hood, but when I set the cache key like this it serves cached content at `/prefix/ID` but a request for `/ID` is still passed to the app and returns a 404.
Comment: Because `/ID` ($request_uri) isn't the same key as `ID` (~^/prefix/(?.+)$).
Answer: map $request_uri $page_id {
    default $request_uri;
    ~^/prefix(?<id>/.+)$ $id;
}

Note that leading /.
Comment: it may be a bit helpful to provide a bit more instruction here.  The site automatically flagged this is low quality because you didn't put much content into the post.  Maybe an additional set of instructions would be helpful.


Variable must provide either dimension expression or an array initializer Syntax error on token, misplaced construct

Question: Sou novato em programação para Android e gostaria de solucionar este erro:
<code>package br.pedromazer.cantoliturgico;

import br.pedromazer.cantoliturgico.R.string;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ListView;

public class Lista extends Activity {

    @Override
    protected void onCreate(Bundle b) {
        // TODO Auto-generated method stub
        super.onCreate(b);
        setContentView(R.layout.lista);

        btnVoltar = (ImageButton) this.findViewById(R.id.btnVoltar);
        btnVoltar.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                //Ao invés de trabalhar aqui, criar um evento cf. acima do ImageButton
                //Aqui chama o método com um evento
                btnVoltar_onClick(v);
            }
        });

        lstAlunos = (ListView) this.findViewById(R.id.lstAlunos);

        ArrayAdapter<string> array = new
            ArrayAdapter<string> (this, android.R.layout.simple_list_item_single_choice), alunos;

        lstAlunos.setAdapter(array);

        lstAlunos.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                lstView_onClick(v);
            }
        });

    }

    public void btnVoltar_onClick(View v) {

        this.finish();

    }

    public void lstView_onClick(View v) {

        Intent i = new Intent(this, Lista.class);
        this.startActivity(i);

    }

    String[] alunos = ***new String[]***("Aluno A", "Aluno B", "Aluno C");
    ImageButton btnVoltar;
    ListView lstAlunos;

}
</code>
Comment: Tem certeza que é assim que instância um array em Java (`***new String[]***("Aluno A", "Aluno B", "Aluno C");`)? Não deveria ser `new String[] {"Aluno A", "Aluno B", "Aluno C"};`. Outro erro é que está usando `string` como o tipo do `Adapter`, deveria ser `String`.
Answer: Posta a stack!
Em todo caso tente assim:
<code>    String[] alunos = new String[] {"Aluno 1", "Aluno 2", "Aluno 3"};

    ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_single_choice, alunos);

    ListView listView = (ListView)findViewById(R.id.lstAlunos);

    listView.setAdapter(arrayAdapter);
</code>


Compile error oracle procedure

Question: Hej. I have a task that says to create a procedure that adds column "BRUTTO" to a table "TABELA_1, then fills that column with values based on values from column "NETTO" and output all records from TABLE_1, including newly created BRUTTO. It works without commented out code but doesn't otherwise. Apparently it doesn't see column BRUTTO yet so I can't reference it like that. Any help appreciated.
CREATE OR REPLACE PROCEDURE WSTAW_BRUTTO_I_WYSWIETL
AS
    --CURSOR C IS
        --SELECT NAZWISKO, NETTO, BRUTTO FROM TABELA_1;
    V_VAT NUMBER(9,2) := 24;
BEGIN
    EXECUTE IMMEDIATE 'ALTER TABLE TABELA_1 ADD BRUTTO NUMBER';
    EXECUTE IMMEDIATE 'UPDATE TABELA_1 SET BRUTTO = NETTO * (1 + :1 /100)' USING V_VAT;
    --FOR V_REC IN C
    --LOOP
        --DBMS_OUTPUT.PUT_LINE('| '||V_REC.NETTO||' | '||V_REC.BRUTTO);
    --END LOOP;
END WSTAW_BRUTTO_I_WYSWIETL;

Answer: Your procedure won't compile because you can't access a column before it is added to the table. Not sure why you wrote a procedure with dynamic SQL for this. A plain SQL statement should work. Moreover, you can't use bind variable in a DDL, It would have raised

ORA-01027: bind variables not allowed for data definition operations

during run time.
You should also consider using BRUTTO as a VIRTUAL COLUMN, rather than a column itself.
ALTER TABLE TABELA_1 ADD BRUTTO NUMBER AS ( NETTO * (1 + 24 /100) );

Demo
If you still think you want a procedure and it has to compile, you should put the block inside EXECUTE IMMEDIATE, but it's not recommended.
CREATE OR REPLACE PROCEDURE wstaw_brutto_i_wyswietl AS
    v_vat   NUMBER(9,2) := 24;
BEGIN
    EXECUTE IMMEDIATE 'ALTER TABLE TABELA_1 ADD BRUTTO NUMBER AS ( NETTO * (1 + '
                      || v_vat
                      || ' /100) )';
    EXECUTE IMMEDIATE q'{BEGIN
      FOR V_REC IN ( SELECT NETTO,BRUTTO FROM TABELA_1 )
      LOOP
        DBMS_OUTPUT.PUT_LINE(V_REC.NETTO||','||V_REC.BRUTTO);
      END LOOP;
    END;}'
;
END wstaw_brutto_i_wyswietl;
/

Demo2

Compile error oracle procedure


Complex analysis derivatives

Question: If a function $f(x,y)=u(x,y)+i\cdot v(x,y)$ is $\mathbb{C}$-differentiable,how can I prove that
for $u$ and $v$ the partial derivatives exist?
I have figured out if f is continuously differentiable then the derivative value must be $f_x$,but $f_x$ exists only when $u_x,v_x$ exist.So how can I ensure their existence?
Answer: Let $z_0\in\mathbb C$. Asserting that $f$ is differentiable at $z_0$ means that the lime$$\lim_{h\to0}\frac{f(z_0+h)-f(z_0)}h$$ exists. In particular, the limit$$\lim_{h\to0,\ h\in\mathbb{R}}\frac{u(z_0+h)+iv(z_0+h)-u(z_0)-if(z_0)}h$$exists, which is the same thing as asserting that both limits$$\lim_{h\to0,\ h\in\mathbb{R}}\frac{u(z_0+h)-u(z_0)}h\text{ and }\lim_{h\to0,\ h\in\mathbb{R}}\frac{v(z_0+h)-v(z_0)}h$$exist. But this means that $u_x$ and $v_x$ exist at $z_0$.
A similar argument shows that $u_y$ and $v_y$ exist at $z_0$.
Answer: Unpack the definition; the function is $\mathbb{C}$-differentiable if $\lim_{z\to z_0} \frac{f(z)-f(z_0)}{z-z_0} = f'(z_0)$ exists.
$$\lim_{z\to z_0} \frac{f(z)-f(z_0)}{z-z_0} - f'(z_0) = 0$$
$$\lim_{z\to z_0} \frac1{z-z_0}\left(f(z)-f(z_0) - f'(z_0)(z-z_0)\right) = 0$$
$$\lim_{z\to z_0} \frac1{|z-z_0|}\left|f(z)-f(z_0) - f'(z_0)(z-z_0)\right| = 0$$
$$\lim_{(x,y)\to (x_0,y_0)}\frac1{\|(x,y)-(x_0,y_0)\|}\left\|u(x,y)+iv(x,y)-u(x_0,y_0)-iv(x_0,y_0) - L_{f'(z_0)}(x-x_0,y-y_0)\right\| = 0$$
There $L_{\zeta}$ is the linear map from $\mathbb{R}^2$ to $\mathbb{C}$ that acts the same as multiplication by $\zeta$. Split this into real and imaginary parts; we get
$$\lim_{(x,y)\to (x_0,y_0)}\frac1{\|(x,y)-(x_0,y_0)\|}\left\|u(x,y)-u(x_0,y_0)- L(x-x_0,y-y_0)\right\| = 0$$
for some linear transformation $L$, and similarly for the imaginary part. That's the definition of differentiability for a function from $\mathbb{R}^2$ to $\mathbb{R}$; we have proved, straight from the definition, that if a function is $\mathbb{C}$-differentiable, its real and imaginary parts are $\mathbb{R}$-differentiable. A $\mathbb{R}$-differentiable function has partial derivatives, and we're done.
Next, of course, is verifying the relation between those partial derivatives (the Cauchy-Riemann equations). Related, the theorem to remember from this: a function is $\mathbb{C}$-differentiable at a point if and only if it's $\mathbb{R}$-differentiable at that point and its partial derivatives there satisfy the Cauchy-Riemann equations.
Yes, we could have gotten just the partial derivatives more easily. The full power of differentiability at that point is worth a little extra effort.

Complex analysis derivatives


How can I get the confidence scores of LPRNet?

Question: I am a newbie working on the LPRNet provided by openvino toolkit:
https://github.com/openvinotoolkit/training_extensions
I want to get the probability of the predicted result but it seems that tf.nn.ctc_greedy_decoder only returns neg_sum_logits and I'm not sure how to convert it into prabability.
Does anyone know how can I get that?
Any suggestion will be appreciated!
Thanks.
Answer: You may try to use the validation app.
Inference Engine Validation Application is a tool that allows to infer deep learning models with standard inputs and outputs configuration and to collect simple validation metrics for topologies. It supports top-1 and top-5 metric for Classification networks and 11-points mAP metric for Object Detection networks.
You may refer here for some insight: https://docs.openvinotoolkit.org/2019_R1/_inference_engine_samples_validation_app_README.html
And also this is a step by step explainations for the application of validation app: https://www.youtube.com/watch?v=4WAQSx3LC-M


Access keys inside nested dictionary python

Question: I have a JSON object like this below. Actually huge JSON file, simplified to ask this question.
"header": {
        "headerAttributes": {
            "pageCount": 5,
            "totalCount": 5
        }
    },
"payload": [
    {
        "firstKey": [
                {
                    "nestedKey_1": "1",
                    "nestedKey_2": "2"
                },
                {
                    "nestedKey_3": "3",
                    "nestedKey_4": "4"
                }
            ]
    }
]

Now I wrote below python code to access values inside [].
Total_Orders_Count = json_response ['header']['headerAttributes']['totalCount']
for i in range(0,Total_Orders_Count):
            dict = json_response ['payload'][i]
            inner_dict = dict ['firstKey'] [0]
            print inner_dict ['nestedKey_1'] + '(' + inner_dict['nestedKey_2'] + ')'

The above code works fine. However, the usage of dict ['firstKey'] [0] doesn't work for values more than 1.
Two Questions.
1. Is there a better way to access Key values inside [].
2. Can we find length of number of values inside []. For this list, length of values under "firstKey" is 2.
Any help is appreciated.
Comment: also don't call your variable `dict`
Comment: "the usage of dict ['firstKey'] [0] doesn't work for values more than 1" ? what do you mean?
Comment: `len(json_response['payload'][i]['firstKey'])`
Comment: @barmar Thanks for this to get the length
Answer: Just loop over the lists directly. There is no need to know a length up front:
for d in json_response ['payload']:
    for inner_dict in d['firstKey']:
        print '{0[nestedKey_1]}({0]nestedKey_2})'.format(inner_dict)

The for <name> in <listobject> loop is a for each construct; no indices are generated. Instead, the loop assigns each element from the list to the target name.
I changed the name dict to d to avoid masking the built-in type. I also used string formatting to put the values from the inner dictionary into a string.
Note that I dropped using the totalCount key altogether. There is no need to look at that value here.
As for finding the length of a list, just use the len() function. Again, there is no need to use that function here, iteration directly over the list removes the need to generate indices up front.
Answer: In the JSON you provided, there is only one element in the outer list of payload. But the code tries to access the first 5 elements of that list, which don't exist.
Try to avoid using direct access to values in a list like this di['key'], instead use 'di.get('key','default')`, unless you are sure it exists.
To loop through the keys-values and get the length of values under 'firstKey', use the following code:
for payload in json_response.get('payload',[]) :
    # Length of values under firstKey
    print(len(payload.get('firstKey',[])))
    # To access nested Keys
    for i in payload.get('firstKey',[]) :
        for k,v in i.items() :
            print(k,':',v)


If $a$ and $b$ both commute with $[a,b]$, then $(ab)^n = a^nb^n[a,b]^{\frac{n(n-1)}{2}}$

Question:
Assume $a,b \in G$ for a group $G$ and assume

$a$ commutes with $[a,b]$ and
$b$ commutes with $[a,b]$

(defining $[a,b]:=a^{-1}b^{-1}ab$). For every $n \in \mathbb{N}$, prove that $$(ab)^n = a^nb^n[a,b]^{\frac{n(n-1)}{2}}$$

(Note: The original post ommitted the $a^nb^n$ on the right hand side; hence many of the comments in the post...)
Since, $a$ and $[a,b]$ commute, we know
$$(a[a,b])^n = a^n[a,b]^n$$
Similarly, since $b$ and $[a,b]$ commute, then
$$(b[a,b])^n = b^n[a,b]^n$$
From these two findings, $[a,b]^n$ can be isolated so that
$$[a,b]^n = a^{-n}(a[a,b])^n = a^{-n}([a,b])^n$$
But after this point, I get stuck. Any suggestions on how to go about this? Any help is appreciated!
Comment: There seems to be something missing here - the statement in the $n=1$ case is $ab = [a,b]^0 = e$, which isn't right.
Comment: As the other comments point out the statement is false. What is true is that $(ab)^n = a^n b^n [b,a]^{n(n-1)/2}$, assuming $a$ and $b$ commute with $[a,b]$.
Comment: You need to define $[a,b]$.
Comment: That wasn't what quasi was saying. The issue quasi was highlighting is one I mentioned parenthetically about the abelianization: if $a$ and $b$ *also* commute with each other (an *additional hypothesis... e.g., take $b=e$), then it is clear your formula cannot be correct as written.
Comment: Moreover, if we assume $a,b$ commute, then for any fixed positive integer $n$, the stated claim reduces to $(ab)^n=1$, which need not be true.
Comment: @quasi and all other commenters, I apologize for my poor choice of wording. The problem is supposing two things 1.) $a$ commutes with $[a,b]$ and 2.) $b$ commutes with $[a,b]$. To shorten this, I used the word "both" which may have sounded like $a$ and $b$ commute, but that isn't what I intended. I will edit the statement of the problem now.
Comment: @ArturoMagidin Oh I think I see the issue now. Thank you for clarifying.
Answer: You have the wrong formula, that's why you are not getting it.
I will use the convention that $[x,y]=x^{-1}y^{-1}xy$, so that $xy=yx[x,y]$. Under the assumption that $[a,b]$ centralizes both $a$ and $b$ the formula is identical for the convention $[x,y]=xyx^{-1}y^{-1}$, as I will show at the end.
The correct formula is:

If $[a,b]$ commutes with both $a$ and $b$, then $(ab)^n = a^nb^n[b,a]^{\binom{n}{2}}$ for all integers $n$, where $\binom{n}{2}=\frac{n(n-1)}{2}$ for any integer $n$.

Note what you are missing: you are missing the $a^nb^n$ factor preceding the commutator (which one is clearly missing, since the images in $G^{\rm ab}$ should still satisfy the identity!) (Note: Corrected later...) And also you have the commutator backwards.
Lemma. If $x$ and $y$ commute with $[x,y]$, then $[y,x^n] = [y,x]^n$ for all integers $n$.
Proof. This holds for $n=1$. Assuming it holds for $k$, we have
$$[y,x^{k+1}] = [y,x^kx] = [y,x][y,x^k]^x = [y,x][y,x^k] = [y,x][y,x]^k = [y,x]^{k+1},$$
and if $[y,x^n] = [y,x]^n$, then
$$[y,x^{-n}] = [x^n,y]^{x^{-1}} = [x^n,y] = [y,x^n]^{-1} = [y,x]^{-n},$$
as desired. $\Box$
Above, we are using the standard commutator identities $[a,bc]=[a,c][a,b]^c$ and $[a,b^{-1}]=[b,a]^{b^{-1}}$.  Note that this implies that if $[a,b]$ commutes with $a$ and $b$, then since $[b,a]=[a,b]^{-1}$, we have $[a^r,b^s]=[a,b]^{rs}$ for all $r,s\in\mathbb{Z}$. (In fact, the commutator bracket is a bilinear map on $G/Z(G)$ when $[G,G]\subseteq Z(G)$.)
Proof of the formula.
We prove the formula by induction on $n$ (you can also prove it using commutator collection).
The equation holds for $n=1$, since $\binom{1}{2}=0$. Assuming that $(ab)^n = a^nb^n[b,a]^{\binom{n}{2}}$ for $n\gt 0$, we have:
$$\begin{align*}
(ab)^{n+1} &= (ab)(ab)^n \\
&= aba^nb^n[b,a]^{\binom{n}{2}}\\
&= aa^nb[b,a^n]b^n[b,a]^{\binom{n}{2}}\\
&= a^{n+1}b[b,a]^nb^n[b,a]^{\binom{n}{2}}\\
&= a^{n+1}bb^n[b,a]^{n+\binom{n}{2}}\\
&= a^{n+1}b^{n+1}[b,a]^{\binom{n+1}{2}}.
\end{align*}$$
So the equation holds for all positive integers. Finally, for $n\gt 0$,
$$\begin{align*}
(ab)^{-n} &= \Bigl((ab)^n\Bigr)^{-1}\\
&= \Bigl( a^nb^n[b,a]^{\binom{n}{2}}\Bigr)^{-1}\\
&= b^{-n}a^{-n}[b,a]^{-\binom{n}{2}}\\
&= a^{-n}b^{-n}[b^{-n},a^{-n}][b,a]^{-\binom{n}{2}}\\
&= a^{-n}b^{-n}[b,a]^{n^2-\frac{n^2-n}{2}}\\
&= a^{-n}b^{-n}[b,a]^{\frac{n^2+n}{2}}\\
&= a^{-n}b^{-n}[b,a]^{\frac{-n(-n-1)}{2}}\\
&= a^{-n}b^{-n}[b,a]^{\binom{-n}{2}},
\end{align*}$$
as desired. $\Box$
The other convention, where $[x,y]=xyx^{-1}y^{-1}$ would have $xy=[x,y]yx$. But if $[x,y]$ is assumed to commute with $x$ and $y$, then $yx(x^{-1}y^{-1}xy)=xy=[x,y]yx = yx[x,y]$,
so we have that $xyx^{-1}y^{-1} = x^{-1}y^{-1}xy$. Thus, both conventions will lead to the same formula under this assumption.
In short, you are missing the factors $a^nb^n$, and (corrected later) your commutator is backwards.
Comment: Thanks for an easy-to-follow and self-contained answer! I must have copied down the formula incorrectly. Flipping the commutator seems to fix everything!
Comment: @DavidC.Huang the major error is the missing $a^nb^n$, though...
Comment: Oh my goodness, I didn't even realize my major typo until now! I totally meant to include the $a^nb^n$. I feel so silly; I see what you mean now. Thank you
Comment: For those of us that tuned in during the 9th inning, we only see the corrected statement and not the original incorrect one making the comments a bit moot, however this was an interesting post and nice detailed proof (@ArturoMagidin)


Glitch com JPopupMenu em Java Swing

Question: Criei uma pequena aplicação para testar um JPopupMenu juntamente com um JTextField, o problema que encontrei é que quando clico muito rápido, várias vezes seguidas juntamente selecionando os itens uma vez ou outra ele da um "glitch"/bug na tela, ele deixa os componentes gráficos todo estranho. Acontece também se for fazendo isso devagar, selecionando alguns itens, ir fazendo aparecer e desaparecer o Popup. Lembrando que o problema acontece randomicamente, não tendo nem uma ação em especial para faze-lo acontecer.
Código: (Algumas partes geradas pelo Netbeans)
<code>package blackscreendeveloper.loginteste.view;

import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;

public class Login extends javax.swing.JFrame {

    public Login() {

        initComponents();

        JPopupMenu menu = new JPopupMenu();

        JMenuItem item1 = new JMenuItem("Item 1");
        JMenuItem item2 = new JMenuItem("Item 2");
        JMenuItem item3 = new JMenuItem("Item 3");

        menu.add(item1);
        menu.add(item2);
        menu.add(item3);

        txtLogin.setComponentPopupMenu(menu);
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        txtLogin = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(32, Short.MAX_VALUE)
                .addComponent(txtLogin, javax.swing.GroupLayout.PREFERRED_SIZE, 260, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(35, 35, 35)
                .addComponent(txtLogin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(25, Short.MAX_VALUE))
        );

        pack();
        setLocationRelativeTo(null);
    }// </editor-fold>

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Login().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify
    private javax.swing.JTextField txtLogin;
    // End of variables declaration
}
</code>
Imagem do Glitch: (Ficou dessa forma nesse caso, mas pode mudar)
Comment: Testei aqui seu código e esse problema não ocorreu de forma alguma.
Comment: O que seria então? Problema na maquina? Você testou na forma que descrevi? Clicando de forma rápida?
Comment: Sim, o problema não ocorreu.
Comment: Alguma ideia do que poderia ser?
Comment: Outra coisa incoerente na pergunta é o fato do código ter o LAF nimbus configurado mas seu print não está com o LAF nimbus.
Comment: O print postado é da forma que eu executei. O LAF pode estar sendo a causa? Qual você usou?
Comment: Não sei, como não é possivel reproduzir o bug, não tenho como sugerir nada pois não sei a origem.Mas suspeito que não tem nada a ver com java, senão o problema ocorreria comigo tambem.
Comment: Vou testar no computador de casa e irei retornar, para verificar se o problema ocorre em outro computador também.
Comment: Pode ser a ide tambem. Tenta gerar o jar e simular pra ver se ocorre. Se sim, pode ser versao do jdk com problemas, ou até o recurso do aero do seu windows(pelo print você parece estar usando windows 7)
Comment: Testei no Windows 10 agora mesmo. Poraqui está ok... estranho. Estou usando o Nimbus também no windows 10 então descartado ser o LAF. Vou testar em outro PC com Windows 7 amanhã e volto para um parecer. Agradeço até o momento.
Comment: Então você acaba de constatar que não há problema algum com o java e nem com a API swing :)
Comment: Irei testar no Windows 7 novamente amanhã para ver o problema. Mas provavelmente é realmente o PC que eu estava.
Answer: Testei em outro PC com Windows 7 e em outro com Windows 10 e por minha surpresa nada ocorreu, funcionou perfeitamente. Suponho eu que possa ser algum driver, programa ou algo do tipo que está fazendo ocorrer o problema. Caso alguém tiver o mesmo problema, sugiro testar em outro computador, caso continuar ocorrendo, é válido uma possível reinstalação de drivers ou formatação do computador. Agradeço as ajudas.

Glitch com JPopupMenu em Java Swing


Prove that the function $f:\mathbb{R}^2\rightarrow\mathbb{R}$ is constant

Question:
Suppose that the function $f:\mathbb{R}^2\to\mathbb{R}$ has first order partial derivatives and that $$\frac{\partial f}{\partial x}(x,y)=\frac{\partial f}{\partial y}(x,y)=0\qquad\text{for all $(x,y)\in\mathbb{R}^2$}$$ Prove that the function $f:\mathbb{R}^2\rightarrow\mathbb{R}$ is constant.

Since $\frac{\partial f}{\partial x}(x,y)=\frac{\partial f}{\partial y}(x,y)=0$ for all $(x,y)\in\mathbb{R}^2$, so $\nabla f(x,y)=0$. Let $(x_1,y_1),(x_2,y_2)\in\mathbb{R}^2$. Define $\gamma:\mathbb{R}\to\mathbb{R}^2$ be a differentiable mapping with $\gamma(0)=(x_1,y_1)$ and $\gamma(1)=(x_2,y_2)$. Now, let $g=f\circ\gamma:\mathbb{R}\to\mathbb{R}$, then we have $g'(t)=\nabla f(\gamma(t))\cdot\gamma'(t)=0$ for all $t\in\mathbb{R}$. $g$ is constant on $[0,1]$, thus, $f(x_1,y_1)=f(\gamma(0))=g(0)=g(1)=f(\gamma(1))=f(x_1,y_1)$ which implies $f$ is a constant.

I am looking for different ways to show $f$ is constant. Can someone give me a hint or suggestion to start with a new way? Thanks
Comment: That's my favorite proof.
Comment: That proof has a problem. You haven't shown  f is differentiable, so the chain rule is not applicable.
Comment: @zhw $f$ has first order partial derivatives
Comment: @zhw: The function $f$ has continuous first partial derivatives.
Comment: @ChristianBlatter Yes, you are obviously right.
Comment: @Simple Existence of the partials is not enough to show f is differentiable, although as ChristianBlatter noted, the partial derivatives are continuous, anad that is enough.
Answer: The fact that $\frac{\partial f}{\partial x} (x,y)= 0 $, implies that $f(x,y) = \phi(y) + c,$ for some differentiable function $\phi$. Thus,
$$\dfrac{\partial f}{\partial y} (x,y)= \phi'(y)  \implies 0 =  \phi'(y) \implies \phi(y) = C.$$
Finally,
$$f(x,y) = C +c = \mathrm{constant}.$$
Answer: Hint/Suggestion: If a function is constant almost everywhere, then it is either a horizontal plane or piece-wise horizontal planar, where changes in the $Z$ value of the plane occur at the discontinuities.
Show that the existence of the derivative at all points implies that it is horizontal planar and continuous, in which case it must be a horizontal plane (constant).
Answer: $$f(x,y)-f(0,0)=\bigl(f(x,y)-f(x,0)\bigr)+\bigl((f(x,0)-f(0,0))\bigr)=y f_y(x,\eta)+x f_x(\xi,0)=0\ .$$


Send Mail After Checking Date Field Value

Question: My content type (product) has a date field named Expired Date. All I want is like this:
check value of expired date field from content type product. If value equal to 7 days from now, send mail with list of node title and node url.
How to do this with Rules? or any suggestion modules?
Comment: While this doesn't directly answer your question. It will give you are start on what you need to accomplish. You'll need rules and rules scheduler. http://drupal.stackexchange.com/questions/64695/how-do-i-use-rules-scheduler-to-disable-and-enable-a-commerce-product-entity-bas
Answer: Yes you could do this through rules granted the product expiration date is a field.

Create a new rule to run on cron maintenance tasks
Condition--> has field name
Pick your field name
Action--> execute custom PHP.

I don't know what your level of PHP experience is so I'll hold off on putting any code down, but the next step would be to write a short snippet of PHP that takes the sites current datetime and checks the values of your chosen field for values that are 7 days away from expiration (rules should give you tokens for both items).

Then in that same custom PHP area use rules_action_mail() to send the email out with the results (for reference: https://drupal.org/node/322834).

You could also do this with a SQL query in the PHP area: http://www.barnettech.com/content/dbquery-drupal-creating-sql-queries-drupal-way . Just run through your field in the database and check for the values you need, then return the results in the mail message.
If I were to do something like this, I would implement hook_cron() in a custom module: https://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook_cron/7 vs. using Rules since it would require less steps.
Edit: As requested:
See here to make a Drupal 7 module: https://drupal.org/node/1074360
Using hook_cron would go something like:
<code>function mymodule_cron(){
 myfunctions();
}

function myfunctions(){
//do cool stuff
}
</code>
As far as what would go into "myfunctions", it would probably be a query on the database, returning those results, then sending those results in an email with mail(). That would be it.
Comment: Thank you for your suggestion. I will try it soon and let you know. Can you please give me an idea about using hook_cron() with this situation..? I'm interested want to use custom module.. since my php level also good. :)
Comment: See my edit above :-)!
Answer: yes, it's posible only with rules and one more module, first you have to calculate in days the difference betwen date fields, here the solution, then, with rules-conditional module add an if, add a condition: your diff value calculated is > than 7, send your email.
Answer: I've saved this(Someone's else answer I can't remember) earlier because its the best way to do publish/unpublish content based on a date feild (which you can replace it with Send Mail) using Rules and sub-module (Rules Scheduler)
After you enable them follow these steps:

at /admin/config/workflow/rules/components/add
Create a ruleset (name it "Unpublish Content")
In the Settings/Variables:
Data type = "Node"
Label = "node"
Machine name = "node"
Save
...next screen...Add rule

Name = "Unpublish Content Rule"
Save Conditions:
Content is published

Data selector = node
Save

Content is of type = node
Value = your-content type
Save Actions:

- Unpublish content
Data selector = node
Save at /admin/config/workflow/rules
Create a rule (name it "Unpublish Rule"

- React on event = After saving new content
Save Conditions:
Content is of type
Data selector = node
Value = your-content-type
Save Actions:

- Schedule component evaluation

- Component Value = Unpublish Content

- Data selector = node:field-your-node-date-field
Identifier value = unpublish [node:nid]

- node Data selector = node
Save

Good luck!


Determine if two proportions from the same sample are different

Question: Is there a test I can use to compare two proportions from the same sample that are not mutually exclusive?
For example, I would like see if the proportion of people that answered "yes" to a particular question is significantly different from the proportion of people that answered "yes" to a different question.
Answer: The within-subjects test of equality of proportions is McNemar's test.  I discuss it fairly thoroughly here: What is the difference between McNemar's test and the chi-squared test, and how do you know when to use each?  The answer also provides an example demo in R, should you use that, but it should be easy to do in any software.
Answer: You could state as your null hypothesis the possibility that both answer statistics are drawn from the same binomial distribution, for the binomial that maximizes the chance that they are drawn from the same binomial.
I think @gung provides the better answer here. Note that the McNemar's test wikipedia article describes the use of the exact binomial sign test for small sample size (assuming equal population for both questions).
Comment: McNemar's test is equivalent to a binomial test, but a very specific one. The details are spelled out in my linked answer.


How to approach a proof where the answer can be both false and true?

Question: Definition of symbols:
Given $E = \{a,b\}$ an alphabet, $E^*$ denotes all strings over the alphabet i.e. $E^* = \{a,b,aa,ab,\dots\}$.
I have to answer: Given $A\subseteq E^*$, is $AA \subseteq A$?
If I define $A = \{a,b,aa,ab\}$, then by definition $AA$ is the concatenation of $A+A$, thus
$$AA = \{aa,bb,aaaa,abab\}$$
Since not every element in $AA$ is an element in $A$ that proves $AA$ is not a subset of $A$.
Whereas if I define $A = \{\epsilon\}$, then $AA = \{\epsilon +\epsilon\}=\{\epsilon\}=A$. This proves AA is indeed a subset of A.
What should I do here? I got a true case and a false case
Comment: The question "is $AA \subset A$?" actually means "is $AA \subset A$ in general?"; that is, "is $AA \subset A$ for all $A$?".
Comment: A few remarks: The empty string shoul dbe $\in E^*$. And with your $A$ we have $AA=\{aa,ab,aaa,aab,ba,bb,baa,bab,aaaa,aaab,abab\}$.
Answer: First as @HagenvonEitzen said you got your $AA$ wrong.
However you indeed have a case which is false and the other one which is true.
But the question as it is asked, ask whether the property hold for every $A\subseteq E^*$. And since you have found a counter example you can conclude that the property is false.


The fixed point iteration part b

Question:
I've solved part a. And for part b, I solved $g'\left(x\right)^2$ and when c=0 or $x=-b/c$, we have the minimum, but according to the problem, we can't reach it. So the minimum occurs when $x^2=2|c|$ and $b^2=9/2|c|$. To finish the proof, I need to find the relation between x and b. And use b to represent x, can I combine these two equations: $x^2=2|c|$ and $b^2=9/2|c|$ and say that $x=2b/3$? And still I don't know how to approach part c, any hints? Thanks a lot!
Answer: $$g^2(x)=b^2+\frac{2bc}{x}+\frac{c^2}{x^2}$$
Let $y=\frac{1}{x}$. Then
$$g^2(x)=b^2+2bcy+c^2y^2$$
We can check easily that this is a parabola that opens upward and touches the $x$-axis at only one point $y=-\frac{b}{c}$.
Now we want to show that $g^2(x)\geq 2|c|$ if $x^2\geq 2|c|$, i.e.,
$$-\frac{1}{\sqrt{2|c|}}\leq y \leq \frac{1}{\sqrt{2|c|}}$$
for some region of $b$.
There are two cases:

You can see from the picture, both cases should work. We need to find the intersection of the line $y=\frac{1}{\sqrt{2|c|}}$ and the parabola. That point is where $g^2(x)=2|c|$. When $-\frac{b}{c}>0$, it must also satisfy $-\frac{b}{c}>\frac{1}{\sqrt{2||c}}$. When $-\frac{b}{c}<0$, it must also satisfy $-\frac{b}{c}<-\frac{1}{\sqrt{2||c}}$.
Now there are four cases to discuss:

$c>0, b<0$; the result from the quadratic formula in $b$ tells you that $b=-\frac{3}{2}\sqrt{2c}$. In this case, $-\frac{b}{c}>\frac{1}{\sqrt{2||c}}$.
$c<0,b>0$; you will see that this case does not work.
$c>0, b>0$; this case does not work.
$c<0,b<0$; this case works, it satisfies $-\frac{b}{c}<-\frac{1}{\sqrt{2||c}}$.

In both working cases, when $b^2\geq \frac{9}{2}|c|$, they still satisfy the criteria for $y$.
For part (c), you just need to draw the curve $b^2=\frac{9}{2}|c|$, shade the region where $b^2\geq\frac{9}{2}|c|$ on the $bc$-plane. It should be a parabola passing through the origin. The convergence comes from part (a) and (b). We see that whenever $x_0^2\geq 2|c|$, by part (b), all the following points $x_n^2\geq 2|c|$. This guarantees that $|g'(x)|\leq \frac{1}{2}$. This also gives the convergence rate.
Comment: So I plug in $y=1/{\sqrt 2|c|}$ into the equation of $g(x)$. Since we know that y needs to be positive and $y=-b/c$, then b and c must have different signs. Then $b^2\ge 9|c|/2$. There are two cases, which are b is positive and c is negative or b is negative and c is positive. How can we rule one situation out or both of them work?
Comment: Plus I have problem calculating $2bc/\sqrt 2|c|$. If b is positive and c is negative. Then we have $2bc/\sqrt 2|c|$ = ${-3\sqrt2c^2}/\sqrt {2|c|}$. Then $g^2(x)= 5|c|-3c\sqrt |c|$. Then from there how can we get to the conclusion that $g^2(x)\ge 2|c|$?
Comment: @J.doe: I found a mistake I made. The two cases should both work. For your question, you will need some more analysis on the parabola. I will edit.
Comment: Got it! thanks!

The fixed point iteration part b


Find the condition that the given vectors are parallel.

Question: Find the condition that the vectors $\vec a=k\hat{i}+l\hat{j}$ and $\vec b=l\hat{i}+k\hat{j}$ are parallel.
Answer is $l^2=k^2$.
But I dont know how to find it using formula.
I searched everywhere but cant find something similar to this.

Edit -

This question is not from the scalar product questions. So please help me.
Comment: Are $\vec i, \vec j$ the usual unit vectors?
Comment: I don't understand what you want. Why don't you consider $l^2=k^2$ as a formula?
Comment: If parallel then a = pb where p is a any zero number. equate coefficients of i and j and away you go.
Comment: Its a and b vector, i cap and j cap. I dont know how to write. Sorry for that.
Answer: Two vectors  $\vec v $ and $\vec u $ are parallel only if their cross product is zero.

Using this concept, we have $$\vec a \times \vec b =\vec 0$$ $$k^2 - l^2 =0 \Rightarrow l^2=k^2$$ and we are done!!

Handicap of cross product is not a problem. If two vectors are parallel, then one of them will be a multiple of the other. So divide each one by its magnitude to get a unit vector. If they're parallel, the two unit vectors will be the same.
We can see this is satisfied by $\vec a $ and $\vec b $, so they are parallel. Hope it helps.
Comment: Without using cross product.
Comment: I know using cross product. This is not what i am looking for.
Comment: @John Sr This is the simplest condition to show two vectors are parallel. Even Arnaldo has expanded my thoughts on the same lines. Hope I can understand your problem.
Answer: If $\overrightarrow{a}=ki+lj$ is parallel to $\overrightarrow{b}=li+kj$ then, by definition, there is $\alpha$ such that
$$\overrightarrow{a}=\alpha\cdot \overrightarrow{b} \rightarrow ki+lj=(\alpha l)i+(\alpha k)j \rightarrow (k-\alpha l)i+(l-\alpha k)j=0$$
once we have a null vector then each coordinate is zero.
That give us:
$k=\alpha l \quad (1)$
$l=\alpha k\quad (2)$.
Putting $(2)$ in $(1)$ we get:
$$k=\alpha l=\alpha^2 k \rightarrow k(1-\alpha^2)=0$$
so $k=0$ or $\alpha = \pm 1$.
1) If $k=0$ then, from $(2)$, we get $l=0$ and then $l^2=k^2$
2) If $\alpha = \pm 1$ then, from $(2)$, we get $k=\pm l$ and square both sides and get $l^2=k^2$.
Comment: After comparing i am not understanding what you are doing. Can you explain?
Comment: of course, I will write in more details.
Comment: please take another look. Is that clear?
Comment: Can i find the value of aplha from equation 1 and put it in equation 2? Is it correct? Then i got the answer.
Comment: Yes, you can, but the value of $\alpha$ is already found. See $2)$.


Finding the smallest positive integer $n$ such that $S_n$ contains an element of order 60.

Question: I am trying to find the smallest positive integer $n$ such that $S_n$ contains an element of order 60. I know that every permutation in $S_n$ can be expressed as the product of disjoint cycles, and I also know that the order of a permutation is the least common multiple of the lengths of the cycles in its disjoint cycle product.
So, suppose $\sigma \in S_n$ such that $|\sigma|=60$. Then $60=lcm \left\{|c_1|, \ldots , |c_m|  \right\}$, where $c_i$ is one of the cycles in the disjoint cycle product of $\sigma$. The prime factorization of 60 is $2^2\cdot 3 \cdot 5$, but the least common multiple of 2, 3, and 5 is 30, so that doesn't help. However, the least common multiple of 3, 4, and 5 is 60. I just don't know where to go from here.
Also, what is meant by a "disjoint cycle pattern"? Thanks for your help!!
Comment: Without further context, I would assume this is a disjoint cycle pattern: https://en.wikipedia.org/wiki/Cycle_notation#Permutation_as_product_of_cycles
Comment: Here are some [answers to this kind of problem](http://oeis.org/A000793).
Answer: You are definitely on the right track. As you know that $lcm(3,4,5)=60$, you know that the following permutation has order $60$:
(1 2 3)(4 5 6 7)(8 9 10 11 12)
So $S_{12}$ definitely has an element of order $60$.
However, $3$, $4$, $5$ isn't the only set of numbers with an lcm of $60$. For example, $5$, $12$ also works. But that would give an element of $S_{17}$, which isn't any better.
You just need to do a little bit of explaining of various cases to show that any other set of numbers with an LCM of $60$ can't have a sum of less than $12$.