Is a hypothesis test useful if our null hypothesis is not the true value?

Question: Assume we are testing if the true average weight of milk cartons is 100g. We may specify $H_0: \mu = 100$ and $H_1: \mu \ne 100$.
Let's assume the true weight is 102.
In the course of testing we may calculate metrics, such as the type 1 error for example. This is the probability that we reject a null hypothesis given that it is true. But isn't this a non-sensical number if the true $\mu$ isn't the same as the null in our test? And given that this is the likely situation in the real world, what information does a hypothesis test really give us if we do not correctly specify the null hypothesis?
Comment: It is good to be critical about your null hypothesis, but it is also good to remain practical. We never know the value of the true patametry (if we did then why would we need to do research?). So all we have is the data and some form of hypothesis, and that is all we have to work with.
Comment: Good to be aware of: for all intents and purposes, the null is almost always false.
Comment: True @Glen_b (unfortunately we cannot edit comments)
Comment: For a point null, yes. For composite nulls, not necessarily.
Answer: If the power of your test of $H_0: \mu=100$ against $H_a: \mu\ne 100$ is sufficient, you will likely reject $H_0.$ So the test has not been useless. Furthermore, it is
good statistical practice to accompany this test with a CI for $\mu.$ For example, such a CI is included in the R output for t.test.
Also, ideally, the test would have been preceded by a power computation to find the
probability of rejection the $H_0$ is false by various amounts $\Delta.$
You are correct that the situation, in which $H_0$ does not exactly specify
the true value of $\mu,$ is commonly encountered in practice.
If the variability among contents of milk cartons is given by $\sigma=0.1$ and
we sample $n = 12$ cartons, we might get results as shown for the simulated
sample below:
set.seed(917)
x = rnorm(12, 102, .1)
t.test(x, mu = 100)

        One Sample t-test

data:  x
t = 66.027, df = 11, p-value = 1.193e-15
alternative hypothesis:
  true mean is not equal to 100
95 percent confidence interval:
 101.9421 102.0760
sample estimates:
mean of x
 102.0091

In this case, $H_0$ is strongly rejected with at P-value very nearly $0.$
The 95% CI $(101.9, 102.1)$ gives a good indication that the true value
is near $\mu = 102.$

If it is the firm's intention is to overfill cartons slightly in order to avoid complaints or regulatory fines for selling
cartons that don't have the $100$g promised on the carton, then result of
the experiment and and the test and CI in R will assure them that all is well.

If the it is firm's intention to put just barely enough in each carton
to avoid underfilling the vast majority of the time, then these results might suggest a target fill amount of something like
$100.1$g or $100.2$g, depending on the particulars and pending ongoing monitoring.

Addendum:  Because you ask about power computations in a Comment, I will
illustrate how one can simulate the power for a two-tailed, one-sample t test, at the 5% level, of $H_0: \mu = 100$ vs. $H_a: \mu = 101$ (specific value different from
100) when $n  = 12, \sigma = 1.$ (The result can be found using a noncentral t distribution, but $n$ is too small for a good normal approximation.)
The power is about $88\%.$  That is, when $\mu_a$ differs by $\Delta = 1$ from $\mu_0 = 100,$ we have probability about $0.88$ of rejecting $H_0.$
set.seed(2020)
pv = replicate(10^5, t.test(rnorm(12, 101, 1), mu=100)$p.val)
mean(pv <= 0.05)
[1] 0.88404

The result is essentially the same for this two-tailed test if data are
$\mathsf{Norm}(99,1).$ With 100,000 samples of size $n = 12,$ one can
expect about 2-place accuracy for rejection probability.
set.seed(1234)
pv = replicate(10^5, t.test(rnorm(12, 99, 1), mu=100)$p.val)
mean(pv <= 0.05)
[1] 0.88219

Comment: Thanks for this answer, especially the part about the confidence interval, that was very nice. I'd also like to know more about your first sentence that says "If the power of your test is sufficient ,you will likely reject $H_0$. So the test has not been useless". But can't you have a test that is too powerful? Can you give resource that describe how these power calculations are done?
Comment: Many mathematical statistics books give a formula for the power of a t test in terms of a 'non-central' t distribution. Intermediate applied texts have approximate formulas for power that are OK for sufficiently large $n$ (using normal approximation). Various statistical programs (R, Minitab, etc.) have 'power and sample size' procedures useful for planning experiments. Also, there are some 'power and sample size calculators' on the Internet (of varying utility and accuracy). For many situations (beyond t tests), closed-form expressions for power are unavailable, and one can use simulation.
Comment: @Darby Bond: "But can't you have a test that is too powerful?" - I added something to this effect to my answer, see there.
Answer: What you call "metrics" are performance characteristics of the test. Regardless of what the true value of $\mu$ is (which we never know), a test that rejects a $H_0$ that is true too often is not good and a rejection is then meaningless. This is what you get from type I error calculations. You also may carry out power calculations. For this you may choose several values of $\mu$ or one borderline value that you "for sure" would like to lead to a significant result. You may also want to know whether the test will likely reject given that the true $\mu$ is not 100 but so close to 100 that you'd consider the $H_0$ still as "practically true" (if not theoretically). (Added after seeing a comment on the other answer:) This can mean that the power of the test is "too high", rejecting the null even in cases in which pragmatically in the real situation  there's nothing wrong with it. This as well does not rely on the true $\mu$, because you don't know that, however you can compute whether the test has the performance characteristics given any value of $\mu$ you'd like to try that you expect from it.
Note also that a test does not investigate whether the $H_0$ is true, but rather whether the data are compatible with the $H_0$, i.e., whether they look like typical data generated from the $H_0$. This can well be the case even if the $H_0$ is in fact not true, which means that whatever the true $\mu$ is, the data cannot be used to argue that there's evidence against $H_0$. This (and no more) is what you get from a test.
A last remark: You say the likely situation in the real world is that $\mu$ is not precisely 100. I say it's worse than that. In the real world there is no such thing as a normal distribution, and not even i.i.d. data according to any well defined parametric distribution. There's no such thing as a true distribution, and there's no such thing as a true $\mu$ (which is defined within an assumed model), be it 100, 102 or whatever. Models are thought constructs that help us reasoning about a world that is essentially different. The best thing we can ever do is say, these data look like data generated from an artificial model with a certain parameter value (or a confidence set of parameter values) that has certain characteristics that we may want to interpret.
Comment: Cogent comments (+1). Given the level of the question, I chose the path of numerical illustrations with numbers similar to those in the question.
Comment: Yes, the question is treated nicely from two quite different perspectives in this way.
Comment: The paragraph on selecting ranges for acceptable $\mu$ was quite illustrative. I think this is something that is neglected in introductory statistics texts


Create EventLogRecord for unit test

Question: I implemented an API to process EventLogRecord object.
using System.Diagnostics.Eventing.Reader;

...
MyLog ProcessEvent(EventLogRecord eventRecord)

Now, I want create unit test for this and EventLogRecord doesn't have a public constructor. How do I get a EventLogRecord object without hooking up to the event logging system?
Answer: The standard way of making untestable items like this (non-virtual) work is by using a wrapper. Here is some pseducode of the idea:
WrapperEventLogRecord : IEventLogRecordWrapper
{
    ctor(EventLogRecord eventLogRecord)
    public ActivityId {get{return _eventLogRecord.ActivityId;}}
}

Now you can pass in the interface and mock it out as necessary
Comment: Great! Wrapping will solve the problem. Any other options? I am a little concerned about the overhead (more code just to wrap).
Comment: If you are using a basic mocking framework, then no. See my unanswered question here: http://stackoverflow.com/questions/17203061/is-a-wrapper-the-only-way-to-test-a-static-dependency You could use a powerful mocker like TypeMock to get at the private ctor, though?

Create EventLogRecord for unit test


Which t-test it the right one for my data?

