With respect to right hand guitar technique, what does it mean to not scoop?

Question: Scooping comes up in in this answer:

Move your hand in parallel with the strings (i.e. don't scoop)

What exactly does that mean?  I've only seen it in reference to tone.
Comment: You could leave a comment under the answer asking for explanation. What I think he means is that for this technique you shouldn't turn your wrist, i.e. make a circular movement with your pick, but instead move it in a straight line.
Comment: I have the suspicion it means... not moving the hand in parallel with the string, as if with a scoop (https://www.youtube.com/watch?v=zXIPaKibKKg)
Comment: @SomeDudeOnTheInterwebs ha, i like the cutco video.  i guess i don't see where, on a right handed guitar, the right hand would move parallel to a string while picking (while tapping, i could see).  for picking consecutive notes on a string, i don't tend to move much, if at all.  if i pick notes on two different strings, i generally move perpendicular to the strings, not parallel.  i imagine that means i don't scoop but i'm still not sure what plane the circular motion from 'scooping' happens in.
Comment: @MattL. okay, actually curling the wrist makes sense i think.  as in i shouldn't keep my forearm still, curling my wrist to reach strings, i should try to move in a straight line across the strings, perpendicular to the direction they're strung in, which will require my forearm to move a lot more?  if you post an answer, i'll accept.
Comment: http://music.stackexchange.com/questions/20637/what-is-a-flat-wrist -- I think that this is a similar idea in the context of bass guitar.
Comment: @Dave ha well if evh scoops like that post says, i think that just makes me feel worse about myself...
Answer: Particularly when using only upstrokes with tones on the same string, at least I get a more pronounced scooping motion when the pick moves towards the string. You still strike perpendicular to the string. I believe what is described is whether or not this motion is parallel to the body of the guitar.
If you try striking a a chord using up- and downstrokes, and you limit yourself to only move your wrist, not your lower arm, I think you will see this scooping motion. (Don't anchor the palm on the bridge, since then it won't be as noticeable).
Comment: @aeroNotAuto: For clarity: anchoring to bridge or pick guard is not wrong by any means, I just meant it should be avoided in this case to see the "scooping" effect more clearly.
Comment: +1 i actually think i do have a slight problem with this and i suspect my anchoring may play a large role in it...not to the bridge, to the pick guard, but still.
Comment: if the avoidance of scooping means moving the hand parallel to the plane of the strings in order to move from string to string, doesn't anchoring keep the hand in one place, forcing me to scoop?  **edit:** nevermind.  i just tried it and anchoring just gives me a feel for distance from the guitar; my hand is still able to move enough between nearby strings.  excuse my haste.
Answer: In the answer you linked, the reference to scooping could have meant to keep your pick close to the strings as you move up and down the neck as opposed to allowing your picking hand to "scoop" (drop) below the neck.  Obviously the only person who can say for sure is the person who posted said linked answer.
This advice applies to playing fast picking runs where you don't want any wasted motion slowing you down.  So you don't want your pick to stray too far away from the strings you will be picking.
It does not refer to the picking motion itself (which would be perpendicular to the strings) but to your hand position as you move to different places on your fretboard.
To use an analogy - if you are playing a fast run on the 2nd and 3rd strings - pretend like those are the rails of a railroad track and your picking hand is the train. Don't let the train get off the track as it moves back and forth to play higher or lower notes on the fretboard.
Comment: by scoop below the neck you mean move toward the bridge?  is this related to your comment about straying too far away from the strings to be picked?  i am unsure why the pick would be farther from the strings when picking near the bridge, and closer to the strings when picking near the neck.  i certainly could see lots of wasted motion if the picking hand were moving between the neck and bridge repeatedly, though.
Comment: @aeroNotAuto Not closer to bridge closer to the ground.  If you are playing a fast run on the 2nd and 3rd strings - pretend like those are the rails of a railroad track and your picking hand is the train.  Don't let the train get off the track.
Comment: sorry if i'm being dense, but i don't get what direction you mean by the ground.  if i'm standing, playing an electric, toward the ground takes me away from the strings i'm playing/prevents me from playing the strings i want.  we are talking about the same thing, right?  for a right handed guitar, left hand moving about the fretboard, right hand nearly stationary, picking notes on the g and b strings (unless you mean while tapping).  is scooping common in that people will downpick and follow through with their hand, moving it in the picked direction, and then have to return to the string?
Comment: @aeroNotAuto   Yes - I think you are getting it.  Most beginning guitarist or those who don't play really fast picking patterns tend to scoop their picking hand down past the strings and then come back up.  That is a good way to play rhythm guitar because you can get your wrist swinging in time with the rhythm like a pendulum.  But it will slow you down if you are doing fast picking.
Comment: ohhhh it totally makes more sense now that you put it in the context of rhythm guitar
Comment: kiprainey clarified in the original question, but +1 for your patience while spoon feeding me until i figured out up from down
Answer: As mentioned in my comment, it would be best to ask the user who answered that other question what he exactly meant. Here I can tell you what I think he meant, and also what my take on this issue is.
First of all I think that "scooping" is not at all a standard term when it comes to right-hand guitar technique. What I think is meant by it in the context of the question is the movement of the pick on a circle that is perpendicular to the plane of the strings (which is of course only an approximate plane, depending on the fretboard radius and the setting of the bridge). This movement is caused by a curling movement of the wrist (like playing badminton).
Instead, what (I think) should be done when playing fast downstrokes (this is what the original question is about) is a small up-down movement of the pick by moving it in the plane of the strings. This movement will usually also follow (a very small part of) a circle, but this time the circle lies in the plane of the strings. The movement won't normally be an exact straight line because usually palm muting is required and your palm is fixed to the low strings. So I think that a large portion of the movement should come from your wrist and not so much from your forearm, it's just that the wrist moves differently: it moves up and down and doesn't turn.
Comment: yea, i commented on that answer, asking for an explanation.  i just assumed this was a widespread term i hadn't heard of yet/i didn't know i'd get such varied answers.
Comment: standard term or not, kiprainey did clarify.  your original suspicion appears to be on point.


Does $E\frac{1}{\|x\|^{4}} \rightarrow \frac{1}{E\|x\|^4}$ in high dimensions?

Question: Suppose we have a Gaussian distribution centered at zero, covariance matrix $\Sigma$ with $\operatorname{Tr}\Sigma=1$ and $\operatorname{Tr}\Sigma^2=\frac{1}{2}$
When I try various sequences of such Gaussian distributions (for instance, by letting $\lambda_i=c_1 i^{-c_2}$ and solving for $c_1,c_2$), I see the following:
$E\frac{1}{\|x\|^{4}} \xrightarrow{simulation} \frac{1}{E\|x\|^4}$
Can this be shown more rigorously?

notebook
Comment: This norm is the following? $$\Vert \mathbf{x} \Vert^4 =\left(\sum_{i=1}^n x_k^2\right)^2$$ the fourth power of the Euclidian distance?
Comment: This question looks like it's making some unstated assumptions.  After all, consider the sequence of diagonal covariance matrices in dimensions $d=1,2,3,\ldots$ with $(1/d,0,0,\ldots,0)$ on the diagonal.  Their spectral norms $1/d$ converge to $0.$ Yet, in all those cases $E[1/||X||^4]$ is *infinite* while $E[||X||^4] = 3/d^2 \to 0.$  Indeed, the very statement of the question makes no sense, because the right hand side is itself a sequence rather than a number.  Perhaps you mean something like $E[||X||^4]E[1/||X||^4]\to 1$?
Comment: Looks like a case for Jensen's inequality
Comment: I may be missing something but Jensen's bounds the quantity in question from the wrong side
Comment: Oh, okay. My thought was that with a strictly convex function it should only reach equality when the variance is 0.
Comment: I guess that the distribution of $\Vert \mathbf{x} \Vert^4$ will approach a singular distribution (ie a constant value). Then you have for any continuous function $f$ that $E[f(x)] = f(E[x])$. The problem that remains, is proving that  $\Vert \mathbf{x} \Vert^4$ approaches a singular distribution. Possibly some variant of law of large numbers can do that (it will be tricky because of the correlation between the terms $x_k$ in the summation).
Comment: Actually, the function f:x = 1/x is not continuous. The expectation E[1/X] may not exist or can be infinite.
Comment: @Sextus You're right -- I was forgetting that.  (The spherical factor of $\rho^{n-1}$ multiplies the density and vanishes at the origin.)  I'll delete that comment to avoid confusing anyone.
Comment: $\operatorname{Tr}\Sigma=1$ is one of the original assumptions, so you can't have (1/d,....)
Comment: the ratio of E[||X||^4] and E[1/||X||^4] going to 1 would explain the observed phenomenon
Comment: There was a suggestion on Mathoverflow to use an integration trick which may justify switching the order of E/reciprocal  -- https://mathoverflow.net/questions/431036/does-e1-f-to-1-ef-in-high-dimensions?noredirect=1#comment1109319_431036
Answer: Reformulation in terms of linear combination of $\chi^2(1)$ variables
We can reformulate the problem.
Let's rewrite $$\Vert \mathbf{x} \Vert^4 =\left(\sum_{i=1}^n x_k^2\right)^2 = Y_n^2$$
Such that we can focus on the variable
$$Y_n = \sum_{k=1}^n x_k^2$$
and the problem statement in terms of $Y_n$ becomes
$$E[1/Y_n^2] \to 1/E[Y_n^2]$$
we can make another reformulation and consider the eigenvalues $\lambda_k$ of the matrix $\Sigma$ then we can express $Y_n$ as a linear combination of $n$ iid chi squared variables.
$$Y_n \sim \sum_{k=1}^n \lambda_k Z_k \qquad \text{where $\forall k:Z_k \sim \chi^2(1)$}$$
where we have the conditions that

$\sum_{k=1}^n \lambda_k = 1$, which relates to the condition that $Tr(\Sigma) = 1$.
$\max(\lambda_k) \to 0$, which relates to the spectral norm approaching zero.

The mechanism behind the convergence
The expectation and variance of $Y_n$ is
$$E[Y_n] = \sum_{k=1}^n \lambda_k = 1$$
and
$$\text{Var}[Y_n] =  \sum_{k=1}^n 2 \lambda_k^2 \to 0$$
Intuitively: The variable $Y_n$ approaches a constant value $1$ and that is how $E[1/Y_n^2]$ will approach $1/E[Y_n^2]$.
I am not sure how to make this formal. I am thinking about something like the continuous mapping theorem. If $Y_n \to 1$ then $f(Y_n) \to f(1)$. But I am not sure whether the decreasing variance is sufficient to state that $Y_n \to 1$ and what sort of convergence is exactly needed or allowed to make the statements.
A problem with the convergence
In intuitive terms we see that the variance shrinks to zero and that is what makes the convergence happen, at least seemingly in simulations. A point that worries me is that a function like inverse $E[1/Y_n^2]$ can involve division by zero and result into an infinite or undefined expectation. For instance if we have some normal distributed variable $W_n \sim \mathcal{N}(1,1/n)$ then we do not get convergence $E[1/W_n] \to 1/E[W_n]$ because the expectation of $1/W_n$ is undefined.
So a problem with the above intuitive reasoning is that the $E[1/Y_n^2]$ may be undefined when the density of $Y_n$ at zero is finite. For instance the inverse of the square of a chi-squared distribution has no finite expectation value when $\nu \leq 4$ (see the variance of a inverse chi-squared distribution).
What we need to proof is that we can not have the $\lambda_k$ in such a way while $max(\lambda_k)$ approaches zero.
I imagine for instance a dominant term that approaches zero very slowly while the remaining terms approach zero very quickly. E.g. some slowly decreasing function of $n$ such that
$$\lambda_k = \begin{cases} f(n) &\quad \text{if} \quad k=n \\
\frac{1-f(n)}{n-1} &\quad \text{if} \quad k\neq n \end{cases}$$
Then $Y_n$ is a sum of two chi squared variables, one with 1 degree of freedom and another with $n$ degrees of freedom.
$$Y_n \sim f(n) \chi(1) + \frac{1-f(n)}{n-1} \chi(n-1)$$
I don't believe that this $Y_n$ has a non-zero density. I also don't believe that any other similar approach can result in a non-zero density for $Y_n$.
We have
$$Y_n \sim \sum_{k=1}^n \lambda_k Z_k > \sum_{k=1}^n \min(\lambda_k) Z_k \sim \Gamma(k=n/2, \theta = 2 \min(\lambda_k))$$
Because the $Y_n$ is gonna be made of at least 4 components (otherwise $\max(\lambda)$ can't approach zero) you get that the variable $Y_n$ is at least as large as a scaled chi-squared variable with more than 4 degrees of freedom and the density at zero should should be zero.
Comment: @YaroslavBulatov I think an important step in that lemma is by considering the inequality $\Vert x \Vert \geq R$ where $R$ is a gamma distributed variable. For the [inverse gamma distribution](https://en.m.wikipedia.org/wiki/Inverse-gamma_distribution) the moments exist if the shape parameter is sufficiently large and so the expectation of $(1/\Vert x \Vert)^p$ also exist.
Comment: Would de la Vallée-Poussin theorem be useful here? It [was used](https://mathoverflow.net/a/430978/7655) to show that you can switch order of expectation and reciprocal for $\left\|x\  \sum_ix_i \right\|^2$
Comment: So it seems the tricky part is establishing conditions equivalent to "shape parameter is sufficiently large". Intuitively, the spectrum of $\Sigma$ should be heavy tailed. Simply restricting first two moments are not sufficient. However, using polynomial decay with restriction on first 2 moment constraint may be. Some discussion on conditions is here -- https://mathoverflow.net/a/431220/7655
Comment: BTW, if eigenvalue decay is fixed at power-law 1, it turns out you can switch the order of E and reciprocal -- https://math.stackexchange.com/questions/4551590/what-is-e1-x-4-where-x-sim-gaussian0-c-cdot-diag1-1-2-1-3-1-4-ld/4552910#4552910
Comment: The approach of the density to zero in the point zero $$f_{Y_n}(0) \to 0$$ , might possibly also be reasoned by using the characteristic function which will be a product $$\varphi(t) = \prod_{k=1}^n (1-2\lambda_k it)^{-1/2}$$ and the inversion formula which will lead to $$f_{Y_n}(0) = \frac{1}{2\pi} \int_{-\infty}^{\infty} \varphi(t) dt$$ but I am not yet sure how to show that this integral will equal zero.
Comment: Something in the answer needs to be still improved. It is not just important that the desnity is zero at the point zero $f_{Y_n}(0) = 0$, we must also have the derivative equal to zero.
Comment: Showing that $f_{Y_n}^\prime(0) = 0$ and $f_{Y_n}(0) = 0$ might be possible by writing the distribution density function [as a mixture of Chi squared distributed](https://stats.stackexchange.com/questions/72479/generic-sum-of-gamma-random-variables) variables and then use the coefficients of the smaller order terms to compute the values of the density.


How can I find the CDF and PDF of $Y$?

Question:
Problem
Let $X$ be a $\operatorname{Uniform}(0,1)$ random variable, and let $Y=e^{-X}$.
Find the CDF of $Y$.
Find the PDF of $Y$.
Find $\mathbb E[Y]$.

My problem
If I solve for the range of $y$ I get $\left(1, \frac 1e \right)$, but because $Y$ is not an increasing function, my second bound is smaller than my first. I am really confused as to how I would be able to solve for the CDF and PDF in this case... Any help would be greatly appreciated.
Answer: For $y$ in the interval $(1/e,1)$ we have
$$\small F_Y(y)=\Pr(Y\le y)=\Pr(e^{-X}\le y)=\Pr(-X\le \ln y)=\Pr(X\ge -\ln y)=1-(-\ln y)=1+\ln y.$$
For completeness, we add that $F_Y(y)=0$ if $y\le 1/e$, and $F_Y(y)=1$ for $y\ge 1$. Note, in the above calculation, the switch in the direction of the inequality, when $\Pr(-X\le \ln y)$ was replaced by $\Pr(X\ge -\ln y)$.
Now the pdf is easy to find. For $E(Y)$, we can use the newly found pdf of $Y$, or else bypass the distribution of $Y$ entirely, computing $\int_0^1 e^{-x}\,dx$.
Comment: This is very helpful. Thanks. However, would the CDF be 0 for y < 1 and 1 for y > 1/e? This part does not really make sense.
Comment: Yes, I computed the cdf only for "interesting" $y$. But the cdf is defined for all $y$. If $y\gt 1$, then for $Y\le y$, so $F_Y(y)=\Pr(Y\le y)=1$. And if $y\lt 1/e$, we cannot have $Y\le y$, so $F_Y(y)=0$.

How can I find the CDF and PDF of $Y$?


Sample size determination for a pilot study

Question: I am struggling to figure out how should I approach to decide the sample size for a pilot study. The pilot study will be funded so a proposal is required justifying the sample size. The study participants are patients from a city hospital which will be extended to multiple cities in the main study. Patients will be evaluated based on the present of an attribute (this is not a randomized control trial, however, based on a character, we will have two groups of patients). Most of the measurements obtained will be numeric. From a previous study with a broader goal has a response rate of 40%.
I read some literature and liked the idea of deciding the sample size based on feasibility a good literature. I do have a confusion, though. When I calculate the sample size based on the proportion of nonresponse for a particular level of confidence, what does the margin of error mean here? Is is the margin of error for the estimates from my study or, the margin of error for the nonresponse rate?
Any help is greatly appreciated! Thank you.
Comment: What is the purpose of your pilot study? What do you hope to get at the end of this... what question are you trying to answer? Next, what are you going to measure in order to answer the question? Once you have a measure, how are you going to analyze your data and with what degree of precision and power do you need from your analysis to answer the question? If you know this... can you just work backwards to determine sample size?
Comment: Since time and money are not constraints, enroll everybody everywhere all the time.  Follow nonresponse up with personal visits and arm-twisting to get data from everyone.  You might as well do this worldwide, since you have unlimited resources.  If these recommendations (which are perfectly logical consequences of your assertions) strike you as ridiculous, then you need to back up and consider (1) the resources you might actually get and (2) what the objectives of this study are.  We can't tell you anything useful until you disclose at least that much information.
Comment: Often pilot studies are used to determine the required sample size for the size next study.  Sample size is often related to variance.  So since the variance is often not known (approximately)  the estimate from the pilot study is used.  Of course to two studies should be close to identical.
Comment: @whuber Did some editing... I hope you are a bit calmer now :)
Comment: @MattS Thank you, Matt, for your suggestion. I will look into this option to see if I can make it work.
Comment: I like the above mention my Michael that the purpose of a pilot study is for generating data that will allow you to calculate sample size in a future pivotal study. There is a rule of thumb mentioned in the literature that 12 subjects per group is a good starting off point when no other data is available for estimations.  However, Many things are unclear in your question. Most importantly, what is the ultimate goal (e.g. the response of subjects to a drug; a diagnostic device/method study; or is it something altogether different)?
Comment: @jeffalltogether The ultimate goal is to see, out of all these patients those who have a treadmill, for example, in the house are more physically active. We can have the average physical activity of these patients per week. We can also find the correlation of physical activity with well-being and test if patients with a treadmill have a higher correlation between physical activity and personal well-being.
Answer:
The ultimate goal is to see, out of all these patients those who have a treadmill, for example, in the house are more physically active. We can have the average physical activity of these patients per week. We can also find the correlation of physical activity with well-being and test if patients with a treadmill have a higher correlation between physical activity and personal well-being.

I think in your case you would want to start with a simple cohort study as opposed to a randomized control trial (RCT). An RCT would be ideal (but more costly) for your eventual pivotal study. The goal of this cohort study would be to ask: does exposure to x (having a treadmill in the house) associate with outcome Y (increased physical activity)?
Such a study would recruit a group of people with a treadmill in the house and a group of people without a treadmill (the unexposed group) and follow them for a set period of time and note differences in the incidence of physical activity (PA) between the groups at the end of this time.
The groups should be matched in terms of other variables such as economic status and other health status so that the variable being assessed, the independent variable (in this case, owning a treadmill) can be isolated as the cause of the dependent variable (in this case, PA).
your statistical method would be based on your measure(s) of PA.  One thing to consider is how many PA measures can you obtain from each cohort, and how often will you take these measures (daily, weekly, monthly).
From my perspective, focusing on a large group of PA measures and identifying their variance within the two groups and between the two groups would be critically important for this pilot study.  You may find some measures vary a lot and would be terrible as metrics to design a future pivotal study, whereas others are less variable and would require a much smaller sample size in a future pivotal study to obtain an appropriate Power.
If you do perform any statistical significance testing using this pilot study data, take it with a grain of salt.  The family-wise error rate will come into play.  If multiple comparisons are done or multiple hypotheses are tested, the chance of a rare event increases, and therefore, the likelihood of incorrectly rejecting a null hypothesis (i.e., making a Type I error) increases.
Here there is an explanation and advice given on sample size estimations for cohort studies.  Remember to consider any sample size will need to be adjusted to account for the expected drop-outs from your study.
Lastly, you may be able to perform a less costly Case-Control Study to determine if people that have higher levels of PA tend to own treadmills.  It may be difficult to calculate your measures of PA on people based on a questionnaire or survey, but the study would be simpler to perform, because you would not need to find and follow people over time.  However, it would be less valuable to help you plan for a pivotal study.
Hope this helps.
Comment: @jeffaltogether Thank you for your elaborate response! However, it will be a cross-sectional study. Mail surveys will be sent out to the participants and 40% of the participants are expected to have a treadmill in the house.


Can you request songs to learn from piano teacher

Question: My piano teacher mostly teaches me pieces in the genre of classical/children e.g. the last piece she taught me was Entrance of the Gladiators.  I'm getting bored of these songs and I want to request songs I listen to on youtube like richard marx Right Here Waiting.  Is this appropriate to make this request to learn my choice of song?
Note my teacher has at least 10 students and those near/at my skill level all have the same books and learn the same pieces.
Comment: Absolutely it is appropriate. If your teacher says yes, you'll get more out of your lessons; if your teacher says no, it is also appropriate to find a new teacher.
Comment: I've kind of only had one one-on-one teacher—well two, my guitar teacher and his wife on piano and voice—at lest before college and not counting one-off masterclass type situations. And the best thing was that not only did he have a personalized plan for what to teach and when, but he would drop that immediately if I brought music in to learn. It is _so_ important to learn the things that _you_ love. Either find a teacher that embraces that or do the extra part on your own because it's an important part of finding your voice as a musician.
Comment: To follow up on Aaron's comment: the answer to almost any question that begins "Can I request?" is yes :)
Comment: This reminds me of when I had my piano/keyboard teacher asking me if I wanted to focus on classical or modern songs at the first meeting. Perhaps you can open a conversation similar to this with your teacher to let them know what you're really interested in.
Comment: choose Zez Confrey's "Dizzy Fingers"
Answer: Edit - Now this is the top answer, I'll quickly answer the question, which is yes, you certainly can! But please read on...
I'd like to put forward a caveat - even if your teacher is willing, this may not be your only concern. It sounds like you might be interested in learning a very different skill. Let me explain through a quick personal interlude.
I was roughly classical grade 7-8 playing standard, and I asked my teacher if we could move towards jazz and 'modern' music, and he happily obliged. It turned out he was very talented at playing 'by ear', and so he basically taught me that skill from scratch. My finger dexterity was useful, but everything else I had to relearn, and this included not being dependent on sheet music at all. There are many new skills involved with this including knowing more scales, understanding chord theory, 'hearing' chord progressions, etc... and of course a lot of practice!
I was lucky that my teacher could teach these skills. If he hadn't, he probably would have tried to get me to find sheet music of the songs and teach me in the same way that most teachers are used to teaching. This may be what you're after, in which case no problem. If you want to embrace a very different form of piano, however, it may be possible that you will need a different teacher regardless of willingness since even some excellent sheet music teachers may not have the skills to teach this very different skill.
After 20 years I have now re-embraced classical (you can't beat playing a bit of Beethoven...) but I continue to write my own 'modern' pieces, improvise, and play along to songs I like as well. Additionally I can sit down at the piano and jam in any key with other musicians, or get someone to sing a song and play along with them after just a few run throughs to 'get' the chords on which I can then play the tune or improvise a backing. This more spontaneous, social aspect of music has bought me an enormous amount of enjoyment.
To be honest, I don't even think I'm that good! I don't practice nearly enough, and am ill-disciplined with my practice (maybe I should get a teacher again!) However my experience is that it's a much less common skill than being able to read music. However it is not an easy transition; beyond the obvious interface between hands and keyboard, I find the two to be almost completely different skills.
Answer: I hope you have a good enough relationship with your piano teacher that you don't have to be frightened of making such a request.
But why ask?  You want to play this piece, get hold of the music and just do it.  No permission required!  Here's one source.  It isn't expensive.
Maybe in the lesson you can say 'May I play you something I've done by myself?'   Perhaps also 'Can you help me on bar xx' I'm finding that bit hard?'
https://www.virtualsheetmusic.com/score/HL-166888.html
Comment: Even better, if the OP can just pick up sheet music for a song in unfamiliar genre and play it right away, they probably don't need the teacher at all.
Answer: Yes, of course you can ask. But there may well be caveats.The sheet music may not be available at an appropriate level for your playing. I guess these days, it can be bought in any key - which is something your teacher will be considering with any piece you learn.
It will also be important for the teacher regarding the style of the piece. But by and large, if teacher agrees to half of your suggestions, it's good. And she should give reasons for accepting and rejecting. It would be unresonable to expect her to transcribe music for you, although that's exactly what I did in a lot of my lessons - students brought along  a recording, and it got transcribed there and then - usually. In some form that was useful for each student. (More frequently on guitar or bass, although it did happen on piano, too).
Bear in mind that some teachers have their own curriculum which excludes this sort of approach - for better or worse - so it's your choice if the idea is refused whether you ccontinue with her, or search for another.
Answer: Sure, your teacher should be able to find something within any song to further your skills.  However, that particular style of music may not be something your teacher is comfortable with but that shouldn't make a difference. I had a classically handicapped organ teacher who was always asking what I was working on behind his back and would proffer advice despite jazz not being his forte. A deviated twist of the wrist is a twist of the wrist regardless of style.
Something else to keep in mind, your teacher may have a plan for you.  They may be exposing you to varied technical factors found in the music they are prescribing in order to cumulatively build upon your technique or reading skills.
It can't hurt to ask and discern if your teacher is reticent because they have a plan or because they are insecure in the new music.
Your teacher should be able to find technique adjustments to make in every two to eight bars of music even in popular music.  Actually, especially in popular vocal scores since those are not often very pianistic.
Even if the style is not in your teachers wheelhouse they should be able to suggest how to "tell a story."  Playing is not merely getting from the first to last bar regardless of technical proficiency.  There is much going on in-between such as phrasing, breathing, bringing out a line, dynamics, climax, entasis . . . . Ask your teacher to play the piece.  The very thing you may learn is what not to do.


Combining effect sizes to learn about the difference between two groups?

Question: I am interesting in learning if there is difference between the control and the treatment group in a paper I am reading. Unfortunately the paper only compares the respective conditions to a 0 effect size. The paper does not have open data or report standard deviations.
The relevent results reported in the paper are:

A one-sample t test on the recommended IAT measure indicated that the mean D score for the participants in the control condition (M = −.19 was significantly less than zero, t(29) = −2.50, p = .019. The estimated Cohen's d for this effect was .46. In contrast, a one-sample t test indicated that the mean D score for the participants in the perspective taking condition (M = −.13) was not significantly less than zero, t(29) = −1.61, p = .119.

Is it possible to compare the two effect sizes to learn about the difference between the two conditions instead?
Answer: I assume that what you are interested in is the difference in differences. Simply differencing the mean D for the treatment and control is this value (i.e., -.19 - (-.13) = -.06). You can compute a t-test on this difference by recovering the standard deviations of the difference scores from the t-value:
$$ s_D = \sqrt{\frac{M_D^2 N}{t^2}} . $$ For the control group, this is:
 $$ s_D = \sqrt{\frac{-.19^2(30)}{-2.50^2}} = 0.416 . $$
For the treatment group this is:
 $$ s_D = \sqrt{\frac{-.13^2(30)}{-1.61^2}} = 0.442. $$
With these values, you can compute a t-test comparing these two mean difference scores:
$$
t = \frac{M_{D_{Tx}} - M_{D_{Cg}}}{
\sqrt{
\left(\frac{ s_1^2(N_1 - 1) + s_2^2(N_2 - 1)}{N_1 + N_2 - 2}\right)
\left(\frac{N_1 + N_2}{N_1N_2}\right)
}  } ,
$$
$$
t = \frac{-0.19 - (-0.13)}{
\sqrt{
\left(\frac{ 0.442^2(30 - 1) + 0.416(30 - 1)}{30 + 30 - 2}\right)
\left(\frac{30 + 30}{30(30)}\right)
}  } = -0.1397 .
$$
This is a more meaningful test of any treatment effect and is the interaction in a 2 by 2 split-plot ANOVA (time by treatment).
Note that the authors computed Cohen's d as the mean difference divided by the standard deviation of the mean difference. A more standard Cohen's d for paired data is to divide by either the pre-test standard deviation or both the pooled pre and post-test standard deviations. Dividing by the standard deviation in differences is standardizing change relative to variability in change across people rather than simply variability in the measure across people. I think that the latter is far more interpretable.


I need to calculate the intersection of an arbitrary line and a vertical or horizontal line

Question: Let us say I have a straight line. I also have a graph, 480x360. How could I take this line, and calculate where it intersects the edge of the graph?
The graph's x-axis spans from -240 to 240, the y-axis spans from -180 to 180. (apologies if this isn't clear enough, I'm not the best at explaining)
Comment: How is your line given? What parameters about it are available to you?
Comment: I suggest you update your question so that the above comment is contained in the question. That will help other people understand what you are asking without need to go through comments.
Comment: The line has 2 points, of which I can calculate the y intercept and the slope.
Answer: The equation for a line is $y = ax + b$, where $a$ and $b$ are constants which determine the precise form of the line in 2D. Then solve the equations:
$y = ax + b$
Such that $x = \pm 240, -180 \leq y \leq 180$. And:
$x = (y - b) / a$
Such that $a \neq 0, y = \pm 180, -240 \leq x \leq 240$
Comment: Thank you! (I had to add more characters to post this)
Answer: I'll assume you have some sort of equation in $x$ and $y$ defining your line.
Then, to pick one of your edges to start with, the equation of the right edge of your graph is $$x = 240$$ Plug that into your equation and solve for the value of $y$, and let's call that value $y_0$. Then that intersection point is $$(240, y_0)$$
You then do the analogous procedure three more times for the other edges. But note that you'll need to check the range of your answers - most likely only two out of the four intersection points will actually lie within range of your graph.
To get a more specific answer, you'll have to be more specific about what form you have your line in.
Answer: Let's just say without loss of generality the equation of the line is ax + by = c. Then to find when it intersects the right edge of the screen, we plug in x = 240 and then we can solve the linear equation to find the point where it intersects the top edge. We can find the other intersections by plugging in x = -240, y = 180, and  y = -180 to see where it intersects the left, upper, and bottom edges, respectively.


how can I calculate confidence interval with small sample in R?

Question: I have 50 observations, and I can get a mean and standard deviation values.
In this situation, how can I get a 95% confidence interval in R?
using bootstrapping?
0.594697 0.7976501 0.7355372 0.62818 0.747004 0.7532847 0.7995311 0.6793388 0.8202614 0.8590078 0.738024 0.7661064 0.7637131 0.7321101
0.776 0.744 0.7648953 0.7586619 0.7785349 0.7878261 0.7713004
0.7475 0.6495327 0.7227616 0.7196819 0.8996283 0.782305 0.7246596 0.7146497 0.7353723 0.7438424 0.7124183 0.7059484 0.848659 0.7678571 0.737467 0.7839335 0.677763 0.7725173 0.7493671 0.7091932 0.7445008 0.7404922 0.816358 0.8039816 0.7058824 0.7371795 0.8243243 0.7151899 0.7307692
Comment: What's wrong with the regular t-stat approach to a confidence interval for $\bar{x}$? The command is something like t.test(X)\$conf.int.
Answer: I pasted your $n=50$ observations into R.
A Shapiro-Wilk test doesn't reject the null hypothesis of
normality, even though a histogram suggests slight left skewness.
Any skewness may be inconsequential: the sample mean and median are nearly equal.
summary(x)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
 0.5947  0.7232  0.7458  0.7504  0.7779  0.8996

In these circumstances either of the following 95% confidence intervals
from R seems useful: (a) a nonparametric confidence interval $(0.737,\, 0.746)$ for
the population median $\eta,$
or (b) a t confidence interval $(0.735,\, 0.766)$ for the population mean $\mu.$
wilcox.test(x, conf.int=T)$conf.int
[1] 0.7371894 0.7641243
 attr(,"conf.level")
 [1] 0.95
t.test(x, conf.int=T)$conf.int
[1] 0.734852 0.765924
 attr(,"conf.level")
 [1] 0.95

In my experience I would expect a nonparametric bootstrap CI, as suggested by @storyteller0815 (+1), to
give about the same result (because these two traditional CIs are
in substantial agreement). I did a simple quantile-method bootstrap
procedure with 2000 iterations, obtaining $(0.736, 0.766).$
Answer: Check out the package simpleboot. To get the CI for the mean:
install.packages("simpleboot")
library(simpleboot)
library(boot)
d <- c(0.594697, 0.7976501, 0.7355372, 0.62818, 0.747004, 0.7532847,
       0.7995311, 0.6793388, 0.8202614, 0.8590078, 0.738024, 0.7661064,
       0.7637131, 0.7321101, 0.776, 0.744, 0.7648953, 0.7586619, 0.7785349,
       0.7878261, 0.7713004, 0.7475, 0.6495327, 0.7227616, 0.7196819,
       0.8996283, 0.782305, 0.7246596, 0.7146497, 0.7353723, 0.7438424,
       0.7124183, 0.7059484, 0.848659, 0.7678571, 0.737467, 0.7839335, 0.677763,
       0.7725173, 0.7493671, 0.7091932, 0.7445008, 0.7404922, 0.816358,
       0.8039816, 0.7058824, 0.7371795, 0.8243243, 0.7151899, 0.7307692)

boot.obj <- one.boot(d, FUN = mean, R = 10000)
boot.ci(boot.obj, conf = 0.95, type = "all")

BOOTSTRAP CONFIDENCE INTERVAL CALCULATIONS
Based on 10000 bootstrap replicates

CALL :
boot.ci(boot.out = boot.obj, conf = 0.95, type = "all")

Intervals :
Level      Normal              Basic
95%   ( 0.7354,  0.7655 )   ( 0.7357,  0.7655 )

Level     Percentile            BCa
95%   ( 0.7353,  0.7650 )   ( 0.7353,  0.7650 )
Calculations and Intervals on Original Scale

The different types of CI's all look pretty similar.
Comment: Thanks professor! While I like the shortcuts, I can still bootstrap my 2.5 and 97.5 quintiles as you taught in your stochastic course.
Comment: For what it's worth: With data in `x`, my 'percentile boostrap' was as follows: `a = replicate(2000, mean(sample(x, 50, rep=T)))`
`quantile(a, c(.025,.975))`, which returned $0.7361697, 0.7655921$--essentially the same result as above (+1).
Answer: Bootstrapping should work fine in your case. I would recommend having a look at the shape of your distribution because the choice of an adequate bootstrap method depends on the skewness of the distribution.
For an overview see here:
https://projecteuclid.org/download/pdf_1/euclid.ss/1177013815


how can i write sql query with join and where clause in linq or lambda

Question: I wrote below query in MsSQL now I want to write this query using C# linq
SELECT JD.*
FROM Job_Details JD
INNER JOIN MstCustomer Cust ON JD.Cust_ID = Cust.Cust_ID
WHERE Cust.SAP = 'Yes'

Comment: Possible duplicate of https://stackoverflow.com/questions/2767709/join-where-with-linq-and-lambda
Answer: A fairly simple join would do.
from jd in Job_Details
join cust in MstCustomer
on jd.Cust_ID equals cust.Cust_ID
where cust.SAP == 'Yes'
select jd

Answer: You asked for it using a lambda expression
You only want the Customers with Cust.SAP equal to "Yes", but you don't want the SAP in the end result. Hence it is more efficient to join only with the customers you actually want in your final result. Therefore do the Where before the Join:
IQueryable<JobDetail> jobDetails = ...
IQueryable<Customer> mstCustomers = ...

// Step 1: filter only the Yes customers:
var yesCustomers = mstCustomers.Where(customer => customer.SAP == "Yes");

// Step 2: Perform the join and select the properties you want:
var result = jobDetails.Join(yesCustomers, // Join jobDetails and yesCustomers
   jobDetail => jobDetail.Cust_Id,         // from every jobDetail take the Cust_Id
   customer = customer.Cust_Id,            // from every customer take the Cust_Id
   (jobDetail, customer) => new            // when they match use the matching items
   {                                       // to create a new object
       // select only the properties
       // from jobDetail and customer
       // you really plan to use
   })

TODO: if desired, make it one big LINQ statement. Note that this doesn't influence the performance very much, as these statements do not perform the query. They only change the  Expression of the query. Only items that do not return IQueryable perform the query: ToList / FirstOrDefault / Any / Max / ...


Função load desabilita funções do JQuery .hide() e .show()

Question: Aqui em baixo tenho esse dois formulários:

            <form>
            </form>

            <form>
            </form>

Aqui defino meu jquery , carrego minha Navbar na primeira linha , e oculto meus 2 formulários , e quero que quando clique na classe .BtnLogin apareça o formulário Login e oculte o cadastro , vice e versa , porém não funciona , somente aparece quando dou um reload na página , e logo após some ; o que fazer?
$(document).ready(function () {
    $("#menu").load("menu.html");
    $("#Historia").load("historia.html");
    $("#cadastro").hide();
    $("#login").hide();
});

$(document).on("click", ".BtnLogin", function () {
    $("#cadastro").hide();
    $("#login").show();
});

$(document).on("click", ".BtnCadastro", function () {
    $("#login").hide();
    $("#cadastro").show();
});

Minha Navbar com os botões (BtnLogin e Btncadastro) abaixo:

<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarText" aria-controls="navbarText" aria-expanded="false" aria-label="Toggle navigation">

</button>

             Barcelona (current)

             Creta

             Dubrovnik

    <form class="form-inline my-2 my-lg-0">
        <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">

    </form>

Comment: Onde estão os seus botões?
Comment: Estão na minha NavBar.
Answer: Tem 2 problemas no seu código:
Falta cancelar a ação dos links com event.preventDefault():
$(document).on("click", ".BtnLogin", function (e) {
   e.preventDefault();
    $("#cadastro").hide();
    $("#login").show();
});

$(document).on("click", ".BtnCadastro", function (e) {
   e.preventDefault();
    $("#login").hide();
    $("#cadastro").show();
});

Se você não cancelar a ação do click no link, irá direcionar a página em href.
Outro problema é que o id="Login" está com L maiúsculo e no seletor $("#login") está com L minúsculo. O JavaScript é case sensitive, ou seja, "Login" e "login" são duas coisas diferentes.
Comment: Obrigado pela ajuda , porém não funcionou , simplesmente agora os as ancoras que deveriam levar a pag do cadastro não funcionam.
Comment: Uai colega! Mas então sua pergunta tá confusa. O que vc quer fazer afinal?
Comment: Quero clicar no BtnCadastro e ocultar meu formulário de login e da um show no formulário cadastro ; e quando clicar no BtnLogin ocultar meu formulário de cadastro e da um show no formulário login.
Answer: Eu criei um pequeno exemplo parecido com o seu problema, veja se você consegue adaptar no seu código.
Veja abaixo, que eu mudei a maneira de chamar o evento de clique para os dois botões:

  $(document).ready(function(){
    $('#cadastro').hide();
    $('#login').hide();
  })

  $('#btnCadastro').click(function(){
    $('#cadastro').show();
    $('#login').hide();
  })

  $('#btnLogin').click(function(){
    $('#cadastro').hide();
    $('#login').show();
  })
  .form-cadastro,.form-login{
    height:100px;
    width:100px;
  }

  .form-cadastro{border: 3px solid black;color:black}
  .form-login{border: 3px solid red;color:red}

  CADASTRO

  LOGIN

CADASTRO

LOGIN


Maintain source positions at runtime with Antlr

Question: I have a script language based on Antlr: A parser and a tree grammar that builds runtime objects (e.g. statements). When I deal with the statements at runtime, I want to know the original source positions (e.g. when I throw errors, I want to state the line and position in the script source.)
What is the best strategy to attach the source positions to my runtime objects? And if I'm not asking too much, I want to have as little impact on my grammar files as possible.
I have tried to put as little code into the grammar as possible to increase quality, e.g. one of my (many) expressions looks like this:
multiplyExpression returns [Expression value]
: ^('*' l=expression r=expression)
{
    $value = sb.newBinaryExpression(CorIdentifier.MULTIPLY, $l.value, $r.value);
}
;

where sbis my ScriptBuilder that acts as an adapter between the generated code and my runtime. I know I can add the source position as an additional parameter to newBinaryExpressionbut then I have to touch all other expressions as well. I was hoping that I can put the token stream into sb only once and fetch the source position from the stream without affecting the grammar source at all.
I was hoping that, since Antlr is used by many scripting languages, there is a standard way to handle this since source position handling is a single aspect and I don't want to have it cluttered all over the grammar file, not very DRY.
Answer:
I was hoping that, since Antlr is used by many scripting languages, there is a standard way to handle this

You make it sound like ANLTR does not support this. Sure there is: every CommonToken and CommonTree objects exposes public getLine() and getCharPositionInLine() methods, but you discard these instances and create your own nodes (Expression). Don't be surprised to make some extra effort in embedding this information in your own nodes :)
You could let your runtime objects extend CommonTree classes and let your (combined) grammar construct these custom runtime objects (your classes now inherit the getLine() and getCharPositionInLine() methods). See: Using custom AST node types.
Comment: Thanks for pointing me to the TreeAdaptor, that was exactly what I was looking for.


Lync 2010 to 2013 Migration

Question: I'm tasked with upgrading out system from Lync 2010 to Lync 2013.  To do this requires co-existence.
I have our 2013 environment up and running.  Test users on the 2013 system can talk/IM/see presence of users on the 2010 system and vice versa.  Users are able to share the desktop and programs between systems.  The Edge servers are working.
I have found that the meet URL is not working if initiated by a user on the 2013 system.
A meeting will open up.  It will show the 2013 and 2010 user in the meeting but IMs only show on the user computer and desktop sharing fails, but does not give me an error only a warning that leads to the links below.
I have found info about the warning messages that are showing up in the local logs but am very gun shy about forcibly removing my Conferencing info on our production servers (http://blog.rassie.dk/2013/03/lync-multiparty-im-and-voice-fails/ and here).
Are there any solutions I can test that are not as drastic?
Comment: Are you talking about internal only users meeting, or internal/external meeting ?
Comment: Only internal users.  Scenario doesn't work inside or outside the organization though.
Answer: I spoke with Microsoft and after being sent to the article posted (http://blog.rassie.dk/2013/03/lync-multiparty-im-and-voice-fails/) by support we decided to run the suggestions in the article.
Only difference is we ran it just to remove the old Conference Directory left over for 2007 Compatibility that was not in use.
In our case:
<code>Remove-CsConferenceDirectory -Identity 1 -force
</code>
After a reboot of the new front end servers a conference started by a 2013 user was now usable by all participants.

Lync 2010 to 2013 Migration


Moving primary domain controller to new server

Question: I have just purchased a new server that will be the new primary domain controller. I was wondering if anyone knew any articles or tutorials on how to do this change over? I would imagine it is just simply setting up the role and importing a backup of the Active Directory from the old domain controller. I just want to make sure I'm not missing any crucial tasks in between.
Comment: There is no such thing as a "Primary Domain Controller" any more. That went away with NT4.
Comment: @SpacemanSpiff I agree. That doesn't change the fact that people still say PDC and BDC like they're real things. A DC holding the PDC Emulator role is entirely different than what an NT4 PDC was.
Comment: @MarkM: That doesn't change the fact that you can't demote a DC with the PDC emulator role.  And if it goes down, you'll end up having to seize the role.
Comment: I am certain this is already covered by existing questions, but I not finding a good one to mark as duplicate.
Comment: @surfasb newer versions of dcpromo will move the FSMO roles automatically off the server you're demoting. Older versions would just error out complaining of the fact.
Comment: @MarkM - Yes but the PDC Emulator FSMO role is still relatively important and likely still held by the first DC created.
Comment: @surfasb I wasn't implying any of that. The same is true of the other roles as well, not just PDC Emulator. My point is that the notion of a Primary Domain Controller is as antiquated as classful networking. It's a history lesson.
Comment: @MarkM Hey! Lay off classful networking! Plenty of IP stacks still set a default subnet mask for you based on that! :-)
Comment: I think that this might be getting a bit off-track and chatty. @surfasb If you feel like discussing the merits of using PDC and PDC Emulator interchangeably, feel free to join [chat]. Most of the others that have commented on this are regulars.
Answer:
Add new computer to domain
Promote system to a domain controller (dcpromo)
Transfer FSMO roles
Verify/Make the new system a Global Catalog.
Wait some time for replication to take place.  Run dcdiag/repadmin and so on to make sure everything transferred
Demote old system (dcpromo)
Double check DNS zones & AD to make sure old system was removed.

Migrate any other data or services as needed.
Of course you could leave the old system up so you have another spare DC.
Comment: @TheCompWiz,  http://technet.microsoft.com/en-us/library/cc732877(WS.10).aspx - `In a single-domain forest, configure all domain controllers as global catalog servers. Because every domain controller stores the only domain directory partition in the forest, configuring each domain controller as a global catalog server does not require any additional disk space usage, CPU usage, or replication traffic`.
Comment: @TheCompWiz: I believe that's only the case in a multiple domain forest but isn't applicable in a single domain forest. I believe that the MS best practice for a single domain forest is for all DC's to also be GC's.
Comment: @all.  I stand 100% corrected... severely... and repeatedly.  I honestly remember reading a technet article a while ago (5+ years ago maybe?) that cautioned against having multiple GCs in the same subnet/domain... but thanks for the correction.
Comment: What about having multiple global catalogs?
Comment: @timbrigham, sorry, I am not sure I understand what you are asking.
Comment: GC is an option during DCPromo, you don't have to do it separately.
Comment: Microsoft frowns on having multiple GCs in the same network.  I've seen some replication conflicts occur because of doing such.  You can in a fairly small environment with few concerns... but in larger environments... that can be a big headache.
Comment: @TheCompWiz - Are you referring to multiple GCs in the same AD site?
Comment: @CompWiz - pretty certain that you're wrong. The scenario you don't want is with multiple domains in a forest, the Infrastructure Master in each domain should not be a GC.
Comment: @TheCompWiz Like everyone else has mentioned, you're wrong. The Infrastructure Master role is only useful when you have multiple domains in the same forest. In a single domain situation, IM does nothing, so there is no benefit to putting it on a server that doesn't hold a GC.
Comment: @TheCompWiz: No harm, no foul. I certainly appreciate your input (I'm sure everyone else does as well).
Comment: Agree, GCs on all DCs - which happens by default when you do DCPROMO, by the way - and if all the DCs are GCs, the Infrastructure Master role can be anywhere. Also, to be honest, if you don't understand that AD is a multi-master system, and that "restoring the database from backup" to deploy a new DC does not apply, doing the MSCA training or equivalent for Windows Server/AD is highly recommended.
Answer: In addition to what Zoredache stated in his answer, make sure to update all of the domain clients to use the new DC for DNS.
On a side note, if the original DC you're replacing is the only DC in the domain, then running DCPROMO on the original DC will transfer the FSMO roles to the new DC without the need to manually transfer them. If it's not the only DC in the domain, then DCPROMO will transfer the FSMO roles to another DC, I'm just not sure how it selects the DC to assume the roles.
Comment: @TheCompWiz Could you elaborate on a time when you had dcpromo silently fail? I've never once had it leave AD in any obscure state. I've had plenty of times where it refuses to actually do anything because something I fed it was garbage...
Comment: to be sure... I'd still suggest moving the FSMO + GC roles manually and verify they've been completed rather than relying on dcpromo to transfer the roles.  dcpromo silently fails quite often and does a very poor job of documenting those failures.
Comment: @ChrisS I would... but this is neither the time/place to do such.
Answer: Something that I didn't see anyone else mention is time services. Your PDC is presumably the primary time keeper for the domain...that role/config should be redone on the new PDC.


toggling decorators

Question: What's the best way to toggle decorators on and off, without actually going to each decoration and commenting it out? Say you have a benchmarking decorator:
# deco.py
def benchmark(func):
  def decorator():
    # fancy benchmarking
  return decorator

and in your module something like:
# mymodule.py
from deco import benchmark

class foo(object):
  @benchmark
  def f():
    # code

  @benchmark
  def g():
    # more code

That's fine, but sometimes you don't care about the benchmarks and don't want the overhead. I have been doing the following. Add another decorator:
# anothermodule.py
def noop(func):
  # do nothing, just return the original function
  return func

And then comment out the import line and add another:
# mymodule.py
#from deco import benchmark
from anothermodule import noop as benchmark

Now benchmarks are toggled on a per-file basis, having only to change the import statement in the module in question. Individual decorators can be controlled independently.
Is there a better way to do this? It would be nice to not have to edit the source file at all, and to specify which decorators to use in which files elsewhere.
Answer: You could add the conditional to the decorator itself:
def use_benchmark(modname):
    return modname == "mymodule"

def benchmark(func):
    if not use_benchmark(func.__module__):
        return func
    def decorator():
        # fancy benchmarking
    return decorator

If you apply this decorator in mymodule.py, it will be enabled; if you apply it in othermodule.py, it will not be enabled.
Comment: This doesn't allow per-file toggling, and if the decorators are from a standard library or otherwise can't be edited it would have to be done in wrappers for every decorator.
Comment: @engineerC: You could inspect `func.__module__` to determine whether or not to enable the decorator.
Answer: I've been using the following approach.  It's almost identical to the one suggested by CaptainMurphy, but it has the advantage that you don't need to call the decorator like a function.
import functools

class SwitchedDecorator:
    def __init__(self, enabled_func):
        self._enabled = False
        self._enabled_func = enabled_func

    @property
    def enabled(self):
        return self._enabled

    @enabled.setter
    def enabled(self, new_value):
        if not isinstance(new_value, bool):
            raise ValueError("enabled can only be set to a boolean value")
        self._enabled = new_value

    def __call__(self, target):
        if self._enabled:
            return self._enabled_func(target)
        return target

def deco_func(target):
    """This is the actual decorator function.  It's written just like any other decorator."""
    def g(*args,**kwargs):
        print("your function has been wrapped")
        return target(*args,**kwargs)
    functools.update_wrapper(g, target)
    return g

# This is where we wrap our decorator in the SwitchedDecorator class.
my_decorator = SwitchedDecorator(deco_func)

# Now my_decorator functions just like the deco_func decorator,
# EXCEPT that we can turn it on and off.
my_decorator.enabled=True

@my_decorator
def example1():
    print("example1 function")

# we'll now disable my_decorator.  Any subsequent uses will not
# actually decorate the target function.
my_decorator.enabled=False
@my_decorator
def example2():
    print("example2 function")

In the above, example1 will be decorated, and example2 will NOT be decorated.  When I have to enable or disable decorators by module, I just have a function that makes a new SwitchedDecorator whenever I need a different copy.
Comment: Will this work with a decorator that takes arguments?
Comment: But how to switch off a decorator AFTER the function has been created? Here you redefine `example2`...
Answer: I think you should use a decorator a to decorate the decorator b, which let you switch the decorator b on or off with the help of a decision function.
This sounds complex, but the idea is rather simple.
So let's say you have a decorator logger:
from functools import wraps
def logger(f):
    @wraps(f)
    def innerdecorator(*args, **kwargs):
        print (args, kwargs)
        res = f(*args, **kwargs)
        print res
        return res
    return innerdecorator

This is a very boring decorator and I have a dozen or so of these, cachers, loggers, things which inject stuff, benchmarking etc. I could easily extend it with an if statement, but this seems to be a bad choice; because then I have to change a dozen of decorators, which is not fun at all.
So what to do? Let's step one level higher. Say we have a decorator, which can decorate a decorator? This decorator would look like this:
@point_cut_decorator(logger)
def my_oddly_behaving_function

This decorator accepts logger, which is not a very interesting fact. But it also has enough power to choose if the logger should be applied or not to my_oddly_behaving_function. I called it point_cut_decorator, because it has some aspects of aspect oriented programming. A point cut is a set of locations, where some code (advice) has to be interwoven with the execution flow. The definitions of point cuts is usually in one place. This technique seems to be very similar.
How can we implement it decision logic. Well I have chosen to make a function, which accepts the decoratee, the decorator, file and name, which can only say if a decorator should be applied or not. These are the coordinates, which are good enough to pinpoint the location very precisely.
This is the implementation of point_cut_decorator, I have chosen to implement the decision function as a simple function, you could extend it to let it decide from your settings or configuration, if you use regexes for all 4 coordinates, you will end up with something very powerful:
from functools import wraps

myselector is the decision function, on true a decorator is applied on false it is not applied. Parameters are the filename, the module name, the decorated object and finally the decorator. This allows us to switch of behaviour in a fine grained manner.
def myselector(fname, name, decoratee, decorator):
    print fname

    if decoratee.__name__ == "test" and fname == "decorated.py" and decorator.__name__ == "logger":
        return True
    return False

This decorates a function, checks myselector and if myselector says go on, it will apply the decorator to the function.
def point_cut_decorator(d):
    def innerdecorator(f):
        @wraps(f)
        def wrapper(*args, **kwargs):
            if myselector(__file__, __name__, f, d):
                ps = d(f)
                return ps(*args, **kwargs)
            else:
                return f(*args, **kwargs)
        return wrapper
    return innerdecorator

def logger(f):
    @wraps(f)
    def innerdecorator(*args, **kwargs):
        print (args, kwargs)
        res = f(*args, **kwargs)
        print res
        return res
    return innerdecorator

And this is how you use it:
@point_cut_decorator(logger)
def test(a):
    print "hello"
    return "world"

test(1)

EDIT:
This is the regular expression approach I talked about:
from functools import wraps
import re

As you can see, I can specify somewhere a couple of rules, which decides a decorator should be applied or not:
rules = [{
    "file": "decorated.py",
    "module": ".*",
    "decoratee": ".*test.*",
    "decorator": "logger"
}]

Then I loop over all rules and return True if a rule matches or false if a rule doesn't matches. By making rules empty in production, this will not slow down your application too much:
def myselector(fname, name, decoratee, decorator):
    for rule in rules:
        file_rule, module_rule, decoratee_rule, decorator_rule = rule["file"], rule["module"], rule["decoratee"], rule["decorator"]
        if (
            re.match(file_rule, fname)
            and re.match(module_rule, name)
            and re.match(decoratee_rule, decoratee.__name__)
            and re.match(decorator_rule, decorator.__name__)
        ):
            return True
    return False

Answer: Here is what I finally came up with for per-module toggling. It uses @nneonneo's suggestion as a starting point.
Random modules use decorators as normal, no knowledge of toggling.
foopkg.py:
from toggledeco import benchmark

@benchmark
def foo():
    print("function in foopkg")

barpkg.py:
from toggledeco import benchmark

@benchmark
def bar():
    print("function in barpkg")

The decorator module itself maintains a set of function references for all decorators that have been disabled, and each decorator checks for its existence in this set. If so, it just returns the raw function (no decorator). By default the set is empty (everything enabled).
toggledeco.py:
import functools

_disabled = set()
def disable(func):
    _disabled.add(func)
def enable(func):
    _disabled.discard(func)

def benchmark(func):
    if benchmark in _disabled:
        return func
    @functools.wraps(func)
    def deco(*args,**kwargs):
        print("--> benchmarking %s(%s,%s)" % (func.__name__,args,kwargs))
        ret = func(*args,**kwargs)
        print("<-- done")
    return deco

The main program can toggle individual decorators on and off during imports:
from toggledeco import benchmark, disable, enable

disable(benchmark) # no benchmarks...
import foopkg

enable(benchmark) # until they are enabled again
import barpkg

foopkg.foo() # no benchmarking
barpkg.bar() # yes benchmarking

reload(foopkg)
foopkg.foo() # now with benchmarking

Output:
function in foopkg
--> benchmarking bar((),{})
function in barpkg
<-- done
--> benchmarking foo((),{})
function in foopkg
<-- done

This has the added bug/feature that enabling/disabling will trickle down to any submodules imported from modules imported in the main function.
EDIT:
Here's class suggested by @nneonneo. In order to use it, the decorator must be called as a function ( @benchmark(), not @benchmark ).
class benchmark:
    disabled = False

    @classmethod
    def enable(cls):
        cls.disabled = False

    @classmethod
    def disable(cls):
        cls.disabled = True

    def __call__(cls,func):
        if cls.disabled:
            return func
        @functools.wraps(func)
        def deco(*args,**kwargs):
            print("--> benchmarking %s(%s,%s)" % (func.__name__,args,kwargs))
            ret = func(*args,**kwargs)
            print("<-- done")
        return deco

Comment: Interesting approach. I'd go a bit further and make the decorator a full-up class, with `enable()` and `disable()` methods. A `__call__()` method allows it to behave like a decorator, albeit one with state. This will get rid of the `enable` and `disable` functions and the need to have a global `_disabled` set, since each individual decorator will maintain that state.
Answer: I don't think anyone has suggested this yet:
benchmark_modules = set('mod1', 'mod2') # Load this from a config file

def benchmark(func):
  if not func.__module__ in benchmark_modules:
      return func

  def decorator():
    # fancy benchmarking
  return decorator

Each function or method has a __module__ attribute that is the name of the module where the function is defined. Create a whitelist (or blacklist if you prefer) of modules where benchmarking is to occur, and if you don't want to benchmark that module just return the original undecorated function.
Answer: I would implement a check for a config file inside the decorator's body. If benchmark has to be used according to the config file, then I would go to your current decorator's body. If not, I would return the function and do nothing more. Something in this flavor:
# deco.py
def benchmark(func):
  if config == 'dontUseDecorators': # no use of decorator
      # do nothing
      return func
  def decorator(): # else call decorator
      # fancy benchmarking
  return decorator

What happens when calling a decorated function ? @ in
@benchmark
def f():
    # body comes here

is syntactic sugar for this
f = benchmark(f)

so if config wants you to overlook decorator, you are just doing f = f() which is what you expect.
Answer: another straight way:
# mymodule.py
from deco import benchmark

class foo(object):

  def f():
    # code

  if <config.use_benchmark>:
    f = benchmark(f)

  def g():
    # more code

  if <config.use_benchmark>:
    g = benchmark(g)

Answer: Here's a workaround to automatically toggle a decorator (here: @profile used by line_profiler):
if 'profile' not in __builtins__ or type(__builtins__) is not dict: profile=lambda x: None;

More info

This conditional (only if needed) instantiation of the profile variable (as an empty lambda function) prevents raising NameError when trying to import our module with user-defined functions where the decorator @profile is applied to every profiled user function. If I ever want to use the decorator for profiling - it will still work, not being overwritten (already existing in an external script kernprof that contains this decorator).

toggling decorators


What is the difference between moderation and adjustment

Question: What is the difference between moderation and adjustment in regression analysis? How can I conduct each of them in SPSS? I would appreciate any type of help.
Thanks..
Comment: I suggest adding the tag "spss" to the question.
Answer: I am a newbie but moderation means interaction so add an interaction.
To adjust add the variable with no interaction.
https://stats.idre.ucla.edu/spss/webbooks/reg/chapter6/regressionwith-spsschapter-6-more-on-interactions-of-categorical-variablesdraft-version/


Using "try:" to write to a file not working

Question: I'm playing around with try: and am expecting 'Hello' to be written to testfile.tx. However when I check the file, 'Hello' doesn't appear. What is wrong with my code?
try:
    f = open('testfile.txt', 'w')
    f.write('Hello')
except TypeError:
    print ('There was a type error')
except OSError:
    print('There was an OS error')
finally:
    print('I always run')

Comment: Maybe use `with open(...)` altogether.
Comment: Works for me. Do you get any errors? Are you sure you're checking the right output file?
Comment: Use `finally: f.close()`
Comment: The file will be created in the current directory.  It sounds like you're just looking in the wrong directory for the file (and the directory where you're looking might also have an empty file of the same name).  You can add this code to see the actual current directory `import os; print(os.getcwd())`
Comment: @JorgeGandara, I understand that you're frustrated. But [there are good reasons for rate limiting and other restrictions on question asking](https://meta.stackoverflow.com/q/255583/354577). Changing an old question is counterproductive for many reasons, not least of which that you aren't likely to get answers to the new question that way. In any case, profanity is not appropriate. Please read our [code of conduct](https://stackoverflow.com/conduct).
Comment: But the buffer would be flushed anyway when the process exists and the OS cleans up the open file descriptors, wouldn't it? Guess this may depend on the file system and its internal caching...
Comment: Your edit completely changed the question. Please don't do that, especially if you've already received answers. But `foo.format(a, b)` and `foo.format((a, b))` are different things. See [New style formatting with tuple as argument](https://stackoverflow.com/questions/15181927/new-style-formatting-with-tuple-as-argument). I'm rolling the question back to its original form.
Comment: @Chris How is someone who doesn't know the proper terminology and is learning how to code supposed to ask "perfect questions"? I just know how to describe my issue. It seems like the only people allowed to ask questions are advanced coders. Makes no sense. There should be consideration for "dumb questions", not just complete shunning. How am I supposed to "fix my existing questions" if I don't even know proper coding terminology and am looking for help just TRYING to get started in coding.
Comment: @JorgeGandara, there's no requirement to be perfect. 'How am I supposed to "fix my existing questions" if I don't even know proper coding terminology'—I think you already know this from earlier comments but just in case: not by completely changing what you've asked. That invalidates existing answers. The idea is to _improve_ questions, not _overwrite_ them. The self-answer that you posted below has a comment on it that suggests one way to clarify what you were asking. Perhaps you could edit that into the question?
Answer: I see you already fixed the problem by doing this:
try:
    f = open('testfile.txt', 'w')
    f.write('Hello')
except TypeError:
    print ('There was a type error')
except OSError:
    print('There was an OS error')
finally:
    f.close()
    print('I always run')

This is alright, and properly writes the data in the buffer. However, you're better off using a context manager.
This syntax is more concise, less mistake-prone, and automatically closes the file even if an error occurs:
with open('testfile.txt', 'w') as f:
    f.write("Hello")

Comment: Got it, I'll change the code
Comment: I agree, - I just wanted to be as consistent with what the poster had in their code as possible
Answer: I didn't close the file with f.close()
I added f.close() and it works now!
Thanks for everyone's help!
Comment: Oh, so you were running this code inside of an IDE or shell, not as a separate script?  Mentioning that would have been helpful.


Uncaught SyntaxError: Unexpected token 'else'

Question: Estou tentando colocar um botão de próximo episodio, ele está funcionando normal, o problema é que ele aparece nos filmes, onde ele deveria só aparecer em episódios de séries. Tentei resolver o erro sozinho fazendo a class do botão retornar um valor que só apareceria se estivesse em "Episódios", caso estivesse em outro lugar ele retornaria "Array", então tentei usar o css para quando ele tiver "Array" no class ele ocultasse o botão com o display: none, mas não funcionou e deu erro: Uncaught SyntaxError: Unexpected token 'else'
Se alguém poder ajudar eu agradeço
Obs: uso o tema Wordpress "Dooplay" versão 2.4.1
Código:
player.once('play', () => {

    <?php
     $postmeta = doo_postmeta_episodes($postid);
     $tmdbids  = doo_isset($postmeta,'ids');
    $temporad = doo_isset($postmeta,'temporada');
    $episode  = doo_isset($postmeta,'episodio');
     $episode_pagi = DDbmoviesHelpers::EpisodeNav($tmdbids,$temporad,$episode);
     $next_episode = doo_isset($episode_pagi,'next');
     $link_next = !empty($next_episode) ? $next_episode['permalink'].'" title="'.$next_episode['title'].'"' : 'href="#" class="nonex"';
    ?>

$('.jw-media').append(`<a class="<?php echo $postmeta ?>" target="_parent" href="<?php echo $link_next ?>" id="proximoep">Próximo Episódio <i class="fas fa-forward"></i></a>`);

});

    player.on('time', e => {

        let duration    = player.getDuration();
        let currentTime = Math.floor(e.position);

     if(currentTime > duration - 120){
            $('#proximoep').hasClass('Array');
            $('#proximoep').css('display', 'none');
     } else {
            $('#proximoep').css('display', 'inline-block');
           }  else {
            $('#proximoep').css('display', 'none');
        }
    });

Comment: O seu `if` possui dois `else`. Isso não faz muito sentido.
Comment: entendo, você sabe algum jeito de arrumar isso, ou poderia me recomendar alguma documentação sobre, serei muito grato
Answer: O código tem os dois else seguidos,
sendo a condição if uma condição de verdadeira ou falso
Deveria ter um código com a seguinte estrutura
if(condição) {

   //código quando a condição é verdadeira
} else if ( condição2) {

  //código quando a 2 condição é verdadeira~
} else {

  /código quando todas as anteriores condições são falsas
}

Pelo que percebi da ideia do seu código, na parte final do mesmo, falta-te um if
uma vez que a função hasClass devolve um bool
onde o código deveria ser o seguinte
if(currentTime > duration - 120){
    if($('#proximoep').hasClass('Array')) {
        $('#proximoep').css('display', 'none');
    } else {
        $('#proximoep').css('display', 'inline-block');
    }
 } else {
    $('#proximoep').css('display', 'none');
 }


Hosted VPN Server

Question: I would like to find a way to allow multiple computers to securely join a shared network. Ideally we would like to find a complete hosted solution, or run a server on Rackspace or Amazon EC2. I have attempted to install Openswan and xl2tpd on a server. It appears that I need to have an internal network that I can assign IP address from though. I don't have any cloud services that I need the clients to connect to, they only need to communicate with each other. In addition we will need to support Linux, iPhone, and Android clients. Does anyone have suggestions of hosting solutions, or on-line guides that would accomplish something similar to this?
As an added bonus it would be nice to have DNS resolution work between the connected clients.
Answer: Aron,
Clarificaiton. When you say internal network are you thinking publicly routable IP addresses? If yes then you can you the IP address space defined in RFC 1918 to assign to the connected clients. Using private IPs they will be able to communicate with each other because the data will get encapsulated and then encrypted before being tunnelled to server.
http://en.wikipedia.org/wiki/Private_network
Disclaimer: I do not know of any hosted VPN service. I am trying to solve the problem you encountered while running your own service.
Comment: Thank you for the reply. I think that this is were I am getting a little confused. We don't have an internal network at all. In fact there is only a single NIC, the static WAN IP address. When configuring the VPN can I choose any of the RFC 1918 addresses even though I don't have a NIC on the server that has an IP within that subnet?
Comment: Aron, on linux you can always add a virtual interface . Something as simple as ifconfig eth0:0 192.168.1.1 netmask 255.255.255.0 would do that. Here is a link that will help you further. http://www.linuxhomenetworking.com/wiki/index.php/Quick_HOWTO_:_Ch03_:_Linux_Networking

Hosted VPN Server


Find the sum of series $\sum_{n=0}^{\infty}\frac{z^{kn}}{(kn)!}$

Question: $$\sum_{n=0}^{\infty}\frac{z^{kn}}{(kn)!}$$
Later edit:
Is this correct?
$$e^{z\epsilon_p} = \sum_{n=0}^{\infty}\frac{z^n\epsilon_p^n}{n!}$$
$$\sum_{p=0}^{k-1}e^{z\epsilon_p} = \sum_{n=0}^{\infty}\frac{z^n}{n!}\sum_{p=0}^{k-1}\epsilon_p^n $$
$$\sum_{n=0}^{\infty}\frac{z^{kn}}{(kn)!} = \frac{\sum_{p=0}^{k-1}e^{\epsilon_p^nz}}{k} $$
Comment: Hint: consider the sum $$\sum_\omega\exp(\omega z)$$ over every $k$th root $\omega$ of unity.
Comment: What does the series' index have to do with the series' term?
Comment: Maybe there is $n$ instead $p$?
Comment: I am assuming you have to start from the exponential series somehow but I can't find the path.
Comment: I messed up the indexes thinking of something else, sorry.
Comment: @Did Welcome back
Comment: A [related question](http://math.stackexchange.com/questions/610526).
Answer: $$\sum_{n=0} \frac{z^{kn}}{(kn)!}=$$
$$=\frac{1}{k}\sum_{l=0}^{k-1} e^{\omega_{k}^lz}$$
where $\omega_k=\exp(2\pi i/k)$
It can be considered a generalization of $\cosh(z)$ function to multicomplex numbers (For $k=2$ the series is the $\cosh(z)$, for $k=3$ the series is called cosexponential function : $cx(z)=1+z^3/3!+z^6/6!+...$)
http://en.wikipedia.org/wiki/Multicomplex_number
http://books.google.it/books?id=vv_m6Dn3tM0C&lpg=PA19&ots=MrTDonAl7S&pg=PA19|Section&redir_esc=y#v=onepage&q&f=false
Comment: which is also a form of a [Mittag Leffler function](https://www.wolframalpha.com/input?i=mittag+leffler+function) or, almost like you said, a [generalized hyperbolic function](https://www.wolframalpha.com/input?i=generalized+hyperbolic+functions)