Comparing the within-subject variance between two groups of subjects

Question: If each subject has repeated a test multiple times, I am able to compute the mean and variance of their performance. (I am assuming the results to be normally distributed).
1) If it is the variance that is of most interest to me then I believe that it is OK to summarise the variance of a group of subjects by taking the mean of their variances?
2) Would it also be meaningful to look at the variance of the subject variances?
3) I believe this (or a similar) statistic will be required if I am to use a T-test to assess whether the difference in variance between groups is statistically significant?
Very simple example (edited to correct the variances as noted in one answer)
Andrew: 5, 2, 7 (var 4.22 6.33)
Bob: 3, 3, 2 (var 0.22 0.33)
Charles: -2, 1 , 0 (var 1.55 2.33)
Diane: 4, 2, 3 (var 0.66 1.00)
Elsa: 6, -4, -1 (var 17.55 26.3)
Fran: 6, 0, 3 (var 6.00 9.00)
Male mean variance (Andrew, Bob and Charles): 2.00 3.00
Female mean variance (Diane, Elsa and Fran): 8.07 12.1
Question: Is there a significant difference between the male and female within-subject variance for this test?
Comment: so can estimate mean and variance of each subject if I understand you well ?  Then you make groups of subjects ? Why then not compute mean and variance for each group in the same way as you computed it for a subject (i.e. consider a group as a 'subject') ? Why compare variances with a t-test and not with an F-test ?
Comment: Yes, from the within-subject repeats I can estimate each subject's mean and variance. I then wish to compare the variance for groups of subject (e.g. male vs female) to see if there is a significant difference.
I'm not sure I understand your suggestion of considering groups as subjects - can you elaborate?
I'm also not sure how an F-test would be preferable to a T-test?
Comment: Well, from the within subject repeats you can estimate each subject's mean and variance.  I would say that, in a similar way, from the within group repeats you can estimate each group's mean and variance ? If you have the variance for the male and for the female, then you can compare the two variances with an F-test ?
Comment: So for any group, the mean will be the mean of the subject means (equivalent to the mean of all subject tests within the group if all subjects perform the same number of tests?), and the variance will be the variance of the subject means? I feel like this would be disregarding the within-subject variances - hence my suggestion of using the mean of the within-subject variances?
Comment: Are you now talking about multiple tests ? because in your question it says "... repeated **a** test ..." ? I did not say that I would compute the variance of the means ? I would compute the variance of the subjects in the group ?
Comment: Sorry, there is a **single test**, repeated **multiple times by each subject**. I am interested in the variance of these within-subject results. So when you say "compute the variance of the subjects in the group", can you explain what measure you would take from each subject?
Comment: I am just asking questions to see what you have.  So you have a subject $s_i$, the group $g_i$ of the subject and then $n_i$ results for one and the same test ?
Comment: Hopefully the simple example I have just added to the question will help.
Comment: well I ask the questions and others use the answers, anyway, I hope it helps :-)
Answer: You can test this by fitting a linear mixed model. A linear mixed model is like a multiple regression model but you can have random effects. The random effects part is needed because you have multiple tests per observation. You will then model score as a function of sex and test, and the subjects are your random effects. Let's enter your test data in R:
subject <- c(1,1,1,2,2,2,3,3,3,4,4,4,5,5,5,6,6,6)
score <- c(5,2,7,3,3,2,-2,1,0,4,2,3,6,-4,-1,6,0,3)
test <- rep(c(1,2,3),6)
sex <- c(rep(1,9), rep(0,9))
testdata <- data.frame(subject, score, test, sex)
testdata

The data would look like this:
   subject score test sex
1        1     5    1   1
2        1     2    2   1
3        1     7    3   1
4        2     3    1   1
5        2     3    2   1
6        2     2    3   1
7        3    -2    1   1
8        3     1    2   1
9        3     0    3   1
10       4     4    1   0
11       4     2    2   0
12       4     3    3   0
13       5     6    1   0
14       5    -4    2   0
15       5    -1    3   0
16       6     6    1   0
17       6     0    2   0
18       6     3    3   0

Now we fit two models. Both models use sex and test (1-3 in this case) as fixed effects and subject as random effect. The difference between the models is that in the second model, the variance is allowed to differ between women and men. We then compare the models using the anova() command, and if there is a significant difference, this indicates that the more complex model (the one with the differing variances per sex) provides a better fit, and we thus have indirect evidence that the difference in variance is statistically significant:
m1 <- lme(score ~ sex + factor(test), random=~1|subject, data=testdata)
m2 <- lme(score ~ sex + factor(test), random=~1|subject, weights=varIdent(form=~1|sex), data=testdata)
anova(m1, m2)
   Model df      AIC      BIC    logLik   Test    L.Ratio p-value
m1     1  6 167.8734 176.6679 -77.93673
m2     2  7 169.8450 180.1051 -77.92247 1 vs 2 0.02850744  0.8659

There was no difference in this example. But if we change the score for the last female a little (changing score from 3 to -17, increasing the variance) and run the m2 model and the comparison again:
score <- c(5,2,7,3,3,2,-2,1,0,4,2,3,6,-4,-1,6,0,-17)
testdata <- data.frame(subject, score, test, sex)
m2 <- lme(score ~ sex + factor(test), random=~1|subject, weights=varIdent(form=~1|sex), data=testdata)
anova(m1, m2)
   Model df      AIC      BIC    logLik   Test  L.Ratio p-value
m1     1  6 105.3948 109.2291 -46.69739
m2     2  7 102.7737 107.2471 -44.38685 1 vs 2 4.621064  0.0316

Now we see a difference in AIC and logLik, and a low p-value which indicates a difference in variance between the sexes.
Comment: This is how it is done.
Comment: IIRC, testing on the edge of the parameter space can provide overly conservative results, and zero variance is definitely at the edge of the parameter space. I'm not sure what the impact would be with the way you've set up your models here (with weights).
Comment: When you use random effects the you implicitly assume a var-covar matrix that is 'compound symmetrie'.  The implicit assumption that you make is thus that the correltation between the results of the first and the second test is equal to the one between the second and the third test and the correlation between the second and the third.  If that is a reasonable assumption then random effects can be used here, if not you have to use a more general var-covar structure (see my answer)
Comment: Ah, yes of course! I didn't think about the possibility of the subjects becoming better at the test after repeated tries or something like that. I just thought about the tests as a series of unconnected tests (such as questions on an exam or something) that have the same covariance.
Answer: The average of variances is probably not the best variable to use.
Variance is a squared result. In many cases, the standard deviation may be the better result to use, because it is on the same scale as your original data. You can then decide on whether use the arithmetic mean, or e.g. root-mean-square again.
Avoid blindly using standard toolbox functions.
In your case, I already disagree with your variances.
The proper variances are:
6.33, 0.33, 2.33, 1, 26.3, 9.

because you must use the unbiased sample variance. Note that these estimates are much higher than yours, because of the small sample size.
As you can see, there is a massive outlier here - 26.3 is way outside your range. Averaging such squared values is not sound. Take the standard deviations instead:
2.52,  0.58,  1.53,  1.00,  5.13,  3.00

The 5.13 is still large, but not as extreme anymore. The mean standard deviation of the males is 1.54, of the females it is 3.04; the average standard deviation of both is $2.29 \pm 1.66$. But you need to be aware that at this sample size, even your estimates of the mean are pretty unreliable.
You have to make informed decision on a number of steps, including:

variance, or standard deviation? or standard error?
more than one variance/standard deviation (biased, unbiased)
more than one mean (arithmetic, harmonic, geometric, power ...)

Any statistic test such as the t-test will come with some assumption on your input data; and doing the wrong choices will have a considerable impact on your result. Sorry, but I cannot save you from studying these differences yourself. The only choice where I'm fairly confident myself is that you need to use the unbiased variant.
For your actual test, you may want to look at the standard error of the mean, too. This may at first appear redundant to the standard deviation, but it is not. It measures how good your estimation of the mean is. It is tighter than the standard deviation; but if you have differences within this standard error, any difference likely is just random.
Comment: Ah, apologies for the use of biassed sample variance, I was trying to put together the example quickly to illustrate my problem. Also thank you for your other useful comments.
Answer: The fact the same subject does the test multiple times introduces correlation among the observations.  The goal is to get an estimate of the var-covar matrix of your data.  We will assume that the subjects are independent, but that the score for the same subject on the test are dependent.  This means that that var-covar matrix of the data will look like a diagonal matrix, but on the main diagonal you will find $3\times3$ block matrices.
This var-covar matrix can be estimated using the function gls from the package nlme.
Using the same testdata as @Jonas Berge I have the following R-code
library(nlme)
subject <- as.factor(c(1,1,1,2,2,2,3,3,3,4,4,4,5,5,5,6,6,6))
score <- c(5,2,7,3,3,2,-2,1,0,4,2,3,6,-4,-1,6,0,3)
test <- (rep(c(1,2,3),6))
sex <- as.factor(c(rep(1,9), rep(0,9)))
testdata <- data.frame(subject, score, test, sex)
testdata

r.1<-gls(score ~ 1+sex,
    data=testdata,
    corr=corCAR1(form=~ 1|subject),
    method="REML")

The corr=corCAR1(form=~ 1|subject) means that I assume an autoregressive pattern in the scores of the test for by subject. You can try with other assumptions on this correlation structure (see help on gls).
Note that we used option method=REML to get unbiased estimates of the variance.  (see Why does one have to use REML (instead of ML) for choosing among nested var-covar models?)
With summary(r.1) you see what this gives, but at this point this is not so important.  The most important result in this context is that value of the log-likelihood of this model, it will be used as input for a likelihood ratio test further on.
The above model r.1 assumes a correlation structure whereby all subjects have the same variance.  In the second stage we will re-estimate a model, but with different variances for the male and female subjects:
r.2<-update(r.1,
         weights=varIdent(form=~1|sex),
         method="REML")

The option weights=varIdent(form=~1|sex) means that we want different variances by sex. With the summary function one can again find the likelihood for this model.
The second model r.2 has different variances by sex, so it is more general than the first model that assumes that both sexes have the same variance.  Therefore the log-likelihood of the second model will be higher than the lig-likelihood of the second model.  With a likelihood ratio test (see What are the ''desirable'' statistical properties of the likelihood ratio test?) we can find out whether the difference is significant:  the second model r.2 is more general than the first one or the first model is nested within the second one. If we find that the second model's likelihood is significantly higher than the likelihood of the first model, then the model r.2 (with different variances for male and female) fits the data better. So if the likelihood ratio test gives a significant result, then we have reason to believe that the variance differs by sex.
The likelihood ratio test takes two times the difference between the two likelihoods, and this is (asymptotically) a $\chi^2$ with degrees of freedom equal to the difference in number of parameters between teh two models.  The second model has one parameter more (two variances, one per sex) so df=1.
The p-value of the test can be found with:
1-pchisq(2*(r.2$logLik - r.1$logLik), df=1)