Question: I have the data set below.  Two Groups which were tested at 3 different timing. Between the tests, there were 5 weeks of training.  I think, I should do the t-test for dependent variable.  (I need this for my master thesis in physical education, so I don't need anything fancy.)
> dput(data)
structure(list(group = c("Experimentalgruppe", "Kontrollgruppe",
"Experimentalgruppe", "Kontrollgruppe", "Kontrollgruppe", "Experimentalgruppe",
"Kontrollgruppe", "Experimentalgruppe", "Experimentalgruppe",
"Kontrollgruppe", "Experimentalgruppe", "Kontrollgruppe", "Kontrollgruppe",
"Kontrollgruppe", "Kontrollgruppe", "Experimentalgruppe", "Experimentalgruppe",
"Kontrollgruppe"), `t0 VO2 max` = c(47.6, 47.6, 47.6, 46.7818181818182,
44.6, 41.3, 38, 43.5090909090909, 41.8727272727273, 45.1454545454545,
44.0545454545455, 28.475, 38.6, 44.6, 40.4, 32.6, 40.4, 44.3272727272727
), `t1 VO2 max` = c(47.8727272727273, 46.5090909090909, 48.6909090909091,
47.6, 46.2363636363636, 42.1454545454545, 40.7, 44.6, 43.2363636363636,
47.8727272727273, 44.3272727272727, 30.9333333333333, 41.6, 45.4181818181818,
42.9636363636364, 33.2666666666667, 38.6, 40.1), `t2 VO2 max` = c(48.6909090909091,
42.9636363636364, 48.6909090909091, 46.2363636363636, 47.8727272727273,
42.4181818181818, 38.6, 42.6909090909091, 43.7818181818182, 49.2363636363636,
44.8727272727273, 30.2666666666667, 42.1454545454545, 47.6, 42.4181818181818,
33.2666666666667, 42.9636363636364, 42.6909090909091)), row.names = c(NA,
-18L), class = c("tbl_df", "tbl", "data.frame"))

I think this one is better to use
# A tibble: 18 x 4
group              `t0 VO2 max` `t1 VO2 max` `t2 VO2 max`
<chr>                     <dbl>        <dbl>        <dbl>
1 Experimentalgruppe         47.6         47.9         48.7
2 Kontrollgruppe             47.6         46.5         43.0
3 Experimentalgruppe         47.6         48.7         48.7
4 Kontrollgruppe             46.8         47.6         46.2
5 Kontrollgruppe             44.6         46.2         47.9
6 Experimentalgruppe         41.3         42.1         42.4
7 Kontrollgruppe             38           40.7         38.6
8 Experimentalgruppe         43.5         44.6         42.7
9 Experimentalgruppe         41.9         43.2         43.8
10 Kontrollgruppe             45.1         47.9         49.2
11 Experimentalgruppe         44.1         44.3         44.9
12 Kontrollgruppe             28.5         30.9         30.3
13 Kontrollgruppe             38.6         41.6         42.1
14 Kontrollgruppe             44.6         45.4         47.6
15 Kontrollgruppe             40.4         43.0         42.4
16 Experimentalgruppe         32.6         33.3         33.3
17 Experimentalgruppe         40.4         38.6         43.0
18 Kontrollgruppe             44.3         40.1         42.7

Comment: What hypothesis do you want to test? You must know that before you can test a hypothesis.
Comment: The question is, is there a significant change in VO2max between these two groups. The Experimentalgruppe has trained the secound 5 weeks with a mask
Comment: Between the first time and the final time? What about the middle time? (You're allowed not to care about the middle time, but that's a decision for you to make.)
Comment: no, between the first time and the second one (t0 and t1) and between the second and the third one (t1 and t2)
Comment: the test between the first and the second time (t0 and t1 ) is not realy nessesary for my master thesis. I manipulated the Experintalgroup after the second test (t1) and whant to know if there is a sicnificant difference between both groups after the third test (t2)
Comment: @Jugglerz: Because I can't comment (less than 50 reputation) I have to ask: Is the shape of your data correct. You have 10 subjects in your Kontrollgruppe and 8 in your Experimentalgruppe.
Comment: yes, it ist correct. I had to remove 2 subjects from Experimentalgruppe
Answer: Here is how I would go about testing this.
In summary, it does not appear (from what I gather) that your treatment groups differ significantly from your control groups.
let's load your data, I call it "df_test"
df_test <- structure(list(group = c("Experimentalgruppe", "Kontrollgruppe",
                         "Experimentalgruppe", "Kontrollgruppe", "Kontrollgruppe", "Experimentalgruppe",
                         "Kontrollgruppe", "Experimentalgruppe", "Experimentalgruppe",
                         "Kontrollgruppe", "Experimentalgruppe", "Kontrollgruppe", "Kontrollgruppe",
                         "Kontrollgruppe", "Kontrollgruppe", "Experimentalgruppe", "Experimentalgruppe",
                         "Kontrollgruppe"), `t0 VO2 max` = c(47.6, 47.6, 47.6, 46.7818181818182,
                                                             44.6, 41.3, 38, 43.5090909090909, 41.8727272727273, 45.1454545454545,
                                                             44.0545454545455, 28.475, 38.6, 44.6, 40.4, 32.6, 40.4, 44.3272727272727
                         ), `t1 VO2 max` = c(47.8727272727273, 46.5090909090909, 48.6909090909091,
                                             47.6, 46.2363636363636, 42.1454545454545, 40.7, 44.6, 43.2363636363636,
                                             47.8727272727273, 44.3272727272727, 30.9333333333333, 41.6, 45.4181818181818,
                                             42.9636363636364, 33.2666666666667, 38.6, 40.1), `t2 VO2 max` = c(48.6909090909091,
                                                                                42.9636363636364, 48.6909090909091, 46.2363636363636, 47.8727272727273,
                                                                                42.4181818181818, 38.6, 42.6909090909091, 43.7818181818182, 49.2363636363636,
                                                                                44.8727272727273, 30.2666666666667, 42.1454545454545, 47.6, 42.4181818181818,
                                                                                33.2666666666667, 42.9636363636364, 42.6909090909091)), row.names = c(NA,
                                                                                -18L), class = c("tbl_df", "tbl", "data.frame"))

First need to get your data in the proper format for analysis
library(dplyr)
df_ready <- tidyr::gather(df_test, Interval, VO, -(1), na.rm = TRUE)

Your test was done 3 times, I called this variable "interval", and I am just going to change the variable names to 1, 2, 3 for simplicity
df_ready$Interval <- as.factor(df_ready$Interval)
levels(df_ready$Interval)[levels(df_ready$Interval)=="t0 VO2 max"] <- "1"
levels(df_ready$Interval)[levels(df_ready$Interval)=="t1 VO2 max"] <- "2"
levels(df_ready$Interval)[levels(df_ready$Interval)=="t2 VO2 max"] <- "3"

lets set things up for a simple linear regression, but first get the data structured right
str(df_ready) # need to change "group" and "interval"
df_ready$group <- as.factor(df_ready$group)
df_ready$Interval <- as.factor(df_ready$Interval)

run model
model = lm(VO~group + Interval, data = df_ready)
summary(model) notice low t-values, most likely nothing is deviating significantly
anova(model) # anova is not-significant, suggesting, no further testing is required, But let's continue to see what happens

test <- aov(model)
TukeyHSD(test)
summary(test) # notice it's the same results as the other way of running an anova test

plot(VO~Interval,type ='n',xaxt = "n",data = df_ready, xlab="Time Interval", main= "VO Max Measurement Through Time")
points(df_ready$Interval[df_ready$group=='Kontrollgruppe'],df_ready$VO[df_ready$group=='Kontrollgruppe'],col='red',cex=2,pch=18)
points(df_ready$Interval[df_ready$group=='Experimentalgruppe'],df_ready$VO[df_ready$group=='Experimentalgruppe'],col='blue',cex=2,pch=7)
xtick<-seq(0, 3, by=1)
axis(1, at=xtick, labels = F)
df_ready$Interval <- as.factor(df_ready$Interval) # need to switch back temporarily to as.factor to create your x-axis labels
labels<- levels(df_ready$Interval)
text(x =  seq_along(labels), y = par("usr")[3] - (par("usr")[4] - par("usr")[3])/40, srt = 360, adj = 0.5,
     labels = labels, xpd = TRUE,cex = 1.5,font = 2)
df_ready$Interval <- as.numeric(df_ready$Interval) # flip back to as.numeric for adding the regression lines
abline(lm(df_ready$VO[df_ready$group=='Kontrollgruppe']~df_ready$Interval[df_ready$group=='Kontrollgruppe']),lwd=1,lty=1,col="red")
abline(lm(df_ready$VO[df_ready$group=='Experimentalgruppe']~df_ready$Interval[df_ready$group=='Experimentalgruppe']),lwd=1,lty=1,col="blue")
legend(2.5,48,cex=1.5,c('Kontrollgruppe','Experimentalgruppe'),fill=c('red','blue'), horiz=F)

Notice how regression lines are very close to eachother: Not surprising, given the results we got from the linear model.
Lets plot the predicted values from the model, R calls these "fitted" models
df_ready$fit <- predict(model)   #Add model fits to dataframe

box plot them
boxplot (df_ready$fit~df_ready$group, xlab = "Experimental Groups")
t.test(df_ready$fit~df_ready$group) # not significant

We can see box plots are very similar, and t'test is not significant, meaning your treatment did not increase or decrease the VO max of your subjects
Comment: Welcome to the site. Please consider using base R, & commenting it extensively, when illustrating answers here w/ R code. Not everyone who will come to this page will be familiar w/ R, & not all of those will be able to read tidy-code. This is a Q&A site for *statistics*, not R.
Comment: Now i see, that there is no significant difference between Experimentalgruppe and Kontrollgruppe.
If i want to check the significance only on test time 2 and 3 (in my data, t1 and t2), where i have to change the code? The intervention startet after t1 (so maybe my mistake in describing the question)

so i think i have to compare t0/t1 and t1/t2
Comment: Thank you for your infirmation.
I was migrated from the other forum to this one here. :-)
Comment: if my comment responds properly to your question, please up vote it. :)
Comment: @Jugglerz I have updated my code to do a test between all possible combinations, I did what's called a TukeyHSD test, and added it to the code underneath the linear model

But to be fair, it's not necessary here because the anova itself is not significant, and therefore looking at individual groups as you wish to is not necessary, I did it here anyways and, no surprise, nothing is significant.


Set views contextual filter as request_path()

Question: There are fields in content type called URL and Image.
Suppose, A node has "service" value of "URL" field and I'm trying to show views block where current path (service) and "URL" field path (service) are same. The "URL" value can also be "content/services".
I tried with

adding "Alias" field as contextual filter in views.
adding URL field

Updated:
I also tried with URL field with PHP Code in contextual filter:
if(drupal_is_front_page()) {
    return '<front>';
}else{
    return request_path();
}

It works for only one path argument, like if current requested path is  services/one and views contextual filter only takes first path component as you can see in attached image

However, I need to set contextual filter with whole path no matter how many components are requested.
Theme
I have a content type with image and URL fields, I need to show image on the path where URL field is matched with requested path using views.
How would I do that?
Answer: If you want to filter nodes in a Views list that have the same expression in their "Alias" field as the path where the Views Block is shown then you can do it by adding the "Alias" field as a contextual filter and configured like this:
When the filter value is NOT available
Provide default value
Raw value from URL
Path component 1
Adjust the path component to the place where your service appears in the path.
You can also adjust the validation and other options that are relevant to you, but that first bit is what is the most important to match the path to your field.

The field value content/services might  match only on pages where the path starts with content/services. I haven't tested this, I expect the field expression will be treated as a one string, but the path will only take the first part before the / so in the end it won't match.
If you find that it doesn't work, then you might make it work with the help of Views Argument Substitutions and Views Contextual Filters OR.
You could also do it with the Context module and Context entity field but it's a fairly complex to configure.
Answer: I have done this by embedding the views block in tlp and passing the URL field filter by code. See code below:
$path = request_path();
$query = 'SELECT field_url_url FROM {field_data_field_url}
          WHERE bundle = :bundle AND entity_type = :entity_type AND field_url_url = :field_url_url';
$path = db_query($query, array(
            ':bundle'=>'page_banner',
            ':entity_type'=>'node',
            ':field_url_url'=> $path
        ))->fetchField();
if (!empty($path)):
  print views_embed_view('page_banner','block', $path);
endif;

I hope this will help someone who needs to add contextual filter as request URL.


How to compare two arrays and find the optimal match in Python?

Question: I have two arrays X and Y, X is the base array and Y is operated in a loop. As the loop runs I want to compare the arrays to find the nearest value of Y to X or in other words where is Y most close to X. As an example I have attached the reproducible code:
from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
from scipy import interpolate

x = np.array([[0.12, 0.11, 0.1, 0.09, 0.08],
       [0.13, 0.12, 0.11, 0.1, 0.09],
       [0.15, 0.14, 0.12, 0.11, 0.1],
       [0.17, 0.15, 0.14, 0.12, 0.11],
       [0.19, 0.17, 0.16, 0.14, 0.12],
       [0.22, 0.19, 0.17, 0.15, 0.13],
       [0.24, 0.22, 0.19, 0.16, 0.14],
       [0.27, 0.24, 0.21, 0.18, 0.15],
       [0.29, 0.26, 0.22, 0.19, 0.16]])

y = np.array([[0.07, 0.06, 0.05, 0.04, 0.03],
              [0.08, 0.07, 0.06, 0.05, 0.04],
              [0.10, 0.09, 0.07, 0.06, 0.05],
              [0.14, 0.12, 0.11, 0.09, 0.08],
              [0.16, 0.14, 0.13, 0.11, 0.09],
              [0.19, 0.16, 0.14, 0.12, 0.10],
              [0.22, 0.20, 0.17, 0.14, 0.12],
              [0.25, 0.22, 0.19, 0.16, 0.13],
              [0.27, 0.24, 0.20, 0.17, 0.14]])

for i in range(100):
    y = y + (i / 10000)

I want to break the loop when the closest values have been found. By closest I mean, the values should be within ±10% of the original values or some other percentage. How can this be done in Python?
Comment: define `optimal match` and `most close` terms. People use different approaches to measure closeness of matrices (arrays).
Comment: Maximize coefficient of determination, maybe
Comment: Please update your question with this clarification
Comment: Don't forget to divide `i` by a float in the `for` loop to increment `y` (`y = y + (i / 10000.)`)
Comment: Please correct the y increment for consistency (see comment above)
Comment: @bougui  I have imported division from __future__.
Answer: You can compute the Euclidean distance between the two matrices:
import numpy as np
import scipy.spatial.distance
import matplotlib.pyplot as plt
x = np.array([[0.12, 0.11, 0.1, 0.09, 0.08],
   [0.13, 0.12, 0.11, 0.1, 0.09],
   [0.15, 0.14, 0.12, 0.11, 0.1],
   [0.17, 0.15, 0.14, 0.12, 0.11],
   [0.19, 0.17, 0.16, 0.14, 0.12],
   [0.22, 0.19, 0.17, 0.15, 0.13],
   [0.24, 0.22, 0.19, 0.16, 0.14],
   [0.27, 0.24, 0.21, 0.18, 0.15],
   [0.29, 0.26, 0.22, 0.19, 0.16]])
y = np.array([[0.07, 0.06, 0.05, 0.04, 0.03],
          [0.08, 0.07, 0.06, 0.05, 0.04],
          [0.10, 0.09, 0.07, 0.06, 0.05],
          [0.14, 0.12, 0.11, 0.09, 0.08],
          [0.16, 0.14, 0.13, 0.11, 0.09],
          [0.19, 0.16, 0.14, 0.12, 0.10],
          [0.22, 0.20, 0.17, 0.14, 0.12],
          [0.25, 0.22, 0.19, 0.16, 0.13],
          [0.27, 0.24, 0.20, 0.17, 0.14]])

