Unequal Sample Size Effect on Power Calculation

Question: I am new to power analysis and have been experimenting with one-way fixed effects Anova in G*Power (Fixed effects, omnibus, one-way, Post hoc power).
When dealing with unbalanced design, the effect size is affected. When power of such a test is computed, is it also affected by unequal sample sizes (I mean besides the effect size)?
Comment: I would like to know how power calculation for an unbalanced design differs from calculation for a balanced one (fixed one-way Anova, 4 groups). For those familiar with G*Power I can further explain where my question stems from: the program allows to compute an effect size given unequal sample sizes; when the computed effect size is used to calculate power, and given that total sample size is not a multiple of the number of groups, the program bases its calculation on average group size. I'd like to know whether unequal sample sizes directly affect the power calculation.
Comment: An unbalanced design would *not* affect most of what we call "effect sizes". The whole point of designating an effect size was to prize apart meaningful inferences from overpowered analyses - i.e. my drug is only useful if it lowers blood pressure by 10 mmHg compared to control, regardless of $p$.
Comment: There are some cases when an imbalanced design can be *more* powerful than a balanced one, even in case of simple random sampling with 1:1 randomization.
Comment: Could you clarify if your question is about how to conduct a power analysis (i.e., how many observations should I collect?), or is your question about how to conduct ANOVA (i.e., does it matter if my group sizes are different?). In other words, have you already collected your data, or are you making a plan to collect data?
Answer: There is an easy rule of thumb for ANOVA: Unequality in sample sizes deteriorates the power. The reason is that the power depends mostly on the variance of the effect estimator, i.e. the mean differences between the groups. These mean differences have the least variance (given a total sample size) if all the sample sizes are equal.
Comment: Thank you for your answer @Horst Grünbusch. G*Power  outputs a message whenever the total sample size is not a multiple of the number of groups, saying that "the analysis was based on the average group size". Does this imply that the G*Power calculation is correct only for samples of equal size?
Comment: @Gregory that sounds correct to me. Such design assumptions are typical in canned software like G*power and R's `pwr` package as it simplifies the equations and user inputs
Comment: @philchalmers You can take different group sizes into account in G\*Power or in R packages like `pwr`. You do that by specifying the correct effect size $f$, whose formula and resulting value are different for the case of groups of different sizes. If you're interested, I provide more details in my answer below.
Answer: The quick and dirty way to solve for unequal sample size problems would be to just run a simulation. Below is one such example comparing equal groups and two other potential setups using R's SimDesign package: a control group with 40% of the total sample size, and a control group with 70% of the total size for a $k=4$ setting.
library(SimDesign)

# equal and unequal group designs
Design <- createDesign(N = 30 * 4,
                       f2=.3^2,
                       props = list(rep(1/4, 4),
                                 c(.4, .2, .2, .2),
                                 c(.7, .1, .1, .1)))

#-------------------------------------------------------------------

Generate <- function(condition, fixed_objects = NULL) {
    Attach(condition)
    n.each <- N*props
    # stop if groups have fractions
    stopifnot(all.equal(n.each, as.integer(n.each)))
    group <- factor(rep(1:4, times=n.each))
    eta2 <- 1 / (1/f2 + 1)

    # pick a nice SSG from mu=0 deviation form, and solve for SSE
    gmeans <- c(-2, -1, 1, 2)
    SSG <- sum(n.each * gmeans^2)
    SSE <- SSG*(1/eta2 - 1)
    sde <- sqrt(SSE / N)
    DV <- rep(gmeans, times=n.each) + rnorm(N, sd=sde)
    dat <- data.frame(DV=DV, group=group)
    dat
}

Analyse <- function(condition, dat, fixed_objects = NULL) {
    # Fit ANOVA + extract p-value
    aov <- aov(DV ~ group, dat)
    so <- summary(aov)
    ret <- c(p = so[[1]]$`Pr(>F)`[1])
    ret
}

Summarise <- function(condition, results, fixed_objects = NULL) {
    ret <- EDR(results) # empirical detection/rejection rate
    ret
}

#-------------------------------------------------------------------

res <- runSimulation(design=Design, replications=100000,
                        generate=Generate, analyse=Analyse, summarise=Summarise)
subset(res, select=N:p)

# A tibble: 3 × 4
      N    f2 props                      power
  <dbl> <dbl> <lst>
1   120  0.09 [0.25, 0.25, 0.25, 0.25] 0.78252
2   120  0.09 [0.4, 0.2, 0.2, 0.2]     0.75352
3   120  0.09 [0.7, 0.1, 0.1, 0.1]     0.51941

Some of the more annoying features of using standardized effect sizes (like $f^2$) is that you'll often need to work out some of the translation equations to get something useful, such as converting from $f^2$ to
$$\eta^2 = \frac{1}{1/f^2 + 1}$$
so that you can later work with the usual $SS_{total} = SS_{between} + SS_{within}$ and generate data from that structure by solving, for example,
$$SS_{within} = SS_{between}(1/\eta^2 -1)$$
Otherwise, if you know the raw means + standard deviations for each group those could simply be substituted into the simulation, which I personally find more natural in empirical settings.
The true power assuming equal sample sizes can be found via the pwr package, which corresponds to the first row of the above output.
# equal groups
pwr::pwr.anova.test(k=4, n=30, f=.3)

     Balanced one-way analysis of variance power calculation

              k = 4
              n = 30
              f = 0.3
      sig.level = 0.05
          power = 0.7808169

NOTE: n is number in each group

So for control groups that reflect the bulk of the sample size power can drop pretty substantially (hence why equal sample size conditions are ideal).
Comment: I'm not sure I understand fully your whole R code, but it looks like the  effect size $f$ is fixed. It shouldn't be the case if you're comparing an "equal allocation" scenario to an "unequal allocation" scenario, as $f$ is partly a function of the number of observation in each group (i.e. an equal number of observations in each group can lead to a different effect size $f$ than an unequal number of observations in each group – keeping everything else identical).
Comment: @J-J-J that's correct, this simulation example holds $f$ constant and adjusts the within-subject variability term to accommodate to demonstrate the effect of having the same population $f$ across experiments but different sample sizes. The approach you presented makes more sense though as allowing $f$ to change as a function of the group proportions is more realistic. Also, good to know that G*Power does have support for unequal groups; thanks for sharing!
Answer: The answer by Horst Grünbusch mentions a rule of thumb where power decreases with unequal sample sizes, but it is not necessarily true in all situations.
You might gain power if you affect a larger sample size to a group whose mean, compared to other groups, is discrepant from the mean of means. By doing so, you can increase the effect size - and if you increase the effect size, you increase the power to detect this effect.
Below, I give the formulas that lead to this conclusion, followed by a worked example and its application in G*Power, and finally a verification of the result by simulation in R.
For more details about the formulas and use cases where unequal sample sizes may be useful, you may be interested in Jacob Cohen's book on power analysis  (Cohen, 1988, pp. 274-287; see references below).

The effect size $f$ is defined as:
$f=\frac{\sigma_m}{\sigma}$
where:

$\sigma$ is the standard deviation within each group (we assume equal variance),
$\sigma_m= \sqrt{\sum_{i=1}^k w_i(m_i-m)^2}$

For the calculation of $\sigma_m$:

$k$ is the number of groups,
$m_i$ is the group $i$ mean,
$w_i$ is the weight of the group $i$ such as $w_i = \frac{n_i}{N}$, $n_i$ being the number of observations in the group, and $N$ the total number of observations,
and $m$ is the mean of means, weighted per $w_i$, such as:

$m=\frac{\sum_{i=i}^kn_i m_i}{N}= \sum_{i=i}^k w_i m_i$
G*Power has a hidden function to calculate the correct effect size for unequal group sizes; it is available when you click the "determine" button next to the "effect size" field. We can use that to check if it is consistent with the formula above.
First, let's just look what happens with 3 groups whose means are 10, 7, and 7, with a standard deviation $\sigma$ of 5. If we allocate a total of 120 observations equally between the groups (i.e. 40 observation in each group), we have $m = 8$. Then:
$\sigma_m = \sqrt{\frac{1}{3} (10-8)^2 + \frac{1}{3} (7-8)^2 + \frac{1}{3} (7-8)^2} = 1.414 $
So we should have an effect size $f$ such as:
$f = \frac{\sigma_m}{\sigma} \approx 0.28$
With an alpha of 0.05, our power should be about 0.79.
Now, let's have a look at the case of an unequal allocation of observations between groups.
With weights of 0.5, 0.25, and 0.25 (that is, 60 observations in the first group, and 30 observations in each of the remaining groups), we have the following weighted mean:
$m = 10 \frac{60}{120} + 7 \frac{30}{120} + 7 \frac{30}{120} = 8.5$
Consequently:
$\sigma_m = \sqrt{0.5 (10-8.5)^2 + 0.25 (7-8.5)^2 + 0.25 (7-8.5)^2} = 1.5 $
and our effect size $f$ is:
$f = \frac{\sigma_m}{\sigma} = 0.3$
With such an effect size, with an alpha level of 0.05, our power would increase from 0.79 to about 0.84.
Let's see in G*power if those calculations are correct. After accessing the "determine effect size" menu, we first enter the data for the equal allocation scenario with the values given above (10, 7, and 7 for the group means, 5 for the standard deviation, and 40 observations in each group):

The resulting effect size is about 0.28, similar to the result given by the previous calculations.
Now entering the data for the unequal group size scenario, we just change the allocation of observations to 60, 30, and 30, keep the other values untouched, and then click the "calculate" button:

This time, we got an effect size of 0.3, like we found with the previous calculations.
Hence, in this specific scenario, it seems we would increase power if we used unequal group sizes.
But if we're not very confident in those formulas or in G*Power, we can double check that by simulation. In R, we can use the following code:
N= 120 #total sample size
props.equal = c(1/3, 1/3, 1/3) #proportions for the equal allocation scenario
props.unequal = c(0.5, 0.25, 0.25) #for the unequal allocation scenario
n.unequal = N*props.unequal
n.equal = N*props.equal
sd = 5
# creating vectors where we'll store the pvalues generated by each simulation
pvalues.equal = c()
pvalues.unequal = c()
# setting a seed for reproducibility
set.seed(0)
# we run 10000 simulations
for (i in 1:10000) {
  # simulating data for the equal allocation case
  group.equal = c(rep("group1", n.equal[1]), rep("group2",
       n.equal[2]), rep("group3", n.equal[3]))
  df.equal = data.frame(group=group.equal)
  df.equal$value = ifelse(test = df.equal$group == "group1",
                            rnorm(mean=10, sd=sd, n=N),
                            rnorm(mean=7, sd=sd, n=N))
  # fitting anova on the data from this simulated "equal allocation" scenario
  res.equal = anova(aov(value ~ group, data = df.equal))
  # extracting and storing the p-value
  p.equal = res.equal$`Pr(>F)`[1]
  pvalues.equal = c(pvalues.equal, p.equal)

  # simulating data for the unequal allocation case
  group.unequal = c(rep("group1", n.unequal[1]), rep("group2",
        n.unequal[2]), rep("group3", n.unequal[3]))
  df.unequal = data.frame(group=group.unequal)
  df.unequal$value = ifelse(test = df.unequal$group == "group1",
                          rnorm(mean=10, sd=sd, n=N),
                          rnorm(mean=7, sd=sd, n=N))
  # fitting anova on the data from the "unequal allocation" scenario
  res.unequal = anova(aov(value ~ group, data = df.unequal))
  # extracting and storing the p-value
  p.unequal = res.unequal$`Pr(>F)`[1]
  pvalues.unequal = c(pvalues.unequal, p.unequal)
}