It is $0.49$ so there is no significant difference in 'fit' between the two models and therefore we keep the simpler model, with male and female having the same variance.
To find the variances one executes summary(r.2).  At the bottom you find that the residual standard error is 2.66, squaring this yields the variance, and under 'Variance function' one finds that for sex==1 the variance is 2.66^2 * 1, for sex==0 it is 2.66^2 * 1.61.
Comment: Thank you for your questions and detailed answer. In our tests the subjects are performing a task that is already familiar to them, they get no feedback on their performance in the test, and tests are all conducted within a short space of time; therefore I think it is reasonable to assume that there will not be any correlation in within-subject performance. In this case would you agree with the answer given by @JonB, or would your solution still differ in some way?
Comment: @welf: well everyone can make any assumption he likes to make, but what would you do if you estimate $y=\beta_0 + \beta_1x_1 + \beta_2x_2$ then what would you do if you think that $\beta_1$ is zero? Would you estimate $y=\beta_0+\beta_2x_2$ ? Or would you estimate the full equation and perform a hypothesis test to see whether the sample confirms that it could be zero?
Comment: @welf: I would do a hypothesis test, moreover, you might be interested in the value of the two variances, these are easily read from the estimated var-covar matrix while with a mixed effects model you will have to do some ( not so difficult) calculations.
Comment: That makes sense. Out of interest, is there anything explicitly incorrect in my initial suggestion of comparing the mean of within-subject variances? (Or the mean of the standard deviations as @Anony-Mousse mentions)
Answer: I'm not sure if you can assume normality of the performance variances, but I'm still looking into it.  What you're saying makes sense.
Since you are using a within-subjects design (prone to carryover effects) I think it would be most interesting to look at how the variances are changing over time.  Are your subjects performing better or worse?
Yes, you would want to use a two-sample Student's t-test to look at that.
Comment: Thank you for your response. As all results per subject are collected over quite a short period of time, in a randomised sequence, we don't expect there to be much change with time.
Can you give any more information on your comment about normality?
Answer: It is not very well known but as an alternative to linear mixed model suggested by Jonas Berge you can perform a F test of equality of variances
https://en.wikipedia.org/wiki/F-test_of_equality_of_variances
Comment: Interesting, I didn't know about that. But if the mean scores (and variance) of the different tests differ between tests, then there is a risk that normality cannot be assumed and it won't be appropriate, according to the wikipedia article. And also, if we just pool the results from all tests for all men vs women, will that not also violate some assumption of independence of observations? So would it the be best to run this f-test once per test?
Comment: This sounds useful, but I'm not sure how to best apply it to my situation, particularly considering the answer given by @Anony-Mousse and the comment above?
Comment: well, @Anony-Mousse was right you do need to carefully consider your hypothesis i.e. the thing you want to test. As the F-test of equality of variances aim to test the H0: two groups of variances is equal.
Comment: The F-test can be used to compare the variances, but as I explain in my answer, you have to take into account the dependence structure caused by the repeated measures.  With the gls function, you estimate the variance-covariance structure, i.e. also the covariance between repeated measures for the same subject.


Reading a specific line in a .txt file using Visual Basic 6

Question: I am currently working on an EDI file and now I want to load and read only a specific line on a .txt file and put that in a textbox. Here is what my data would look like
ISA*00*          *00*          *01*MKT71          *01*ADEV04         *160331*1001*U*00501*300000001*0*P*>~

GS*IN*MKT71*ADEV04*20160331*1001*300000001*X*005010~

ST*810*300000001~

BIG*20160316*BS13435**NONE~

REF * BM * DHL-2162693540~

REF*CR*5201~