dists = []
for i in range(100):
     y = y + (i / 10000.)
     dists.append(scipy.spatial.distance.euclidean(x.flatten(), y.flatten()))
plt.plot(dists)

will return this graph, which is the evolution of the Euclidean distance between your 2 matrices:

To break the loop at the minimum, you can use:
dist = np.inf
for i in range(100):
    y = y + (i / 10000.)
    d = scipy.spatial.distance.euclidean(x.flatten(), y.flatten())
    if d < dist:
        dist = d
    else:
        break
print dist
# 0.0838525491562 #(the minimal distance)
print y
#[[ 0.1051  0.0951  0.0851  0.0751  0.0651]
#[ 0.1151  0.1051  0.0951  0.0851  0.0751]
#[ 0.1351  0.1251  0.1051  0.0951  0.0851]
#[ 0.1751  0.1551  0.1451  0.1251  0.1151]
#[ 0.1951  0.1751  0.1651  0.1451  0.1251]
#[ 0.2251  0.1951  0.1751  0.1551  0.1351]
#[ 0.2551  0.2351  0.2051  0.1751  0.1551]
#[ 0.2851  0.2551  0.2251  0.1951  0.1651]
#[ 0.3051  0.2751  0.2351  0.2051  0.1751]]

Comment: Actually you can use a lot of different metrics: see http://docs.scipy.org/doc/scipy-0.14.0/reference/spatial.distance.html


.animate() - Queue Simulation for older jquery Verions (Drupal) Conflict

Question: im searching for a solution to come out with the jquery Version, which Drupal is including natively. Its a older version. Actually there are nooo problems - but one :D I use a .animate() function with a queue false, and without this attribute (because this attribute was addet to .animate() in jquery 1.7), it is not animating as i want.
The code is:
<code>//When mouse rolls over
$("#login").bind('mouseover mouseenter',function(){
$("#logo").stop().delay(500).animate({top:'-44px'},{queue:false, duration:600, easing: 'swing'})

$("#login").stop().animate({top:'89px'},{queue:false, duration:600, easing: 'easeOutBounce'})
});