# power = % of times the p-value from the anova was < 0.05
power.equal = sum(pvalues.equal < 0.05)/length(pvalues.equal)
power.unequal = sum(pvalues.unequal < 0.05)/length(pvalues.unequal)
print(paste0("Equal allocation: power of ", power.equal))
print(paste0("Unequal allocation: power of ", power.unequal))
> "Equal allocation: power of 0.7844"
> "Unequal allocation: power of 0.8402"

These results (0.7844 for equal allocation and 0.8402 for unequal allocation) are in line with the results from G*power and our previous calculations.
Of course, when planning a study and calculating the required sample size to reach a given power, making a mistake relative to the real differences between the groups could result in decreased power - in particular if you allocate more observations to a group those mean is in reality close to the weighted mean of means. So testing a variety of plausible scenarios is certainly a good idea when conducting a priori power analysis.
Note that using simulation gives you more flexibility, e.g. you can try to assign different standard deviations to each group to see how it affects power; you could also add a few additional lines of code to test a large range of plausible means for each group (I suspect that trying to do that with G*power would take you much more time).
References
Cohen, J. (1988). Statistical Power Analysis for the Behavioral Sciences (2nd edition). Routledge.
Faul, F., Erdfelder, E., Lang, A.-G., & Buchner, A. (2007). G*Power 3: A flexible statistical power analysis program for the social, behavioral, and biomedical sciences. Behavior Research Methods, 39, 175-191. https://www.psychologie.hhu.de/fileadmin/redaktion/Fakultaeten/Mathematisch-Naturwissenschaftliche_Fakultaet/Psychologie/AAP/gpower/GPower3-BRM-Paper.pdf


How to troubleshoot events in the Windows Event Logs?

Question:
How do you troubleshoot events that are not clear when you read them?

Is there a website to search for those Event IDs and errors?

In the following example event it is clear that the gateway resolution fails for the network location awareness service, but it is not clear what the cause of this event is, nor what error code 0x43 stands for.
Looking for a solution on Google I end up with no results matching this event...
Google Query: nlasvc 4205 0x43

Source:
Microsoft-Windows-NlaSvc
Event ID:
4205
Task Category:
Gateway Resolution
Description:
Gateway resolution failed on interface
{075d4968-2da9-4051-9a43-43da54e86ca5}
for 192.168.1.1 with error: 0x43
Answer: For the other part of your question:
The 0x43 in windows networking world means "The network name cannot be found" 0x43 = Decimal 67. So if you look up windows error code 67, you'll get this up.
I must say that this is one of those times when we'll have to sit and analyze the issue for a good time. I'd probably do the following in this case:

Examine the errors and establish a pattern(like are they occuring after a specific event, like during start up, shutdown, start up of an application, etc.) and then try to narrow down the list of possible culprits.
I will also try to isolate it further by checking if its specific to this user(have another user login to the same box), or specific to this machine(have this user login to another box).
Then use the tools to capture the invisible details: procmon, procexp, tcpview, windbg etc., until the event occurs again, and then look at the info. I usually find something here(success rate > 75%)
possibly something else based on the above three steps.

Of course, I'll keep using Google; hey it's an extension of our brains, no?
The ideal approach in the troubleshooting world has to be isolate-and-conquer. Hope I made some sense.
Comment: +1 - Thinking through the message, understanding what service programs do, and doing basic investigation yourself are the best ways to figure out what an error in a closed-source program means. Read the docs for the product, search the Internet, and understand how the software works. For Windows OS-related errors, I have a lot of good luck w/ searching for the error code (0x00000043) and "winerror.h" (the C "header" file w/ the OS error codes in it). You end up with pages like this (http://msdn.microsoft.com/en-us/library/cc231199(PROT.10).aspx) that can help a lot.
Comment: Seems the Windows errors are more commonly shared than I thought, indeed a good way to look at the right place or trying it in a decimal form. After a closer inspection of the event log: This is happening when I resume from standby, it indicates that it can't find the Router because the connection hasn't been re-established. I don't think I can troubleshoot this much so I might just ignore that log event. :-)
Comment: Found another good site while looking for another error: http://bug.gd/
Answer: I don't know of any sites offering this info and wait to be corrected. However answering your in a general way is say - this is where your skills as fault finder come into play.
i'd start by searching for key words, NlaSvc for example. Then possibly identifying the interface - maybe going to search for other log messages. All in all its a hunt the thimble game and you'll get better at it as you do more.
PS. I'm not saying you haven't done this - but this is how I'd approach a problem like this.
Put it into google, put parts of it into google, find associated information and repeat.
Comment: Google doesn't work for me this time, and indeed, most of the time it does... See for example: http://www.google.be/search?q="Gateway+resolution+failed+on+interface" and looking for any combinations of the keywords I don't get a related answer for 0x43 either, even not 43 or 0x00000043.
Answer: For your second question, try http://eventid.net
They have comprehensive info about almost every error logged in the event viewer.
Comment: I wholly disagree. EventID.net is *CRAP*. It's a bunch of speculating idiots who don't understand that correlation does not imply cause! "Oh, this event happened to me on a Tuesday. Therefore it must be caused by Tuesdays!" I'm sure there's some good information there, but it's mostly crap. It's like a dumber version of ExpertSexChange. (I'd be game for a free community "event ID" type site like Server Fault so that we could kill EventID.net's business... right after we put ExpertSexChange out of business.)
Comment: I stand corrected :-)
Comment: Indeed an useful site, lists a lot of the Event IDs that are appearing in my logs, still no information for NlaSvc.
Comment: Indeed, although sometimes when you Google for a problem, Experts Exchange shows up and for the answers you have to scroll down to the end of the page (just a hotkey) and then you find a solution there. But I wouldn't ask something myself nor pay for their expertise.
Comment: @TomWij: Don't worry-- I have high hopes that Server Fault will decimate ExpertSexChange's business, and you won't have to "scroll down" anymore. *smile*


Inverse progression for training & validation data during training with H2O

Question: I'm training on a dataset with 3600 columns. 100948 training rows & 25238 validation rows.
These are the R commands I'm using:
train_hex = h2o.importFile(localH2O, paste(getwd(), "TrainingData.gz", sep="/"))
train_hex_split = h2o.splitFrame(train_hex, ratios = 0.8)
h2o.deeplearning(x = 242:(ncol(train_hex) - 18), y = "Predict-A",
    training_frame = train_hex_split[[1]], validation_frame = train_hex_split[[2]],
    activation = "RectifierWithDropout",
    hidden = c(1600, 1600, 1600),
    hidden_dropout_ratios = c(0.1, 0.1, 0.1),
    epochs = 100,
    initial_weight_distribution = "UniformAdaptive",
    input_dropout_ratio = 0.1,
    l1 = 0.00001,
    l2 = 0,
    loss = "Automatic",
    shuffle_training_data = TRUE)

After about 24h of training this is the result I'm seeing.

(blue: training; orange: validation)
I'm pretty new to the field and I'm struggling to understand what's going on here? I like the training progress on the blue line. But I don't even understand how the validation can start of lower than the training!?
I'd appreciate any help.
Answer: Here are the most likely explanations for what you are observing, in order of likelihood:
Train/Test split
splitFrame doesn't actually shuffle, but "cuts" the frame into two consecutive pieces (first 80% and last 20%).  If your dataset is sorted in any way, train/test samples will be biased.
Proof:
df <- as.h2o(iris)
head(df)
sp <- h2o.splitFrame(df, ratio=0.8)
head(sp[[1]]) ## same as head(df)

Better split, based on random split assignments per row:
rnd <- h2o.runif(df, seed=1234)
head(df[rnd<0.8,])
head(df[rnd>=0.8,])