Now I want to put only the data DHL-2162693540 located in line number 5 of the .txt file in my Textbox1.
Comment: Just a friendly tip, you may want to read over this page: [The How-To-Ask Guide](https://stackoverflow.com/help/how-to-ask) so you can always be sure that your questions are easily answerable and as clear as possible. Be sure to include any efforts you've made to fix the problem you're having, and what happened when you attempted those fixes. Also don't forget to your code and any error messages!
Answer: The easiest and most straightforward way to do this is to read the first however many lines, and only keep the value of the last line read.
Here is some code that accomplishes that:
Private Sub ReadLines()

    Dim MyLine As String
    Dim DataLineNumber As Integer
    DataLineNumber = 5

    Open "C:\YourFileNameHere.txt" For Input As DataFile

    Do While Not EOF(1) And LineNumber <= DataLineNumber
        Line Input #DataFile, MyLine
        DataLineNumber = DataLineNumber + 1
    Loop

    Close DataFile

    MsgBox MyLine

End Sub

Comment: So I manged to get your code working. but what if the information you need is not on the last line? Let's say it's located somewhere in the middle. e.g you want the info on line 5 given that the text file has 10 lines of data
Comment: Ok so I've made a great progress on my project. Also I think you are missing a code to make the `LineNumber` variable to increment. I think from here I will just need to use substring to extract the exact data I want. Thanks for your help mate.
Comment: Having syntax error on this line of code. Line Input DataFile, MyLine
Comment: Oh ok. I thought you were just not caring lol. I'll fix that real quick. Just a side note/tip - you can highlight code in comments by placing backticks around it.
Comment: @HidekiMTC Try placing a single `#` right in front of the variable `DataFile` in that line. I've edited my answer to show what I am referring to, but the newly changed line will look like this: `Line Input #DataFile, MyLine`
Comment: How do you know what line the desired data is on?
Comment: I've added a variable to make test what line we are on. I made an if statement in the loop which makes sure no more than 6 lines have been read. So if the program is longer than 6 lines, the loop stops after it reads the 6th line.
Comment: Actually  the desired data is really fixed on line number 5. I just want to know how can I extract the data if I need the information on line 5, or line 6 etc.
Comment: Ok, so no matter which line it is fixed on, you can just change the number in the if statement. To extract the data from the line you'll have to split the string containing that line into the good and bad parts. I can help with this, but I'll need more examples of lines containing the data we're looking for. It doesn't matter what the lines 1-4 and 6-whatever look like. But we do need to know either what line 5 looks like, or know exactly how our desired data in line 5 looks like.
Comment: Also, I've edited my code and changed the name of the variable to test the line number, to make it more clear what it is being used for. This also makes it a little cleaner when you want to change the desired line number.
Comment: @HidekiMTC Sure, not a problem! If you think that my answer is a good answer for your question, be sure to mark it as the answer so other users will know the solution when they have this problem.


Lightbox 2.6 center resized image

Question: I added to lightbox.css this code
img {
max-width: 872px;
max-height: 635px;}.lb-outerContainer, .lb-dataContainer {
max-width: 880px;
width: auto!important;
height: auto!important;}

Is working perfectly to resize the big images, but when I have to open a small image, for example width:267 and height: 200 is showing a white space in the right, and I want to show the image in the center. If the white space can be removed is ok, but if is impossible is no problem, I just want the image to be in center.
Here is a image with the problem:
Answer: 1. Add this code to your css to give your page a height value:
body,html {
  height: 100%;
}

2. Look up ".lightbox {" in your lightbox.css file and add this rule to make the images fit the height of your webpage:
  height: 100%;

Lightbox 2.6 center resized image


Create index of hyperlinks to visible sheets in a workbook

Question: I have found and executed code successfully that creates a list of hyperlinks for each sheet in a workbook.  However, I have hidden sheets and do not want the hidden sheets to be included in the list of hyperlinks.  The code that works for all sheets is.
Is there a simple way to remove the hidden sheets from the resulting hyperlink list?
ActiveSheet.Range("P4").Select

Dim sh As Worksheet
Dim cell As Range
For Each sh In ActiveWorkbook.Worksheets
    If ActiveSheet.Name <> sh.Name Then
        ActiveCell.Hyperlinks.Add Anchor:=Selection, Address:="", SubAddress:= _
         "'" & sh.Name & "'" & "!A1", TextToDisplay:=sh.Name
        ActiveCell.Offset(1, 0).Select
    End If
Next sh

Answer: ActiveSheet.Range("P4").Select

Dim sh As Worksheet
Dim cell As Range
For Each sh In ActiveWorkbook.Worksheets
    If sh.Visible = xlSheetVisible Then
        If ActiveSheet.Name <> sh.Name Then
            ActiveCell.Hyperlinks.Add Anchor:=Selection, Address:="", SubAddress:= _
             "'" & sh.Name & "'" & "!A1", TextToDisplay:=sh.Name
            ActiveCell.Offset(1, 0).Select
        End If
    End If
Next sh


Are musical floppy drives tone wheel instruments?

Question: So I'm doing a project involving classifying electrophones according to MIMO's Hornbostel-Sachs system (see here) and I'm looking at musical floppy disk drives specifically (see here).
The drives make sounds mecahnically by electrically pulsing the motor at any number of positions to generate different frequencies (and different notes). For this reason, I've narrowed down my classification choice so far to "52. Electromechanical instruments and devices" which MIMO says are:
"Configurations of
(electrically excited) silent, mechanical moving parts with encoded patterns,
and electronic circuitry. The movement enables the encoded patterns to be
transduced into an analogue fluctuation of an electric current"
Which makes sense to me.
They subdivide this into "Tone wheel instruments", "Photoelectric electromechanical instruments", "Record/playback devices", "Electromechanical samplers", and "Electromechnical sound processing devices". Having read through all of these and their examples, I feel like musical floppy drives are closest to tone wheel instruments such as the Telharmonium, but I am definitely not an expert on the subject.
Hopefully this is the right place to ask this, but is there a better classification in the Hornbostel-Sachs system? Or is this classification correct?
Thanks so much!
Comment: Not sure of this info so I won't post an answer, but from my understanding a tonewheel induces a current electromagnetically (Wikipedia compares the tonewheel operation it to the vibrations of guitar strings over electric guitar pickups).  AFAIK the disk drive creates a series of noises _mechanically_ and the sound comes directly from the moving parts rather than being represented in an analog current and amplified with a loudspeaker.
Comment: @DarrenRinger The part of your comment about disk drives is absolutely correct. (I know nothing about tonewheels, so I've no opinion on the first half of your comment.)
Answer: They are not. Tonewheel instruments have metal disks in them that are cut in a pattern and then a pickup (a coil of wire around a magnet) that is near each wheel. When the wheel spins, the pickup has a periodic current induced in it by the pattern cut in the wheel. The electric current induced in the pickup is normally muted but is unmuted when the appropriate keyboard key is pressed, and then all of the outputs from all of the pickups are mixed together and amplified.
The most famous tonewheel instrument is the Hammond B3 electric organ.
Musical floppy drives make mechanical noises in a way that can be pulsed. By pulsing the floppy drive at different rates, different frequencies of mechanical noise can be created. I don't think a floppy drive fits in any of the categories you listed. I might call it a "modulated friction" device or something like that.
If you want a more mundane example of something similar to a floppy drive, a squeaky door hinge is a good analogy. The faster you swing the door, the higher the pitch of the squeak. If you can swing the door at exactly the right speeds, back and forth, you could play a tune by making it squeak on pitch. The squeak is created by friction in the hinge. If you set up an electric motor to swing the door at set speeds and programmed a song into the motor's control circuit, you would have an electromechanical instrument that works similarly to the floppy drive.
Comment: @user3684314 Yes. According to Wikipedia, there is a category for electrophones for electrically actuated acoustic instruments, category 5.1, which IMHO applies to floppy drives. The specific acoustic category I would put floppy drives in is 1.3, Friction Idiophones, and I believe 1.3.2, Friction Plaques is probably the closest category. And further breakdown I would go to 126.96.36.199, Sets of Friction Plaques. So it's a complicated instrument.
Comment: IIRC at least some floppy systems change rotation speed depending on where the head is accessing, so tones might come both from head movement and the drive motor itself.
Comment: There was a youtube video of an organ that used stepper motors from floppy drives in a fashion similar to a Hammond organ, and I would regard *that* as being a tone wheel instrument, but most music projects using floppy drives use them to convert electrical signals into sound, while tone wheels convert motion into electrical waves.
Comment: @user3684314 Ben Miller's categorization makes sense also. I think the problem is that the categorization system has become a bit dated and needs some work to take into account all modern instruments. The electrophones category is sorely lacking even if it is meant to indicate instruments with purely electrical sources, since a ROMpler is very different from a Theremin, and IMHO they should have separate subcategories.
Comment: @ToddWilcox thank you so much (and Ben Miller as well!). I think I'll ultimately go with electro-acoustic idiophones based on your recommendation (I know it's a little lacking, but for my purposes it's more than enough). Thanks again!
Comment: Thanks this is a great metaphor! So in your opinion would any Hornbostel-Sachs category fit at all?
Comment: @CarlWitthoft I think you're right. Also, to my ear a floppy drive is only semi-pitched. There are a lot of inharmonic noise components of a floppy drive's uhhh... timbre. It's a weird world we live in.
Answer: I'm going to say that the best fit for this would be 515: Transducers.
The closest comparison I can think of is to a loudspeaker. You are sending an electrical signal to a device that converts it to mechanical motion and the sound comes from the resulting vibration.
It doesn't seem to quite fit any of the other categories in the "5: Electrophones" section.
Comment: Agreed.  The top-level category chosen in the question is wrong: "The movement enables the encoded patterns to be transduced *into an analogue fluctuation of an electric current*" (my emphasis) ... this is working in the opposite direction to what's needed here, generating electrical signals from mechanical motion, rather than using electrical signals to regulate a mechanical motion such that it produces the desired sound.
Answer: Read the start of the "Electrophones" section.

Instruments that use materials generating acoustic
  sounds, mechanically-driven signal sources, electronically stored data or
  electronic circuitry to produce electrical signals that are passed to a
  loudspeaker to deliver sound.

A floppy drive does not "produce electrical signals that are passed to a loudspeaker".  The noise from a floppy drive (or an electric drill, or any other piece of machinery) comes solely from the noise of the mechanical parts moving.  The tone is produced in the same way as running a stick along a fence, as each tooth from each cog meshes with the next, with the timbre dictated by the structure and materials of the mechanism. Therefore by this definition it cannot be an electrophone.
What you actually have is an ideophone. Definition (section 1):-

The substance of the instrument itself, owing to its solidity
  and elasticity, vibrates and may radiate sound without requiring stretched
  membranes or strings.

Now to narrow it down.  In all these cases, it's the meshing gears which cause the noise.  So from that list, the best fit seems to be "112.24 Scraped wheels or cog rattles".  Definition:-

A cog wheel, whose axle serves as
  the handle, and a tongue fixed in a frame which is free to turn on the handle;
  when whirled, the tongue strikes the teeth of the wheel one after another.

For meshing cog wheel, each cog wheel is effectively the "tongue" for the previous cog wheel, because that's what causes the noise.  Note that it doesn't quite fit the definition, so the list should either be a little less prescriptive about the structure of that type, or it should have another type to fully cover noisy mechanisms.
And then of course it's actually 112.24-9 because it's mechanically driven.
Comment: Is it not "electrically actuated"? Mechanically driven to me seems like something powered by an engine or a water wheel (water powered organs have existed), etc. A floppy drive is electrically driven and electrically actuated (actuated meaning the thing that chooses which note is being played is electrical, rather than mechanical or human power).
Comment: @ToddWilcox But if you could replace the electric motor with any other kind of motor and the resulting sound would be identical, then the electrical element is irrelevant.  We don't need to reclassify church organs based on whether they have electric motors or small boys pumping the bellows, after all. :)  All that matters is that there's *some* kind of mechanical drive to it, don't you think?  Whether it's an electric motor, a compressed-air drive or a small steam engine in the next room, it's the mechanical action which matters.
Comment: I think the classification system actually does take into account the different ways organs are powered and also actuated. Note that the actuation system and the power system are two different things. For a floppy drive, they are both electrical. Also, floppy drives are pulsed st audio rates, and I can't think of a way to do that without using electronics. So unlike an organ, a floppy drive cannot make music without being electrically actuated.
Comment: @ToddWilcox A stick running along a fence is pulsed at audio rates. :)    My understanding is that this is more concerned with the electrical/electronic system providing some kind of control over the tone shaping, over and above simply making the thing move.  Of course the drive rate sets the frequency, but I don't believe it does anything much with the tone.  Just my opinion though.  That's the problem with classification systems generally, of course - the pigeonholes often show the biases of the designers, and it isn't always obvious how to fit in things they didn't know about.


Form returning value issue

Question: I am trying to adapt a Drupal 5 form to a Drupal 7 form, but something is not working. The form is correctly displayed, but when "Submit" button is clicked the information in the form is not correctly send to $_GET. What am I missing??
<?php
 function my_menu($may_cache) {
  $items = array();
    $items['admin/reporting/report_details'] = array(
    'title' => 'Report: User details by stores',
    'access arguments' => array('access content'),
    'page callback' => 'say_report_details',
    'type' => MENU_CALLBACK,);

 return $items;
}

function say_report_details($values = array()) {
  $form = drupal_get_form("report_details_form");
  //$output = theme("report_page", $form, $output);
  return $form;
}

function report_details_form() {
 $form["search"] = array(
 '#type' => 'fieldset',
 '#title' => t('Search params'),
 '#collapsible' => FALSE,
 '#tree' => TRUE,
 );

 for ($i = 1; $i < 32; $i++) {
  $days_opt[$i] = $i;
 }
 for ($i = 1; $i < 13; $i++) {
  $month_opt[$i] = $i;
 }
 for ($i = 2008; $i < date("Y") + 3; $i++) {
  $year_opt[$i] = $i;
 }

 $form["search"]["from_day"] = array(
  '#type' => 'select',
  '#title' => 'Date from',
  '#options' => $days_opt,
  '#default_value' => (($_GET['from_day'] == "") ? date("d") : $_GET['from_day'])
 );
 $form["search"]["from_month"] = array(
  '#type' => 'select',
  '#title' => ' ',
  '#options' => $month_opt,
  '#default_value' => (($_GET['from_month'] == "") ? date("m") : $_GET['from_month'])
 );
 $form["search"]["from_year"] = array(
  '#type' => 'select',
  '#title' => ' ',
  '#options' => $year_opt,
  '#default_value' => (($_GET['from_year'] == "") ? date("Y") : $_GET['from_year'])
 );

 $form["search"]["to_day"] = array(
  '#type' => 'select',
  '#title' => 'Date to',
  '#options' => $days_opt,
  '#default_value' => (($_GET['to_day'] == "") ? date("d") : $_GET['to_day'])
 );
 $form["search"]["to_month"] = array(
  '#type' => 'select',
  '#title' => ' ',
  '#options' => $month_opt,
  '#default_value' => (($_GET['to_month'] == "") ? date("m") : $_GET['to_month'])
 );
 $form["search"]["to_year"] = array(
  '#type' => 'select',
  '#title' => ' ',
  '#options' => $year_opt,
  '#default_value' => (($_GET['to_year'] == "") ? date("Y") : $_GET['to_year'])
 );

 $result = db_query('SELECT something in the database');

 $strs = array("all" => "All");

 foreach ($result as $store) {
   $strs[$store->tid] = $store->name;
 }

 $form["search"]["store"] = array(
  '#type' => 'select',
  '#title' => 'Stores',
  '#options' => $strs,
  '#default_value' => $_GET['store']
 );

 $form["submit"] = array("#type" => "submit", "#value" => "Show report");

 return $form;
}

function report_details_form_submit($form_id, $form_values) {
  $query = "";
// This next line is the one I am having an issue with right now.$form_values is empty
  foreach ($form_values['search'] as $key => $value) {
     $query .= "&". $key ."=". $value;
  }

 return array('admin/reporting/report_details', $query);
}

The code throws an error at last "foreach" as $form_values is empty for some reason.Thank you!!
Comment: I recommend you to start with [Examples for Developers](http://drupal.org/project/examples). `$_GET` is processed automatically now.
Comment: You can use  the following code in submit button      function report_details_form_submit($form_id, &$form_state) {
  $query = "";
$from_month=$form_state['values']['search']['from_month'];
//In this way you can get values of all fields and use them as per your requirement
Answer: By default Drupal form sends values using post method. If you are looking to recieve values in $_GET you will have to define #method attribute of your form to get.
$form['#method'] = 'get';

Answer: Your code is not correct in many points, but the main reason you are not getting the values you are expecting is that the code to redirect the form is wrong, for Drupal 6/7.
The following code works.
function report_details_form_submit($form, &$form_state) {
  $form_state['redirect'] = array($_GET['q'], 'query' => $form_state['values']);
}

This code is similar to the one executed by search_form_submit(); the difference is that search_form_submit() add the search values to the path, separating them with a slash.
 $keys = $form_state['values']['processed_keys'];
  if ($keys == '') {
    form_set_error('keys', t('Please enter some keywords.'));
    // Fall through to the form redirect.
  }

  $form_state['redirect'] = $form_state['action'] . '/' . $keys;

There are other things that needs to be changed, such as:

hook_menu() doesn't get any parameter, in Drupal 7.
There is no need to use a function that calls drupal_get_form() as page callback. Just use code similar to the following one.
function my_menu($may_cache) {
  $items = array();

  $items['admin/reporting/report_details'] = array(
    'title' => 'Report: User details by stores',
    'access arguments' => array('access content'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('report_details_form'),
    'type' => MENU_CALLBACK,
  );

  return $items;
}

Functions defined from a module should be prefixed with its short name. If "my" is the short name of your module, then every function it defines it should have its name starting with my_, or _my_ (if the function is private).
You should verify the values are set, before to using them. Module code is supposed not to throw any warning. I would rather use the following code.
$form["search"]["from_month"] = array(
  '#type' => 'select',
  '#title' => ' ',
  '#options' => $month_opt,
  '#default_value' => empty($_GET['from_month']) ? date("m") : $_GET['from_month'])

);

Considering that (since Drupal 6) a form builder receives two parameters ($form, &$form_state), I would rather write the code as follows.
function my_menu() {
  $items = array();

  $items['admin/reporting/report_details'] = array(
    'title' => 'Report: User details by stores',
    'access arguments' => array('access content'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('my_report_details_form'),
    'type' => MENU_CALLBACK,
  );

 return $items;
}

function my_report_details_form($form, $form_state) {
  $form["search"] = array(
    '#type' => 'fieldset',
    '#title' => t('Search parameters'),
    '#collapsible' => FALSE,
  );

  $from_date = array(
    'day' => isset($form_state['my_report']['from']) ? $form_state['my_report']['from']['day'] : date('d'),
    'month' => isset($form_state['my_report']['from']) ? $form_state['my_report']['from']['month'] : date('m'),
    'year' => isset($form_state['my_report']['from']) ? $form_state['my_report']['from']['year'] : date('Y'),
  );

  $form["search"]["from"] = array(
   '#type' => 'date',
   '#title' => t('From'),
   '#default_value' => $from_date,
  );

  $to_date = array(
    'day' => isset($form_state['my_report']['from']) ? $form_state['my_report']['to']['day'] : date('d'),
    'month' => isset($form_state['my_report']['from']) ? $form_state['my_report']['to']['month'] : date('m'),
    'year' => isset($form_state['my_report']['from']) ? $form_state['my_report']['to']['year'] : date('Y'),
  );

  $form["search"]["to_day"] = array(
    '#type' => 'date',
    '#title' => t('To'),
    '#default_value' => $to_date,
  );

  $options = array("all" => "All");
  $result = db_query(/* */);

  foreach ($result as $store) {
    $options[$store->tid] = $store->name;
  }

  $form["search"]["store"] = array(
    '#type' => 'select',
    '#title' => t('Stores'),
    '#options' => $options,
    '#default_value' => isset($form_state['my_report']['store']) ? $form_state['my_report']['store'] : 'all',
  );

  $form["submit"] = array("#type" => "submit", "#value" => "Show report");

  if (isset($form_state['my_report']['result'])) {
    $headers = array(/* The headers to use for the table */);

    $form['result'] = array(
      '#theme' => 'table',
      '#header' => $headers,
      '#rows' => $form_state['my_report']['result'],
      '#empty' => t('There are no reports found in the database'),
    );
  }

  return $form;
}

function my_report_details_form_submit($form, &$form_state) {
  $form_state['my_report']['from'] = $form_state['values']['from'];
  $form_state['my_report']['to'] = $form_state['values']['to'];
  $form_state['my_report']['store'] = $form_state['values']['store'];

  // Search the reports, and populate $form_state['my_report']['result'].

  $form_state['rebuild'] = TRUE;
}

In this way, there would not be any need to populate $_GET with the data submitted in the form.
See theme_table() for the value to use as #rows.
Reference

Form generation
drupal_redirect_form()

Form returning value issue


Trocar classe e id de item ao receber evento click com javascript puro

Question: Tenho a seguinte linha:

Quando o usuário clicar na
, o menu fecha e eu gostaria que trocasse o icone e consequentemente, o id da
 do , ficando assim:

JavaScript que eu tenho atualmente, ele "fecha" o menu apenas, gostaria de trocar o icone e o id da li e do icon também, pra ai poder criar um evento ao clicar no botão de abrir o menu:
document.getElementById("fecharMenu").addEventListener("click", fecharMenu);
function fecharMenu() {
    document.getElementById("barraLateral").style.width = "60px";
}

Como eu poderia fazer somente com JavaScript, sem usar Jquery?
Comment: aonde está o ícone?
Comment: É o ``. É icone do Material Design Icons.
Answer: Você pode trocar os atributos da seguinte forma:
document.querySelector("#fecharMenu").addEventListener("click", function(){
   this.id = "abrirMenu"; // troca o id da

   var i = this.children[0]; // seleciona o
   i.id = "iconAbrirMenu"; // troca o id do
   i.className = i.className.replace("mdi-window-close","mdi-menu"); // substitui a classe do
});

Answer: Você pode utilizar o método setAttribute para alterar o Id, da seguinte forma:
document.getElementById("fecharMenu").setAttribute("id", "abrirMenu");

Nesse caso, estou supondo que você tem uma regra css para cada Id de menu:
#fecharMenu {
    background-image : (...)
}
#abrirMenu{
    background-image : (...)
}

Desta forma, ao modificar o id, você mudará o ícone automaticamente.
Mas, acredito que manipular o Id dessa forma não seja a melhor prática. Acredito que manipulando classes seja mais adequado, da seguinte forma:
HTML:

JS:
document.getElementById("menu").addEventListener("click", aoClicarMenu);
function aoClicarMenu(event) {
    if (event.target.classList.contains('aberto'){
        event.target.classList.remove('aberto');
        event.target.classList.add('fechado');
    } else {
        event.target.classList.remove('fechado');
        event.target.classList.add('aberto');
    }
    document.getElementById("barraLateral").style.width = "60px";
}

O código acima verifica se o elemento DOM que disparou o evento, no caso, o li, contém a classe 'aberto', se sim, ela é removida, e a classe 'fechado' é adicionada, e vice-versa. Assim você vai conseguir alternar o comportamento do elemento a cada clique que ele recebe.
Para isso, você teria que ter um CSS para definir o ícone do menu aberto, ou fechado:
.aberto {
    background-image : (...)
}
.fechado {
    background-image : (...)
}


Best Hosted Mail Server for a SaaS Web App?

Question: I'm developing a CRM SaaS based web application, and one of the features i would like to have is the ability for users to foward emails to my app.
The app will also from time to time send out notification emails.
Other than setting up my own mail server, does anyone know of any hosted email servers/services which would allow me to do this?
One of the requirements is that it should have unlimited incoming mails, and if there is any limit on the outgoing, it should be reasonably high.
PS: Also if host has a good API for managing mailboxes that would be a hugh plus
Thanks.
Answer: Rackspace email has an API, "unlimited" has different meanings, you get the storage you pay for, per mb is very cheap if you get a reseller account.


Spring Web Flow Unit Tests: Set attribute in FlowScope without view-state

Question: This is similar to Spring Web Flow - How can I set up unit test with values already in conversationScope?
I've used the solution listed in that question to solve a conversationScope issue, but have been hitting a wall trying to do the same for FlowScope. For some reason, FlowExecution does not have a getFlowScope() method.
Any helps or general pointing in the right direction will be very much appreciated. Thanks!
Update:
To give more context, this is the line in the webflow I'm trying to test:
<evaluate expression="serviceFactory.getInstance(flowScope.config.country).startTransaction(flowScope.SomeList.get(0), 0)" />

and the relavant test statement is:
EasyMock.expect(serviceObjectMock.startTransaction(someObjectMock, 0)).andReturn(true);

and it fails silently. When I walk through the code in the debugger, I see that there was an IndexOutOfBoundsException on this call, which led to my assumption that I have to have the list somehow in flowScope.
Answer: in FlowExecution, you can use getActiveSession().getScope()
that will give you the FlowScope where you can then put your attributes (after the flow started)
What you are trying to do doesn't really make sense because Flow scoped attributes exist for the life of the active flow session.
You cannot set them before the flow starts.
Comment: Hi, thanks for your reply. I want to populate a flowScope attribute before starting the flow since the attribute will be used before the first view-state so I can't pause the flow using setCurrentState, set the attribute, then resume the flow. Do you have any ides how I can do that? Thanks!
Comment: This is the error I get:

java.lang.IllegalStateException: No active FlowSession to access; this FlowExecution has not been started
 at org.springframework.webflow.engine.impl.FlowExecutionImpl.getActiveSession(FlowExecutionImpl.java:188)
Comment: oh I see. you can only get the active session once the flow has started already. my bad.
Comment: you could put attributes in the sessionMap of the MockExternalContext
Comment: sorry, can you clarify a little? i did this         context.getSessionMap().put("test", testObject);
        startFlow(input, context); and it didn't work. do i have to explicitly put it in the flowScope somehow? thanks for your help btw!
Comment: you can try to put your attribute as an input but I am pretty sure that's not what you want to do.
Comment: last thing I am thinking about would be to create a MockFlowSession with "new MockFlowSession(Flow flow, AttributeMap input)" where you put your attribute then create a "new MockFlowExecutionContext(FlowSession flowSession)" and then start it
Answer: For anybody who's interested, I learnt that I did not have to explicitly set the attribute in the flowScope, as EasyMock handles that while it goes through the list of "expects".
My problem was that "flowScope.SomeList.get(0)" refers to an attribute that was set in the previous line, and I used "new ArrayList()" as a return value in the "expect" statement for that line.
And also, the "failing silently" part was due to me not enabling DEBUG level info in the test profile for Spring.
This in the test log4j.xml file solved the problem:
    <logger name="org.springframework">
    <level value="DEBUG" />
</logger>

Comment: I am wirting junit for spring webflow and i kind of stuck for sometime can you please look in this post and provide any suggestion http://stackoverflow.com/questions/39010531/not-able-to-get-the-flow-scope-variable-from-one-state-transition-to-another-sta thanks


Android: Perform actions on a ShapeDrawable within an ImageView?

Question: I have created a ShapeDrawable and placed it within an imageview that is dynamically created within my layout. Here's the code I use to assign the drawable to my ImageView. Notice that I call on a method to set a random color, I also set the height and width using user filled text fields, but that's irrelevant here.
ShapeDrawable shape;

public void makeShape(){

    shape = new ShapeDrawable(new RectShape());
    shape.setIntrinsicHeight(Integer.parseInt(ET_Height.getText().toString()));
    shape.setIntrinsicWidth(Integer.parseInt(ET_Width.getText().toString()));
    shape.getPaint().setColor(chooseColor());
    iView.setImageDrawable(shape);
}

This part of the code works wonderfully, it's when I later try and access the Drawable to change it's color on a user click, utilizing the same color method from before.
public void onClick(View v){

    iView.getDrawable().getPaint().setColor(chooseColor());
}

Obviously this code doesn't work, but it's the closest I have come to being able to complete it. I can't access the drawable via "shape" either, and I don't understand why.
So what's the best way to gain access to the drawable to change it's color, alpha, rotation, etc in the onClick method?
Thanks!
Answer: Try iView.setImageDrawable(shape) again after changing the shape parameters.
Comment: It doesn't work. I'm attempting to call the same random color generator code on the existing shape but it's not changing anything.
Comment: Ok. Did you try creating a new shape drawable and setting it again in the image view instead of just changing the color?
Answer: I have used Abhinav's solution to this same problem and it worked for me
Basicly useing the same parameters I Used to create the shape then just created the same shape again and set color and bounds to the existing shape


Finite logarithm moment generating function

Question: I'm having troubles solving this problem:
Let $\mu$ a probability measure on $\mathbb{R}$. Let $\Lambda(t) \in [-\infty,\infty]$ $t \in \mathbb{R}$, be the logarithm moment generating function of $\mu$, i.e. $$\Lambda(t) = \log\int_\mathbb{R} e^{tx}d\mu(x)$$
Prove that if exists $r > 0$ such that $\Lambda(t) < \infty \forall |t| < r$ then $\mathbb{E}(\max_{i=1,\dots,N} X_i) < \infty$ when $X_i$ are independent and identically distributed from $\mu$.
I'm really stuck with this, any help will be appreciated
Thanks
Comment: It's a standard Chernoff bounding technique. $e^{tE(M_n)}\le E(e^{tM_n})\le nE(e^{tX})$, Hence for $t>0$, $E(M_n)\le \frac{\log n+\Lambda(t)}t$, so pick any $t\in(0,r)$. You can minimize the RHS over all $t$ to get a possibly decent upper bound. In case of standard normal $X$ ($\Lambda(t)=t^2/2$), the optimized bound yields $E(M_n)\le\sqrt{2\log n}$ - very close to the real value of $E(M_n)$.
Comment: @A.S. Perhaps you should post that as an answer
Answer: Hint: Use the Jensen's inequality along with fact that $$\mathbb{E}\left(e^{t\max\left(X_{1},\dots,X_{n}\right)}\right)\leq\sum_{i=1}^{n}\mathbb{E}\left(e^{tX_{i}}\right)=n\mathbb{E}\left(e^{tX}\right)=ne^{\Lambda(t)}.$$


Elimination of a singularity

Question: Let $z=a+ib$ with $b>0$; the function
$$f(x)=\frac{e^{iz|x|}}{|x|}$$ is in $L^2(\mathbb{R}^3)$; in fact
$$\int_{\mathbb{R}^3}|f(x)|^2dx=4\pi\int_{0}^{+\infty}\frac{e^{-2b\,r}}{r^2}r^2dr=\frac{2\pi}{b}<\infty$$
For the singularity in $x=0$ $f(x)\notin H^2(\mathbb{R}^3)$; now I take
$$g(x)=\frac{e^{iz|x|}-1}{|x|}$$. So I've eliminated the singularity and now the function is in $H^{2,-s}$, with $s>\frac{1}{2}$, isn't it?
Answer: I'm not sure exactly what the question is. But you have changed the function into a different function that doesn't have the singularity. But the new function doesn't agree on the values with the old function on all the other points (it's an entirely new function) so it wasn't a case of a removable singularity if that's what you were asking.
Comment: Maybe my request is not clear; I Know that the function $g$ is a new function with no relation with $f$. I want know if this new function is in the weighted Sobolev space. I cited $f$ only for example.

Elimination of a singularity


Equivalence between the Operator Norm in the Space of Linear Functionals and Norm on Hilbert Space

Question: I'm a little surprised that I'm stuck on this point, but I have my bad days. I am trying to understand a statement made in the proof of Theorem VI.1 in p.184 of Reed and Simon Volume I Functional Analysis. Let $L(H,\mathbb{C})$ denote the space of linear functionals (operators) from the Hilbert space $H$ to another Hilbert space of complex numbers $\mathbb{C}$. Now, Let $T$ be an operator in $L(H,H)$, the space of operators from $H$ into $H$. Then consider $Tx$ in $L(H,\mathbb{C})$.
It says the operator norm of $Tx$ in $L(H,\mathbb{C})$ is the same as the norm of $Tx$ in $H$.
I know what an operator norm is. To define the operator norm of $Tx$ in $L(H,\mathbb{C})$:
$$\sup_{y\neq 0} \frac{|\langle Tx,y \rangle|}{\langle y,y \rangle^{1/2}}$$
and the norm of $Tx$ in H  is just $\langle Tx,Tx \rangle^{1/2}$.
The conclusion of the two being equal tells me that assuming $\langle y,y \rangle=1$, we have:
$$|\langle Tx,y \rangle|= \langle Tx,Tx \rangle^{1/2}$$
Is that even true? Where did I go wrong?!
Comment: No, that's not true; you ignored the supremum. Your last equality only holds for those $y$ at which the supremum is attained.
Comment: of course, @joriki is right about that, but I figured this was simply a typo because it is so obviously wrong (take $y$ orthogonal to $Tx$).
Answer: In the definition of the operator norm we have
$$\|T\| = \sup_{\|x\| = 1} \|Tx\| = \sup_{x \neq 0} \frac{\|Tx\|}{\|x\|}$$
simply by homogeneity of the norm.
Then note that by Cauchy-Schwarz we have $|\langle Tx,y\rangle| \leq \|Tx\|\,\|y\|$, so for $\|y\| = 1$ this gives $|\langle Tx,y\rangle| \leq \|Tx\|$ and hence $\sup_{\|y\| = 1} |\langle Tx, y \rangle| \leq \|Tx\|$. Of course, we may assume $Tx \neq 0$. Taking $y = \frac{Tx}{\|Tx\|} = \frac{Tx}{\langle Tx,Tx \rangle^{1/2}}$ then yields $|\langle Tx,y\rangle| = \|Tx\|$, so
$$\sup_{\|y\| = 1} |\langle Tx, y \rangle| = \|Tx\|$$
as desired.
Comment: @Rohan: By the way what you're asking about is a special instance of the [Riesz representation theorem](http://en.wikipedia.org/wiki/Riesz_representation_theorem)
Comment: What exactly do you mean by the homogeneity of the norm? Thanks!
Comment: @Rohan: $\|\lambda x\| = |\lambda| \|x\|$
Comment: By what I'm asking for, do you mean the Theorem VI.1. In that case, that is true, I'm just developing analogues to operators!
Comment: @Rohan: I meant the fact that the linear functional $x \mapsto \langle \cdot, y\rangle$ has norm $\|y\|$ follows from (part of) the Riesz representation theorem. Could you clarify what exactly you mean by "developing analogues to operators"?
Comment: It is true that part of the statement of Riesz's theorem is that $y\mapsto\langle\cdot,y\rangle$ is isometric, but I would be inclined not to invoke Riesz except where surjectivity of the map is used.  As also seen in this answer, the fact that $\langle\cdot,y\rangle$ has norm $\|y\|$ follows from a combination of Cauchy-Schwarz and plugging in $y$.
Comment: @Jonas: Agreed, I can't argue with that, of course. I just thought mentioning Riesz might be helpful, but certainly the isometry part is the easiest bit of the proof of that result.


A logic puzzle involving a balance.

Question:
Possible Duplicate:
Optimal algorithm for finding the odd spheres

You have 12 balls and you know that they all weigh the same except for 1 which is heavier or lighter than all the others (you don't know which though). How can you make sure you know which ball is the heaviest/lightest in only 3 weighings?
The way I approached it was to split up the 12 balls into three sets of 4 and weigh two of the sets. If the sets balanced the scale, then I know the ball I am looking for must be in the set of 4 balls not weighed, else, I disregard said set and arbitrarily choose the heaviest set of 4 (as opposed to choosing the lightest set). I split the heaviest set of 4 balls into 2 and weigh that... etc.
Repeating this process until all 3 tries have been "used up", even if everything just so happened to be in your favor (the arbitrary choice you have in choosing the heaviest or lightest set happens to be the correct choice) in the end you still end up having to choose between 2 balls. A 50% chance is good, but I am wondering, is there a way to make sure 100%?
Comment: Yes, there is a way that guarantees finding the odd-one-out and determining if it's heavier or lighter. Your first step (4 against 4) is good, but you should think harder about the second.
Comment: I believe there is a method to find the anomalous ball from 13 in three weighings - but it is not possible to guarantee that you will know whether it is heavier or lighter.
Comment: @Mark: of course there is such a method: just execute a 12-ball protocol leaving one ball aside. If one of the 12 is anomalous, you'll find it, and if not, you'll know it's the 13th. This works assuming you know there's precisely one anomalous ball.
Comment: @AlonAmit: and if I can tell the odd one from 13, I can do the same for 14 by your method? - Clearly not, but that depends on the nature of the solution for 13. I need the knowledge that exactly one is different.
Comment: @Mark: Yes, like I said... you need the knowledge that precisely one is different. Maybe I'm misunderstanding what you're trying to say? What, in your view, is wrong with my proposed solution for 13?
Comment: @AlonAmit - I've added a comment to your solution. My point was mainly that for your argument to work for 13 balls, it had to be based on a solution for 12 which hadn't already used the information.
Answer: It's hard to believe this classic puzzle isn't already documented in MSE, but FWIW, here's one of the standard "static" solutions. "Static" means that the weighings are fixed in advance - we know which coin (or ball, or whatever) goes on which arm of the balance at each step regardless of the outcomes of previous weighings. This seems like a harder problem to solve, but in fact, it makes the process of finding a solution somewhat easier than the more natural case-by-case analysis.
Create a 3-by-12 matrix. The rows correspond to weighings, the columns correspond to coins. Each entry in the matrix is either L (the coin goes on the left of the scale in this weighing), R (the coin goes on the right) or O (the coin is left out in this weighing).
Now if a coin is heavy, it will make all the weighings in which it has L to be left-heavy, all those in which it is R to be right-heavy, and all the ones where it's O to be balanced. For a light coin it's the other way around. So each pair of (coin, weight bias) creates a sequence of results, and you just need to make sure that all those sequences are different for all the (coin, bias) combinations. In other words, the columns of the matrix must all be different, and moreover, none of them should be inverses of each other (since if coin x is the inverse of coin y, you can't tell a heavy coin x from a light coin y).
Here's an example solution (I use +, - and blanks here instead of R, L and O since it's easier to grasp I think) which has a little bit of structure making it easy to verify the requirements.
<code>1 2 3 4 5 6 7 8 9 A B C
+     + - + -   - +   -
  +   + + - - -   - +
    + - + +   - -   - +
</code>
EDIT: to explain once again what all this means, in the first weighing we pit coins 1, 4, 6 and 10 against coins 5, 7, 9 and 12. The second weighing has 2, 4, 5, 11 against 6, 7, 8, 10 and the last one has 3, 5, 6, 12 against 4, 8, 9, 11. So the weighings are always 4 against 4, and as mentioned, the result of weighing #1 don't matter at all for how we choose to handle the other weighings. It's all static.
If coin 1 is heavy, for example, we'll get "Left, balanced, balanced". No other coin can do that by being heavy (there's no other column like this one) and no other coin can do that by being light (since there's no column that goes "- blank blank").
Comment: The comment on the original post works with this scheme. If we have 13 balls/coins etc then there is one which is unweighed - and if all the others balance we know it is the bad one, but we don't know whether it is heavy or light.
Comment: +1 I had never seen this problem solved this way. Your 3x12 matrix is curious in its own right. If you add a column of pluses (bad for this puzzle, but ignore that) instead of a column of blanks, you get the check matrix of the ternary Hamming code of length 13. If you playing football pools (guess the outcome, win/draw/loss, of 13 matches), then you can use the check matrix (for much the same reasons as in your solution) to generate a system $3^{10}$ 13-tuple guesses with the nice property that you can guarantee that one of the 13-tuples has at least 12 correct guesses.
Comment: @Jyrki: honored to be the one bringing this to your attention :-) certainly the column condition on the matrix is equivalent to other objects in coding and design theory.
Answer: Here is the first solution I came up with.  There may be a cleaner one to be found.
Weigh four against four to start.  If they are equal, you can easily find the odd ball from the remaining four by weighing against two known balls, then one known ball.
If the scales are uneven, let us call the lighter one scale 1 and the heavier scale 2.  Keep three balls on scale 1, then exchange the fourth with a ball from scale 2.  Remove the remaining three balls on scale 2 and replace them with known balls.
If the scales now balance, you know that the odd ball was removed from scale 2, and is heavier than the others.  If scale 1 is still lighter, you know that the odd ball is one of the three kept balls on scale 1, and is lighter than the rest.  If scale 2 is lighter, the odd ball must be one exchanged between the two scales.
In all three cases, you can determine the odd ball in one more weighing.
Answer: Alon's answer is a good one, but it set me puzzling as to why it is that we can deal with 13 balls and not 14. After all, in three weighings there are 27 possible combinations (the scales can go either way, or be level). The answer for 13 balls allows us to discover the bad ball (13 options) and for twelve of these to say whether it is heavy or light - a total of 25 possibilities - what has happened to the missing two?
The problem is that we are constrained to use eight balls in each weighing - if we could use nine balls we would be able to use all the possibilities. This can be achieved if we have an extra ball, X, which we know to have the correct weight. With balls ABCDEFGHIJKLMN and X weigh as follows:

ABCDX v IJKLM
AEFIX v CDHLM
CGIJL v FHKMX

This scheme enables us to identify whether any of the balls ABCDEFGHIJKLM is the bad one, and if so whether it is heavy or light. If all the weighings come out level, then N is the bad one, but we don't know whether it is heavy or light.

A logic puzzle involving a balance.


Is there any such error logged by CentOS somewhere that can conclusively reveal "it is now time to pay for ECC"

Question: I have a 32GB non-ECC RAM dedicated server with CentOS.
Once for day it randomly crashes without any error in /var/log/kern.log, /var/log/messages, mysql, apache.
CPU/RAM/IO are not particularly high nor low.
Is there any such error logged by CentOS somewhere that can conclusively reveal "it is now time to pay for ECC" ?
Comment: What type of hardware?
Comment: Intel® Core™ i7-4770 Quadcore Haswell incl. Hyper-Threading Technology, 32 GB DDR3 RAM, 2 x 2 TB SATA 6 Gb/s 7200 rpm HDD (Software-RAID 1) Class Enterprise. This is what I know.
Comment: This is far from a full answer, but if you're running Redis, it has a built-in memory test (http://antirez.com/news/43). This is the only instance I know of server software that does that, though.
Answer: What would you like it to log?  CentOS can't know that the contents of non-ECC memory has become corrupt, because it's not knowable; it can only know that the contents of memory make no sense, and panic on the grounds of whatever self-inconsistency it found.  That inconsistency might have arisen from RAM corruption, but it might also have arisen from a kernel bug, or some other cause.
The only way to know definitively that memory has become corrupt is to use memory that explicitly includes support for checking for such corruption; to wit, ECC memory.
Edit: that is a completely different question to the one you asked.  But my strategy would be: run memtest86+ on the hardware, to see if there are any easy-to-catch repeatable errors, and enable remote syslogging on the server (as when the kernel panics, it often stops writing to the FS but can still squeeze a log message out the NIC), to see what's logged on the next panic.
Comment: +1 I am going to use memtest for the first time. I am glad I asked this question, I got two really helpful answers.
Comment: Once you are satisfied, don't forget to accept one by clicking the tick outline.  My apologies if you are familiar with this procedure.
Comment: Thanks and please bear with me, I am new to such matters. So the only way for me to find out whether my server is crashing once for day because of memory corruption or not is to get ECC. No hints anywhere beforehand?
Answer: ECC memory has two advantages:

It is registered, meaning that there is a register before other components on the chip.  This is supposed to remove electrical load from the memory controller.  This is true of all RDIMMs, not just ECC RAM.
It can detect errors, and if not recover from them at least report that they happened

Given this, it is actually very difficult to determine whether you would have benefited from ECC ram without having ECC ram.  By definition you cannot log the failure to detect an error, and you certainly don't have data on whether the error which may or may not have happened was the result of the memory controller messing up.
That said, if you run memtest, you will determine a couple things.  If you find no errors, either you need ECC RAM, or the problem is with something else (so if you rule absolutely every piece of hardware and software out as the cause, you have shown the need for ECC RAM).  If you find consistent errors, chances are the RAM is bad and just needs to be replaced.  If you find inconsistent errors, the CPU might be bad, or you might need ECC RAM.  If you find that memtest86 crashes, either the lowest-order DIMM is bad, or the CPU is bad, or you need ECC RAM.
Regardless, this is very tricky to definitely show.  ECC RAM is most useful in applications where invisible errors in calculations are likely to cause extreme problems, or in applications where the sheer quantity of RAM combined with other conditions makes errors statistically likely.  However, these criteria themselves are fuzzy and subjective, so it follows that there isn't really an objective criterion for this.
Comment: +1 this is going to be tremendously helpful, never used memtest before now. Thanks Falcon
Comment: Technically, there is such a thing as unregistered ECC RAM although it is comparatively rare.
Comment: I don't think I've seen unregistered ECC ram in any new hardware at all, but yes, if you had some it might not help as much in this case.
Answer: If anywhere, it would probably log to
 /var/log/mcelog

(this is where critical CPU events go on RHEL breds)


Set a parameter as an interface or a list of interfaces

Question: I'm pretty new to Go and there are some subtilities that I don't get yet
For instance, I have a function who may be called like this :
myVar.InitOperation("foo",Operator.EQUAL,"bar")
myVar.InitOperation("foo",Operator.INCLUDE,[]interface{}{"baz",1,"boo"})
myVar.InitOperation("foo",Operator.GREATER_THAN,1)

So I declared this function as :
func InitOperation(attr string, operator Operator, value interface{}){
    if operator.String() == "BAR"{
        doSomething(attr,operator,value)
    } else if (operator.String() == "INCLUDE" {
        doSomethingElse(attr,operator,value)
    }
    // And so on regarding to the case
}

The thing is that when I pass a string or an integer, it goes well but when I pass an array, it is parsed as a single element.
In my function doSomethingElse, I'm trying to iterate over values, and as you may guess, I have an error.
Fine, I'll just set values as []interface{} and not interface{}. Here, everything goes well but when I'm calling doSomething, it is parsed as [[myValue]] which is logical but not what I expect.
My question is, is there a way to pass either an []interface{} or interface{} who can be red as a value or an array of values regarding to the case ?
Thanks !
Answer: You need a type assertion:
func InitOperation(attr string, operator Operator, value interface{}){
    if operator.String() == "BAR"{
        doSomething(attr,operator,value)
    } else if (operator.String() == "INCLUDE" {
        doSomethingElse(attr, operator, value.([]interface{}))
    }
    // And so on regarding to the case
}

func doSomethingElse(attr string, operator Operator, value []interface{}) {
    for _, v := range value {
        fmt.Println(v)
    }
}

Comment: Thank you, it worked.
Very elegant solution, I'm gonna love Go :)


Define $\langle,\rangle_{(x,y)} = dx\otimes dx + h(x)^2dy\otimes dy.$ Compute the Gaussian curvature of $\mathbb{R}^2$ with this metric.

Question:
Let $h$ be a $C^\infty$ function on $\mathbb{R}$. At each $(x,y) \in \mathbb{R}^2$ define $$\langle,\rangle_{(x,y)} = dx\otimes dx + h(x)^2dy\otimes dy.$$ Compute the Gaussian curvature of $\mathbb{R}^2$ with this metric.

The Gaussian curvature is given by $K=\Omega_2^1(e_1,e_2)$ in this case I think. In order to fin $K$ I need to find the connection 1-form $\omega_2^1$ and to find this I can use the first structural equation, but for that I need an orthonormal frame $(e_1,e_2)$ and a coframe $(\theta_1,\theta_2)$.
So given the metric how can I find an orthonormal frame with respect to it? If I set $e_1=a\frac{\partial}{\partial x} + b\frac{\partial}{\partial y}$ and $e_2 = c\frac{\partial}{\partial x} + d\frac{\partial}{\partial y}$, then $$\langle e_1,e_2\rangle_p=ac+h^2(x)bd= \delta_{12}$$ and $$\langle e_1,e_1\rangle_p=a^2+h^2(x)b^2=1, \langle e_2,e_2\rangle_p=c^2+h^2(x)d^2=1$$ given these how do I find the coefficients? The two latters suggest that $a=1, b=0$ and $c=1$ and $d=0$, but this wont satisfy the first equation since it's always $1$ then.
Comment: Renaming the variables, this is simply the metric induced on a surface of revolution, so you should get $K = -h''/h$; an orthonormal frame is $e_1 = \partial_x$, $e_2 = \partial_y/h$ and the corresponding coframe is $\theta_1 = {\rm d}x$, $\theta_2 = h\,{\rm d}y$.
Comment: You don't even care about $e_1$ and $e_2$. Remember that the metric is given by $\theta^1\otimes\theta^1+\theta^2\otimes\theta^2$ when $\theta^1,\theta^2$ is an orthonormal coframe. Then use the structure equations to find $\omega^1_2$ and then $d\omega^1_2$ is immediate.
Comment: I'm not sure how you derived this. Is it not possible to derive the orthonormal frame from the given equations? @IvoTerek
Comment: The coordinate fields are already orthogonal (there are no mixed ${\rm d}x\,{\rm d}y$ terms), so I just normalized them.
Comment: Do you mean $\partial/\partial x$ and $\partial/\partial y$? I have a feeling that there is some relation with the metric to the coordinate fields you are mentioning that I'm not understanding. @IvoTerek
Answer: Your approach is fine. It's not hard to see that the orthonormal frame you are looking for is given by $e_1=\frac{\partial}{\partial x}$ and $e_2=\frac{1}{h(x)}\frac{\partial}{\partial y}$ (instead of trying to solve the equations think about how to force the conditions you want).
The dual frame $(\theta^1,\theta^2)$ is then given by $\theta^1=dx$ and $\theta^2=h(x)dy$. In this case the strucutral equations then relate these and the connection $1$-forms by
\begin{align*}
d\theta^1&=-\omega_2^1 \wedge \theta^2 \\
d\theta^2 &= \omega_2^1 \wedge \theta^1.
\end{align*}
On $\mathbb{R}^2$, the $1-$form $\omega_2^1$ is a linear combination of $dx$ and $dy$ so $\omega_{2}^1=adx + bdy$.
The first equation gives $0 = -(adx+bdy) \wedge h(x)dy = -ah(x)dx \wedge dy$ and since $h(x) > 0$, we have that $a = 0$.
The second equation gives that $h'(x)dy \wedge dz = (adx+bdy) \wedge dx = bdy \wedge dx = -bdx \wedge dy $ so $b = -h'(x)$ and $$\omega_2^1  = -h'(x)dy.$$
Now $\Omega_2^1 = d\omega_2^1 = -h''(x) dx \wedge dy$ and so $$K=\Omega_2^1(e_1,e_2)=-h''(x)dx \wedge dy\left( \frac{\partial}{\partial x}, \frac{1}{h(x)}\frac{\partial}{\partial y}\right) = -\frac{h''(x)}{h(x)}.$$


How to do feature selection for learning from positive and unlabeled examples?

Question: I have a binary classification task for German webpages for which I only have positive examples. That is why I use learning from positive and unlabeled examples as described on this page, also known as partially supervised learning.
At the moment, I'm just excluding very rare features which occur only once and very frequent features, i.e., stop words and those which occur in more than 50% of all positive examples.
As for classifiers, I want to test Naive Bayes (the positive example webpages are quite short, so I favor the multivariate version with boolean features) and Support Vector Machines (SVM). I've read that feature selection is not so important for SVM as it does not effect the classification results very much. Is that true?
As I'm not so familiar with feature selection algorithms, can you recommend an algorithm that works especially well with features from positive examples only and which generally yields better results than just cutting off very rare and very frequent features? If it is not possible to give a general answer to this question and if it highly depends on my data set, then please say so as well. Thanks a lot!
Answer: My experience with SVM has shown it to be fairly robust to uninformative features. Other classifiers, like Naïve Bayes, for example, tend to be more sensitive to such features, making feature selection a relatively more important part of the classification workflow. In terms of feature selection algorithms, I'm a fan of using information theory-based metrics, like mutual information. When I use this, I usually generate a graph of the distribution of the input feature's mutual information during cross-validation, and then manually select some cut-off.
Comment: Please correct me if I'm wrong, but for calculating mutual information you need data from two classes, right? I only have data from the positive class. How to do efficient feature selection having only this one class? Or do I have to apply the partially supervised learning algorithms first to get a set of reliable negative data and then perform mutual information on both this negative and the positive data?
Comment: +1 The SVM is an approximate implementation of a generalisation bound that is independent of the dimensionality of the feature space, so there is good reason to suppose it will work well with redundant features.  Selecting the features using e.g. cross-validation invalidates that bound, and is very likely to result in over-fitting the CV error, so quite often feature selection will make the model worse rather than better (although of course the CV error that you have optimised will not reflect that).
Comment: You're right, you need two classes for mutual information. For a similar problem, I used active learning techniques to identify my negative-class data. Your partially supervised approach should work as well.
Comment: Okay, so doing feature selection except for cutting off rare and frequent terms before identifying the negative data does not make sense. That was my main question (apparently, I didn't make it clear enough). Thank you very much!
Answer: In order to make feature selection with unlabeled data, what about clustering+ANOVA to study which variables are more important? With the clustering you learn the distribution from the data, and using ANOVA will let you know which variables are more interesting for your study.
In addition, you may use ANOVA on all your data to see which variables are able to explain your variance.


How to make sure the the saved document fits the schema in MongoDB?

Question: I have a MEAN app and I occasionally change the schema of the user document in MongoDB.
When I save a new document to the collection, I would like for the saved document to fit the schema exactly, otherwise raise an exception, is it possible?
Currently I can save partial document or even worse, try to save some non existing fields (in the schema) which MongoDB ignores.
Thanks
Answer: Basically, Schema is the blueprint of a collection.  Each schema maps to a MongoDB collection and defines the shape of the documents within that collection.
Now come to your issue
1: Can save partial document : If you do not want to save partial document you have to mark all fields as required in document.It will throw an error if you send partial document
2: try to save some non existing fields : As you already written mongoose schema ignores the non existing fields But if you want an error to be thrown if client send some unwanted data then you have to handle this on your route.For that i will recommend you to use a library called tv4
And also if u want to handle both points then also go for tv4
Comment: Thanks. If I want all of my fields to be required, should I add it to all of them? I plan on doing it in unit tests and not in operational so I can go  bit crazy here... About tv4.validate(data, schema), Do you know what the arguments are? can it get mongoose schema and JSON as data?
Comment: By default every field in mongoose schema is optional. for making all fields u have to add required:true in each field .No tv4 has its own way of defining schema most of bit similar to mongoose schema i used this in my application in route level before making call to my db in this way i restrict client side unwanted data .  and yes JSON as data
Comment: So you have to have a schema for tv4 and a schema for Mongo?
Comment: Yes, i told u tv4 is used for route level checking and mongoose schema is a blueprint for database


menu items saved with menu_link_save() don't have the delete button, and I can't edit the menu path

Question: When I add menu items manually, they work fine.  When I try this I get no delete link in the admin, and I can't edit the menu items.
<code>$link = array();
$link['link_title'] = "text";
$link['link_path'] = 'node';
$link['menu_name'] = $menu;
$link['expanded'] = 1;
$link['module'] = "dl_migration";
$link['weight'] = $i;
menu_link_save( $link );
menu_cache_clear_all();
</code>
Answer: The reason the "delete" link is not shown is that the link is only shown when the menu item is created by (or associated to) the Menu module. _menu_overview_tree_form() contains the following code:
<code>  // Only items created by the menu module can be deleted.
  if ($item['module'] == 'menu' || $item['updated'] == 1) {
    $operations['delete'] = l(t('delete'), 'admin/build/menu/item/' . $item['mlid'] . '/delete');
  }
</code>
menu_link_save() uses some defaults for the array <code>$item</code> passed as argument; this means that if the module associated with the menu link is not explicitly set, it receives the default value ("menu").
<code>  // Load defaults.
  $item += array(
    'menu_name' => 'navigation',
    'weight' => 0,
    'link_title' => '',
    'hidden' => 0,
    'has_children' => 0,
    'expanded' => 0,
    'options' => array(),
    'module' => 'menu',
    'customized' => 0,
    'updated' => 0,
  );
</code>
Comment: I think the idea is that users should not be allowed to delete links programmatically added by third-party modules; users should just be able to disable those links. It makes perfectly sense to me, especially in the case a module help text makes reference to those links.
Comment: You can propose a feature request for Drupal. It would help to have a flag that allows to modules to create a menu link that can be deleted from users, even if the value for "module" is not "menu." In that way, a module could add custom links users can delete, and still be able to delete the links when it is uninstalled.
Comment: Uhm, yeah, that's what I said above.  Thanks for fleshing out the answer tho.  It's a stupid paradigm though, don'tcha think?
Comment: It should be an option -- during the large migration I'm setting up we are going to be using a module to create a set of menus.  Marking those with our module name is preferable because it limits things conceptually.  Ah well.
Answer: Specifying the module name is what caused the lack of ability to delete.  I'm not sure why, though.  Sort of lame I think.


Proving $\DeclareMathOperator{\Re}{Re}\DeclareMathOperator{\Im}{Im}\Re{(\cosh z}) = \cosh(\Re z)\cdot \cos(\Im z)$

Question: I want to show $\Re{(\cosh z)}) = \cosh(\Re z)\cdot \cos(\Im z)$.
I did the following:
\begin{align*} \cosh(\Re z)\cdot \cos(\Im z) &= \frac {1}{2}(e^{\Re z}+e^{-\Re z})\cdot \frac {1}{2}(e^{i\Im z}+e^{-i\Im z}) \\& = \frac {1}{4}(e^{\Re z}+e^{-\Re z})\cdot (e^{i\Im z}+e^{-i\Im z}) \\
&= \frac {1}{4}(e^{\Re z}+e^{-\Re z}) \cdot 2\\
& = \frac {1}{2}(e^{\Re z}+e^{-\Re z}) \\
&= \frac {1}{2}\Re(e^z+e^{-z}) \\
&= \Re(\cosh z)
\end{align*}
Using: $\cosh(x) = \frac {1}{2}(e^x+e^{-x})$ and $\cos(x) = \frac {1}{2}(e^{ix}+e^{-ix})$.
I would be very glad if someone could tell me if this is correct!
Comment: I don't see how you got the third equality.
Comment: Delete the first equality for sure. Now as written, it looks like you assume the result and finagle around a bit. That's not what you've done.
Comment: @AndresMejia Is this better?
Comment: yeah, for sure. I edited the formatting a bit for readability. I hope you find that okay.
Comment: @AndresMejia Sure, thanks! Better formatting is always welcome.
Comment: @AndresMejia Well, I used $(e^{iIm(z)}+e^{-iIm(z)}) = 2$ when $z >0$. Maybe this is wrong, though.
Comment: Why would $e^{ix}+e^{-ix}=2$ for $x \in \mathbb R_{>0}$? Note also that $Re(e^{ix}) \neq e^{Re(ix)}$ for $x \in \mathbb R$. This can be seen, for example because there are $x$ with $Re(x)>1$. You seem to use this in your fifth equality.
Comment: @AndresMejia Well, $e^{iIm(z)}+e^{-iIm(z)} = 2cos(Im(z))$. And if you plot both actually, you can observe we have $2$. That's why I thought this is true, but I'm not sure about the correctness, hence why I asked!
Comment: It seems easier to prove starting from $\operatorname{Re}(\cosh z)$.
Comment: @Zelda_CompSci It is not true that $(e^{i\Im z}+e^{-i\Im z})=2$.
Comment: @Zelda_CompSci How do we justify the step $ \frac {1}{2}(e^{\Re z}+e^{-\Re z}) = \frac {1}{2}\Re(e^z+e^{-z}) $?
Answer: Let $z=x+iy$, then we have that
$$\cosh z=\frac{e^z+e^{-z}}2=\frac12e^xe^{iy}+\frac12e^{-x}e^{-iy}=\frac12e^x(\cos y+i\sin y)+\frac12e^{-x}(\cos y-i\sin y) $$
$$ \implies \operatorname{Re}(\cosh z)=\frac12e^x\cos y+\frac12e^{-x}\cos y=\frac{e^x+e^{-x}}2\cos y=\cosh x \cdot\cos y$$
Comment: This doesn't really answer the question in the body.
Comment: I should clarify that I did not downvote
Comment: @AndresMejia Yes you are right! I've just revised the derivation.
Comment: Upvoted simply because I consider this the most direct and clearest proof. It seems some of the other answers are unnecessarily obfuscated because they wanted to mirror what the OP did. We shouldn't fall into this trap - it's never a given that the OP has found the simplest solution or the clearest way to present something. This solution gives some valuable tips - in a problem like this, encode the real and imaginary parts into single letter variables for clarity. Invoke the trigonometric form early to help split the real and complex parts. All these things will make future problems easier.
Comment: @Deepak Thanks a lot for you kind appreciation! I must agree with you :P
Answer: As an alternative, but taking the path of OP so that his /her error can be seen:
$$ \cosh\left[\operatorname{Re}(z)\right] \cdot \cos\left[\operatorname{Im}(z)\right] = \left(\frac{e^{\operatorname{Re}(z)} + e^{-\operatorname{Re}(z)}}{2}\right) \left(\frac{e^{i\operatorname{Im}(z)} + e^{-i\operatorname{Im}(z)}}{2}\right)$$
$$ = \frac{e^{\operatorname{Re}(z) + i\operatorname{Im}(z)} + e^{\operatorname{Re}(z) - i\operatorname{Im}(z)} +  e^{-\operatorname{Re}(z) + i\operatorname{Im}(z)} + e^{-\operatorname{Re}(z) - i\operatorname{Im}(z)}}{4} $$
$$ = \frac{e^{\operatorname{Re}(z) + i\operatorname{Im}(z)} + e^{-\operatorname{Re}(z) - i\operatorname{Im}(z)} + e^{\operatorname{Re}(z) - i\operatorname{Im}(z)} +  e^{-\operatorname{Re}(z) + i\operatorname{Im}(z)} + }{4} $$
$$ = \frac{e^{Re(z) + i\operatorname{Im}(z)} + e^{-\operatorname{Re}(z) - i\operatorname{Im}(z)} + e^{\operatorname{Re}(z) - i\operatorname{Im}(z)} +  e^{-[\operatorname{Re}(z) - i\operatorname{Im}(z)]}}{4} $$
$$ = \frac{e^{\operatorname{Re}(z) + i\operatorname{Im}(z)} + e^{-[\operatorname{Re}(z) + i\operatorname{Im}(z)]}}{4} + \frac{e^{\operatorname{Re}(z) - i\operatorname{Im}(z)} + e^{-[\operatorname{Re}(z) - i\operatorname{Im}(z)]}}{4} = \frac{\cosh {z}}{2} + \frac{\cosh {\overline {z}}}{2}$$
$$  = \frac{\cosh {z} + \cosh {\overline {z}}}{2} = \frac{2\operatorname{Re}{\left[\cosh{z}\right]}}{2} = \operatorname{Re}{\left[\cosh{z}\right]}$$
Answer: Using the sum of angles formulae,
$\cosh(x+iy)=\cosh(x)\cosh(iy)+\sinh(x)\sinh(iy)$
but $
\cosh(iy)=\cos(y)$ and $\sinh(iy)=i\sin(y)$
so:   $\cosh(x+iy)=\cosh(x)\cos(y) + i \sinh(x)\sin(y)$
QED


If a function $f$ is injective then is $g\circ f$ also injective even if nothing is said about $g$?

Question: I have been struggling with the following two questions:
For any nonempty sets $A,B,C$ and for any functions $f: A\to B$ and $g: B\to C$,
a) if (f) is injective, then $(g \circ f) $ is injective
b) if (g) is surjective, then $(g\circ f)$ is surjective
My main confusion comes from how for example part a, it doesn't say anything about whether or not g is injective. we know if $f(x)$ is injective, then $f(x_1)=f(x_2)$ implies $x_1=x_2$. But for g if $g(x) = \sqrt{x}$, and f(x)= 9, g(fx) = 3 or -3. So in this case can i still call $g \circ f$ an injective function?
Comment: Consider $f(x)=x, g(x)=x^2$; if $g$ maps $x$ to $\pm\sqrt x $, then $g$ is not a function
Answer: If $f$ is injective, $g\circ f$ doesn't have to be injective too. Suppose that $A$ has more than one point and that $g$ is constant.
Comment: is there a proper way for us to prove it? Because I can't seem to write a proper proof for "it is not injective" but only "it doesn't have to be"
Comment: If $A$ has two distinct points $a$ and $a'$ and $g$ is constant, then $a\neq a'$, but $g\bigl(f(a)\bigr)=g\bigl(f(a')\bigr)$. What else do you need?
Comment: ah i see now i was thinking of how to prove g(f(a)) is not equal to g(f(a')) when f(a)=f(a'). Thanks for the help!
Answer: Both a)  and b) are false. Just consider that $A$, $B$ and $C$ have more than one element each, and a constant function $g$.
Answer: a) and b) are false.
Please look at this function.
For a) it has to be (g), for b) it has to be (f).
This is one good anti-exam for both