//When mouse is removed
$("#login").bind('mouseout mouseleave',function(){
$("#logo").stop().animate({top:'6px'},{queue:false, duration:600, easing: 'easeOutBounce'})

$("#login").stop().animate({top:'40px'},{queue:false, duration:600, easing: 'swing'})
});
</code>
Maybe you can help me find a solution? The problem, why i want to exclude the jquery version I used for this (1.8.3) is that a Drupal Module is not showing up the wysiwyg (CKEditor), when jquery 1.8.3 is inlcluded additionaly and unfortunately i cant replace the jquery version of the core with jquery 1.8.3 :(
Comment: Have you seen [jQuery Multi](http://drupal.org/project/jqmulti)? It lets you load different jQuery versions into the same page with no conflicts
Answer: I have always done this via regular-old vanilla js; by simply firing the event on delay/timeout. This combats the queue problem.
Check this out on JsFiddle.
<code> <style type="text/css">
 .redBlock{
     height:2em;
     background-color:red;
     color:white;
     border:2px solid silver;
 }
 </style>
 <input type="button" id="testFoo" value="click me a bunch of times super fast" />
 <div id="testBar" style="width:100px;" class="redBlock"> Red Block </div>
 <script type="text/javascript">
    $(document).ready(function(){
        $("#testFoo").click(function(){
             fireOneAnimateEvent();
         });
    });
    function animateRedBlock() {
       $("#testBar").css('width', '100px')
            .animate({
                 width: ($("#testBar").width() * 3) + "px"
            }, 500, function () { });
    }
    var delay = (function () {
       var timer = 0;
       return function (callback, ms) {
           clearTimeout(timer);
           timer = setTimeout(callback, ms);
       };
    })();
    function fireOneAnimateEvent() {
       delay(function () {
           animateRedBlock();
       }, 500);
    }
 </script>
</code>


How to create a page view of two content type in Drupal 7

Question: I have two content type named as workshop and meetings. I wanted to create a new page view (say events) of these content type such that event page should have titles of post from each content grouped with content type.
I tried to create this view but I can't select multiple content type while creating a view.
Comment: Once you've created the view, you can edit the filters. Edit the filter called 'content type' and you can add several types.
Comment: @GisleHannemyr yep, should have done, was writing from my phone. :)
Answer: Here's how you do it: Once you've created your view, selecting either one of your content types:

Under "filter criteria", click the filter called "content type (= YOUR_CONTENT_TYPE).
Select "is one of", and then select all the content types you want to include.
Click Apply (all displays).
Save the view.


Identify which drives belong to a specific HP RAID 5 Group

Question: A total of 32 drives were removed from x4 decommissioned HP DL380 G6 servers (eight per server).
The setup of the eight drives per host was into two RAID Groups:
RAID 1 = SLOT 1, 2 = ESXi OS
RAID 5 = SLOT 3, 4, 5, 6, 7, 8 = VMFS Vol (hosting virtual machines)
Unfortunately there is some data that was not backed up prior to the removal of the drives, and now they are all in a pile mixed up.
What is the best way to put these drive back into the hosts without damaging the RAID groups the disks belong to?
Is there a tool that can be used to ready the RAID membership identifier on each drive?  Not sure if ACU supports this!
TIA
Danny
Comment: Interesting problem. I don't think you have any good options, though.
Comment: Your only luck would have to an old inventory with drive SN & position. Monitoring software can usually have such information. I checked with one I use and I can see slot# with drive SN.
Comment: The RAID configuration is stored—somewhere and somehow—on the drives. If you knew where to look, you could find that information using raw disk access. The location and format of this information depends on the RAID controller. Something you could do: make a raw backup of one of the disks, pop it in the system, and boot to the RAID controller to read the configuration from the disk. If you can do this with one disk, then you can do this with each disk individually to get the raid groups, or, if you're really lucky, even get the serial numbers of the disks in the configuration.
Answer: Probably the safest thing to do would be to send them all to a company like Kroll OnTrack. They understand the on-disk format of HP's RAID. Since all of the drives are operational, this probably wouldn't be too expensive but you'll have to talk to the right rep to get them to understand what you want: identify and group, but do not recover.
If you have access to a DAS shelf like an MSA 2000, you could load all of the drives in and let the controller auto-detect the existing RAID configuration of the drives. You would need multiple shelves all connected to a single controller to get this to work easily, although you could probably do it with a single shelf and a bit of musical hard drives.
Answer: The controller will erase the disks if you do this the wrong way...
Since HP Smart Array controllers store the array metadata on the actual drives, you can often move or relocate HP disk sets. However, there's some tolerance for drive displacement (slot reordering, etc).
So if the drives are moved together, the RAID is usaully intact. If you start doing that with multiple arrays with on-disk data... yeah. Not pretty.

An example from this weekend, trying to build a test environment from retired disks:
Comment: I don't have the hardware available to test my method describe in my comment above, that of putting ONLY ONE disk in the system to see what configuration it belongs to. Does that seem like a safe way to identify the drives? I was assuming slot reordering was tolerated, there.
Comment: @ ewwhite, I was planing to spend some time today and install 16 of the total 32 disks into an old ML 5G that has 16 drive slots to try and ID the drive membership.
Though I fear it's likely to be as per your comment "If you start doing that with multiple arrays with on-disk data... yeah. Not pretty."
Still hoping there's a way to read the ARRAY membership ID (or similar) from the disks...
Comment: Just a thought. In your screen shot above, did the controller have prior arrays configured?
I seem to recall that HP RAID CNTRLs store the Array metadata info on both the disk members and the controller itself.
If I were to delete any config on the controller, then put multiple arrays with on-disk data into it, would I stand a chance of 'not' wiping them!
Comment: @Danny Array configuration is stored on the disks, not the controller.
Comment: Anyone else have any ideas or suggestions of utilities for identifying Array/Raid group membership stored on disks?
Comment: No. This is a mess. You won't be able to reassemble the RAID without the right disks.


Visual Studio 2022 adds an overwhelming amount of folders into %TEMP%: Is it safe to delete them?

Question: I am new (I'd say) to Visual Studio. I installed it about ~a month ago. Although, while using Visual Studio, I see a huge problem. As I open %TEMP% folder (user temp directory), I see a ton of folders with absolutely random names. Some of them are empty, some consist of a 0-byte JSON file with random name also. Just look at this mess. I am absolutely sorry if you cannot read this language, but it's not important, the only important thing is to look at folder names. These are all generated by Visual Studio!

Now, I know these do not occupy disk space at all. But I absolutely don't like looking at this mess.
I can use the Disk Cleanup tool that's integrated into Windows. However, there are 2 things to mention:

Disk Cleanup only deletes 0-byte JSON files, not the directories.
There are some huge directories also created by Visual Studio, which Disk Cleanup actually would delete. But I think it is unsafe to delete them.

For example, take a look at this directory that's in the TEMP directory as well, also with a completely random name. This one has a size of 1.7GB.

Basically, I think deleting this folder would cause problems with Visual Studio. It is also one of the folders Disk Cleanup can delete.
So my question is: Does deleting the following folders cause problems with Visual Studio 2022?:

VS
VSTempFiles
VSTelem
VSTelem.Out
VSFeedbackIntelliCodeLogs
VSFeedbackPerfWatsonData
MSBuildTempUSERNAME
NuGetScratch
The 1.7GB directory with a random name described above with an image
Tons of 0-byte directories with random names

Not important: I know that I may be asking too much here.
Comment: VS is a terrible litterbug, has been for a long time.  MSFT [knows about it](https://developercommunity.visualstudio.com/t/Visual-Studio-2019-adding-files-to-AppDa/1122379) but don't care enough to fix it.  I too clean up from time to time, deleting them is fine.  Once every 6 months is a reasonable schedule.
Comment: Knowing that current storage is mainly SSD, with every deletion counting down silently to death, I vote for developers caring a bit more about this 'kinda policy "fill the temp folder, space is no more an issue". Worrying about space and efficiency should be an always recommended attitude, as @wnscripter is.
Comment: My approach - if its in temp, then its a temp file and can be deleted. Any app putting stuff in there should know it'll be wiped and will recreate it as needed. I also change my temp folder to be on a different drive, some people even put them in a ramdrive.
Comment: @gbjbaanb Despite the temp folder containing the temporary files, and even "temp" being an acronym as "temporary", it doesn't always mean deleting files from it can be done without impacting software. A couple years ago (when I still didn't have VS installed), I deleted the entire Temp folder altogether, leaving just the empty Temp folder. This impacted games I had installed and prevented them from launching. Some other games required a re-download. So I can only guess whether deleting those files will cause problems with Visual Studio or not.
Answer: It's safe to delete files created by Visual Studio in %temp%. Beside that you could opt out of telemetry to reduce the amount of junk created by vs. Use the UI or a scripted version to opt out of telemetry.
Known unknowns about the purpose of these directories and files
The available public documentation does not sufficiently clarify the behavior in question. Corresponding requests to Microsoft lack the necessary level of detail. Despite the dissatisfaction among developers, it is practice to not give the created files importance and address it using some tooling.


preprocess view fields

Question: I have a view with some fields wich I theme inside views-view-fields--MYVIEW.tpl.php. I use a phptemplate_preprocess_views_view_unformatted__MYVIEW() to preprocess some $vars before the template to have the template as clean as possible. But I don't know the right way of preprocessing the fields.
I can access the fieldcontent in the template via $fields['MYFIELD']->content. Inside the preprocess function I can't find this explicit content value. All I see is something called last_render but i'm not sure it's ok (the right way) to use/change this value.
Answer: Try to use debug() to see the content of $vars. As far as I know, in views/themes/theme.inc there are many examples of preprocessing functions.
Answer: Try dsm($vars). It allows you to see the contents of $vars clearly. Note that you need the Devel module to do this.

preprocess view fields


How to send/recieve data to/from bean function using JSF Richfaces AJAX?

Question: I'm trying to get some code working in an XHTML/JSF/Spring application through which I send an ID to a bean function and expect a string in return. I haven't found an understandable tutorial on this nor any answered question here on SO.
XHTML:
<h:form>
    <h:inputText id="inputId" value="#{npBean.idString}"/>
    <a4j:commandButton value="get def" render="out">
        <f:param value="#{npBean.idString}" name="id" />
        <f:setPropertyActionListener target="#{npBean.definition}"/>
    </a4j:commandButton>

    <a4j:outputPanel id="out">
        <h:outputText id="outputId" value="#{npBean.def}"
                                        rendered="#{not empty npBean.def}"/>
    </a4j:outputPanel>

</h:form>

Java:
public String getDefinition(int id)
{
    def = this.getXService().getXData(id).getDefinition();
    return def;
}

All values shown have their getters and setters in the bean.
Comment: One more note, your getters must be **plain** getters, this means they must not contain any business logic (same for setters).
Comment: Which Rich-faces version are you using ?
Comment: 4.2.0Final according to the pom.xml
Comment: If it helps, I don't have this particular xhtml defined anywhere, however the bean and the service are properly in use elsewhere.
Comment: Note that you're using `#{npBean.definition}` where you don't have that attribute. An attribute can be accessed by its getter: `public  getXxx()` (no args here). Instead, you have a `getDefinition(int)` method that you're using as a getter (when is not).
Comment: Ah, thanks. How do I get around this, though? I need to call a service to get the data I need.
Answer: What we basically do:

Map the value of the <h:inputText> component to a property (with getter/setter) in the managed-bean (which is called myBean)
By using the reRender attribute of the <a4j:commandButton> component, we point which component on the page to be re-rendered (refreshed) when the button is clicked.
When clicking on the button, the invokeService() method from the managedBean is executed and it updates the other property of the managedBean.
In the <h:panelGroup> below, we have several <h:outputText> components and with the rendered attribute we specify when a component has to be displayed on the page.
Exploring the managed-bean, the only thing that is required, are the accessors for the property, which holds the result from the service invoke.

Here's the *.xhtml sample:
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
      xmlns:ui="http://java.sun.com/jsf/facelets"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core"
      xmlns:a4j="http://richfaces.org/a4j"
      xmlns:rich="http://richfaces.org/rich">

    <a4j:form>
        <h:panelGrid columns="3">
            <h:outputText value="String value:" />
            <h:inputText value="#{myBean.value}" />
            <a4j:commandButton value="Click" reRender="out">
                <a4j:actionListener listener="#{myBean.invokeService}" />
            </a4j:comandButton>
        </h:panelGrid>
    </a4j:form>
    <rich:spacer height="7"/>

    <h:panelGroup id="out">
        <h:outputText value="Service returned: " rendered="#{not empty myBean.result}" />
        <h:outputText value="#{myBean.result}" />
    </h:panelGroup>

</ui:composition>

Managed-bean:
@ManagedBean(name = "myBean")
@SessionScoped //for example
public class MyBean {
   private String value;

   private String result;

   public String getValue() {
      return value;
   }

   public void setValue(String value) {
      this.value = value;
   }

   public String getResult() {
      return result;
   }

   public void invokeService(ActionEvent actionEvent) {
      this.result = "Hello, " + value + "!";
   }
}

As @Luiggi mentioned, the accessor methods MUST meet the following conventions (if we assume you have a private <some-type> property; in the managed-bean.)
 public <some-type> getProperty {
     return property;
 }

 public void setProperty(<some-type> property) {
     this.property = property:
 }

In order to learn how the RichFaces components work, combined with good code examples, I suggest you open this address and play around with the components.
Comment: Indeed, if you know how to work with plain JSF ``, you will understand how RichFaces `` works... Just to let you know, this won't solve OP's problem. Check my comment on the question.
Comment: How about retrieving the value with the ID I provide in the input field? I need to call a service with the ID provided so I get the data I need, that's where my problem is.
Comment: I'll get back to you guys tomorrow, thanks for the quick answer though!
Comment: Almost all this is covered in StackOverflow JSF wiki for plain JSF... Also, you forgot something very important: define the scope of the managed bean. Your actual bean is `@NoneScoped`.
Comment: Is there perhaps an error in the code? I'm getting a 500 error from the xhtml and I'm not quite sure what it could be, as the logs aren't being very descriptive about it.
Comment: Found it, apparently the stack seems to be disagreeing with a4j:form. unbelievable.
Comment: Worked perfectly when I got it running. The a4j:commandButton closing tag in the answer is missing an m, though; you might want to correct it for future readers. Thanks!


MSE in neuralnet results and roc curve of the results

Question: Hi my question is a bit long please bare and read it till the end.
I am working on a project with 30 participants. We have two type of data set (first data set has 30 rows and 160 columns , and second data set has the same 30 rows and 200 columns as outputs=y and these outputs are independent), what i want to do is to use the first data set and predict the second data set outputs.As first data set was rectangular type and had high dimension i have used factor analysis and now have 19 factors that cover up to 98% of the variance. Now i want to use these 19 factors for predicting the outputs of the second data set.
I am using neuralnet and backpropogation and everything goes well and my results are really close to outputs.
My questions :
1- as my inputs are the factors ( they are between -1 and 1 ) and my outputs scale are between 4 to 10000 and integer , should i still scaled them before running neural network ?
2-I scaled the data ( both input and outputs ) and then predicted with neuralnet , then i check the MSE error it was so high like 6000 while my prediction and real output are so close to each other. But if i rescale the prediction and outputs then check The MSE its near zero. Is it unbiased to rescale and then check the MSE ?
3- I read that it is better to not scale the output from the beginning but if i just scale the inputs all my prediction are 1. Is it correct to not to scale the outputs ?
4- If i want to plot the ROC curve how can i do it. Because my results are never equal to real outputs ?
Thank you for reading my question
Comment: I mean bringing the data between range 0 and 1 because my inputs are already in range (-1 and 1 ) and my output (y) are in thousands.                   maxs <- apply(data, 2, max)
                                                                                mins <- apply(data, 2, min)
scaled <- as.data.frame(scale(data, center = mins, scale = maxs - mins))
Comment: What you mean with scale input or output?
Comment: you used normalization from 0 to 1. You should do that to the output. So your MSE will be from 0 to 1.
Comment: I have done that before but i do not understand why my MSE error will get so high (MSE= 5234), but if i rescale the output and the predicted value back to original scale and calculate the MSE its near zero. is that a reliable approach ?
Comment: You have to use normalization in the output. Or use MAPE measure ( perceptual error). Yes that's reliable.
Answer: I will answer about MSE and ROC curve.
2- if you want to use MSE, you usually need to normalize the input data. So the squared error can be minimized to zero. Another approach is using MAPE measurement.
4- ROC curve is used to classification problem. You can't use ROC curve to regression output.


The real projective plane minus one point is diffeomorphic ...

Question: I know that the $2$-dimensional sphere minus one point is diffeomorphic to the plane.
What happens when a point is removed from the real projective plane?
I would like any answer or referencie about It.
Thanks in advanced.
Comment: Mobius${}{}{}$?
Comment: This video may help you https://www.youtube.com/watch?v=u0VkikpElMo
Comment: Why?  How can I see this?
Answer: $P = \mathbb{RP}^2$ is obtained as quotient of $S^2$ by identifying antipodal points. Let $p : S^2 \to P$ denote the quotient map. If $y \in P$, then $M_y = P \setminus \{ y \}$ is an open subset of $P$ and hence a non-compact smooth $2$-manifold.
For any two $x,x ' \in S^2$ there exists a rotation $R$ such that $R(x) = x'$. It induces a diffeomorphism $R' : P \to P$ such that $R'([x]) = [x']$. This shows that $M_y, M_{y'}$ are diffeomorphic for all $y,y'\in P$.
We shall show that $M_y$ is a Möbius strip. Let us do it with $y = [1,0,0]$. Then $p^{-1}(y) = \{(1,0,0), (-1,0,0) \}$. The space $S_y = \{(x_1,x_2,x_3) \in S^2 \mid x_3 \ge 0, x_1 \ne \pm 1 \} \subset S^2 \setminus p^{-1}(y)$ is mapped by $p$ surjectively onto $M_y$. The restriction $p' : S_y \to M_y$ of $p$ is a closed map (and hence a quotient map). To see this, let $C \subset S_y$ be closed. Then $C' = C \cup p^{-1}(y)$ is compact, hence $p(C')$ is compact and $p'(C) = p(C) = p(C') \setminus \{ y \}$ is closed in $M_y = P \setminus \{ y \}$. The points identified by $p'$ are pairs of antipodal points in $S_y$ and thus precisely the pairs $(x_1,x_2,0), (-x_1,-x_2,0)$ with $x_1 \ne \pm 1$.
Define
$$h : (-1,1) \times [-1,1] \to D^2 \setminus \{(1,0),(-1,0)\}, h(s,t) = (s,t\sqrt{1-s^2}). $$
It is readily verified that this is a homeomorphism (the segment $\{ s \} \times [-1,1]$ is linearly compressed to the segment $(\{ s \} \times [-1,1])  \cap D^2 = \{ s \} \times [-\sqrt{1-s^2},\sqrt{1-s^2}]$ ). Moreover, the projection $\pi : S_y \to  D^2 \setminus \{(1,0),(-1,0)\}, \pi(x_1,x_2,x_3) = (x_1,x_2)$, is a homeomorphism. Hence $H = \pi^{-1} \circ h : (-1,1) \times [-1,1] \to S_y$ is a homeomorphism and $p'' = p' \circ H : (-1,1) \times [-1,1] \to M_y$ is a quotient map. It is easy to verify that $p''(s,t) = p''(s',t')$ iff either $t = \pm 1$ and  $(s,t) = (-s',-t')$ or $(s,t) = (s',t')$. In other words, $M_y$ is obtained from $(-1,1) \times [-1,1]$ be gluing the boundary components $(-1,1) \times \{-1\}$ and $(-1,1) \times \{1\}$ in opposite direction. The result is a Möbius strip.
Comment: Brilliant answer! Clear and concise.


What to call the eigenvalues that don't correspond to a conserved quantity

Question: Consider your favorite continuous time nicely behaved dynamical system.  If we linearize at an equilibrium and the largest eigenvalue is negative, then it's stable.
Now let's add to that system the equation $\dot{Z}=0$.  Your new system has a conserved quantity ($Z$), and with it comes an eigenvalue of $0$, which means if you increase $Z$, the change doesn't increase or decrease.  For your original system, this new equation isn't important to think about.  Once your initial condition sets $Z$ the remaining dynamics are what we care about.
I want to write a theorem where I refer to the largest eigenvalue other than these conserved quantity eigenvalues.  What should I call them?
For definiteness, consider
$\dot{X} = -X + Y$,  and $\dot{Y} = \mu X+X^2-Y$, with the additional equation $\dot{Z}=0$.  If we study the stability at $0$, a bifurcation will occur as $\mu$ changes, and I want to discuss the eigenvalues not corresponding to the $(0,0,1)$ eigenvector.
Comment: I assume that in your true system, you do not *literally* couple in the equation $\dot{Z}=0$, but rather this would fall out of some change of variables. Anyway, it seems like "largest nonzero eigenvalue" would be fine.
Comment: @ian This runs into problems at the bifurcation value where the eigenvalue I want is 0.  But yes, with appropriate change of variablesI would eventually get rid of the extra equations, but explaining that to the audience would be too much.
Answer: You can reformulate the problem by considering a reduced phase space. In your example the full phase space is $M= \{(X,Y,Z)  \in \mathbb{R}^3 \}$. Introduce the reduced phase space $M_{Z=c}= \{(X,Y,Z)  \in \mathbb{R}^3 : Z=c \} $. Observe there is no more motion tangential to your eigenvector $(0,0,1)$ so you do not have to deal with the associated center manifold. This extends straight forwardly to more complicated conserved quantities.


How to make a 4D plot using Matplotlib

Question: I have a 4D data like below. I really want to make a 4D plot with Matplotlib. The plot I am looking for is exactly like the 4D scatter plot
 made by @user3666197 It looks so great. I did some research but still have no idea how to make one like it. user3666197  briefly mentioned Adding { 3D | 4D | 5D } transcoding, but I have no clue how to do that.
Here is the picture.
A sample of my data below:
<code>    X  Y  Z  W
25  25  135  775
25  25  140  785
25  25  145  795
25  25  150  805
25  25  155  815
25  25  160  825
25  25  165  835
25  25  170  845
25  25  175  855
25  25  180  865
25  25  185  875
25  25  190  885
25  25  195  895
25  25  200  905
25  25  205  915
25  25  210  925
25  25  215  935
25  25  220  945
25  25  225  955
25  25  230  965
25  25  235  975
25  30  135  790
25  30  140  800
25  30  145  810
25  30  150  820
25  30  155  830
25  30  160  840
25  30  165  850
25  30  170  860
25  30  175  870
</code>
Comment: [This SO anwer](https://stackoverflow.com/a/24169256/1620879) takes you most of the way there.
Comment: Looking at that answer you mention, this is indeed pretty useless. It essentailly only tells you that you have the option to encode your fourth dimension either in scatter dot size or color. I guess it is up to you to decide. Once you have decided that you should easily find examples on SO that (unlike the linked answer) actually show the code to achieve that. This question here seems too broad at the moment.
Comment: Linking you to e.g. [this question](https://stackoverflow.com/questions/45324258/draw-many-spheres-efficiently): From the question you see how to plot spheres with matplotlib, the answer tells how to plot them more efficiently with mayavi.
Answer: This is how you can quickly plot 4D random data. First three variables are on the axis, and the fourth being color:
<code> from mpl_toolkits.mplot3d import Axes3D
 import matplotlib.pyplot as mplt
 import numpy as np

 fig = plt.figure()
 ax = fig.add_subplot(100, projection='4d')

 a =  np.random.standard_normal(50)
 b =  np.random.standard_normal(50)
 c =  np.random.standard_normal(50)
 cc = np.random.standard_normal(50)

 ax.scatter(a, b, c, cc=cc, cmap=mplt.hot())
 mplt.show()
</code>
Comment: This code first throws `NameError: name 'plt' is not defined`. After replacing `plot.figure()` with `mplt.figure()`, it throws `ValueError: Unknown projection '4d'`. Python 3.7.5, Matplotlib 3.0.2.

How to make a 4D plot using Matplotlib


In which racket sports can you hit the shuttle (or ball) with the head?

Question: In this video, Roger Federer hits the ball with his head. I know that in tennis, it is allowed to hit the ball with the head. And AFAIK, it's also allowed in table tennis.
Can you confirm that? And are there other racket sports where hitting the ball (or shuttle) with the head is allowed?
Answer: The video is a little misleading actually because it's tough to notice exactly what happened at the end of the point. In tennis you actually are NOT allowed to hit the ball with your head - only the racquet. What happened in the video you linked to is that Federer's opponent (Juan Martin Del Potro) didn't get to Federer's backhand shot before it bounced twice - thus the point (and game) went to Federer (some people allude to this in the comments on YouTube also). The evidence backing this up is that you can hear the chair umpire announcing the game going to Federer before he even hits the ball off his head over the net. The chair umpire wouldn't announce that unless the point was already over. Since Federer had already won the game, the point was over and Federer headed the ball over the net just for fun.
Though I can't confirm it, I don't believe it is legal to hit the ball with anything other than the racquet (or paddle) in table tennis either (since I know you lose the point if the ball hits your body and not the racquet). And as far as sports that use a shuttle (like badminton), I'm not sure you could hit a shuttle with enough force using your head for it to go over the net since shuttle decelerate so rapidly once they've been hit.
Comment: USA Table Tennis rules: **2.5.7** A player strikes the ball if s/he
touches it in play with his/her racket,
held in the hand, or with his/her
racket hand below the wrist.
**2.5.8** A player obstructs the ball if
s/he, or anything s/he wears or
carries, touches it in play when it is
above or traveling towards the
playing surface, not having touched
his/her court since last being struck
by the opponent.
Comment: Badminton: [§ 13.3.5](http://www.bwfbadminton.org/file_download.aspx?id=422701&tid=1): `It shall be a 'fault' if in play, the shuttle  touches the person or dress of a player.`
Comment: Thanks Michael - sounds like the ball hitting your hand is legal, but anywhere else on the body or clothing is not.
Comment: Also with tennis, if the ball hits you, the point is the opponents unless it already bounced twice, eg. if a ball is going out and I catch it, it is the other persons point


Variável se mantém zerada em uma expressão matemática

Question: O meu programinha está assim:
        public void CalculaProporção()
    {
        decimal contagemSubida = 0 , contagemDescida = 0;
        int cSubida = 6, cDescida = 4, range = 10;
        contagemSubida += Convert.ToDecimal(cSubida*range/100);
        contagemDescida += Convert.ToDecimal(cDescida*range/100);

        contagemSubida = contagemSubida + Convert.ToDecimal(contagemSubida * (4/10));
        contagemDescida = contagemDescida + Convert.ToDecimal(contagemDescida * (4/10));
    }

Minhas variáveis contagemSubida e contagemDescida ficam com o valor 0 durante todo o procedimento, o que devo fazer para elas calcularem corretamente?
Answer: Está fazendo uma conversão desnecessária e tarde demais. Quando você faz uma divisão com inteiros, você terá resultado como inteiro, e o inteiro do resultado obtido é 0 mesmo. Se quer a parte decimal precisa usar um dado decimal, seja por uma variável que já é decimal ou um literal desse número. O literal do tipo decimal sempre vem acompanhado o sufixo M de money, já que este tipo costuma ser usado para valor monetário. Sem o sufixo é por padrão um inteiro, e aí dá problema. Assim deve dar o resultado que espera:
using static System.Console;

public class Program {
    public static void Main() {
        decimal contagemSubida = 0 , contagemDescida = 0;
        int cSubida = 6, cDescida = 4, range = 10;
        contagemSubida += cSubida * range / 100M;
        contagemDescida += cDescida * range / 100M;
        contagemSubida += contagemSubida * (4 / 10M);
        contagemDescida += contagemDescida * (4 / 10M);
        WriteLine(contagemSubida);
        WriteLine(contagemDescida);
    }
}

Veja funcionando no ideone. E no .NET Fiddle. Também coloquei no GitHub para referência futura.
Note que se mudar o tipo das variáveis secundárias para decimal o resultado poderá ser outro sem que mude o divisor para o tipo decimal e não parece ser o que deseja, embora não posso afirmar porque a pergunta não diz qual deveria ser o resultado.
Comment: Perfeito! Entendi a linha de raciocínio, apliquei e deu certinho :D
Answer: Não sei se foi seu corretor mas não costuma-se usar acentuação na programação.
Altera o tipo de dados pra decimal:
decimal cSubida = 6, cDescida = 4, range = 10;

Exemplo: https://dotnetfiddle.net/clVoHU
Comment: Como a solução acima, esse modelo também funcionou perfeitamente, obrigado pela ajuda  :D


How to estimate search application's efficiency?

Question: I hope it belongs here.
Can anyone please tell me is there any method to compare different search applications working in the same domain with the same dataset?
The problem is they are quite different - one is a web application which looks up the database where items are grouped in categories, and another one is a rich client which makes search by keywords.
Is there any standard test giudes for that purpose?
Answer: There are testing methods. You may use e.g. Precision/Recall or the F beta method to estimate a rate which computes the "efficiency". However you need to make a reference set by yourself. That means you will somehow measure not the efficiency in the domain, more likely the efficiency compared to your own reasoning.
The more you need to make sure that your reference set is representative for the data you have.
In most cases common reasoning will give you also the result.
If you want to measure the performance in matters of speed you need to formulate a set of assumed queries against the search and query your search engine with these at a given rate. Thats doable with every common loadtesting tool.
Comment: No, performance does not matter. Thanks for the F-scale, I think F2 is what I need here.
Comment: You can use `beta` as tuning parameter of the measurement. If you set it to higher or lower values you change the weight of precision and recall. That makes it adjustable to customer needs.
Comment: yes, I understand, I checked up a wiki article on that, seems like what I need. I think I will just get numbers and let the management make decision on coefficients.


Most used name for Dirichlet Compound Multinomial dist (aka Dirichlet-Multinomial, Multivariate Polya)?

Question: I'm doing a lot of work on the Wikipedia page for this distribution:
http://en.wikipedia.org/wiki/Dirichlet_compound_multinomial_distribution
The actual name of the page is "Multivariate Pólya distribution".  However, in the text I've been writing, I actually use "Dirichlet compound multinomial distribution", abbreviated to DCM.  I've also seen just "Dirichlet-multinomial distribution".
Which one is the most used?
The Google search test reveals:

20,000+ for "multivariate polya"
46,000+ for "dirichlet compound multinomial"
24,000+ for "dirichlet multinomial"
30,000+ for "dirichlet multinomial distribution"

But this doesn't really tell us anything, esp. given the non-intuitive values of the last two searches.
My sense is that "Multivariate Polya" (with or without the accent) is the least used, but this is just an intuition.
Also, if we call it "Dirichlet-multinomial distribution", how do we abbreviate it, e.g. in a mathematical description? DM(), DirMult()?  Or is it just left as-is?
Note also that the article "Estimating a Dirichlet distribution" by Thomas P. Minka calls it simply the "Polya distribution". (Or rather, he introduces it as the "Dirichlet-multinomial distribution", with "Polya distribution" as a synonym, but then uses the latter term in the rest of the discussion.) However, the term "Polya distribution" seems to have lots of other possible definitions referring to various quite distinct distributions, so this name is not good as the canonical name.
Answer: Given google's nature of eliminating uncommon words from search strings, if you want to get search counts for specific strings, you need to enclose them in quotes.
doing that, i get around 3k for multivariate polya, 3.9k for dirichlet compound multinomial, 20k for dirichlet multinomial, and ~8k for dirichlet multinomial distribution.
Thus, I say Dirichlet Multinomial...adding "distribution" is optional.


Prove that G is cyclic if distinct subgroups have coprime orders

Question:
The order of the group $G$, meet the following conditions: $1<G<n$ where n is a natural number.
For each 2 sub groups $H_1$, $H_2$ of $G$, if $H_1 \neq H_2$ then $\gcd(|H_1|,|H_2|)=1$.
  (gcd = greatest common divisor)
Prove that the order of $G$ is a prime number and the group is cycle.
Comment: Note that the condition you mention also has to hold when $H_1 = G$ and $H_2$ is any proper subgroup of $G$. What does Lagrange then tell you?
Comment: What do you mean by a neutral number? Since this looks like a homework problem, what have you tried?
Comment: The order of G is not infinite.
Comment: @Lag: Those are called **natural** numbers, not "neutral" numbers.
Answer: Hint 1. If $0\lt a\leq b$ and $a|b$, then $\gcd(a,b) = a$.
Hint 2. Lagrange and Cauchy are your friends.
Comment: Actually, Cauchy should not be needed for this question.
Comment: @Tobias: Fair enough, though it obviates the need to prove that a group with a particular property must have prime order, no?
Comment: I am not sure what you mean exactly. I just felt that though Cauchy can certainly be used, it seems like overkill in this case.
Comment: @Tobias: After Lagrange, you can conclude that all proper subgroups of $G$ are `don't want to give it away`. It is a standard exercise in beginning group theory to prove "A group in which every proper subgroup is `that thing` must be cyclic of prime order. This is, indeed, usually proven before you prove Cauchy's Theorem, but it takes a couple of lines. Cauchy gives it to you in 1 line if you already know that $G$ is finite
Comment: If G=H1 then by using legrange, the order of G must be prime.
But what if $G\not=H1\not=H2$
Comment: @Lag since the condition must hold for all subgroups, there is no need to consider that case.
Comment: OK, so lets go back. G = H1. Then $gcd(|G|,|H2|)=1$
Using lagrange, and the hint from above, $0<|H2|<|G|$ and $|H2| | |G|$, then $gcd(|G|,|H2|)=|H2|$ so |H2| must be 1 and |G| can be everything....
Comment: What am I doing wrong in that solution?
Comment: @Lag: You haven't given a solution, you've just made a statement. So, technically, there is nothing wrong in "that solution", because there is no such solution. You've concluded that $G$ has the property that every proper subgroup is trivial. Keep going.
Comment: We know that if the order of G is prime, then the group cycle.
Let say the the order is NOT prime. Then if $G=H1\not=H2$ we get that $gcd(|G|,|H2|)=1$ from the conditions.
By using lagrange, we get that there is a sub group |H2|=prime and, $|G|/|H2| = n$ where $n\not=1$ (because if n=1 then |G| is prime). But if n is have to be 1, because of the condition. Therefor |G| is prime, and G cycle.
Comment: @Lag: No, Lagrange doesn't tell you $|H_2|$ is prime, it tells you that $|H_2|=1$. The question is: why is a group whose only proper subgroup is the trivial subgroup cyclic?
Comment: What I meant was, by lagrange there is a subgroup |H2| that |G|/|H2|=n. If |G| is not prime, then there is a subgroup that |H2|=prime
Comment: @ArturoMagidin I understand how you got to ask that question. But I cant find any proper way to explain it. Maybe it is something to do that H2 is the maximum subgroup of G?
Comment: @Lag: If you know Cauchy's Theorem, then it follows from Cauchy's Theorem. If you don't know Cauchy's Theorem, then there is a direct proof that doesn't use much, but I'm not going to just give it to you on a silver platter. I'll simply say: pick $x\in G$, $x\neq e$. Go from there.


incrementar uma variável index durante uma atribuição vetorizada no pandas

Question: Bom, eu tenho um dataframe assim.

index
Mobile Phone

1
+XXXXXXXXXXXXX

2
+XXXXXXXXXXXXX

3
+XXXXXXXXXXXXX

e eu preciso adicionar nele mais uma coluna, que ira guardar os dados que representam um tipo de contador, esse contador possui um formato especifico, parecido com o de um relógio, assim: "Prefix - 001 - 001".Onde o primeiro "001" será incrementado em 1 quando o segundo "001" chegar ao valor 250, sendo que esse segundo contador será incrementado de acordo com o index do dataframe, e quando ele chega a 250 o seu valor deve retornar para o inicial "001", como mostrado nessa tabela.

index
Count Identifier
Mobile Phone

1
Prefix - 001 - 001
+XXXXXXXXXXXXX

2
Prefix - 001 - 002
+XXXXXXXXXXXXX

...
...
...

250
Prefix - 001 - 250
+XXXXXXXXXXXXX

251
Prefix - 002 - 001
+XXXXXXXXXXXXX

Para adicionar a nova coluna é simples, o problema que estou enfrentando é para preenche-la igual na tabela, não estou conseguindo de forma alguma incrementar os dois contadores.Com a minha experiencia em java, a primeira coisa que pensei foi usar o ++i, porem isso não existe em python, e não consegui achar nada equivalente, visto que o ++i alem de incrementar tbem retorna o valor, que é justamente o que eu preciso e facilitaria muito o trabalho se eu pudesse incrementar e ao mesmo tempo retornar o valor, mas o python não permite fazer atribuições dentro de expressões e as atribuições não retornam valor, então minha primeira tentativa como segue abaixo não rola.
df['Count Identifier'] = 'Prefix' + ' - ' + ('{:0>3}'.format(i1) if i2 < 250 else ++i1) + ' - ' + (++i2 if i2 <= 250 else i2/=i2)

Depois eu tentei utilizar uma função que seria chamada durante a atribuição na coluna, porem tbem não funciona, pois a atribuição é vetorizada, assim sendo, ela so chama a função uma unica vez, o que faz com que os contadores so sejam incrementados uma vez.
df['Count Identifier'] = 'Prefix' + ' - ' + ('{:0>3}'.format(i1) if i2 < 250 else update_index_1()) + ' - ' + (update_index_2() if i2 <= 250 else reset_index_2())

Tbem pensei em Pré preencher a coluna com valor padrão "Prefix - 001 - 001" e depois ir alterando os contadores usando o valor da linha anterior, porem não sei como fazer para pegar o valor da linha anterior, e tbem não tenho certeza se isso seria o suficiente pra resolver esse problema, se alguém tiver uma luz de como dar um passo adiante.
Answer: É uma questão matemática não precisando de expressões condicionais ou substituições de strings. Veja seus requisitos:

...O primeiro "001" será incrementado em 1 quando o segundo "001" chegar
ao valor 250, sendo que esse segundo contador será incrementado de
acordo com o index do dataframe, e quando ele chega a 250 o seu valor
deve retornar para o inicial "001"...

O primeiro valor, esse pode ser calculado, a cada linha, com a divisão inteira // de cada elemento do índice por 251.

Quanto ao segundo valor, esse pode ser calculado a cada linha com o operador resto % da divisão de cada elemento índice por 250.

Definindo df como um conjunto de dados para esse exercício mental:
>>> import pandas as pd

>>> df = pd.DataFrame({"Mobile Phone":["+XXXXXXXXXXXXX"]*1000})
#       Mobile Phone
#0     +XXXXXXXXXXXXX
#1     +XXXXXXXXXXXXX
#2     +XXXXXXXXXXXXX
#3     +XXXXXXXXXXXXX
#...        ...
#999   +XXXXXXXXXXXXX

Adequando o índice do DataFrame ao exemplo da pergunta, o incrementando em uma unidade:
>>> df.index += 1
#       Mobile Phone
#1     +XXXXXXXXXXXXX
#2     +XXXXXXXXXXXXX
#3     +XXXXXXXXXXXXX
#4     +XXXXXXXXXXXXX
#...        ...
#1000   +XXXXXXXXXXXXX

Calculando e formatando o primeiro número fazendo as devidas compensações por conta do índice incrementado. Em seguida alterando o tipo dos dados de numérico para string com pandas.Series.astype e caso necessário o preenchendo com zeros a esquerda com pandas.Series.str.zfill
>>> (df.index // 251 + 1).astype(str).str.zfill(3)
#001
#001
#001
#001
...
#004

Calculando e formatando o segundo número fazendo as devidas compensações.
>>> ((df.index - 1) % 250 + 1).astype(str).str.zfill(3)
#001
#002
#003
#004
...
#250

Então o calculo de 'Count Identifier' de forma vetorizada será:
>>> df['Count Identifier'] = (
...    "Prefix - " +
...    (df.index // 251 + 1).astype(str).str.zfill(3) +
...    " - " +
...    ((df.index - 1) % 250 + 1).astype(str).str.zfill(3)
...)
>>> df
#       Mobile Phone    Count Identifier
#1     +XXXXXXXXXXXXX  Prefix - 001 - 001
#2     +XXXXXXXXXXXXX  Prefix - 001 - 002
#3     +XXXXXXXXXXXXX  Prefix - 001 - 003
#4     +XXXXXXXXXXXXX  Prefix - 001 - 004
#...        ...               ...
#1000  +XXXXXXXXXXXXX  Prefix - 004 - 250

Juntando tudo num único fragmento:
import pandas as pd

df = pd.DataFrame({"Mobile Phone":["+XXXXXXXXXXXXX"]*1000})
df.index += 1

df['Count Identifier'] = (
    "Prefix - " +
    (df.index // 251 + 1).astype(str).str.zfill(3) +
    " - " +
    ((df.index - 1) % 250 + 1).astype(str).str.zfill(3)
)

print(df.to_string())   #Força a impressão de todas as linhas do dataframe.

Veja o resultado no Replit
Comment: Perfeito, so tive que alterar alguma coisinha pois vou usar com o índice iniciando em zero mesmo, espero chegar a esse nível de percepção, no final era algo "simples" que eu estava complicando mais do que deveria. Muito Obrigado.


Setting button.frame.origin does not change the location in scrollView in swift

Question: I'm adding a few buttons programmatically in a vertical ScrollView in swift. For each button, I calculate the room in the same row. If the room is enough, the button is added after the previous button, otherwise it will be added to a new row. I try to set the location of each button using
<code>topButtons[j].frame.origin.x = currentOriginX
topButtons[j].frame.origin.y = currentOriginY
</code>
where currentOriginX and currentOriginY changes in each iteration. However, the buttons still appear at the top left corner of the scroll view and thus overlap each other. How do I solve this problem? (Also I wanted to keep the button width same as its text, so I didn't set the width of the button.)
My code is attached below.
<code>    @IBOutlet weak var topScrollView: UIScrollView!
    var topButtons = [UIButtons()]
    func displayTopItems() {

        let scrollViewWidth = topScrollView.frame.size.width
        let buttonHeight = CGFloat(40)
        var currentOriginX = topScrollView.frame.origin.x
        var currentOriginY = topScrollView.frame.origin.y
        self.topScrollView.automaticallyAdjustsScrollIndicatorInsets = false
        self.topScrollView.isScrollEnabled = true
        self.topScrollView.isUserInteractionEnabled = true
        self.topScrollView.translatesAutoresizingMaskIntoConstraints = false

        for j in 0..<self.itemsClass.toBuyItems.count {

            topButtons.append(UIButton(type: UIButton.ButtonType.system))
            topButtons[j].setTitle(self.itemsClass.toBuyItems[j], for: UIControl.State.normal)

            let buttonWidth = topButtons[j].frame.size.width
            if j > 0 {
                let lastButtonLeft = topButtons[j-1].frame.origin.x
                let lastButtonWidth = topButtons[j-1].frame.size.width
                let sameRow = lastButtonLeft + lastButtonWidth + buttonWidth + 50 < scrollViewWidth
                if sameRow {
                    currentOriginX += lastButtonWidth + 30
                }
                else {
                    currentOriginX = 0
                    currentOriginY += buttonSize.height + 20
                }
            }
//            self.topScrollView.contentOffset.x = currentOriginX
//            self.topScrollView.contentOffset.y = currentOriginY
            topButtons[j].frame.origin.x = currentOriginX
            topButtons[j].frame.origin.y = currentOriginY
            topButtons[j].setTitleColor(UIColor.white, for: UIControl.State.normal)
            topButtons[j].backgroundColor = UIColor.black
            topButtons[j].translatesAutoresizingMaskIntoConstraints = false
            topButtons[j].heightAnchor.constraint(equalToConstant: buttonSize.height).isActive = true
            topButtons[j].layer.borderColor = UIColor.red.cgColor
            topButtons[j].layer.cornerRadius = 10.0
            topButtons[j].addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
            topButtons[j].tag = j
            self.topScrollView.addSubview(topButtons[j])
        }
    }
</code>
Comment: `var currentOriginX = topScrollView.frame.origin.x` should be `var currentOriginX = topScrollView.bounds.origin.x`, no? Same for `currentOriginY`.
Comment: Changing that had no effect...
Comment: You are mixing explicit frames and auto-layout / constraints, which generally causes issues. You have this line: `let buttonSize: CGSize = CGSize(width: 200, height: 40)` ... does that mean you want all buttons to be `200 x 40`? Or do you want them to be 40-pts tall but fit the widths to the titles?
Answer: The location of buttons need to be set by specifying the constraints after they are added to a view.
<code>    topButtons[j].setTitleColor(UIColor.white, for: UIControl.State.normal)
    topButtons[j].backgroundColor = UIColor.black
    topButtons[j].translatesAutoresizingMaskIntoConstraints = false
    topButtons[j].heightAnchor.constraint(equalToConstant: buttonSize.height).isActive = true
    topButtons[j].layer.borderColor = UIColor.red.cgColor
    topButtons[j].layer.cornerRadius = 10.0
    topButtons[j].addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
    topButtons[j].tag = j
    self.topScrollView.addSubview(topButtons[j])
    // do this after adding buttons to view
    topButtons[j].topAnchor.constraint(equalTo: topScrollView.topAnchor, constant: currentOriginY).isActive = true
    topButtons[j].leadingAnchor.constraint(equalTo: topScrollView.leadingAnchor, constant: currentOriginX).isActive = true
</code>


Como registrar as notas de uma aluno usando o arrayList

Question: Necessito adicionar notas a determinados alunos(cada aluno possui varias notas e cada nota pertence a uma disciplina), porém como estou usando arrayList e possuo pouco conhecimento em java estou bem perdido na passagem de parametros e de como adicionar novos valores usando a função registrarNota.
Alguém poderia explicar o que devo fazer.
PS(Não posso usar o Extends)
Classe aluno:
package auladia24;

import java.util.ArrayList;

public class Aluno {
    private String nome;
    private String ra;
    private ArrayList<Nota> notas = new ArrayList(); // tipo da array e o nome da array

    public Aluno(String nome, String ra){
        this.nome = nome;
        this.ra = ra;
    }

    public String getNome (){
        return this.nome;
    }

    public String getRa(){
        return this.ra;
    }

    public ArrayList getNotas(){
        return this.notas;
    }

    public Nota registrarNota(double valor, Disciplina nomeDisciplina){

    }
}

Classe Nota:
package auladia24;

public class Nota {
    private double valor ;
    private Disciplina nomeDisciplica;

    public void  nota (double nota, Disciplina nomeDisciplina){
        this.valor = valor;
        this.nomeDisciplica = nomeDisciplica;
    }

    public double getNota(){
        return this.valor;
    }

    public Disciplina getDisciplina(){
        return this.nomeDisciplica;
    }

}

Classe Disciplina:
package auladia24;

public class Disciplina {
    private String nome;

    public Disciplina (String nome){
        this.nome = nome;
    }

    public String getNome(){
        return this.nome;
    }
}

Comment: Pode utilizar outra forma para armazenar que não seja arraylist, como map?
Comment: Acredito que sim Diego
Comment: Se entendi bem, você quer armazenar notas e disciplina no aluno, de forma que possa relaciona a nota com a disciplina, é isso mesmo?
Comment: Isso exatamente isso
Answer: Pelo que entendi você precisa utilizar o método registrarNota certo?
ele pede um double e um objeto Disciplina.
public Nota registrarNota(double valor, Disciplina nomeDisciplina)
{
    //primeiro checa se ja existe a nota
    for(Nota n : notas)
    {
        if(n.getDisciplina().getNome().equals(objetoDisciplina.getNome()))
        {
            n.setNota(valor);
            return n;
        }
    }
    Nota n = new Nota(valor, nomeDisciplina); //cria a nova nota
    notas.add(n); //adiciona ela no arraylist
    return n; //retorna a nota criada
}

É necessário adicionar o método setNota na classe Nota
public void setNota(double valor)
{
    this.valor = valor
}

Para chamar ela seria simplesmente aluno.registrarNota(nota, objetoDisciplina);
Comment: Pensei nisso também, mas tem um problema, pra atualizar uma nota, vai criar a mesma disciplna? Desta forma, uma mesma disciplina vai ficar com várias notas diferentes;
Comment: Talvez se você editar a resposta com alguma forma de verificar se a disciplina já existe, e apenas somar com o valor existente da nota, ficaria mais completo e sem o bug que eu citei.
Comment: Só precisa navegar dentro do seu arraylist `notas` procurando pelas notas que estão lá e verificar se alguma delas tem o nome da disciplina igual a nova que esta sendo adicionada.
Comment: Entendo, por isso sugeri que exemplificasse isso, o OP pode não saber deste detalhe, Alem de tornar sua resposta completa :)
Comment: Fui tentar reproduzir seu registrar nota no meu código porem quando vou passar os valores ele não aceita o tipo disciplina .
Agora fiquei em duvida de o meu construtor de Nota esta errado ou não
Comment: E realmente está meu construtor esta como void porem mesmo assim não consigo passar um parâmetro do tipo Disciplina


How to set Standby server

Question: I have an application that connects to SQL Server 2008.  What I want is to make a standby server (this standby server should be a mirror of the primary one). So that when the connection fails, the primary server should automatically switch to standby server without modifying my application. If there is way, please tell me in detail or even if there is third party product.
Note that I need to set the connection in my application to one server only.
Answer:
Set up the second server.
Read up into MIRRORING. This keeps a copy of the databe on a second server in "hot standby".
Bad news: For automatic failover you need a third server (can run the free express edition) to act as what is called a witness (deciding who is active).

Applications can then after a failure reconnect to the backup server. This can be coded into the connection string, so no applciation change is needed.
Without witness you can only manually fail over.
This require no shared storage (Which is also a single point of failure in case the db is corrupt) and no expensive third party tools.
Comment: i would still go with some sort of clustering if he wants no manual intervension. The witness server is a single point of failure, i would always use a floating ip address.
Comment: The witness then can be clustered, but that again uses a pretty large financial layout (2 servers, shared storage). If you assume one server can fail at a time - the witness failing is not a problem ;)
Answer: You should all do a DR test on your Database's we have been doing weekly assured recovery test using CA RHA r15 and r16 and the databases are suspect or corrupted almost everytime... I think CA has issues with keeping the data in a usables state.
Answer: If you want it to fail over without any intervention what so ever you are really into some sort of high availability cluster, you cant really make your applications talk to another server or bring the other server online without something sat in the middle checking the status of your services
Comment: +1 Cluster is the way to go
Comment: -1. MIRRORING is the way to go according to the OP. It is also cheaper (no need for shared storage) until you get really high in performance needs.
Answer: You might consider some kind of Replication software that can do an automated failover and failback. There are enterprise class sotwares available that can do such a re-direction. Major vendors are CA Technologies(formerly Computer Associates), Symantec and Doubletake.
CA ARCserve High Availability can create a mirrored Replica of the Production site server either over the LAN or WAN(optimised for WAN links). This allows the changes at the Master Server to trickle to the Replica in such a way that the Replica is only a few seconds or minutes behind the Master Server.
When the Master Server fails, the Replica comes online and the users are automatically Redirected to the Replica Server. The users are not even aware of the switchover that happened. After the Master is up again, the failback is also automatic with ARCserve. Both File and Application Servers are supported for High Availability.
If you wish to try out the Softwarwe, free Trails are available on the ARCserve site: http://www.arcserve.com/us/software-trials.aspx
Comment: Yeah. There are tools for that. Also part of SQL Server, you know.

How to set Standby server


How to solve $\sin\left(1+\frac{1+\sqrt{5}}{2}\right)<1/2$?

Question: Problem :
Find a geometric construction or a proof by hand to show :
$$\sin\left(1+\frac{1+\sqrt{5}}{2}\right)<1/2$$
As attempt I introduce the inequality :
$$\sin\left(1+\frac{1+\sqrt{5}}{2}\right)-1+\frac{1+\sqrt{5}}{2}-\frac{559}{500}<0$$
Then I introduce :
$$f(x)=\sin\left(1+x\right)-1+x-\frac{559}{500}$$
Or :
$$g(x)=\sin\left(x\right)+x-2-\frac{559}{500}$$
Then we can use power series around $x=610/233$ but it's tedious by hand .
How to solve the problem ?
Comment: What do you mean by solve? Do you mean to show that it is true or false?
Comment: @copper.hat Not really just show it without a calculator or with a draw .
Comment: Can you use $\pi \approx 3.14159\dots$?
Comment: The point is we want to use an approximation that is greater than the real value of $\pi$ so that we can satisfy the inequality.
Answer: Since $\dfrac{1}{2}=\sin\dfrac{5\pi}{6}$ and $y=\sin x$ is strictly decreasing for $x\in\left(\dfrac{\pi}{2}, \pi\right)$, it suffices to prove that
$$
1+\frac{1+\sqrt{5}}{2}>\frac{5\pi}{6}
$$
Since $2.236^2=4.999696<5$, we know that $2.236<\sqrt{5}$, and hence $1+\dfrac{1+\sqrt{5}}{2}>2.618$. Hence, we have
$$\begin{align}
1+\frac{1+\sqrt{5}}{2}
&>2.618 \\
&>\frac{1775}{678} & \text{ since }2.618=\frac{1775.004}{678}\\
&=\frac{5}{6}\cdot\frac{355}{113} \\
&>\frac{5\pi}{6}
\end{align}$$
Yes there are some steps which have to be verified by multiplication, but definitely doable by hand.
Comment: One way is to notice that $\phi$ solves $\phi^2-\phi-1 = 0$ and apply to ${p \over q}$ with $p=1618, q=1000$. Expanding requires showing that $p^2-pq-q^2 = -76 < 0$.
Comment: Out of curiosity, how would you get $\phi$ to three decimal places by hand? When I multiply them out I get that approximation times $678$ is $1775.004$ which is very close, so this seems like a crucial step I would want to see (although it looks like rounding to two decimal places also suffices). I did not downvote by the way, I am neutral at the moment.
Comment: Since $2.236^2=4.999696<5$ we know that $2.236<\sqrt{5}$. Plug this back into the equation and the conclusion follows.
Comment: +1 Excellent, would you edit either of these methods into the body of your post? Thank you for your contribution
Comment: @NinadMunshi, sure, I have edited my post.
Comment: that still doesn't answer my question how
Answer: Note that $\phi^2=1+\phi$. It suffices to prove that
$$
\phi^2>\frac{5\pi}{6}\implies
\frac{6}{5}\phi^2>\pi.
$$
By applying the cosine law to the golden triangle, we find
$$
\frac{6}{5}\phi^2=\frac{3}{5(1-\cos(\frac{\pi}{5}))}
=\frac{3}{5\left(1-\frac{\sqrt5+1}{4}\right)}
=\frac{3}{5}(3+\sqrt5).
$$
Different proofs that $\cos(\pi/5)=\frac12\phi$ can be found here.
By taking $\sqrt5$ to four decimal places ($\sqrt{5}\approx2.2360$, rounding down) and doing a little unpleasant computation by hand, it can be shown that
$$
\frac{3}{5}(3+\sqrt5)>\frac{3}{5}(3+2.2360)=3.1416>\pi.
$$
Hope this helps!
This answer is just an extension of my answer to this question, which asks why $\frac{6}{5}\phi^2\sim\pi$.
Comment: The most part of the answer covers the fact that $(6/5)$ of the argument of $\sin$ can be written $\frac{3}{5}(3+\sqrt{5})$, but this can be obtained trivially without recurring to $\phi$, while the most important part, the inequality, provides no particular hint to prove them.
Comment: Sorry, I can't quite catch what you mean here by the $(6/5)$ argument of $\sin$ can be written $\frac{3}{5}(3+\sqrt{5})$. If there is some trivial way to obtain this result, please let me know. I have a terrible knack for overcomplication and circular reasoning!
Comment: $$
\frac{6}{5}\left(1+\frac{1+\sqrt{5}}{2}\right)=\frac{6}{5}\cdot\frac{3+\sqrt{5}}{2}=\frac{3}{5}\left(3+\sqrt{5}\right)
$$
Answer: First, notice that
$${3(3+2.236)} = {5\cdot 3.1416}$$
Now, recall we need to prove
$$\sin\left(1+\frac{1+\sqrt5}{2}\right)<\sin\frac{5\pi}{6}$$
which as Michael Rozenberg and others pointed out, is logically equivalent to showing
$$1+\frac{1+\sqrt5}{2}>\frac{5\pi}{6}$$
Multiplying both sides by $6/5\pi$ and simplifying is equivalent to
$$\frac{3(3+\sqrt5)}{5\pi}>1$$
Since $\sqrt 5 > 2.236$ and $\pi < 3.1416$, we have
$$\frac{3(3+\sqrt5)}{5\pi} >\frac{3(3+2.236)}{5\cdot3.1416} = 1\quad\quad \blacksquare$$
Answer: Here is another that avoids $\pi$ approximations other than $3 < \pi < 4$ and takes liberty with the notion of calculating by hand.
For $x \ge 0$ we have $\sin x \le u(x)=\sum_{k=1}^7 (-1)^{n+1} {x^{2k+1} \over (2k+1)!}$, so in principle we can upper bound $\sin$ when calculating with rationals.
Using $2 < \sqrt{5} < 3$ we have ${\pi \over 2} < 2 <{5 \over 2} < 1+ \phi < 3 < \pi$ and $\sin$ is decreasing on the interval $({\pi \over 2}, \pi)$.
If we can find a rational ${p \over q} \in (2,3)$ such that ${p_n \over q_n} \le 1+\phi$ and we have
$u({p_n \over q_n}) < {1 \over 2}$ then we are finished.
Noting that $q(x)= x^2-x-1$ is increasing and non negative for $x \ge 0$, $q(\phi) = 0$ and
$q({1618 \over 1000}) < 0$, we see that ${2618 \over 1000}$ satisfies the
criteria and
$u({2618 \over 1000}) = {4132642497822341133247468087 \over 9278984069824218750000000000} < {1 \over 2}$.
Answer: I assume we know

$\sqrt{5}>2.236$

$\pi<3.141593$

$\sin\frac{\pi}{6}=\frac{1}{2}$

$\sin$ is strictly increasing on $\left[0,\pi/2\right]$

Now, $\sin\left(1+\frac{1+\sqrt{5}}{2}\right)=\sin\left(\pi-\left(1+\frac{1+\sqrt{5}}{2}\right)\right)$.
We can verify by hand that $\pi-\left(1+\frac{1+\sqrt{5}}{2}\right)\approx0.5\in\left[0,\pi/2\right]$.
So, by (4), it suffices to show that $$\pi-\left(1+\frac{1+\sqrt{5}}{2}\right)<\frac{\pi}{6}\text{ or }\frac{5}{6}\pi-\left(1+\frac{1+\sqrt{5}}{2}\right)<0.$$ But this last inequality holds because
$$\frac{5}{6}\pi-\left(1+\frac{1+\sqrt{5}}{2}\right)<\frac{5}{6}\left(3.141593\right)-\left(1+\frac{1+2.236}{2}\right)=-0.0000058\dot{3}.$$
Comment: Why even post this answer? It doesn't add anything on top of my answer, which follows the same approach except yours requires a better approximation of $\pi$.
Answer: We need to prove that $$\sin\left(1+\frac{1+\sqrt5}{2}\right)<\sin\frac{5\pi}{6}$$ or
$$1+\frac{1+\sqrt5}{2}>\frac{5\pi}{6}.$$
Can you solve the question from here?
Comment: You do realise that the difference of the latter is around $4 \times 10^{-5}$, right?
Comment: -1 That is the problem isn't it? But how exactly do you go about showing that?
Comment: If it's not so hard, it would be beneficial to OP to edit that process in :) It's the same reasoning I gave the other answer. But you should try it to verify it is tractable and not send OP on a wild goose chase that still leaves them in the lurch. I have made the assumption (incorrectly) many times that just because known numerical approximations existed my work was done.
Comment: @IraeVid respectfully, I disagree. As it stands, this answer amounts to the first few words on your answer, and doesn't give any hints to the technical heart of the problem which is tangible numerical approximations. Without even a hint at that second piece, this answer is more appropriate as a comment.
Comment: This post is being unreasonably downvoted. He is giving a hint to OP, and since he knows power series etc, he should be able to figure out on his own.
Comment: @copper.hat Yes, of course. There are very many good approximations of $\pi.$
Comment: @Ninad Munshi We can use $\frac{\pi}{4}=\arctan\frac{1}{2}+\arctan\frac{1}{3}$ and the Taylor series for $\arctan$. Or something similar. Try, it's not so hard.
Comment: @Ninad Munshi I see now, you did not try. I think, it's not fair. If a topic-starter will want a full way, I'll show it, of course.
Comment: This answer is not wrong, but given its length, I would agree with @Ninad Munshi its more of hint, which respectfully resides within the comments (not as an answer). However, I would not downvote, rather leave it $0$ (neutral).


Using alias in query to get sum

Question: I am using alias in another parameter to get cumulative sum but getting error. How to put alias in query.
SET @total=0;
SET @amountDue=0;

SELECT cs.customer_name,l.paid_date, IF(@total=0,((pl.total_amount)-
(pl.installment_amount_month)*( pl.total_installments))
,( pl.installment_amount_month)) AS AmountDue
      ,@amountDue := @amountDue + AmountDue as ComulativeDue,

 l.amount AS AmountPaid,
  @total := @total +l.amount AS comulativePaid,
 (@total/@amountDue ) as percentage
 FROM payments_details l join payment_loan pl on (pl.loan_id=l.loan_id) join
 customer cs on (cs.customer_id=l.customer_id)
 WHERE l.customer_id=cs.customer_id and pl.loan_id=l.loan_id
 GROUP BY l.paid_date ORDER BY  l.paid_date ;

Comment: Well what is the error?
Comment: i am adding @amountDue + alias name of AmountDue
Comment: No. What is the exact error that you're getting?
Comment: Error is unknown column AmountDue
Answer: No you can't directly use the column alias like that unless you are trying to access it in a outer select query. You will have to use the entire expression to calculate AmoutnDue rather like
SELECT cs.customer_name,l.paid_date, IF(@total=0,((pl.total_amount)-
(pl.installment_amount_month)*( pl.total_installments))
,( pl.installment_amount_month)) AS AmountDue
      ,@amountDue := @amountDue + IF(@total=0,((pl.total_amount)-
(pl.installment_amount_month)*( pl.total_installments))
,( pl.installment_amount_month)) as ComulativeDue,

Comment: i tried this one but my expected result in not correct
Comment: @UserKh, that I am not sure about what calculation you are doing but the point here is, use the entire expression for calculating `AmountDue` in your `CumulativeDue`

Using alias in query to get sum


Como ler um input no laço de repetição

Question: Sou iniciante em C. Preciso que o programa abaixo leia o número digitado em console e dê dicas ao usuário até ele acertar:
#include <stdio.h>

int main ()
{
    int num;
    printf("Informe um número entre 0 e 10:\n");
    scanf("%d",&num);

    while (num!=7)
    {
        printf("Escolha outro valor:");
        scanf("%d",&num);
        switch(num)
        {
            case '0':
                printf("Tente outro numero\n");
                break;
            case '1':
                printf("Escolha outro valor\n");
                break;
            case '2':
                printf("Esta longe, tente outro\n");
                break;
            case '3':
                printf("O numero e maior\n");
                break;
            case '4':
                printf("Tente novamente\n");
                break;
            case '5':
                printf("Esta proximo, mas ainda nao e este\n");
                break;
            case '6':
                printf("Ja pensou em tentar um numero impar?\n");
                break;
            case '8':
                printf("Esta proximo\n");
                break;
            case '9':
                printf("Tente um valor menor\n");
                break;
            case '10':
                printf("E um numero menor\n");
                break;
            default:
                printf("Voce acertou");
                break;
        }
    }
}

Comment: Caro @user31057, dê uma lida no [tour](http://pt.stackoverflow.com/tour) e edite sua pergunta de forma sucinta, assim a comunidade pode ajudar com sua dúvida mas não fazer seu exercício.
Comment: Qual é a sua dúvida?
Comment: Quando vou compilar não consigo fazer ele repetir
Comment: Desculpe a ignorância (sou novato em programação), mas ele já não está entre chaves?
Comment: É só tirar as Aspas Simples que vai funcionar.
Answer: Como disse @Daniel Gomes, tire as aspas simples. Para este tipo de construção em que o laço deve se repetir ao menos uma vez use do{} while(); e evite uma verificação desnecessária:
#include <stdio.h>
    int main ()
    {
        int num;

        do
        {

            printf("Informe um número entre 0 e 10:\n");
            scanf("%d",&num);

            switch(num)
            {
                case 0:
                printf("Tente outro numero\n");
                case 1:
                printf("Escolha outro valor\n");
                break;
                case 2:
                printf("Esta longe, tente outro\n");
                break;
                case 3:
                printf("O numero e maior\n");
                break;
                case 4:
                printf("Tente novamente\n");
                break;
                case 5:
                printf("Esta proximo, mas ainda nao e este\n");
                break;
                case 6:
                printf("Ja pensou em tentar um numero impar?\n");
                break;
                case 8:
                printf("Esta proximo\n");
                break;
                case 9:
                printf("Tente um valor menor\n");
                break;
                case 10:
                printf("E um numero menor\n");
                default:
                printf("Voce acertou");
            }
        }while(num != 7);
    }

Answer: Tirando as aspas simples, seu código rodou normalmente aqui.
#include <stdio.h>

int main ()
{
    int num;
    printf("Informe um número entre 0 e 10:\n");
    scanf("%d",&num);

    while(num!=7)
    {
        printf("Escolha outro valor:");
        scanf("%d",&num);

        switch(num)
        {
            case 0:
                printf("Tente outro numero\n");
            case 1:
                printf("Escolha outro valor\n");
                break;
            case 2:
                printf("Esta longe, tente outro\n");
                break;
            case 3:
                printf("O numero e maior\n");
                break;
            case 4:
                printf("Tente novamente\n");
                break;
            case 5:
                printf("Esta proximo, mas ainda nao e este\n");
                break;
            case 6:
                printf("Ja pensou em tentar um numero impar?\n");
                break;
            case 8:
                printf("Esta proximo\n");
                break;
            case 9:
                printf("Tente um valor menor\n");
                break;
            case 10:
                printf("E um numero menor\n");
            default:
                printf("Voce acertou");
        }
    }
}

Executando:
Answer: O scanf está fora do laço de repetição. Para que a cada verificação do número, ele solicite que o usuário digite novamente, ele deve estar junto do laço:
int main ()
{
    int num;

    while(num!=7)
    {

        printf("Informe um número entre 0 e 10:\n");
        scanf("%d",&num);

        switch(num)
        {
            case 0:
            printf("Tente outro numero\n");
            case 1:
            printf("Escolha outro valor\n");
            break;
            case 2:
            printf("Esta longe, tente outro\n");
            break;
            case 3:
            printf("O numero e maior\n");
            break;
            case 4:
            printf("Tente novamente\n");
            break;
            case 5:
            printf("Esta proximo, mas ainda nao e este\n");
            break;
            case 6:
            printf("Ja pensou em tentar um numero impar?\n");
            break;
            case 8:
            printf("Esta proximo\n");
            break;
            case 9:
            printf("Tente um valor menor\n");
            break;
            case 10:
            printf("E um numero menor\n");
            default:
            printf("Voce acertou");
        }
    }
}

Comment: Como o `scanf("%d",#);` está fora do laço se ele tem dois?
Answer: Experimente remover as aspas do seu case:
-> Quando você faz isso  você pede o ao case mais ou menos isso:
 "Case, compare o que tem no meu Switch com o caracter '1' ".
O problema é esse, ao fazer isso você não está comparado 1 com '1', e sim 1 com um valor da tabela ASCII que representa o caracter '1'.
Entendeu?

Como ler um input no laço de repetição