Sampling for scoring
The parameter 'score_training_samples' is set to 10,000 by default (to avoid taking too long for large datasets), so only 10k rows of the training data (out of the ~100k) are used for computing the training MSE.  On the other hand, 'score_validation_samples' is set to 0 by default, so the full validation set (~25k rows) is used for computing the validation MSE.
This means that the statistical accuracy of the computed training MSE is not as good as the validation MSE, and the training sample of 10k (random) rows might include a few too many "outliers" or "hard-to-predict" observations, you can try different random splits of the data.
Distribution
Of course, all of this really depends on the distribution/data.  I assume you have a normally distributed response, and the squared error (quadratic) loss is appropriate.  Otherwise, the MSE is a less meaningful metric, and the deviance is preferred.  If you have outliers, you can try the 'gaussian' distribution with 'Absolute' or 'Huber' loss. Otherwise, you can try other distributions such as 'poisson' or 'gamma'.
Hope this helps, please feel free to ask for more questions (also see https://groups.google.com/forum/#!forum/h2ostream).
Comment: Note that this answer is now outdated.  The R h2o.splitFrame() behavior changed in the rel-tibshirani release of H2O (Oct./Nov. 2015 timeframe).  The changed behavior randomly assigns each row to a result frame using a row-by-row coin flip.  See https://github.com/h2oai/h2o-3/commit/f2b73c87eb12494998a529360f14da5a2bb11a38
Comment: Welcome to CV. Note that your username, identicon, & a link to your user page
are automatically added to every post you make, so there is no need to sign
your posts. In fact, we prefer you don't.


Tried Eb alternate tuning but guitar intonation is off and I'm unsure how to fix it

Question: I have a fender mexican strat, with 10s. I have never changed string gauge, I only tuned all the strings down half a step to Eb from E.
The issue I am running into is that the low Eb, Ab, Db, and Gb strings are all sharp. I tested the intonation by playing the string open and then checking the 12th fret. These 4 strings seem to be in tune when played open but all of them are sharp when played at the 12th fret. The low Eb is the worst and the rest of them are just slightly sharp. I tested this using consistent attacks on both open and 12th fret.
I tried to fix the issue by adjusting the saddles. I made the saddle adjustments in increments by moving the saddle towards the bridge after loosening the string and it seemed to only make the Eb more sharp. I also got the point where I can't physically turn the screw further as it is very tight and I don't want to strip the screw.
I'm not sure what to do now. I have very little experience with guitar set ups so I wanted to see if I can get any advice on how to proceed without damaging something.
Thanks!
Answer: Start by re-setting the neck - with lower pitch comes lower tension, so the strings may be affected by the action. A high action will necessitate the strings having to be pressed harder, sending them sharp. Using the 12th fret harmonic is a time-honoured way to check against the fretted 12 pitch.
That's of course after putting on a new set of strings, as old strings can be difficult to intonate.
Next comes setting the string height, by saddle adjustment, to at least get it playing properly again.
Because the string tension is less, you may want to also adjust the spring tension on the vib.
Then test intonation. It's possible to remove the little springs that are behind the saddle, although I've only ever had to do that on low E.
Changing the string gauge, or string tension shouldn't give problems like this.
Failing all that, search for some shorter saddles that will fit and effectively make the strings longer.
Comment: Hey TIm, thanks for the answer I appreciate it. So I put on a new set of strings and let it sit for a couple of hours. I tuned the strings to Eb tuning and I'm still running into issues with the low Eb, Ab, and Db intonation - all of them are sharp. The high Eb is also slightly sharp.

At this point - do you recommend trying to lower the action on the lower strings and seeing if that helps? I like the way it plays currently but I can give that a shot.

Also do you mind clarifying the part about adjusting the spring tension? I'm not sure I understand. Thank you!
Comment: How are you checking it? Using the 12th fret harmonic, pressing at 12th fret, using a tuner..? Is your action quite high?
Comment: So I'm unable to reliably hit the harmonic so I'm using a headstock tuner. I'm playing the open string and then fretting the octave at the 12th fret. Im using a soft attack for both the open and the octave. I checked the action at the low Eb and the high Eb. According to an action ruler I have, the action at the low Eb is kinda high (suggested range is 1.5-2.0 mm and mine is about 2.25 mm) and the action at the high Eb is fine (suggested range is 1.0-1.5 mm and mine is around 1.25mm). I
Comment: Harmonics are fun but tuners are better, so keep using that.
Comment: Lowering the low E might help the intonation a little. You should have plenty of room to pull the high E back some.
Comment: And while yeah, perfect is good, you can go far with good-enough-for-now intonation. Don't let chasing this problem keep you from practicing.
Comment: Thanks for your answer. I noticed most of my strings were sharp while checking the intonation so I tried lowering the action as you recommended. I was actually able to get all 6 strings perfectly intonated by lowering the action but now the action is too low for me to feel comfortable while playing. I'd like to raise the action back up but i know it will throw off the intonation.

if i raise the action to a comfortable position, and the strings go sharp once again, do you recommend adjusting the saddles to fix the intonation? Im fine if its sharp, I just dont want my bends to sound off
Answer: I'm more experienced with Telecasters than Stratocasters, but I see this problem with gauges much higher, such as .013s trying to get into standard-neck baritone territory. I took off the low-Es spring to gain some space, but it seems impossible to have blues-rock post-1982 if you can't intonate a Strat in Eb.
Taking it to a luthier for a setup is a reasonable course, but at this point, depending on the age of the instrument, maybe changing the strings might be an idea. Not necessarily string guages — stick with 10s if you're happy with them — but the current set might be played out, hindering your attempts at intonation.
ETA: An answer to a previous question explaining what a setup entails.
Comment: Hey thanks for the answer Dave. I did change the strings a couple of hours ago and the lower strings still seem to be sharp.

What do you recommend at this point, if you have any suggestions? I have access to a luthier but the one I am looking at would set me back around a $100 for a full set up and he is booked for about 2 weeks (he has to hold onto the instrument). I'd prefer to try to fix it myself if it is in my control at all
Comment: There's a lot to this that would be easier if I could pick up the instrument and see you with it. New players often fret too hard, so you might be pulling sharp with just your hands, so practice fretting barely hard enough to get the note out would be good in general and helpful here.
Answer: Yeah you need to get a high resolution tuner, one that shows 1 cent up or down increments so you can dial in your intonation a lot more precisely.  I think your intonation is off.
Answer: You should send guitar to a professional luthier whenever you want to change tune and/or string gauge, even if it is just half step down or a simple Drop D. Strings have tension, and the truss rod is not the only thing that keeps the strings in tune.
Comment: I don't know; being able to maintain your own guitar is a valuable skill that can be learned.
Comment: Disagree. A set-up is expensive - may not necessarily be to your liking, and means you have to take the guitar, lose it, then go and get it back. Non of the things involved in simple set-ups are dangerous - excepting doing stupid things with trussrods - and can be learned just by doing - which is what most of us did before the thousands of 'experts' showed us how on the 'net. Learn a new skill !
Comment: Noooooooooo! These are the simple things you should learn how to do. Heck I switch between Standard Tuning and Drop D _mid-song_. Ain't got time for no guitar tech >:D


How to define & mathematically denote "true individual probability"?

Question: The notion of an individual's "true probability" or "true risk" of a certain outcome $Y$ is contested [1, 2, 3]. Nevertheless, it is often discussed and useful for certain kinds of analyses. However, all the works I can find only describe this quantity in words and do not define it mathematically.
How could one define and mathematically denote the "true individual probability" of a (binary) outcome $Y$ for a given individual? Is there a standard notation?
Is there notation for something like "P(outcome y=1 for individual i, given all there is to know about this individual and the state of the universe)" ?
Comment: Trivially there could be notation that you invented, but what use would that notation be? Notation only has point for expressing or deriving something that couldn't be expressed or derived more simply otherwise.
Answer: Maybe you had problems with finding it because it is ambiguous. First of all, what is probability is a philosophical question, so there is no single answer to what it means. But that's a different story. If your quantity of interest is $X$, then the notation for the probability is simply $P(X)$. If you want to condition it on something, it's $P(X|Y,Z,\dots)$.

given all there is to know about this individual and the state of the universe

But what would it be? If you knew everything about every atom in the universe, or even everything on the sub-atomic level, with a perfect understanding of the universe, then without any uncertainty you would know what would happen, based on your knowledge and the knowledge of the laws of physics. In such a case, the probability would be always equal to one; it would be certain.
Comment: "...then without any uncertainty you would know what would happen" while that *may* be true, [it is still a contested hypothesis, as far as I know](https://en.wikipedia.org/wiki/Determinism#Modern_scientific_perspective) (due to quantum effects, if I understand correctly - not my area of expertise). In any case, this is slightly beyond the point, isn't it? Even if a property is 0 or 1, I might still want to define and denote it. ;-)
Comment: @EikeP. but you want to condition on *everything*, so this assumes *perfect knowledge* of the universe. That's why, as I said, it starts getting philosophical, since the question arises if, beyond the laws of physics, there is some "randomness" that couldn't ever be explained by them. Chaotic systems are deterministic, but complicated, for comparison. But the mere fact that there is such a discussion means that having "a notation" for something not clearly defined would not solve any problem.
Comment: Again, totally not my field, but isn't part of the argument explicitly that even with perfect knowledge of the universe, one cannot predict these quantum effects, i.e., they are *truly random*? In any case, how would you then define the aim of individual risk modeling, if not by referring to some underlying, true risk/probability that you're trying to estimate?
Comment: @EikeP. as said in the answer, you condition on specific things, not on "everything".


Using CHttpFile with HTTPS sites

Question: I have this code that I use to read a data file from my website:
CInternetSession    iSession;
CHttpFile           *pWebFile = nullptr;
DWORD               dwStatusCode;
CString             strError, strTargetZIP, strDownloadURL;

strTargetZIP = theApp.GetWorkingPath() + _T("AutoUpdate\\MWBDataUpdate.zip");
strDownloadURL = _T("http://www.publictalksoftware.co.uk/mwbdata/MWBDataUpdate.zip");

// ask user to go online
if (InternetGoOnline((LPTSTR)(LPCTSTR)strDownloadURL, hWnd, 0))
{
    TRY
    {
        // our session should already be open
        // try to open up internet session to my URL
        // Use flag INTERNET_FLAG_RELOAD
        pWebFile = (CHttpFile*)iSession.OpenURL(strDownloadURL, 1,
        INTERNET_FLAG_TRANSFER_BINARY | INTERNET_FLAG_DONT_CACHE | INTERNET_FLAG_RELOAD);

        if (pWebFile != nullptr)
        {
            if (pWebFile->QueryInfoStatusCode(dwStatusCode))
            {
                // 20x codes mean success
                if ((dwStatusCode / 100) == 2)
                {
                }
                else
                {
                    // There was a problem!
                    strError.Format(IDS_TPL_INVALID_URL, dwStatusCode);
                    AfxMessageBox(strError, MB_OK | MB_ICONERROR);
                }
            }
        }
        else
        {
            // Note, there is no error log.  Use new error message?
            AfxMessageBox(IDS_STR_UPDATE_CHECK_ERR, MB_OK | MB_ICONERROR);
        }
    }
    CATCH(CException, e)
    {
        e->GetErrorMessage(szError, _MAX_PATH);
        AfxMessageBox(szError, MB_OK | MB_ICONERROR);
    }
    END_CATCH

    // Tidy up
    if (pWebFile != nullptr)
    {
        pWebFile->Close();
        delete pWebFile;
    }
    iSession.Close();
}

I have recently changed my site to use HTTPS and I am trying to find if all I need to do is just change the URL here in my code. I have looked up the latest documentation for CHttpFile and it only mentions HTTP.
Thanks for the clarification.
Answer: CInternetSession::OpenURL calls InternetOpenUrl API. InternetOpenUrl needs INTERNET_FLAG_SECURE for secure websites.
Change the url from http:// to https://
Add INTERNET_FLAG_SECURE to OpenURL's option.
Example:
CInternetSession isession;
CString url = _T("https://www.google.com");
CString filename = _T("c:\\test\\test.html");
CHttpFile *httpfile = (CHttpFile*)isession.OpenURL(url, 1, INTERNET_FLAG_SECURE |
    INTERNET_FLAG_TRANSFER_BINARY | INTERNET_FLAG_RELOAD);
if (httpfile)
{
    DWORD dwStatusCode;
    httpfile->QueryInfoStatusCode(dwStatusCode);
    if(dwStatusCode == 200)
    {
        char buf[0x1000] = { 0 };
        DWORD read = 0;
        CFile file;
        if (file.Open(filename, CFile::modeCreate | CFile::modeWrite))
            while(InternetReadFile(*httpfile, buf, sizeof(buf), &read) && read)
                file.Write(buf, read);
    }

    httpfile->Close();
    delete httpfile;
}

Comment: Thanks. Can I clarify? Here https://msdn.microsoft.com/en-us/library/windows/desktop/aa383661(v=vs.85).aspx I see: "This flag is used by HttpOpenRequest and InternetOpenUrl, but this is redundant if https:// appears in the URL.". So am I right in saying I either leave the URL as it is and use this flag, or leave flags alone and use HTTPS prefix?
Comment: Yes, apparently `INTERNET_FLAG_SECURE` is optional if url starts with `"https://"`. I didn't notice that before.

Using CHttpFile with HTTPS sites


jenkins displays username instead of project name

Question: When I enter project configuration in Jenkins (in Firefox), the first field (Project name) displays my Jenkins username instead of actual project name. Every time I change config, I need to change that back to project name (like "foo+tests").
Running latest jenkins version, on ubuntu 12.04.
How to fix that?
Comment: What happens when you open the project's/job's config page in IE? If you see the same, then there's something (script/cron etc) messing with that job's config.xml file. This file is different than config.xml for Jenkins (which sits at $JENKINS_HOME location). Or there may be a scriptler script that you might be using which is replacing the name of the job to your jenkins user name. If I were you, I'd create a cron(2 line shell command called from cron every 5 secs) to send me an alert as soon as something changes the value of the job name in job's config.xml to my email id from ubuntu box.
Comment: It turned out it was KeeFox FF extension that was messing with project name field, not the server-side jenkins config..
Answer: It was KeeFox FF extension that was messing with project name field in Jenkins.


Find the bounds for the norm $T:l_2 \to l_2$.

Question:
Given $T:l_2 \to l_2$ define as $T((x_1,x_2,\ldots,x_n,\ldots))=(x_2-x_1,x_3-x_2,\ldots,x_{n+1}-x_n,\ldots)$ then which of the following is true,

$\|T\|=1$
$\|T\|\geq2$
$1<\|T\|\leq2$
None of above.

What I did-
I used $\|T\|^2=\langle T,T\rangle$, so after calculation I got $\|T(x)\| = \left( \sum_{i=1}^\infty (x_{i+1}-x_i)^2 \right)^{1/2}$. Now I got stuck. How to proceed further? Please help.
Comment: Note that $\langle T,T\rangle$ is standard notation; $$ is not. $\qquad$
Comment: Ok will keep in mind for future. thanks @MichaelHardy
Answer: First note that if $x,y\in\mathbb{R}$, then
$$ (x-y)^2=x^2-2xy+y^2\leq 2(x^2+y^2) $$
since $2|xy|\leq x^2+y^2$.
Therefore if $x\in \ell^2$ with $\|x\|_2=1$, then
$$ \|Tx\|^2=\sum_{i=1}^\infty (x_{i+1}-x_i)^2\leq 2\sum_{i=1}^\infty (x_{i+1}^2+x_i^2) = 2\sum_{i=1}^\infty x_i^2+2\sum_{i=1}^\infty x_{i+1}^2\leq 4$$
Hence $\|T\|\leq 2$. On the other hand, for each $n\geq 1$ we can define an element
$$ x=\Big(-\frac{1}{\sqrt{n}},\frac{1}{\sqrt{n}},\dots,\frac{(-1)^n}{\sqrt{n}},0,\dots\Big) $$
of $\ell^2$ such that $\|x\|_2=1$ and $\|Tx\|_2^2=\frac{4}{n}(n-1)+\frac{1}{n} =\frac{4n-3}{n}$, so it follows that $\|T\|=2$.
Answer: With $x=(x_n)_n$ and $Ux=(x_{n+1})_n$ we have obviously $\|Ux\|\leq\|x\|. $ So $$\|Tx\|=\|Ux-x\|\leq \|Ux\|+\|x\|\leq 2\|x\|.$$ So $\|T\|\leq 2.$
For $k\in N, $ let $x(k)=(x_{k,n})_n, $ where $ x_{k,n}=(-1)^n$ for  $n\leq k  $ and  $x_{k,n}=0  $ for $ n>k. $  Then $\|x(k)\|=\sqrt k$ and $\|Tx(k)\|=\sqrt {4(k-1)^2+1}. \;  $  So $\lim_{k\to \infty}\|Tx(k)\|/\|x(k)\|=2. $
So $ \|T\|\geq 2. $


PHP only match the words in array using regex

Question: I am using str_replace to "clean" the words of the ones I do not desire, this way I can create a schedule for the teams. However, every time there is more words I need to eliminate, so I end up editing the file every day. I wanted to use regex, but I couldn't get only the team names. So I want to add the teams in an array and only get the team names thus cleaning the junk words.
so it would be something like:
Boston Celtics vs. Brooklyn Nets

That is if I can format it to include "vs." between both teams. Otherwise, it will be just
Boston Celtics Brooklyn Nets

here is the code I am using to remove the words.
<?php
$name1 = array("Spectrum Center","Charlotte, NC","Bankers Life Fieldhouse","Indianapolis, IN","Wells Fargo Center","Philadelphia, PA","Quicken Loans Arena","Cleveland, OH","bc","Chesapeake Energy Arena","Oklahoma City, OK","Toyota Center","Houston, TX","American Airlines Center","Dallas, TX","GAME PREVIEWBUY TICKETS","United Center","Chicago, IL","Target Center","Target Center","Staples Center","Los Angeles, CA","Minneapolis, MN","Amway Center","Orlando, FL","TD Garden","Boston, MA","Palace of Auburn Hills","Detroit, MI","Pepsi Center","Denver, CO","Vivint Smart Home Arena","Salt Lake City, UT","Talking Stick Resort Arena","Phoenix, AZ","Air Canada Centre","Toronto, ON","Barclays Center","Brooklyn, NY","FedExForum","Memphis, TN","ORACLE Arena", "Oakland, CA","Golden 1 Center","Sacramento, CA","Smoothie King Center","New Orleans, LA","BMO Harris Bradley Center","Milwaukee, WI","Philips Arena","Atlanta, GA","Madison Square Garden","New York, NY","AmericanAirlines Arena","Miami, FL","AT&T Center","San Antonio, TX","Verizon Center","Washington, DC","FOX SPORTS SOUTHEAST - CHARLOTTE","FS FLORIDA","WFNZ 610 AM","ESPN 580 / SALSA 98.1 FM (ESP)","WGN-TV","ROOT","WLS-AM 890 / WRTO 1200 (ESP)","790 AM","FSI","1070 THE FAN NORTH","CSN BAY AREA","830 WCCO","95.7 GAME SOUTHEAST","TSN2",'92.9 "THE GAME"',"TSN RADIO 1050 TORONTO ALTITUDE","CSNHD","KKSE 950AM","98.5 HUB FSSW","YES","103.3 ESPN","WFAN CSN-CA","CSN","KHTK 1140 1500 ","FOX SPORTS WISCONSIN","FSI","AM 620 WTMJ","1070 THE FAN","FS NORTH","CSN BAY AREA","830 WCCO","95.7 THE GAME","FOX SPORTS SOUTHEAST","TSN2","92.9 FM",'"THE GAME"',"TSN RADIO 1050 TORONTO","ALTITUDE","CSNHD","KKSE 950AM","98.5 THE SPORTS HUB","FSSW"," YES","103.3 ESPN","WFAN","-CA","CSN","TSN2","KHTK SPORTS 1140 AM","1500 AM","NBATV CANADA","FS OKLAHOMA HD","WWLS 98.1FM OKC / 930AM (ESP)","KZNS","PRIME TICKET","TCN-PHI","AM 570 LA SPORTS","97.5 THE FANATIC","FS DETROIT","MSG","105.1 WMGC-FM","ESPN NY 98.7","FSNOLA","WRNO 99.5FM","FSOHIO","WTAM 1100 / 100.7 WMMS / 87.7 FM (ESP)","FS-SUN","SPORTSNET ONE","SPORTSNET ONE","790 THE TICKET / S: WAQI 710 AM","SPORTSNET 590 THE FAN","WOAI 1200AM","WMFS","FSAZ","ARIZONA SPORTS 98.7FM / KSUN 1400AM (ES)","NWHD","RIP CITY RADIO 620","OR","SPE/SPECD","710 AM ESPN / 1330 AM ESPN DEPTES","WLS 890AM","KGWHD","-CHICAGO","CW35 HD","TSNN","TSN1/4","790 THE TICKET","/ S:","WRTO MIX 98.3 FM","TSN4/5","740 AM","100.7 WMMS / 87.7 FM (ESP)");

$name = $_POST["teamname"];
$name = str_replace($name1,"",$name);
$name = str_replace(",","",$name);
$name = str_replace("\n\n", '
', $name);
$name = str_replace("\r\n\r\n", '
', $name);

if(isset($_POST["teamname"])){
    echo $name;
    }
?>

is there a better way to acquire the result I am looking for.
edit:
I use the code in this answer to make the string of the schedule into an array. Hoever, i am having dificultes interacting with the regex loop i got from another answer (forgot the link) while they both work separately. i would need to first explode it into an array and ise that array to pass the regex in another loop. How can I use both loops?
this is what i have so far.
<?php
$search = array("Boston Celtics","Brooklyn Nets","New York Knicks","Philadelphia 76ers","Toronto Raptors","Golden State Warriors","LA Clippers","Los Angeles Lakers","Phoenix Suns","Sacramento Kings","Chicago Bulls","Cleveland Cavaliers","Detroit Pistons","Indiana Pacers","Milwaukee Bucks","Dallas Mavericks","Houston Rockets","Memphis Grizzlies","New Orleans Pelicans","San Antonio Spurs","Atlanta Hawks","Charlotte Hornets","Miami Heat","Orlando Magic","Washington Wizards","Denver Nuggets","Minnesota Timberwolves","Oklahoma City Thunder","Portland Trail Blazers","Utah Jazz","7:30 PM","7:00 PM");

$results= array(
"7:00 PM ET
CSN, FSI, 97.5 THE FANATIC, 1070 THE FAN
Indiana Pacers
Philadelphia 76ers",
       "7:30 PM ET
CSNHD, YES, 98.5 THE SPORTS HUB, WFAN
Brooklyn Nets
Boston Celtics",
       "7:30 PM ET
FS-SUN, FSOHIO, SN, 790 THE TICKET / S: WRTO MIX 98.3 FM, WTAM 1100 / 100.7 WMMS / 87.7 FM (ESP)
Cleveland Cavaliers
Miami Heat",
       "Excepteur sint occaecat cupidatat non proident"
    );
foreach ($results as $result) {
   $pattern = "/\b(" . implode('|', $search) . ")\b/i";
   $found   = preg_match_all($pattern, $result, $matches);
   $time = $matches[0][0];
   $team1 = $matches[0][1];
   $team2 = $matches[0][2];

   if ($found) {
       echo $time."   ".$team1." vs ".$team2."
";
   }
}

$t = "7:00 PM ET
CSN, FSI, 97.5 THE FANATIC, 1070 THE FAN
Indiana Pacers
Philadelphia 76ers
Wells Fargo Center
Philadelphia, PA
GAME PREVIEWBUY TICKETS
7:30 PM ET
CSNHD, YES, 98.5 THE SPORTS HUB, WFAN
Brooklyn Nets
Boston Celtics
TD Garden
Boston, MA
GAME PREVIEWBUY TICKETS
7:30 PM ET
FS-SUN, FSOHIO, SN, 790 THE TICKET / S: WRTO MIX 98.3 FM, WTAM 1100 / 100.7 WMMS / 87.7 FM (ESP)
Cleveland Cavaliers
Miami Heat
AmericanAirlines Arena
Miami, FL";
$pieces = explode("TICKETS", $t);

$teans = '';

foreach($pieces as $cat) {
    $cat = trim($cat);
    $teans .= "<category>" . $cat . "</category>\n";
    echo $cat."
";
}
?>

Comment: How about you define what you want and grab that with `preg_match_all`.
Comment: Can you show us examples of **actual** input (not test cases that you wrote in code).  Are there actual line breaks in the input?  It looks like the input is predictably structured such that you might be able to get away from using regex for this.
Comment: @MikeBrant this would be what it looks lie=ke after u copy from the NBA site
7:00 PM ET
CSN, FSI, 97.5 THE FANATIC, 1070 THE FAN
Indiana Pacers
Philadelphia 76ers
Wells Fargo Center
Philadelphia, PA
GAME PREVIEWBUY TICKETS
so what I am doing is I explode after TICKETS which both for loop works separately, but I need to use the array the explode loop creates and go thru it looking for matches
Answer: i did what i was looking for.
<?php
$search = array("Boston Celtics","Brooklyn Nets","New York Knicks","Philadelphia 76ers","Toronto Raptors","Golden State Warriors","LA Clippers","Los Angeles Lakers","Phoenix Suns","Sacramento Kings","Chicago Bulls","Cleveland Cavaliers","Detroit Pistons","Indiana Pacers","Milwaukee Bucks","Dallas Mavericks","Houston Rockets","Memphis Grizzlies","New Orleans Pelicans","San Antonio Spurs","Atlanta Hawks","Charlotte Hornets","Miami Heat","Orlando Magic","Washington Wizards","Denver Nuggets","Minnesota Timberwolves","Oklahoma City Thunder","Portland Trail Blazers","Utah Jazz","7:00 PM ","7:30 PM ","7:30 PM ","8:00 PM ","8:00 PM ","8:00 PM ","10:00 PM ","10:30 PM ","10:30 PM ");

$t = "7:00 PM ET
CSN, FSI, 97.5 THE FANATIC, 1070 THE FAN
Indiana Pacers
Philadelphia 76ers
Wells Fargo Center
Philadelphia, PA
GAME PREVIEWBUY TICKETS
7:30 PM ET
CSNHD, YES, 98.5 THE SPORTS HUB, WFAN
Brooklyn Nets
Boston Celtics
TD Garden
Boston, MA
GAME PREVIEWBUY TICKETS
7:30 PM ET
FS-SUN, FSOHIO, SN, 790 THE TICKET / S: WRTO MIX 98.3 FM, WTAM 1100 / 100.7 WMMS / 87.7 FM (ESP)
Cleveland Cavaliers
Miami Heat
AmericanAirlines Arena
Miami, FL
GAME PREVIEWBUY TICKETS
8:00 PM ET
CSN-CHICAGO, FS FLORIDA, WLS-AM 890 / WRTO 1200 (ESP), ESPN 580 / SALSA 98.1 FM (ESP)
Orlando Magic
Chicago Bulls
United Center
Chicago, IL
GAME PREVIEWBUY TICKETS
8:00 PM ET
FOX SPORTS WISCONSIN, FOX SPORTS SOUTHEAST - CHARLOTTE, AM 620 WTMJ, WFNZ 610 AM
Charlotte Hornets
Milwaukee Bucks
BMO Harris Bradley Center
Milwaukee, WI
GAME PREVIEWBUY TICKETS
8:00 PM ET
bc
TSNN, 105.1 WMGC-FM, 1500 AM
Washington Wizards
Detroit Pistons
Palace of Auburn Hills
Detroit, MI
GAME PREVIEWBUY TICKETS
10:00 PM ET
CSNNWHD, FSSW, RIP CITY RADIO 620, WOAI 1200AM
San Antonio Spurs
Portland Trail Blazers
Moda Center
Portland, OR
GAME PREVIEWBUY TICKETS
10:30 PM ET
bc
TSN1/4, AM 570 LA SPORTS, 790 AM
Houston Rockets
LA Clippers
Staples Center
Los Angeles, CA
GAME PREVIEWBUY TICKETS
10:30 PM ET
NBCS - BA, ROOT, SN, 95.7 THE GAME, KZNS
Utah Jazz
Golden State Warriors
ORACLE Arena
Oakland, CA";

$pieces = explode("TICKETS", $t);
foreach ($pieces as $result) {
   $pattern = "/\b(" . implode('|', $search) . ")\b/i";
   $found   = preg_match_all($pattern, $result, $matches);
   $time = $matches[0][0];
   $team1 = $matches[0][1];
   $team2 = $matches[0][2];

   if ($found) {
       echo $time."   ".$team1." vs ".$team2."
";
   }
}
?>

DEMO http://rextester.com/THKE48416


Trying to find getAdminStatus method

Question: The SuperAdmin page in my web application has a method call to getAdminStatus() but I cannot find any occurences of this method when searching the entire solution. Is this method part of the .net 2.0 framework.
<code>  <ItemTemplate>
   <asp:Label runat="server" ID="admin" Text="<%= getAdminStatus() %>"></asp:Label>
    </ItemTemplate>
</code>
Thanks,
Answer: No it's not.
Is it possible this method is part of an external library (third party or otherwise)?

Trying to find getAdminStatus method


What is the period of the harmonic oscillator?

Question: I am trying to find the elapsed time $T$ (or transit time) over one cycle of the harmonic oscillator
$$\ddot{x} + \omega^2x=0.$$
I worked this out to be
\begin{align}
  T
  &= \int_{R}^{-R} \frac{\mathrm{d}x}{-y}
  + \int_{-R}^{R} \frac{\mathrm{d}x}{y}\\
  &= \int_{R}^{-R} \frac{\mathrm{d}x}{-\sqrt{R^2-\omega^2x^2}}
  + \int_{-R}^{R} \frac{\mathrm{d}x}{\sqrt{R^2-\omega^2x^2}}\\
  &= -\frac{1}{\omega} \int_{R}^{-R} \frac{\mathrm{d}x}{\sqrt{D^2-x^2}}
  + \frac{1}{\omega} \int_{-R}^{R} \frac{\mathrm{d}x}{\sqrt{D^2-x^2}}
\end{align}
where $D=R/\omega$.
When I evaluate the definite integral, I get $T=4\arcsin(\omega)/\omega $, which makes no sense to me because $\arcsin(\omega)$ bounds $\omega$ at unity. Since $\omega$ is the angular frequency, the answer should be $T=2\pi/\omega$.
Could someone point out where I went so wrong?
Answer: Your setup is entirely correct, but your evaluation of the integral is not. The primitive of $\frac{1}{\sqrt{D^2 -x^2}}$ is $\text{arctan} \frac{x}{\sqrt{D^2 -x^2}}$; taking the appropriate limits yields the desired factor $\pi$, for each integral.
Edit: As @MichaelSeifert rightly pointed out, the integral can also be expressed in terms of $\text{arcsin}$, since
\begin{equation}
\text{arctan} \frac{x}{\sqrt{D^2 -x^2}} = \text{arcsin} \frac{x}{D}.
\end{equation}
As $\text{arcsin} 1 = \frac{\pi}{2}$, you get the requested answer.
Comment: The integral isn't wrong: $\arctan \frac{x}{\sqrt{D^2 - x^2}} = \arcsin (x/D)$.  Draw a right triangle with hypotenuse $D$ and opposite side $x$ to see this.
Comment: Oh, okay. This solves my problem. I realize now how long it has been since Calculus II :)
Comment: You're absolutely right, thanks! I'll edit my answer.
Answer: I'm assuming you integrate once to find the first integral
$$
E(x,y)=\frac12(y^2+ω^2x^2)
$$
and that the points of largest amplitude are $(x,y)=(\pm R,0)$. But then the constant is
$$
E=\frac12ω^2R^2
$$
and thus the equation for $y$ is
$$
y=\pmω\sqrt{R^2-x^2}
$$
Now use the substitution $x=R\sin u$ to solve the resulting integral for the half-period,
$$
\frac T2=\int_{-R}^R\frac{dx}y=\frac1ω\int_{-\pi/2}^{\pi/2}du=\frac{\pi}{ω}
$$
Comment: Out of curiosity what is the function $E(x,y)$?
Comment: It is constant on $E(x,\dot{x})$.


how to remove accessory from cellForRowAtIndexPath

Question: i have the indexPath number... i need to remove the cell accessory from that cell based on the number in the variable i have?
NSInteger *removeAccessoryFrom = 3;

                    [studentTableView cellForRowAtIndexPath:removeAccessoryFrom].accessoryType = UITableViewCellAccessoryNone;

Answer: It doesn't work like that. You need to reload the table data (either for the whole table or for just this row) and, inside cellForRowAtIndexPath, set the accessoryType to UITableViewCellAccessoryNone conditionally. In other words, you keep a list, or have some other way of knowing, at every moment, and for the entire table, exactly what cells get exactly what accessory. That way, any time cellForRowAtIndexPath is called, you can configure this cell for this index path correctly.
Comment: Yep, one can use `reloadRowsAtIndexPaths` rather that just `reloadData`, but either way the cell must be reloaded, with the change made inside `cellForRowAtIndexPath`.
Comment: @HotLicks Good point, though - I've added a phrase to cover that.


First time use of ruby server - Command gives no response

Question: I just set up my Ruby server, it appears successful as I am able to see the welcome page at localhost:3000. I am following the beginner tutorial at http://api.rubyonrails.org.
The very first command I'm asked to enter is
$ bin/rails generate controller welcome index

The terminal simply goes to the next line awaiting another command, no folders created as would be expected.  Any ideas why this would happen?  I have restarted the Server, and created a new app from scratch, any help with what could be wrong is appreciated.
Comment: I typed "$ bin/rails generate controller welcome index"                              There was no output, I also tried  "bin/rails generate controller welcome index" with no output and also "rails generate controller welcome index" with no output.
Comment: Try it without the "$"
Comment: Can you copy exactly everything you typed and the output?
Comment: The cursor simply goes to the next line awaiting another command.
Comment: When I run that command it works for me, so there has to be something else. You're typing this in terminal? Are you on Windows? Mac?
Comment: Im on a Mac, server has started and I can see the welcome screen at Localhost:3000, its as if its not recognising any commands at all
Comment: Keiths-iMac:blog Home$ rails server
=> Booting WEBrick
=> Rails 4.2.1 application starting in development on http://localhost:3000
=> Run `rails server -h` for more startup options
=> Ctrl-C to shutdown server
[2015-05-27 10:28:07] INFO  WEBrick 1.3.1
[2015-05-27 10:28:07] INFO  ruby 2.2.2 (2015-04-13) [x86_64-darwin14]
[2015-05-27 10:28:07] INFO  WEBrick::HTTPServer#start: pid=35794 port=3000
bin/rails generate controller welcome index
rails generate controller welcome index
rails server -h
Comment: This is the first time I have tried using ROR, so it has never worked correctly as of yet.
Comment: Oh, try doing it without doing rails server first. Or open a new Terminal and do it there.
Comment: Thanks again, will upvote when i get some rep up and it allows, great community!
Comment: You can actually accept answers to your own questions by hitting the green check mark -- but no hurry at all, just letting you know it's possible. :)
Answer: Summarizing the answer from the comments here.
The problem was that the OP was trying to run the command inside of rails server. The fix was to either run the command in another Terminal window, or before starting the server.
Answer: have you tried bundle exec rails controller welcome index ? You're bundler or env may not be properly setup.
Comment: Thanks for the reply, Wayne lue, steered me in the right direction, I'll keep in mind what you have said if i run into further issues in the tutorial.


oVirt Hosted-Engine upgrade filed

Question: I'm getting problems upgrading oVirt Hosted-Engine from 4.2.8 to 4.3.3.
After installing this release in Engine VM, I ran yum update, then engine-setup and got this error:
              --== DATABASE CONFIGURATION ==--

[WARNING] This release requires PostgreSQL server 10.6 but the engine database is currently hosted on PostgreSQL server 9.5.14.
[ INFO  ] Verifying PostgreSQL SELinux file context rules
[ ERROR ] Failed to execute stage 'Environment customization': could not stat file "base/13699369/1259_fsm": Permission denied

[ INFO  ] Stage: Clean up
          Log file is located at /var/log/ovirt-engine/setup/ovirt-engine-setup-20190602110956-iqr6bc.log
[ INFO  ] Generating answer file '/var/lib/ovirt-engine/setup/answers/20190602111120-setup.conf'
[ INFO  ] Stage: Pre-termination
[ INFO  ] Stage: Termination
[ ERROR ] Execution of setup failed

But I don't find any solution on how to solve this issue.
Maybe I'm doing something wrong?
Answer: Solved using this.
Full lists here.

oVirt Hosted-Engine upgrade filed


need help typing out a 2 dimensional array

Question: i am trying to type out a 2 dimentional array in a messagedialog using JOptionPane.
I have tried but i am not sure how to do it. This is what i have so far.
Where my program starts:
package p4;

import javax.swing.JOptionPane;

import arrays.Integer2dArrays;

public class Exercise4b {
public void testArray(int[][] array) {
    String message = "";
    message += "toString: " + Integer2dArrays.toString( array ) + "\n";
//      message += "elements: " + Integer2dArrays.elements( array ) + "\n";
//      message += "max: " + Integer2dArrays.max( array ) + "\n";
//      message += "min: " + Integer2dArrays.min( array ) + "\n";
//      message += "sum: " + Integer2dArrays.sum( array ) + "\n";
//      message += "average: " + String.format( "%1.2f", Integer2dArrays.average( array ) ) + "\n";
    JOptionPane.showMessageDialog( null, message );
}

public static void main(String[] args) {
    Exercise4b e4b = new Exercise4b();
    int[][] test1 = {{1,2,3,4},{-5,-6,-7,-18},{10,9,8,7}};
    int[][] test2 = {{1,2,3,4,5,6},{-7,-8,-9},{2,5,8,11,8},{6,4}};
    e4b.testArray(test1);
    e4b.testArray(test2);
}
}

Where i am suposed to create a method that converts the array to a string.
    package arrays;

    public class Integer2dArrays {
        public static String toString(int[][] array){

        }

    }

Comment: You should specify what output you expect. There are many ways to transform an 2D array to a string.
Comment: So your problem is displaying the content of the array?
Answer: To display an two dimensional array in a simple fashion you could use this method:
public class Integer2dArrays {
    public static String toString(int[][] array){
        StringBuilder sb = new StringBuilder();
        for(int i=0;i<array.length;i++) {
            for(int j=0;j<array[i].length;j++) {
                sb.append(array[i][j]).append(", ");
            }
            sb.append("\n");
        }
        return sb.toString();
    }
}

This will produce output the following way:
int[][] test1 = {{1,2,3,4},{-5,-6,-7,-18},{10,9,8,7}};

would be:
1, 2, 3, 4,
-5, -6, -7, -18,
10, 9, 8, 7,

If you want a different form of output please specify what format you expect.


Aggregator custom template file is not overriding the default one on Drupal 7

Question: I have the Aggregator module enabled in Drupal 7. I have one feed and I'm showing it on the front page in a block. The block has under the feed a 'more-link'.
I want to change the text depending on the language and feed that I'm showing.
I added a copy of aggregator-summary-items.tpl.php to my theme folder and customized the file.
My problem is that is still showing the default one. Is there something I'm missing?
Answer: I don't think it uses template files.
Just override the function in your template.php.
(replace 'mytheme' with your theme's name).
/**
 * Returns HTML for an individual feed item for display in the block.
 *
 * @param $variables
 *   An associative array containing:
 *   - item: The item to be displayed.
 *   - feed: Not used.
 *
 * @ingroup themeable
 */
function mytheme_aggregator_block_item($variables) {
  // Display the external link to the item.
  return 'link) . '">' . check_plain($variables['item']->title) . "\n";
}

Answer: Your template file is either badly named or you put it in the wrong place, which can change depending on the theme.
To know which files may be candidates for templating, you can use Devel Themer which was quite buggy last time I checked, but does a good job at listing candidate template files. Just enable it long enough to check them, and then get rid of it.
Comment: thx @Countzero, now i can change the block entirely and see what template file i need to change.


moving a point in 3d space

Question: I have a point at 0,0,0
I rotate the point 30 deg around the Y axis, then 30 deg around the X axis.
I then want to move the point 10 units forward.
I know how to work out the new X and Y position
MovementX = cos(angle) * MoveDistance;
MovementY = sin(angle) * MoveDistance;

But then I realised that these values will change because of Z, won't they?
How do I work out Z and have I worked out X and Y correctly?
Thanks!
Comment: Use rotation matrices. :) They take a considerable investment of effort to learn but once you know how to use them everything becomes much less work.
Comment: Ok I guess the equivalent in OpenGL would be...

glRotatef( 30.0f, 0.0f, 1.0f, 0.0f );

glRotatef( 30.0f, 1.0f, 0.0f, 0.0f );

glTranslate( 0.0f, 0.0f, 10.0f );

But I want to do it manually so that I know the world coordinates of the point (so that I can compare it to other coordinates)
Comment: I don't know too much about OpenGL but if your point is starting at (0,0,0) then drhirsch is correct and your point won't be moving anywhere through rotations. So the only function that would do anything is the glTranslate. Therefore your new position would be (0,0,10). However I feel like that might not be what you were going for. Are you sure your point doesn't have a direction vector associated with it?
Answer: You should multiply point coordinates to full rotation matrix, which is matRotationTotal = matRotationX * matRotationY * matRotationZ. Check this article for details.

moving a point in 3d space


SUM values based on Distinct Values of another column

Question: I have a table :
Sales ID
100   a
100   a
103.5 c
105   d
105   d

....
I want to simply get the value 308.5( which is 100+103.5+105, the unique values).
I've tried this:
select sum(case when rownum=1 then sales end) from
(select sales,id, row_number() over (partition  by id) as rownum from table) subquery

But every time I refresh it I'm getting a different value.
What is the alternative way?
Comment: Let's say after next refresh, you got 100, a and 101, a, how do you want to do the calculation? 100+101+103.5+105 or 100+103.5+105?
Answer:
But every time I refresh it I'm getting a different value.

That would suggest that the underlying data is changing -- which is unlikely on Vertica.  Or more likely that you have multiple values for a single id.  You can test the latter:
select id, count(distinct sales)
from t
where min(sales) <> max(sales);

Answer: You could use a subquery for distinct sales
    select sum(t.distinct_sales)
    from  (
        select distinct Sales as distinct_sales
        FROM my_table
    ) t

Answer: You would have to de-dupe by running a SELECT DISTINCT first, and SUM()-ming afterwards. Like so:
WITH
-- this is your input - don't use in real query
input(Sales,ID) AS (
          SELECT 100,'a'
UNION ALL SELECT 100,'a'
UNION ALL SELECT 103.5,'c'
UNION ALL SELECT 105,'d'
UNION ALL SELECT 105,'d'
)
, -- < - replace this comma with "WITH", and start the real query here ...
uq (sales) AS (
  SELECT DISTINCT
    sales
  FROM input
)
SELECT
  SUM(sales)
FROM uq;
-- out   SUM
-- out -------
-- out  308.5
-- out (1 row)
-- out
-- out Time: First fetch (1 row): 7.795 ms. All rows formatted: 7.826 ms

-- if ( 100 , 'a' ) is different from ( 100 , 'd' ), then it would be the below

WITH
-- this is your input - don't use in real query
input(Sales,ID) AS (
          SELECT 100,'a'
UNION ALL SELECT 100,'a'
UNION ALL SELECT 103.5,'c'
UNION ALL SELECT 105,'d'
UNION ALL SELECT 105,'d'
)
, -- < - replace this comma with "WITH", and start the real query here ...
uq (sales,id) AS (
  SELECT DISTINCT
    sales
  , id
  FROM input
)
SELECT
  SUM(sales)
FROM uq;
-- out   SUM
-- out -------
-- out  308.5
-- out (1 row)
-- out
-- out Time: First fetch (1 row): 11.084 ms. All rows formatted: 11.117 ms

Answer: You want the sum of sales from the distinct pairs of sales and id:
select sum(t.sales) from (
  select distinct sales, id
  from table
) t

or:
select sum(t.sales) from (
  select sales from table
  group by sales, id
) t


Define Spring bean with a Map-typed constructor argument

Question: In my Grails app, I'm trying to define a Spring bean in resources.groovy that requires a Map-typed constructor arg. I tried this:
Map<Class, String> mapArg = [(String): 'foo']
myBean(MyBeanImpl, mapArg)

But I get the error message:

org.springframework.beans.factory.BeanCreationException: Error
  creating bean with name 'myBean': Could not resolve matching
  constructor (hint: specify index/type/name arguments for simple
  parameters to avoid type ambiguities)

The implementation class has a single constructor which is defined thus
MyBeanImpl(Map<Class, String> map) {
  // impl omitted
}

My guess is that the problem is caused by the fact that I've defined a constructor that takes a single Map arg which has the same signature as the default constructor Groovy adds to every class.
If so, a solution would appear to be to add a factory method such as
MyBean getInstance(Map map) {
  // impl omitted
}

But I'm not sure how I can call this to define a bean (in resources.groovy) that is constructed from a factory method that requires a parameter.
Comment: That ought to work.  One slight wrinkle is that you need to define the map as `[(String):'foo']` with parentheses in order to use the `Class` object as a map key rather than the string "String", but I don't think generic type parameters are significant in deciding whether or not the constructor matches.
Comment: @IanRoberts in the code itself, I did have brackets around the class for the reasons you state. I've updated my question, well spotted.
Answer: As far as I can tell the syntax you're using ought to work.  Does the alternative syntax:
Map<Class, String> mapArg = [(String): 'foo']
myBean(MyBeanImpl) { bean ->
  bean.constructorArgs = [mapArg]
}

work any better in your case?  Failing that, declaring the map as a bean in its own right should definitely do it:
import org.springframework.beans.factory.config.MapFactoryBean

classMap(MapFactoryBean) {
  sourceMap = [(String):'foo']
}

myBean(MyBeanImpl, classMap /* this is a RuntimeBeanReference */)


Finding an unitary matrix, $P$, and diagonal matrix, $D$, such that $P^{-1}AP = D$.

Question: Let $A = \begin{pmatrix} 0 & i \\ i & 0 \end{pmatrix}$. I need to find an unitary matrix, $P$ and diagonal matrix $D$, such that $P^{-1}AP = D$ (Or determine why those can't be found)
Now, for this to happen, $A$ must be a normal matrix, and this is true iff there's an orthonormal basis for $V$ composed by eigenvectors of $T$.
How do I do this in practice? Do I have to find the eigenvectors of $A$ and then apply on them Gram-Schmidt process?
Or should I first check that $A$ has $n$ different eigenvalues, since $D$ must be $D=\text{Diag}(\lambda_1, \ldots, \lambda_n)$
Answer: Step 1: Find the eigenvalues of $A$. In this case, they are $\{i,-i\}$.
Step 2: Find the corresponding eigenvectors (up to scalar multiplication). They are $(1,1)$ and $(1,-1)$. (In general, if an eigenvalue is repeated, find linearly independent and pairwise orthogonal eigenvectors corresponding to it, if possible—see the comment by @Omnomnomnom below.)
Step 3: Normalize the eigenvectors so that each has unit norm: $(2^{-1/2},2^{-1/2})$ and $(2^{-1/2},-2^{-1/2})$.
Step 4: Form a matrix $P$ having the eigenvectors as columns: $$P=\left(\begin{array}{cc}\dfrac{1}{\sqrt{2}}&\dfrac{1}{\sqrt{2}}\\\dfrac{1}{\sqrt{2}}&-\dfrac{1}{\sqrt{2}}\end{array}\right).$$
You can check that $P$ is unitary.
Step 5: Now let $D$ be the matrix having the eigenvalues in the diagonal: $$D=\left(\begin{array}{cc}i&0\\0&-i\end{array}\right).$$
Step 6: Check that $A=PDP^{-1}$.
Comment: Note: this process is sufficient when $A$ has no repeated eigenvalues, but may otherwise fail.
Comment: The process _may_ work even if there are less than $n$ distinct eigenvalues. The process fails when an eigenvalue of multiplicity $k\geq2$ has less than $k$ linearly independent eigenvectors.
Comment: $P$ will be unitary as long as the matrix $A$ is Hermitian. This is because eigenvectors corresponding to distinct eigenvalues are orthogonal (see a proof [here](http://www.math.iitb.ac.in/~ars/MA106/week7.pdf)—see Proposition 7.7). In your example, the matrix $A$ is not Hermitian, yet the eigenvectors still happen to be orthogonal.
Comment: @triple_sec try the identity matrix
Comment: @triple_sec or for a less trivial example, the matrix
$$
\pmatrix{1&1&1\\1&1&1\\1&1&1}
$$
Comment: @triple_sec it is not sufficient to have them be linearly independent; they must also be mutually orthogonal.  For example, with the identity matrix, we must disallow choosing $(1,0),(1,1)$, since the resulting $P$ will not be unitary.  Alternatively, once the linearly independent eigenvectors are selected, apply the Gram-Schmidt process (we can do this either to all eigenvectors simultaneously or within each eigenspace separately and achieve the same result.)
Comment: Do I have to check it in the end? (Step #6)
Comment: When do the process can get failed? (My guess is that there are less than $n$ eigenvalues, right?)
Comment: So the process work $\iff$ $A$ has no repeated eigenvalues.
Comment: Also, could you explain why is this process promise $P$ is indeed unitary?
Comment: Thank you, but why is $P$ must be unitary?
Comment: In general, the diagonalization process still works as long as the columns of the matrix $P$ of eigenvectors are linearly independent, but $P$ is not guaranteed to be unitary.
Comment: If $A$ is Hermitian with repeated eigenvalues, then it is possible to follow these steps and choose a $P$ that is not unitary.
Comment: @Omnomnomnom Can you give an example?
Comment: @Omnomnomnom I see. I added an extra instruction to Step 2 to circumvent this caveat.
Comment: @Omnomnomnom You are right. Thank you for the clarification. I will add this, too.


Issues after updated to Xcode 5

Question: I had my iOS App up to 98% completed on Xcode 4.6 and iOS 6.1 and it's working OK.
But then problems begin when I try to update my Xcode to version 5 and the SDK to iOS 7.
When I try to run the app on Xcode 5 but with iOS 6.1 it continues working ok, but when I tried to run on SDK 7 I have these issues:
<code>2013-12-17 19:44:47.656 myAPP[2207:70b] *** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<MKUserLocation 0x9d9af90> valueForUndefinedKey:]: this class is not key value coding-compliant for the key distanceAnnotation.'
*** First throw call stack:
(
    0   CoreFoundation                      0x01bf65e4 __exceptionPreprocess + 180
    1   libobjc.A.dylib                     0x019798b6 objc_exception_throw + 44
    2   CoreFoundation                      0x01c866a1 -[NSException raise] + 17
    3   Foundation                          0x0142d8ca -[NSObject(NSKeyValueCoding) valueForUndefinedKey:] + 282
    4   Foundation                          0x0139a921 _NSGetUsingKeyValueGetter + 81
    5   Foundation                          0x01399f5b -[NSObject(NSKeyValueCoding) valueForKey:] + 260
    6   Foundation                          0x013b9a5a -[NSObject(NSKeyValueCoding) valueForKeyPath:] + 409
    7   Foundation                          0x013c68c6 _sortedObjectsUsingDescriptors + 380
    8   Foundation                          0x013c66d7 -[NSMutableArray(NSKeyValueSorting) sortUsingDescriptors:] + 578
    9   myapp
                        0x00009e50 -[mapa mapViewDidFinishLoadingMap:] + 496
    10  MapKit                              0x0037e974 -[MKMapView mapViewDidFinishLoadingTiles:] + 78
    11  VectorKit                           0x050a3ade -[VKMapView mapDidFinishLoadingTiles:] + 78
    12  VectorKit                           0x050abe4e -[VKMapCanvas mapModelDidFinishLoadingTiles:] + 46
    13  VectorKit                           0x050b82cd -[VKMapModel didStopLoadingTilesWithError:] + 77
    14  VectorKit                           0x051ae2e1 -[VKTileProvider didStopLoadingTilesWithError:] + 49
    15  VectorKit                           0x051b1c99 -[VKTileSource didFinishWithNetwork] + 73
    16  VectorKit                           0x051c3aa3 __41-[VKResourcesTileSource performDownload:]_block_invoke73 + 51
    17  GeoServices                         0x04bb98a6 ___ZNK49-[GEOTileLoaderInternal _loadedTile:forKey:info:]66__49-[GEOTileLoaderInternal _loadedTile:forKey:info:]_block_invoke3$_1clERKN8LoadItem9RequesterE_block_invoke_2 + 85
    18  libdispatch.dylib                   0x021f77f8 _dispatch_call_block_and_release + 15
    19  libdispatch.dylib                   0x0220c4b0 _dispatch_client_callout + 14
    20  libdispatch.dylib                   0x021fa75e _dispatch_main_queue_callback_4CF + 340
    21  CoreFoundation                      0x01c5ba5e __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 14
    22  CoreFoundation                      0x01b9c6bb __CFRunLoopRun + 1963
    23  CoreFoundation                      0x01b9bac3 CFRunLoopRunSpecific + 467
    24  CoreFoundation                      0x01b9b8db CFRunLoopRunInMode + 123
    25  GraphicsServices                    0x033579e2 GSEventRunModal + 192
    26  GraphicsServices                    0x03357809 GSEventRun + 104
    27  UIKit                               0x004dad3b UIApplicationMain + 1225
    28  FarmValencia                        0x000029ad main + 141
    29  libdyld.dylib                       0x0249e70d start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
</code>
Comment: Please post code that resulted in this stack trace.
Comment: Might be because you are not referencing/including the Core Location framework in your project. According to this guide "Location services are provided by the Core Location framework. Maps are provided by the Map Kit framework." The stack trace shows MapKit but no CoreLocation. https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/LocationAwarenessPG/Introduction/Introduction.html
Answer: Theres simply not enough information to correctly debug this item.
I can recommend however that you add a Breakpoint for all Exceptions
Here is an example of adding an All Exception breakpoint in XCode 4. The process is the same in XCode 5
http://www.alauda.ro/2013/02/03/xcode-4-exception-breakpoints/
Aside from that you may try working with NSSetUncaughtExceptionHandler
http://www.cocoawithlove.com/2010/05/handling-unhandled-exceptions-and.html
This will allow you to trap the error and output the results but bear in mind that this is something you should only do during debug.
Wrapping it in an "#if DEBUG" is a good idea.
I hope this helps you out. These kind of bugs are a pain to fix.
NOTE
You may check if the key value set you are using didn't change between SDK's
Answer: Are you by chance sending the message valueForUndefinedKey: to the class MKUserLocation?
Here's what the class reference says about getting user location:
"The MKUserLocation class defines a specific type of annotation that identifies the user's current location. You do not create instances of this class directly. Instead, you retrieve an existing MKUserLocation object from the userLocation property of the map view displayed in your application."
https://developer.apple.com/library/ios/documentation/MapKit/Reference/MKUserLocation_Class/Reference/Reference.html

Issues after updated to Xcode 5


Can't make two 1:1 relations in one model in Prisma. Ambiguous relation detected

Question: I'm trying to make two 1:1 relations in one model in Prisma ORM, but got following error:

Error validating model "Person": Ambiguous relation detected. The fields placeOfBirth and placeOfDeath in model Person both refer to Place. Please provide different relation names for them by adding @relation(<name>).

My prisma schema:
model Place {
    id              Int     @id @default(autoincrement())
    name            String
    persons         Person[]
}

model Person {
    id              Int     @id @default(autoincrement())
    name            String
    placeOfBirthId  Int
    placeOfDeathId  Int
  placeOfBirth    Place   @relation(fields: [placeOfBirthId], references: [id])
    placeOfDeath    Place   @relation(fields: [placeOfDeathId], references: [id])
}

Totally don't get it.
Answer: You have to add a name field to placeOfBirth and placeOfDeath. Then use these names to reference both of them in the Place model.
model Place {
  id     Int      @id @default(autoincrement())
  name   String
  Births Person[] @relation("Births")
  Deaths Person[] @relation("Deaths")
}

model Person {
  id             Int    @id @default(autoincrement())
  name           String
  placeOfBirthId Int
  placeOfDeathId Int
  placeOfBirth   Place  @relation("Births", fields: [placeOfBirthId], references: [id])
  placeOfDeath   Place  @relation("Deaths", fields: [placeOfDeathId], references: [id])
}


Is there any need to check the block name when my module just define a block?

Question: I am reading "Drupal 7 Module Development", and I followed the book's steps to create a block in my module.
/**
   * Implements hook_block_info().
   */
  function first_block_hook_info() {
    $block = array();

    $block['list_modules'] = array(
      'info' => t('A listing of all the enable modules'),
      'cache' => DRUPAL_NO_CACHE
    );

    return $block;
  }
  /**
  * Implements hook_block_view()
  */
  function first_block_view($block_name ='') {
    if ($block_name == 'list_modules') {
      $list = module_list();

      $theme_args = array('items' => $list, 'type' => 'ol');
      $content = theme('item_list', $theme_args);

      $block = array(
        'subject' => t('Enable modules'),
        'content' => $content
      );

      return $block;
    }
  }

first_block_view($block_name = '') is using if ($block_name == 'list_modules') to check which block should be rendered, but I think Drupal will only send  list_modules' to my module.
Is there any need to check the block name in hook_block_view()?
Answer: While your module defines only a single block, technically no, it's not necessary.
But, as soon as you want to add another block, you'll need to distinguish between that and the existing one, so you'll need to check the block delta.
It's a good practice to get into, even if it's not strictly necessary to test the delta in the block view function.
Comment: One more question, I can not find the block( ```'list_module'```) in **Blocks** page, How can I enable the block? thanks.
Comment: The title is whatever comes under the `info` key in `hook_block_info()`...so it'll be called "A listing of all the enable modules" in your case. You can always change `info` to something shorter, and use the `description` key to describe it in more detail. You'll need to clear the caches after doing that for the change to get picked up
Comment: Can I disable caches when develop module?
Comment: Certainly can: http://stackoverflow.com/questions/4892573/drupal-7-how-to-completely-disable-cache


Como evitar estouro de array em C++?

Question: Meu programa estava apresentando um comportamento esquisito, até que eu descobri que estava havendo um estouro de array, por exemplo:
int arr[3];
for (int i = 0; i<10; i++) {
    arr[i]=i;
    cout << arr[i];
}

Neste exemplo claro, i ultrapassa o limite de apenas 3 elementos do array.
Entretanto o C++ não avisa nada e o programa vai literalmente detonando a memória, gerando comportamentos imprevisíveis no programa.
Como é possível fazer com que o C++ avise (e evite) quando ocorre isto?
Comment: Assim como @Maniero falou, o melhor será usar um built in iterator ou comparar com o tamanho do array.
Answer: Programando em C++ em vez de programar em C. O que você está fazendo é C e não C++. Funciona porque C++ tenta manter compatibilidade com C, mas não é o mais adequado.
Utilize um array, ou um vector, ou algo parecido. E use um iterador que garante que não poderá ir além dos limites (exemplo, outro, mais um, com string, um simplificado, exemplo com e sem iterador mas ainda seguro, um último).
Existem ferramentas externas que podem analisar e tentar informar que tem um erro.
Se quer mais garantias, troque de linguagem. C++ é poderosa, flexível e performática, mas não a mais segura que existe. Ela exige que o programador saiba o que está fazendo.
Coloquei no GitHub para referência futura.
Answer: Complementando a solução do Maniero.
Isso é um problema de semântica dinâmica, no qual só é possível saber se vai gerar um erro critico durante a execução, logo não se torna uma responsabilidade do compilador, visto que essa falha não impede a compilação e nem a execução do programa.
Não se trata de um erro e sim de um acesso não confiável a um pedaço de memória não alocada pela variável.
Neste artigo é possível visualizar que é possível acessar uma area de memória fora dos limites do array, porém não é possível escrever nela.

Como evitar estouro de array em C++?


Bootstrap css float right on some divs are not working

Question: I was attempting to float right a few items in a row
I want layout to look like this, even with reducing the browser size

Essentially this image layout is a bit different, but it shows a Create new User and Actions, so Action is like my "Manage bulk users"
I just want the items to align or float to the right, so that if the browser size is reduced it is not easily stacking on top of each other

      Choose your preferred criteria values and click Search

        Create New User

        Manage Bulk Users

Here is a fiddle of my code pasted below
https://jsfiddle.net/03vxqed9/
Answer: Use col-xs-6 that mean all sizes(from smallest to biggest)
and use pull-right/ pull-left instead float
float does NOT work with flex(row is flexable)

@import url('//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-theme.min.css');
body {
  margin: 10px;
}
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

      Choose your preferred criteria values and click Search

        Create New User

        Manage Bulk Users

Answer: you need to use pull-left and pull-right instead of float. See snippet bellow.
use a clearfix class to reset the floated elements.
Hope this will work for you!

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

      Choose your preferred criteria values and click Search

        Create New User

        Manage Bulk Users

Answer: Try This:
HTML Code

        Choose your preferred criteria values and click Search

        Create New User

        Manage Bulk Users

STYLES
@import url('//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-theme.min.css');

body {
  margin: 10px;
}

.top-bar {
  display:flex;width:100%;
}
.panel-right { display:flex;}
.iconx { clear:right;}

Answer: I hope this is what you want.

      Choose your preferred criteria values and click Search

                Create New User

                Manage Bulk Users


jquery validate não valida dentro de modal bootstrap

Question: Estou com problemas para fazer o jquery validate funcionar dentro do modal do bootstrap utilizando um link dinâmico (não sei se este é o motivo). Quando está fora ele funciona perfeitamente mais dentro do mesmo não. segue abaixo os códigos:
documento.php

documento_devolver.php

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

Devolver Documento

        <form action="" method="post" id="devolve">

                            Motivo da devolução:
                            <textarea name="exigencia" id="exigencia" class="form-control"></textarea>

        <input name="usuario_lancamento" id="usuario_lancamento" type="hidden" value="<?php echo $_SESSION['usuarioid']; ?>" />
                    <input name="id_documento" id="id_documento" type="hidden" value="<?php echo $id_documento; ?>" />
                    <input name="action" id="action" type="hidden" value="devolver" />
        <input type="submit" id="btn_salvar" class="btn btn-primary" value="enviar">
        </form>
        <button type="button" class="btn btn-default" id="resetForm">Limpar</button>

Pelo que pude perceber parece que o botão não funciona, pois quando escrevo no campo e dou um click fora ele diz que está preenchido e se apago o que escrevi ele dá erro do campo vazio. Mesmo com o campo preenchido não envia. Testei removendo a validação e enviou.
Desde já agradeço qualquer ajuda.
coloquei no jsfiddle para melhor compreensão:
https://jsfiddle.net/opeta/bLsvkeot/1/
Fiz um teste com o modal abrindo completamente na página pai sem o link externo e funcionou mais para resolver o meu problema eu preciso do link externo.
Comment: Essa pergunta [aqui](http://pt.stackoverflow.com/questions/167210/chamar-layouts-dentro-de-um-modal/167222#167222) é parte do problema, não é? Afinal, qual o motivo de carregar o modal de fora da página?
Comment: @ShutUpMagda essa pergunta é mais especifica pois somente o jquery validate não funciona, cada página que chamo no modal tem um link de edição gerado dinamicamente.  Parece que o validate funciona em parte quando preenchido o campo  e depois apagado. Na solução daquela pergunta não seria possível usar porque os links são dinâmicos. exemplo: documento_devolver.php?id=4
Comment: Você precisa abrir um o modal pra cada id diferente passando o ID para o modal, é isso?
Comment: exatamente o id muda a cada link. se vc reparar eu só chamo o validate na página pai e mesmo assim não funciona.
Answer: Há outras maneiras de fazer (maneiras mais elegantes, inclusive) mas eu acho que vc deve testar isso aqui:
index.php
<!DOCTYPE html>

        <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
        <title>Example</title>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

        <input type="hidden" id="_usuario_lancamento" value="<?=md5(date('H:i:s'))?>">
        <?php echo file_get_contents('modal.php'); ?>

              Launch myModal 1

              Launch myModal 2

modal.php

        <form action='acao/documento_acao.php' method="post" class="modal-content" name="form_myModal" id="form_myModal">

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

Devolver Documento myModal

                        Motivo da devolucao:
                        <textarea name="exigenciamyModal" id="exigenciamyModal" class="form-control"></textarea>

                <input name="usuario_lancamento" id="usuario_lancamento" type="hidden" value="%usuario_lancamento%"/>
                <input name="id_documento" id="id_documento" type="hidden" value="%id_documento%"/>
                <input name="action" id="action" type="hidden" value="devolver"/>
                <button type="reset" class="btn btn-default">

                    Limpar
                </button>
                <button id="btn-salvarmyModal" type="submit" class="btn btn-primary">

                    Confirmar
                </button>

        </form>

documento_acao.php
<?php
foreach ($_POST as $key => $val){
    echo $key.": ".$val."
";
}
?>

Home

Answer: deixarei aqui a solução que encontrei pois precisava recuperar os valores via get ou seja $id = $_GET['id']; que foi criar um iframe e chamar a página independente como eu utilizava com o fancy.box neste caso tem que se chamar de novo o jquery e os plugins a serem utilizados.
página do modal com iframe:
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

    <button type="button" class="modalButton" data-toggle="modal" data-src="modal.php?id=1" data-width="700" data-height="500" data-target="#myModal">Abrir modal</button>

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

página independente, repare que apenas utilizei o form do bootstrap tendo então que chamar o css do mesmo.
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<form action='acao/documento_acao.php' method="post" name="form_myModal" id="form_myModal">

Dynamic Content

                        Motivo da devolucao:
                        <textarea name="exigenciamyModal" id="exigenciamyModal" class="form-control"></textarea>

                <input name="usuario_lancamento" id="usuario_lancamento" type="hidden" value="%usuario_lancamento%"/>
                <input name="id_documento" id="id_documento" type="hidden" value="%id_documento%"/>
                <input name="action" id="action" type="hidden" value="devolver"/>
                <button type="reset" class="btn btn-default">

                    Limpar
                </button>
                <button id="btn-salvarmyModal" type="submit" class="btn btn-primary">

                    Confirmar
                </button>

            </form>


Converting tensor to numpy array in custom loss function

Question: Here is my custom loss function:
import tensorflow.keras.backend as K
import cmath

epsylon=np.finfo(float).eps

def to_array(tensor):
    return tf.make_ndarray(tensor)

def addError(test,range_min,range_max,result):
    err = abs(log(range_max/max(range_min,epsylon)))
    if range_min <= test <= range_max:
        result.append(err)
    else:
        e1=abs(log(test/max(range_min,epsylon)))
        e2=abs(log(test/max(range_max,epsylon)))
        result.append( min(e1,e2) / max(err,epsylon) *100 + err)

def rangeLoss(yTrue,yPred):
    #print(type(yPred))
    a_pred=to_array(yPred)
    a_true=to_array(yTrue)

    result=[]

    for i in range(a_true.size):
        range_min=abs(a_pred[i*2])
        range_max=abs(a_pred[i*2+1])
        test= abs(a_true[i])

        addError(test,range_min,range_max,result)

    return tf.constant(result)

When I run training, it fails with
/home/ubuntu/.local/lib/python3.6/site-packages/tensorflow/python/framework/tensor_util.py:591 MakeNdarray
        shape = [d.size for d in tensor.tensor_shape.dim]

    AttributeError: 'Tensor' object has no attribute 'tensor_shape'

When I modify to_array to use proto tensor
def to_array(tensor):
    proto_tensor = tf.make_tensor_proto(tensor)
    return tf.make_ndarray(proto_tensor)

I get following error:
    /home/ubuntu/.local/lib/python3.6/site-packages/tensorflow/python/framework/tensor_util.py:451 make_tensor_proto
        _AssertCompatible(values, dtype)
    /home/ubuntu/.local/lib/python3.6/site-packages/tensorflow/python/framework/tensor_util.py:328 _AssertCompatible
        raise TypeError("Expected any non-tensor type, got a tensor instead.")

    TypeError: Expected any non-tensor type, got a tensor instead.

Another option I've tried was tensor.numpy(), which resulted in following error:
    <ipython-input-20-0a8051a4a034>:8 to_array
        return tensor.numpy()

    AttributeError: 'Tensor' object has no attribute 'numpy'

And of course there is tensor.eval(session=tf.compat.v1.Session()), which fails too
How do I do this?
Comment: what are the shapes of yTrue, yPred? what is a_prod?
Comment: both yTrue and yProd are column vectors, yProd has 2x elements of yTrue. The purpose behind this is that I'd like to get range estimate instead of single point estimate for yTrue. `a_prod` is a typo
Comment: ok, so following what you said yTrue has shape (N, 1) yPred has shape (2N, 1)... did I understand correctly?
Comment: @MarcoCerliani yes
Comment: ok, I've never seen true and pred with a different number of samples, and I have doubt that keras can handle this. I think that the starting point is to reshape your data in this format yTrue (N, 1) yPred (N, 2)
Comment: @MarcoCerliani how would I declare an output  layer that returns data in shape of (N,2)?
Comment: simply having yTrue with shape (N,2) and a final dense layer like this Dense(2)
Comment: @MarcoCerliani yes, you were right. I was able to implement this algorithm by slicing the yPred into 2 vectors and working separately with each of them
Answer: I have solved the issue by slicing the original tensor. Here is the code:
def above_zero(value):
    return tf.math.maximum(value,np.finfo(float).eps)

def range_loss(yTrue,yPred):
    #shapes: yTrue: (None,1)
    #        yPred: (None,2)
    yTrueSize=yTrue.shape[1]
    min=above_zero(tf.math.abs(yPred[:,:yTrueSize]))
    max=above_zero(tf.math.abs(yPred[:,yTrueSize:]))

    #following step should not be needed, but let's do it just in case
    yTrue=above_zero(tf.math.abs(yTrue))

    baseError    = tf.math.abs(tf.math.log(max/min))
    baseErrorDiv = above_zero(baseError)

    topRange     = tf.math.maximum(min,max)
    bottomRange  = tf.math.minimum(min,max)

    extraError = tf.math.maximum(0.0,tf.math.log(yTrue/topRange))+tf.math.maximum(0.0,tf.math.log(bottomRange/yTrue))
    extraError /= baseErrorDiv

    totalError=tf.math.pow(extraError,2.0)*100+tf.math.pow(baseError,2.0)

    return tf.math.reduce_sum(totalError)


An application of Euler Characteristic to Tetrahedron Packing

Question: The following is an application of Euler's equation to tetrahedron packing of any convex polyhedron. I related it to Euler formula; consequently, a third equation is obtained which is independent of both the number of vertices and Euler characteristic.
Variables
$V$ is the number of vertices;
$E$ is the number of edges;
$F$ is the number of faces;
$T$ is the number of tetrahedrons;
$N'$ is the number of triangulated planes shared between tetrahedrons that fill a given polyhedron
Equations
Euler Equation
$V-E+F=2$
A reformulation of Euler's formula, as Sunghyuk Park proved in the comments below, with application to tetrahedron packing
$V-2T+N'=2$
How it relates to Eruler's equation
$V-E+F=V-2T+N';\\
-E+F=-2T+N'$
Node: I modified the body in response to your valued feedback.
My question originally was 'how to best share such things?'. I should have done this on mathoverflow.
Comment: @MoustaphaItani, never name an equation after yourself! When you encounter a named equation like "Euler's formula," it was not named by Euler, but by other mathematicians. Naming it after yourself is a sure way to have people treat your claims dismissively.
Comment: Sure, by all means share, but not really here. Consider deleting this question from here and reposting at http://mathoverflow.net/ (but avoid leaving both questions up at the same time.)
Comment: Do not deface your post by removing its body or significantly altering it. That makes the answers incomprehensible. I rolled the question back to match the version that Sunghyuk Park answered. He helped you, so give him the courtesy of leaving your question as it was answered.
Comment: This site is not really for original research or opinions on it, unless there is a very specific question. You might want to ask in math.Overflow if your conjecture is a well known consequence of one of the generalizations that already exist . Asking how to communicate it is getting a bit ahead of yourself
Comment: @rschwieb I don't know what to do. These have been sitting in my notebook for many years. I figured that sharing them here is better than keeping them buried with me.
Comment: I also didnt know that. I will delete this and then share a more elaborate description. Thank you.
Comment: I just felt awkward :(
Comment: I see. Make minor edits to reduce the awkwardness, and we can delete comments that became obsolete. No real harm was done:-) This is just something users here take very seriously. Now you know.
Answer: There are linear relations: $E=6T-3N$, $F=4T-2N$. First one because before gluing of tetrahedra, we have 6T edges in total, but for each gluing, 3 are reduced. The second one is because before gluing we have 4T faces in total, which is reduced by 1 for each gluing.
Therefore, $2=V-E+F=V-(6T-3N)+(4T-2N)=V-2T+N$, proving your claim. (Unfortunately, your equation turns out to be nothing but a reformulation of Euler's formula.)
Comment: @MoustaphaItani That is what mathematicians call "triangulation".
Comment: Shouldn't this be noted somewhere? I mean, it shows that Euler's formula has implications on Tetrahedron packing.
Comment: You mean "triangulation", not "packing of tetrahedra"? I don't feel like it says anything more than Euler's formula as Euler's formula itself relates the topology of a polyhedra to its triangulation.
Comment: I am saying packing of tetrahedra. Consider trying it. Draw any polyhedron. Triangulate the planes inside the polyhedron. Break the polyhedron into tetrahedra. The equation will apply in relating T, V and N'.
Comment: The gluing that you talked about is taking place on the inside. It is like describing the internal structure of a polyhedron. I will expand the above to include the equations I found for determining other things. I will share that on mathoverflow.net as @rschwieb recommended.
Comment: I edited the text above and thanked you. I think it is an application of Euler's formula to tetrahedron packing.