Calculate $ \lim_{x\to 1} \frac{\ x^2 -\sqrt{x}}{\sqrt{x}-1}$ and $\lim_{x\to 0} \left(\frac{1}{x}\right)^{\ln(1+\sin^2x)}$

Question: $$ \lim_{x\to 1} \frac{x^2 -\sqrt{x}}{\sqrt{x}-1}$$
$$\lim_{x\to 0} \left(\frac{1}{x}\right)^{\ln(1+\sin^2x)}$$
Please if you can help me in the two limits.
Answer: Hints.
i) For $x>0$, we have that
$$\frac{x^2 -\sqrt{x}}{\sqrt{x}-1}=\frac{x^{1/2}(x^{3/2} -1)}{x^{1/2}-1}=x^{1/2}(x+x^{1/2}+1).$$
ii) We have that $a^b=\exp(b\ln a)$ and
$$\lim_{x\to 0} \left(\frac{1}{x}\right)^{\ln(1+\sin^2x)}=
\lim_{x\to 0} \exp\left(\ln(1+\sin^2x)\cdot (-\ln(x))\right)\\
=\lim_{x\to 0} \exp\left(-x^2\ln(x)\cdot\frac{\sin^2x}{x^2}\cdot \frac{\ln(1+\sin^2x)}{\sin^2x}\right).$$
Now evaluate these (simpler) limits,
$$\lim_{x\to 0} \frac{\sin x}{x}=?$$
$$\lim_{x\to 0}\frac{\ln(1+\sin^2x)}{\sin^2x}=\lim_{t\to 0}\frac{\ln(1+t)}{t}=?$$
$$\lim_{x\to 0} x^2\ln(x)=?$$
Comment: @Dan Balan Yes $\ln(1+t)/t\to 1$. If you do not like radicals replace $x^{1/2}$ with $t$.
Comment: Thank you but I do not understand where it comes t, why did your replacement
Comment: I do not quite understand what you meant to do there
Comment: Well not quite understand what you wanted to do you could make the steps I please, I do not quite understand another form of education are in romania
Comment: I get up there but you could tell me what exp
Comment: @Dan Balan See my edited answer.
Comment: @Dan Balan $\exp(x)=e^x$.
Comment: ln(1+t)/t=1 ok?
Comment: where have you realized exp
?
Comment: could you give me exercise 1, the radical, not quite understand?


apache 2.4 with basic authentication and fail2ban apache-auth

Question: It seems I have a conflict in my configuration on CentOS 7 server.
The issue appears between vhost configuration on apache 2.4 (httpd) with the basic authentication and fail2ban apache-auth banning feature.
I want two things :
1) An authentication for access to my each websites with basic authentication feature.
2) Ban IP with fail2ban from apache errorlog files.
My problem is :

If I have "Deny from all" in location tag inside of vhost configuration file so I have prompt for authentication but I have too lot of errors in apache errorlog file --> "AH01797: client denied by server configuration"
However, if I change "Deny from all" by "Require all granted", the issue dispears but the prompt authentication too obviously.

How can I have this two features together, without conflict?
I hope this is clear. Please ask for any additional information needed.
Answer:
I hope this is clear.

Well not really. Either the issue is that fail2ban doesn't recognize AH01797: client denied but you want it'd happen (then see P.1), or vice versa it find that but you don't want that (then see P.2)

Normally fail2ban's apache-auth should detect this kind of failures.
If it does not either your fail2ban version (or config file) are too old, or you've some different log (compare it with this or provide an example of your log).
If you want that fail2ban ignores this, just open /etc/fail2ban/filter.d/apache-auth.conf (make a backup) and remove the rule for this, for example for newest version it would be something like this:

- failregex = ^client (?:denied by server configuration|used wrong authentication scheme)\b
+ failregex = ^client (?:used wrong authentication scheme)\b

Comment: Thanks sebres, It's perfect. I'm concerne by P.2. I commented the line "^client (?:denied by server configuration|used wrong authentication scheme)\b" in /etc/fail2ban/filter.d/apache-auth.conf file at "failregex" argument level.


Drupal advanced forum - different styles for different forums

Question: With Advanced Forum on Drupal 7, how can I apply different styles to different forum posts, depending upon which forum they are in? Although I can see how to style different forums, there doesn't seem to be any way of using a different style per post depending upon the forum it is in, as there is no CSS class added denoting the posts forum.
Answer: On further investigation I believe this can be done with a combination of assigning a path to a post via pathauto, and the Context module, which can add CSS depending on the path.


Loop de frases de status em HTML

Question: Estou editando uma função de cancelamento de arquivos, e hoje ela mostra apenas o status "Aguardando...", conforme o código:
&js<
            cancelEvent = "";
            $(".ui-overlay").show();
            $("#retorno").empty().html(" Aguardando...");
            $.get("../javascript/Cancela.php#(qs)#",function(data){
                 $("#retorno").empty().html(data);
                     if(data == 1) {
                        processaEvento('#(NF)#','#(DESC)#','#(DT1)#','#(DT2)#','#(OP)#');
                     } else {
                        alert("Não foi possível realizar o cancelamento");
                        document.getElementById("btSalvar").disabled = false;
                        document.getElementById("btSalvar").value = "Salvar";
                     }
            });
            $(".ui-overlay").hide();
        >

Eu quero acrescentar uma sequencia de frases de carregamento, como "Aguarde...", "Efetuando o cancelamento...", "Finalizando o procedimento...", para o usuário pode acompanhar o passo a passo.
Só consigo fazer isso com javascript? Ou alguma sugestão diferente?
Comment: Como é que é isso? É um Ajax?
Comment: poderia postar seu código completo, por favor?
Comment: Editei com o bloco de código inteiro.
Answer: Javascript é a melhor opção, pois você pode alterar o texto de acordo com eventos, mostrando mensagens diferentes para cada status.
Mas você pode usar css para mudar o conteúdo da mensagem usando a propriedade content (veja mais aqui: https://developer.mozilla.org/pt-BR/docs/Web/CSS/content)
E se você quiser só trocar as mensagens sem se preocupar com um evento certo, apenas em um determinado tempo por exemplo você pode usar uma animação do css3, com @keyframes (veja mais aqui: https://developer.mozilla.org/pt-BR/docs/Web/CSS/@keyframes)
Criei um exemplo prático que faz a troca dos textos em 30s

h1:before{
    content: 'Aguarde...';
    font-size: 200%;
    animation-name: head;
    animation-duration: 30s;
    animation-iteration-count: infinite;
}

@keyframes head {
    0% {content: "Aguarde..."}
    25% {content: "Mensagem 2"}
    50% {content: "3a mensagem"}
    75% {content: "Quarta mensagem"}
    100% {content: "Mensagem Final"}
}

Comment: Genial Ricardo! Não necessito de um evento ao certo... por isso os keyframes são perfeitos, não tinha nem ideia da existência deles, muito obrigado.

Loop de frases de status em HTML


Docker. ERROR: Uploading artifacts to coordinator. timeout awaiting response headers

Question: I try to prepare large artifact file (about 1 GB). But I stuck with next error:
<code>...
Stopping my_mysql ... done
$ docker run --rm --volumes-from my_mysql carinamarina/backup backup --source /var/lib/mysql/ --stdout --zip > data/db-data-volume.tar.gz
Unable to find image 'carinamarina/backup:latest' locally
latest: Pulling from carinamarina/backup
ee54741ab35b: Pulling fs layer
a548ccba3eed: Pulling fs layer
f9a81fa3bb17: Pulling fs layer
00d43d18903a: Pulling fs layer
bee2159ca4d3: Pulling fs layer
3a4a2afad82b: Pulling fs layer
bee2159ca4d3: Waiting
3a4a2afad82b: Waiting
00d43d18903a: Waiting
a548ccba3eed: Verifying Checksum
a548ccba3eed: Download complete
f9a81fa3bb17: Verifying Checksum
f9a81fa3bb17: Download complete
ee54741ab35b: Verifying Checksum
ee54741ab35b: Download complete
ee54741ab35b: Pull complete
00d43d18903a: Verifying Checksum
00d43d18903a: Download complete
bee2159ca4d3: Verifying Checksum
bee2159ca4d3: Download complete
3a4a2afad82b: Verifying Checksum
3a4a2afad82b: Download complete
a548ccba3eed: Pull complete
f9a81fa3bb17: Pull complete
00d43d18903a: Pull complete
bee2159ca4d3: Pull complete
3a4a2afad82b: Pull complete
Digest: sha256:aa7de94eb992c54024c3b5a181e8ba0fc61986f26310b723774f01ebcae6788a
Status: Downloaded newer image for carinamarina/backup:latest
Uploading artifacts...
data/db-data-volume.tar.gz: found 1 matching files
ERROR: Uploading artifacts to coordinator... error  error=couldn't execute POST against https://gitlab.my.ru/api/v4/jobs/3764/artifacts?expire_in=1+week: Post https://gitlab.my.ru/api/v4/jobs/3764/artifacts?expire_in=1+week: net/http: timeout awaiting response headers id=3764 token=M9Xe65yo
WARNING: Retrying...
WARNING: Uploading artifacts to coordinator... failed  id=3764 responseStatus=504 Gateway Time-out status=504 Gateway Time-out token=M9Xe65yo
WARNING: Retrying...
</code>

ERROR: Uploading artifacts to coordinator... error  error=couldn't execute POST against https://gitlab.my.ru/api/v4/jobs/3764/artifacts?expire_in=1+week: Post https://gitlab.my.ru/api/v4/jobs/3764/artifacts?expire_in=1+week: net/http: timeout awaiting response headers id=3764 token=M9Xe65yo

My <code>.gitlab-ci.yml</code>:
<code>.backup: &backup_definition
  before_script:
    - apk add --no-cache py-pip
    - pip install docker-compose
    - mkdir -p ~/.ssh
    - chmod 700 ~/.ssh
    - echo "$SSH_KNOWN_HOSTS" > ~/.ssh/known_hosts
    - chmod 644 ~/.ssh/known_hosts
    - echo "$SSH_PRIVATE_KEY" > ~/.ssh/id_rsa
    - chmod 600 ~/.ssh/id_rsa
    - '[[ -f /.dockerenv ]] && echo -e "Host *\n\tStrictHostKeyChecking no\n\n" > ~/.ssh/config'
    - docker login -u gitlab-ci-token -p $CI_BUILD_TOKEN registry.my.ru
  script:
    - cp env/${ENV_NAME}.env .env
    - docker-compose up -d mysql
    - docker-compose exec -T mysql /download.sh
    - docker-compose exec -T mysql /wait-for-it.sh mysql:3306 -- echo "MySql started"
    - docker-compose exec -T mysql /restore.sh
    - docker-compose stop mysql
    - docker run --rm --volumes-from my_mysql carinamarina/backup backup --source /var/lib/mysql/ --stdout --zip > data/db-data-volume.tar.gz
  artifacts:
    paths:
      - data/db-data-volume.tar.gz
    expire_in: 1 week
  tags:
    - tests-runner
  image: docker:latest
  services:
    - name: docker:dind
  when: manual

backup-my2:
  <<: *backup_definition
  variables:
    ENV_NAME: "my2"

backup-my2-repo:
  <<: *backup_definition
  variables:
    ENV_NAME: "my2_repo"
</code>
Small artifacts are process well. I have problem just with large artifacts. How can I increase timeout?
Answer: If you use the golang net/http class library and http.client uses transport, please check if your transport has the ResponseHeaderTimeout parameter set. If it is set, it may be caused by this parameter. The request execution time of the http call exceeds the time set by ResponseHeaderTimeout
Solution
1. http.Client.Transport.ResponseHeaderTimeout parameter
2. Optimize back-end service processing capabilities