Organizing repeated measures data with a grouping variable for MLM

Question: I just started reading about multilevel modeling so I can apply the method to my research data. However, I have yet to come across an illustrative example or even discussion how to organize and set up a model for a repeated-measures design with a grouping variable to counterbalance across materials.
For example, let's say I want to look at the effect difficulty level of paragraph has on time to read a target sentence embedded within each paragraph. To test this, I create 6 paragraphs, in which there are three versions of each paragraph: Difficult (D), Moderate (M), Easy (E). Participants get exposed to all three levels of difficulty but only read one version of each paragraph. So, reading material is repeated-measures, but the specific paragraph participants get differs. To counterbalance across difficulty levels, participants also get different orders of conditions with the restriction that each condition appears in each position an equal number of times (this is the grouping variable; order is a between subjects variable)
So, for the sake of counterbalancing, I administer three different orders of the six paragraphs for the following participants: Beth: DME EDM (order 1) John: MED DME (order 2) Mary: EDM MED (order 3)
So, you can see that everyone gets all levels of difficulties but for different paragraphs.
The dependent measure is the time to read a target sentence for each paragraph. Here is a tabular display of fictitious data of reading time laid out by the experimental design:

So, my first question is, how do I organize the data to prepare for MLM to reflect the order grouping variable and three levels of difficulty, repeated measures? Then how should I start thinking about incorporating random effects into the model?
Answer: The way you have presented the data in the table is a start but needs some additions and changes in order to analyze the data using a mixed modeling framework. The most important thing is that each subject has multiple rows corresponding to a repeated measure. The time to read measure needs to be in its own column. Then you want to create categorical variables representing each of the conditions: version with three categories, and potentially order with three categories (assuming there are only three of them). Your dataset would look something like this:
subject read_time version order
1        1800        1      1
1        1500        1      1
1        1200        2      1
1        1400        2      1
1        1100        3      1
1        1000        3      1
2        1600        1      2
2        1550        1      2
2        1600        2      2
2        1350        2      2
2        1000        3      2
2        1100        3      2

And so on. If I understand your design, version changes within subjects (although all subjects are exposed to all versions) whereas order is a between-subjects factor that is constant within subject.
In terms of modeling this with a mixed model, that depends on your research questions, but the basic model I would set up would regress read_time on the fixed categorical predictors version and order with a random intercept for subject given that we expect responses from the same subject to be more highly correlated than responses from different subjects. In R, you can set up the model using lme4 as such:
library(lme4)
base <- lmer(read_time ~ version + order + (1|subject), data=df)

This fixed effect coefficients from this model will give test the read_time contrasts between the base category for version (presumably 1) against version 2 and version 3 and then provide a set of read_time contrasts between the base category of order (presumably 1) against order 2 and order 3.
You can get the ANOVA F test for this model if you want using anova(base). You may want to subsequently test whether version 2 is different from version 3 and likewise whether order 2 is different from order 3. You can use the multcomp package in R for this. See https://stats.idre.ucla.edu/r/faq/how-can-i-test-contrasts-in-r/


Why is the (reduced) suspension of a genus $g$ surface homotopy equivalent to $(\vee_{2g}S^2)\vee S^3$?

Question: Why is the (reduced) suspension of a genus $g$ surface $X_g$ homotopy equivalent to $(\bigvee_{2g} S^2)\vee S^3$?
An attempt:
We can construct $X_g$ by attaching an $D^2$ to $\bigvee_{2g} S^1$ along the `obvious' map given by the relation in the fundamental group.  So we get a cofibration $S^1\rightarrow \bigvee_{2g} S^1 \rightarrow X_g$.  In particular we have a cofibration sequence,
$S^1\rightarrow \bigvee_{2g} S^1 \rightarrow X_g \rightarrow S^2 \rightarrow \bigvee_{2g} S^2 \rightarrow \Sigma X_g \rightarrow S^3\rightarrow \bigvee_{2g} S^3 \rightarrow \Sigma^2 X_g \rightarrow \cdots$
I'm not sure how to proceed from here.
Comment: The 'obvious' map $S^1 \to \vee_{2g} S^1$ is a product of commutators, which is non-trivial because $\pi_1(\vee_{2g} S^1)\cong *_{2g}\mathbb{Z}$ is non-abelian for $g > 1$. Since suspension induces a homomorphism $\Sigma \colon \pi_1(\vee_{2g}S^1) \to \pi_2(\vee_{2g}S^2)$ the image of this map is also a product of commutators, and hence trivial because all higher homotopy groups are abelian.
Comment: I meant to say "$g\geq 1$"
Answer: $\bigvee_{2g}S^2\to \Sigma X_g\to S^3$  is a cofibration sequence.
Moreover, $H_2(\Sigma X_g) = H_1(X_g) = \mathbb Z^{2g}$ and $H_3(\Sigma X_g)= H_2( X_g) = \mathbb Z$,  and the higher $H_n$'s are zero
$\Sigma X_g$ is simply connected, and so is the space you want to compare it to, so it suffices to find a map which induces an isomorphism in homology.
It's clear that the map $\bigvee_{2g}S^2\to \Sigma X_g$ already induces an isomorphism on $H_2$, so it suffices to find a map $S^3\to \Sigma X_g$ which induces an isomorphism on $H_3$. This map will not come from a map $S^2\to X_g$ by suspension, because $X_g$ has no higher $\pi_i$'s (if I remember correctly, orientable surfaces are always $K(\pi,1)$'s)
So for this, we may want to use the better version of Hurewicz, which not only says that $\pi_2\to H_2$ is an isomorphism (because $\Sigma X_g$ is simply-connected), but also that $\pi_3\to H_3$ is an epimorphism (see here, at "absolute version")
This in particular means that there is $S^3\to \Sigma X_g$ such that $H_3(S^3)\to H_3(\Sigma X_g)$ sends $1$ to $1$, in particular it's an isomorphism on $H_3$, and we get what we wanted


ESXi 5.0 can't parse crontab (ghettoVCB)

Question: I'm trying to run ghettoVCB via cron on a ESXi 5.0 Machine.
This is the command (add some linebreaks for better readability)
/vmfs/volumes/VMs\ Pool/ghettoVCB-master/ghettoVCB.sh
-f /vmfs/volumes/4e5b4f96-ebf53b38-db36-bc305bd75982/ghettoVCB-master/vms_to_backup
-g /vmfs/volumes/4e5b4f96-ebf53b38-db36-bc305bd75982/ghettoVCB-master/ghettoVCB.conf
> /vmfs/volumes/4e5b4f96-ebf53b38-db36-bc305bd75982/ghettoVCB-master/ghettoVCB-backup-$(date +\%s).log

Executing the command did exactly what it should but when I add it to crontab, syslog spit out the following:
2013-05-26T09:32:01Z crond[1481072]: failed user root parsing 1-7 /vmfs/volumes/VMs\ Pool/ghettoVCB-master/ghettoVCB.sh -f /vmfs/volumes/4e5b4f96-ebf53b38-db36-bc305bd75982/ghettoVCB-master/vms_to_backup -g /vmfs/volumes/4e5b4f96-ebf53b38-db36-bc305bd75982/ghettoVCB-master/ghettoVCB.conf > /vmfs/volumes/4e5b4f96-ebf53b38-db36-bc305bd75982/ghettoVCB-master/ghettoVCB-backup-$(date +\%s).log

And here's the entry of the crontab:
0    0    *   *   1-7 /vmfs/volumes/VMs\ Pool/ghettoVCB-master/ghettoVCB.sh -f /vmfs/volumes/4e5b4f96-ebf53b38-db36-bc305bd75982/ghettoVCB-master/vms_to_backup -g /vmfs/volumes/4e5b4f96-ebf53b38-db36-bc305bd75982/ghettoVCB-master/ghettoVCB.conf > /vmfs/volumes/4e5b4f96-ebf53b38-db36-bc305bd75982/ghettoVCB-master/ghettoVCB-backup-$(date +\%s).log

Has anyone an idea why crond can't parse the command?
Answer: Thumb Question - Simple Answer: Cron-Count starts with 0 - so
0    0    *   *   0-6

solves the problem


How to solve equations with modulus in them

Question: For e.g.
(100 * X) % 35 = 25
gives X = 2
and on similar note
(100 * X) % 360 = 80
gives X = 8
and it can be possible that there is no X which satisfy this
for e.g.
(100 * X) % 360 = 70
there is no X possible in above case
Comment: Are you familiar with congruences, i.e $\, a\equiv b\pmod m\iff m\,$ divides $\,a-b,\,$ and their arithmetic? Do you know Bezout's Identity for the gcd, or Fermat's little Theorem? Please give some background or context so that we can answer at the appropriate level.
Comment: @amitchhajer Unfortunately the accepted answer is incorrect, and contains various misunderstandings. I don't think that an MSE answer is the best place to attempt to learn congruence arithmetic. Any textbook on elementary number theory will cover this. I recommend browsing the shelves/pages at your local/virtual library to find a textbook that matches your level of knowledge. While you could learn much from prior answers here, but that would be much less efficient than using a good textbook.
Comment: @BillDubuque doesn't look he is familiar with modular arithmetic,otherwise that notation would have been used. Is my answer complete? Anything you'd like to add?
Comment: @amitchhajer you should have asked AndreNicolas. He answered your question, he would have been happy to provide more details. Anyway, is my answer clear to you?
Comment: who is AndreNicolas?
Comment: @amitchhajer my bad. I thought this was your question. Apparently not. http://math.stackexchange.com/questions/713406/how-do-i-calculate-the-number-of-times-angle-x-should-be-added-to-obtain-angle-y
Comment: same numbers. weird.
Comment: @amitchhajer Please say a litle about how much number theory you know, e.g. the congruence form of your first equation is $\ 100 x\equiv 60 \pmod{360}.\,$ Are you familiar with such congruences and their arithmetic?
Comment: Not really Bill. But I can understand what Sabyasachi has given answer as. Not too good in mathematics. Where should I read more about this?
Answer: Using C notation <code>(a*X) % n = b</code>, such a $X$ exists if and only if the GCD (greatest common divisor) of $a$ and $n$ is a divisor of $b$ (of course, assuming $0 \le b < n$). I am afraid that the method to actually find a solution uses more tools than you are familiar with, but at least you can easily check whether a solution exists, and if so you can always do an exhaustive search, which should be fine in your setting. (If you want to know more, a Google search for "linear congruence" yields plenty of references, but you might have to get familiar with congruences first.)


If three six-sided fair dice are rolled, what is the probability that two dice show one number, and the remaining die shows another number?

Question: If three six-sided fair dice are rolled, what is the probability that two dice show one number, and the remaining die shows another number?
I think the total of possible outcomes is $6^3= 216$, but I don't know how to apply the n C r in this case.
Comment: Where are you stuck?
Comment: The entire statement of the question should be in the body of your question.  Had I not noticed that the question was the continuation of a sentence started in the title, I would have just solved for the favorable cases.  Please edit your question to tell us what you know and where you are stuck.  For instance, how many possible outcomes are there?
Comment: @RobertZ I'm trying to figure out how to even start with this question by using the combination method.
Comment: @N.F.Taussig sorry about that, I'm a bit new on this site, still trying to get used to all the UI and such. I think the total possible outcome is 6^3= 216? but I don't know how to apply the n C r in this case
Answer: Strategy:  Assume the colors of the dice are blue, red, and green to make the dice distinguishable.  To count the favorable cases:

Choose which two dice show the same outcome.
Choose which number those dice show.
Choose which of the remaining numbers the other die shows.

Finally, divide by the total number of possible outcomes, which you have correctly calculated.
Comment: You are correct that there are $\binom{3}{2}$ ways to select two of the three dice to show the same outcome and $\binom{6}{1}$ ways to select the number those dice show.  However, in part 3, how many possible outcomes remain for the third die given that it is different from the outcome shown on the other two dice?  Of these, how many can it show?
Comment: omg I think I got it. It should be 5 C 1 because one of the number was already picked out. You are a savior ! Thank you guys!
Comment: Yes, that is correct.  The answer is $$\frac{\binom{3}{2}\binom{6}{1}\binom{5}{1}}{6^3}$$
Comment: I like this strategy of thinking about these type of problems. Thank you for walking me through it
Comment: So I got 3 C 2 for choosing 2 dice out of three being the same number. Then I got 6 C 1 for the number of ways those number show, then finally I got 6 C 5 for the remaining numbers for the other die.
divided by 216 I got 0.5 but the number doesn't seem right
Comment: You are welcome.
Answer: There are $6\cdot5\cdot4=120$ ways of three different numbers and $6$ ways of three equal numbers. The remaining $216-126=90$ ways are favorable. The probability in question therefore is ${90\over216}={5\over12}$.
Answer: Hint, when you can't find a magical formula, start by counting the favourite outcomes. There are $6\cdot6\cdot6$ possible outcomes altogether. But favourite ones are:

$d_1=d_2=1$ and $d_3\in\{2,3,4,5,6\}$. $5$ outcomes.
$d_1=d_2=2$ and $d_3\in\{1,3,4,5,6\}$. $5$ outcomes.
$...$
$d_1=d_2=6$ and $d_3\in\{1,2,3,4,5\}$. $5$ outcomes.

Then count for

$d_1=d_3=1$ and $d_2\in\{2,3,4,5,6\}$. $5$ outcomes.
$d_1=d_3=2$ and $d_2\in\{1,3,4,5,6\}$. $5$ outcomes.
$...$
$d_1=d_3=6$ and $d_2\in\{1,2,3,4,5\}$. $5$ outcomes.

And one more ...
It should be easy to finish the exercise from here.
Comment: thank you for showing me another way to think of this problem!
Answer: First we need to select those two dies out of the three which show same number which can be done in $^3C_2$ ways. Now for those two dice with same number the third dice can have five different results to satisfy the condition. So the answer will be  $$\frac{^3C_2\times5\times6}{6^3} = \frac{5}{12}$$


Replace VLC plugin for Multicast (NPAPI Deprecated)

Question: we were using the vlc plugin in Chrome to play a multicast stream (RTP Ipv6) but with the deprecation of NPAPI-Plugins we need an alternative. I was trying to search something about html5 video but nothing.
NPAPI deprecation: developer guide
Any idea?
Thanks
Answer: RTP directly to the browser is not a solution I'd use today. The implementation effort to transform a number of RTP packets to Media Segments accepted by the Media Source Extension (MSE) is rather high and perhaps it's not even doable on all browsers (chrome.sockets seems to be a way to do it at least on Chrome browsers). Plugin development for more than a single browser is a nasty business as well. Don't go there!
I am not sure if it fits your requirements but here is what I'd do:
I would setup a process that converts RTP packets to MPEG-DASH packets on a server. Coincidentally I implemented a solution like that. You can find it on Github as RTP2DASH. The example receives multiple qualities of the same stream from ffmpeg but you don't need that - a single video stream from any RTP source should be enough as you can run MPEG-DASH with just a single video stream. Doing DASH seems like a big overhead in the beginning but the advantage is that there are players working on all browsers such as the DASH-IF Reference Player (I wouldn't use that one) or Google's Shaka Player (which is included in my example) already there.


convex border-top and border-bottom with css?

Question: I am trying to have a border only for top and border with a line that is thick (4px) in the middle and at the ends goes to zero. Like in the pic

<code>.hervorheben{
    line-height: 1.6em;
    margin-bottom: 1.6em;
    margin-top: 1.6em;
    text-rendering: optimizeLegibility;
    border-top: 1px solid #105322;
    border-bottom: 1px solid #105322;
    padding: 19px;
    margin: auto auto;
}
</code>
Do you know how to do so with only css?
Answer: You can`t make border like that but you can manage with Pseudo-element (after) like following
<code>.your_class {
    position: relative
}

.your_class:after {
    position: absolute;
    width: 100%;
    height: 4px;
    background: #000;
    border-radius: 100%;
    content: "";
    top: 0;
    left: 0;
}
</code>
Enjoy....
Comment: Thanks that works :-)
How can I get a line above and below a div with a bit margin? I tried this, but didnt worked for me.

.hervorheben:before {
    position: relative;
    width: 80%;
    height: 4px;
    background: #105322;
    border-radius: 100%;
    content: "";
    left: 10%;
    bottom: 0;

}

.hervorheben {
     position: relative;
    }

 .hervorheben:after {
    position: absolute;
    width: 80%;
    height: 4px;
    background: #105322;
    border-radius: 100%;
    content: "";
    left: 10%;
    top: 0;
}
Comment: you change top or bottom property with positive or negative value


Ubuntu Server - Two Interfaces Living Together (in perfect harmony)

Question: Our server has three ethernet interfaces. I have one plugged into the cable modem (for static ip), and one plugged into the router (for access to the rest of the work network). I'm pretty sure that I had both interfaces running simultaneously under Xubuntu, but under Ubuntu Server I can't seem to pull this off; if I connect to the work network, my static ip stops working. This kind of defeats the purpose of having more than one ethernet interface. How can I make these two interfaces live together happily?
route Output:
eth0 down
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
220.127.116.11  *               255.255.255.248 U     0      0        0 eth2
default         rrcs-74-218-198 0.0.0.0         UG    100    0        0 eth2

eth0 up (hangs after first two lines, so I used route -n)
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
126.96.36.199  0.0.0.0         255.255.255.248 U     0      0        0 eth2
192.168.2.0     0.0.0.0         255.255.255.0   U     0      0        0 eth0
0.0.0.0         192.168.2.1     0.0.0.0         UG    100    0        0 eth0
0.0.0.0         220.127.116.11  0.0.0.0         UG    100    0        0 eth2

Comment: How, exactly, does it 'stop working'? Does it go down? Does data flow stop?
Comment: When I `ifup` the other interface, I have trouble accessing the IP address of the server from the outside world. The IP address seems to be accessible from the LAN though...
Answer: Do you have default gateways for both interfaces? If the answer is yes then disable default gateway in the configuration for eth0.
Comment: Ah yes, I thought including the gateway info was required for both interfaces, so I didn't realize that I was making two defaults. I'm a programmer, not a network admin. Don't judge me! ;)
Comment: thx for the hint.. I had the same problem as well!
Answer: I'm guessing that your static IP keeps working perfectly well, but the DHCP setup on the other NIC causes it to become the default gateway as instructde by the DHCP server.
To test this little theory, run route when only connected with the static NIC, when connectde just to the local LAN, and when connected with both.
You should see output something like:
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
192.168.39.0    *               255.255.255.0   U     0      0        0 eth0
default         192.168.39.1    0.0.0.0         UG    0      0        0 eth0

You will see more lines when connected through more NICs, and more if you have any extra network routing configured (such as VPNs). The important line is the one marked as default in destination.
Edit: with the new info added to your question, I'm not entirely sure as I've not seen that arrangement (I know a bit on routing but I'm no export!). It looks like there are two gateways defined, one for each network interface. This may mean that there is no fixed route for packets to public addresses and this leaves two potential problems: if the local LAN is not configured to allow packets from you to be forwarded to public addresses then they won't get out, and if you are using DNS servers that are only accessible down one of the lines and the other line is used you will not get any name resolution. Could you add the output of nslookup example.com and cat /etc/resolve.conf to your information, and I might be able to diagnose further and suggest a fix.
Comment: when I bring up the other interface and run `route`, it prints a line for each interface, then just hangs without printing a line for default.
Comment: The hang will probably be it trying to lookup a name for an IP address, but not being able to see the nameserver and waiting for a timeout before carrying on. It will eventually finish, btu to skip the name resolution completely, use `route -n` in place of plain `route`.
Comment: alright, when I do that, I get one line for each interface as before, then I get a another line for each interface in reverse order, each one beginning with 0.0.0.0 (four lines total).
Comment: You should update your question to include all the new information, i.e. the full output of route in each case, nicely formatted and easy to read.
Comment: good idea.
Answer: You have two default gateways on the same metric, which basically confuses the hell out of the routing engine (it cannot make a clear decision which one to use). Seeing that you have a router, I would suggest you put the server on the other side of that and leave the routing to the router.
Alternatively, if you want to (or have to) leave the server where it is in your network line-up:

ensure there is only one default
gateway (your third line is for a
default gateway to an internal
network, that is unlikely to work in
any case, unless the gateway has
another separate route to the
Internet)
ensure that your server has IP
forwarding enabled: echo 1 >/proc/sys/net/ipv4/ip_forward and that your firewall handles the
forwarding correctly.

The hanging of route on the third lines is caused by the fact that you either do not have internal DNS at all, or the DNS server is not reachable from the server (which could be caused by the routing issue) or it does not have a name for the address 192.168.2.1 (i.e. the pointer records are not set up correctly or at all).


Rowwise column name of minimum value in certain columns excluding NAs

Question: I have a dataset that looks like this:
library(dplyr)
Data <- tibble(Code = letters[1:6],
            Min_0 = c(12.3, NA, 1.1, NA, 0, NA),
            Min_1 = c(3.6, NA, 12.4, 1.7, 15.6, NA),
            Min_2 = c(45.6, NA, 2.4, 28.9, 32.7, NA),
            Min_3 = c(2.3, NA, NA, NA, NA, NA),
            Min_4 = c(52.4, NA, 23.6, 4.6, 0, NA),
            Min_5 = c(0, NA, 5.7, NA, 0.1, NA))

For every row I want to add a column with the minimum value from columns Min_1 to Min_5 or NA if that row only contains NAs. I would also like to add another column that contains the last digit of the column name that has the minimum value for that row.
I think I have a solution to my first question by adapting an answer from this question (in my case I only want to ignore NAs not NAs and zeros).
Min_Function <- function(x, f, ...) ifelse(all(is.na(x)), NA,
                                   ifelse(all(is.na(x)),
                                          0, f(x[x >= 0], na.rm = TRUE, ...)))

Data %>%
    rowwise() %>%
    mutate(Min_Time = Min_Function(c_across(starts_with("Min_") & -ends_with("0")), min))

My real data has many more columns which is why I need to use the starts_with and ends_with to select the columns I am interested in.
However, I don't know how I get an output like this for the second part of my question:
Data %>% mutate(Min_ID = c(5, NA, 2, 1, 4, NA))

Answer: you can use case_when() with the across() function in the mutate statement
something like this
Data <- Data %>%
  rowwise() %>%
  mutate(Min_Value = Min_Function(c_across(starts_with("Min_") & -ends_with("0")), min),
         Min_ID = case_when(
           Min_Value == Min_1 ~ 1,
           Min_Value == Min_2 ~ 2,
           Min_Value == Min_3 ~ 3,
           Min_Value == Min_4 ~ 4,
           Min_Value == Min_5 ~ 5,
           TRUE ~ NA_integer_
         ))

Data

Answer: Data %>%
   mutate(Min_Time = max.col(-across(starts_with("Min_") & -ends_with("0"),
                 ~replace_na(.x, Inf)), 'first')*
            NA^if_all(starts_with("Min_") & -ends_with("0"), is.na))

# A tibble: 6 × 8
  Code  Min_0 Min_1 Min_2 Min_3 Min_4 Min_5 Min_Time
  <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>    <dbl>
1 a      12.3   3.6  45.6   2.3  52.4   0          5
2 b      NA    NA    NA    NA    NA    NA         NA
3 c       1.1  12.4   2.4  NA    23.6   5.7        2
4 d      NA     1.7  28.9  NA     4.6  NA          1
5 e       0    15.6  32.7  NA     0     0.1        4
6 f      NA    NA    NA    NA    NA    NA         NA

Answer: You can try the following data.table solution with melt + dcast
library(data.table)

dcast(
    melt(setDT(Data),
        id.var = c("Code", "Min_0")
    )[
        ,
        Min_Time := gsub(".*_", "", variable[which.min(value)]),
        .(Code, Min_0)
    ],
    ... ~ variable
)[,
    c(names(Data), "Min_Time"),
    with = FALSE
]

which gives
   Code Min_0 Min_1 Min_2 Min_3 Min_4 Min_5 Min_Time
1:    a  12.3   3.6  45.6   2.3  52.4   0.0        5
2:    b    NA    NA    NA    NA    NA    NA     <NA>
3:    c   1.1  12.4   2.4    NA  23.6   5.7        2
4:    d    NA   1.7  28.9    NA   4.6    NA        1
5:    e   0.0  15.6  32.7    NA   0.0   0.1        4
6:    f    NA    NA    NA    NA    NA    NA     <NA>

Answer: Alternatively with just across and which we can get the below
Data %>% rowwise() %>%
  mutate(Min_ID =ifelse(!all(is.na(across(c(Min_1:Min_5)))),which(across(c(Min_1:Min_5))==
min(across(c(Min_1:Min_5)), na.rm = T)), NA))

# OUTPUT

# A tibble: 6 × 8
# Rowwise:
  Code  Min_0 Min_1 Min_2 Min_3 Min_4 Min_5 Min_ID
  <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>  <int>
1 a      12.3   3.6  45.6   2.3  52.4   0        5
2 b      NA    NA    NA    NA    NA    NA       NA
3 c       1.1  12.4   2.4  NA    23.6   5.7      2
4 d      NA     1.7  28.9  NA     4.6  NA        1
5 e       0    15.6  32.7  NA     0     0.1      4
6 f      NA    NA    NA    NA    NA    NA       NA


How to return series/point data from mouseover event?

Question: I've created a donut chart using vue-highcharts/highcharts, and am trying to append text on mouseover to the center of the donut. I've got it appending static text, however I'm trying to return the data from the point I hover over, to display that in the center, however I can't seem to find any relevant data from within the event object. Does anyone know how I might be able to access that data?
chartOptions: {
  chart: {
    plotBackgroundColor: null,
    plotBorderWidth: null,
    plotShadow: false,
    type: 'pie'
  },
  legend: {
    align: 'right',
    enabled: true,
    layout: 'vertical',
    verticalAlign: 'middle'
  },
  plotOptions: {
    pie: {
      allowPointSelect: true,
      cursor: 'pointer',
      dataLabels: {
        enabled: false
      },
      center: ['50%', '50%'],
      showInLegend: true,
      events: {
        mouseOver: (e) => {
          const { chart } = this.$refs.highchartsRef;
          const height = chart.chartHeight / 2;
          const width = e.target.center[3];
          console.log({ chart });
          console.log({ e });
          chart.renderer
            .text('Top Test
Bottom Test', width, height, true)
            .css({
              color: '#4a4a4a',
              fontSize: '16px',
              fontWeight: 700
            })
            .addClass('highcharts-center-label text-center')
            .add();
          },
          mouseOut: () => {
            document.querySelector('.highcharts-center-label').remove();
          }
        }
      }
    },
    series: [{
      name: 'Categories',
      colorByPoint: true,
      size: '100%',
      innerSize: '60%',
      data: this.categories.map(category => {
        return {
          name: category.name,
          y: calculateCategoryWeight(category)
        };
      })
    }],
    title: null,
    tooltip: {
      pointFormat: '{series.name}: {point.percentage:.1f}%'
    }
  }

Answer: Use point.events and a basic function instead of the arrow one.
    plotOptions: {
        pie: {
            point: {
                events: {
                    mouseOver: function() {
                        var point = this,
                            series = point.series,
                            chart = series.chart;

                        console.log(point.y);
                    }
                }
            }
        }
    }

Live demo: http://jsfiddle.net/BlackLabel/7oub1xzj/
API Reference: https://api.highcharts.com/highcharts/plotOptions.pie.point.events


subgroup of cyclic and their order

Question: I understand how any subgroups are cyclic and there is a subgroup for each divisor of $d$
Let's say for example
Let $d$ be a divisor of $n=|G|$. Consider $H=\{ x \in G : x^d =e\}$. Then $H$ is a subgroup of $G$ and $H$ contains all elements of $G$ that have order $d$ and $d$ is equal to 4
can anyone explain?
Comment: Please try to make the titles of your questions more informative. For example, *Why does $a<b$ imply $a+c<b+c$?* is much more useful for other users than *A question about inequality.* From [How can I ask a good question?](https://math.meta.stackexchange.com/a/589/): *Make your title as descriptive as possible. In many cases one can actually phrase the title as the question, at least in such a way so as to be comprehensible to an expert reader.* You can find more tips for choosing a good title [here](https://math.meta.stackexchange.com/a/10144/).
Comment: See https://math.stackexchange.com/a/410464/589
Answer: Many ways to answer that, based on how much group theory you've done so far.
The most elementary way I can think of to compute it is using the following theorem, which is not hard to prove: A cyclic group G of finite order has the following property: For each d which divides |G|, there is a unique subgroup (which is cyclic) of order d. This in fact is if and only if, but we won't need that.
With that theorem your question becomes easy. The only elements $x$ such that $x^4=e$ are elements of order 1, 2, 4. There is a unique element of order 1, the identity element. Given that there is a unique subgroup of order 2, that means there is a unique element of order 2, say $g$, which forms the subgroup of order 2
$$ H=\{g, g^2=e\} $$
Also there is a unique cyclic subgroup K of order 4, say $K=\langle h\rangle =\{h, h^2, h^3, h^4=e \}$. You can immediately see that $h^2$ has order 2 so it must be equal to g because of the uniqueness we discussed above. Also, $h^3$ has order 4. Therefore we have 4 elements with order up to 4, namely $e, g, h, h^3$. We know that there are no more such elements because that would contradict the above theorem, as any new element, say $x$ of order either 2 or 4, distinct from the above, would generate a new subgroup of order 2 or 4, namely $N=\langle x\rangle$.

subgroup of cyclic and their order


How many different committees can be formed when certain people refuse to serve together?

Question: From a group of 8 women and 6 men, a committee consisting of 3 men and 3 women is to be formed. How many different committees are possible for each of the following cases
(a) 2 of the men refuse to serve together
(b) 2 of the women refuse to serve together
(c) 1 man and 1 women refuse to serve together

I tried this much, I don't know how and why should I include the people who refuse?
(a) $\binom{8}{3}\binom{4}{3}$
(b) $\binom{6}{3}\binom{6}{3}$
(c)$\binom{7}{3}\binom{5}{3}$
Comment: What have you tried so far? Also, are these separate scenarios? Or are these constraints for the same question?
Answer: I'll answer (a) and leave the rest for you to solve on your own.
Let $M_1$ and $M_2$ be the two men that refuse to serve together
There are three types of committees

Neither $M_1$ nor $M_2$ are on it.
Only $M_1$ is
Only $M_2$ is

For (1), you need to choose 3 from 4 men. The number of ways to do this is $\binom{4}{3} = 4$
For (2), 2 more men have to chosen from 4 now. The number of ways is $\binom{4}{2} = 6$
For (3), the answer is the same as (2).
The total number of ways to choose the men is 16. For each of these, there are $\binom{8}{3} = 56$ ways to choose the women.

Therefore, the total ways to choose the committee should be $(16)(56) = 896$
Comment: Actually I had not seen the word work together , so I was stuck
Comment: In case 2 and 3, 2 men have to be chosen from 4, not 5. Another way to see it, there are $\binom{6}{3}=20$ ways to chose the men and $\binom{4}{1}=4$ ways are forbidden, so there are 16 ways to choose the men.
Comment: @Gribouillis You're right. Thanks for catching that. Fixed.
Comment: @Gribouillis How do I know 4 ways are forbidden ?
Comment: Because that is the number of ways to choose both men in the committee
Comment: Because you must remove the groups containing the two men that don't want to be together. There are only 4 ways to choose the third man, so there are only 4 such groups.
Comment: I understood there are 4 ways to choose the third man, but how is it that there are 4 ways that two men won't work together :(
Comment: @JohnWhite can u please explain how are there 4 ways to choose both men in committee?
Comment: Once the two men are fixed, there is still one man left to choose from the remaining 4 men which can be done in $\binom{4}{1}$ ways
Comment: @JohnWhite okay, got it :)


Porque essa linha de código me dá erro?

Question: Esta linha de código dá me erro na frase SQLiteDatabase.CREATE_IF_NECESSARY e impede me de fazer a base de dados. Porque isto está a acontecer?
  SQLiteDatabase BaseDados=SQLiteDatabase.openOrCreateDatabase("BaseDados",SQLiteDatabase.CREATE_IF_NECESSARY,null);

O erro que dá é o seguinte:

Error:(16, 54) error: no suitable method found for openOrCreateDatabase(String,int,)
  method SQLiteDatabase.openOrCreateDatabase(String,CursorFactory,DatabaseErrorHandler) is not applicable
  (actual argument int cannot be converted to CursorFactory by method invocation conversion)
  method SQLiteDatabase.openOrCreateDatabase(String,CursorFactory) is not applicable
  (actual and formal argument lists differ in length)
  method SQLiteDatabase.openOrCreateDatabase(File,CursorFactory) is not applicable
  (actual and formal argument lists differ in length)

O código que eu fiz é o seguinte:
public class GestorBaseDados {
Context contexto;
SQLiteDatabase BD;
public GestorBaseDados(Context cont) {
    contexto=cont;
    String erro=null;
    try {

  BD=SQLiteDatabase.openOrCreateDatabase("BaseDados",SQLiteDatabase.CREATE_IF_NECESSARY,null);

    }catch (Exception e)
    {
        Toast.makeText(contexto,"erro "+e.toString(),Toast.LENGTH_LONG).show();

    }

}

}
Isto é uma classe que vai ter todos os métodos para mexer na base de dados.
Comment: Coloca o erro que ocorreu
Comment: E que erro que dá? Sem a mensagem de erro fica mais dificil.
Comment: Foi este : Error:(16, 54) error: no suitable method found for openOrCreateDatabase(String,int,)
method SQLiteDatabase.openOrCreateDatabase(String,CursorFactory,DatabaseErrorHandler) is not applicable
(actual argument int cannot be converted to CursorFactory by method invocation conversion)
method SQLiteDatabase.openOrCreateDatabase(String,CursorFactory) is not applicable
(actual and formal argument lists differ in length)
method SQLiteDatabase.openOrCreateDatabase(File,CursorFactory) is not applicable
(actual and formal argument lists differ in length)
Comment: nem sequer me deixa compilar, o projeto
Answer: Não existe nenhum overload para o método SQLiteDatabase.openOrCreateDatabase() com essa assinatura.
Use
SQLiteDatabase.openOrCreateDatabase("BaseDados", null);

que é o equivalente a
SQLiteDatabase.openDatabase("BaseDados", null, SQLiteDatabase.CREATE_IF_NECESSARY).

Comment: o método openDatabase cria a base de dados também?
Comment: Cria se for necessário, veja que é passada a flag `SQLiteDatabase.CREATE_IF_NECESSARY`
Comment: tanto o primeiro método que me indicou como o segundo dão me erro
Comment: O mesmo erro? Veja se está a escrever bem a chamada ao método.
Comment: já não é o mesmo é outro para a primeira opção que me indicou vou lhe passar o código
Comment: Você não alterou o código. Substitua `BD=SQLiteDatabase.openOrCreateDatabase("BaseDados",SQLiteDatabase.CREATE_IF_NECESSARY,null);` por `BD=SQLiteDatabase.openOrCreateDatabase("BaseDados",null);`
Comment: eu já fiz isso, só que quando pus o código, no site alterei para a forma original para as outras pessoas ver como estava. E continua a não dar, eu fiz um toast e ele diz me que não consegue fazer a base de dados.
Comment: Não sei exactamente o que quer fazer mas o normal é usar uma classe derivada de [SQLiteOpenHelper](http://developer.android.com/intl/pt-br/reference/android/database/sqlite/SQLiteOpenHelper.html) em vez de usar a classe *SQLiteDatabase*. Veja [aqui](https://github.com/codepath/android_guides/wiki/Local-Databases-with-SQLiteOpenHelper) um exemplo de implementação.
Comment: já resolvi o problema tem- se de adicionar um this antes do método  Fica assim:  BD=this.openOrCreateDatabase("BaseDados",CREATE_IF_NECESSARY,null);

Porque essa linha de código me dá erro?


Angular 8: Differential Build Not Working

Question: I am using Angular 8.3.23.
I successfully build and deploy to localhost using:
ng serve --ssl
but when I build for production using:
ng build --prod
The build works without error:
Generating ES5 bundles for differential loading... ES5 bundle generation complete.
When I browse to my app using any of the latest browsers (Opera, Chrome, Firefox), I get console error:
Uncaught TypeError: e.getOwnMetadata is not a function
I have studied the accepted answer for Differential Build/Loading and followed its advice to study the Angular Deployment doc's Differential Loading section. I have verified that my tsconfig.json agrees with the doc's suggestion:
{
  "compileOnSave": false,
  "compilerOptions": {
    "outDir": "./dist/out-tsc",
    "baseUrl": "src",
    "sourceMap": true,
    "declaration": false,
    "module": "esnext",
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es2015",
    "types": ["node"],
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2018",
      "dom"
    ]
  }
}

The Angular doc also has a link to browserslist, which has an example that I followed to add a browserslist at the bottom of my package.json file:
  "browserslist": [
    "defaults",
    "last 2 Opera versions",
    "last 2 Firefox versions",
    "last 2 Chrome versions",
    "not ie <= 11",
    "not Edge <= 86",
    "not Safari <= 20",
    "not iOS <= 11",
    "maintained node versions"
  ]

The root problem is that my app will not initialize, due to the following error:
    Uncaught TypeError: e.getOwnMetadata is not a function
    at main-es2015.d5bb5cb8e875001c3644.js:1
    at a (main-es2015.d5bb5cb8e875001c3644.js:1)
    at main-es2015.d5bb5cb8e875001c3644.js:1
    at Module.zUnb (main-es2015.d5bb5cb8e875001c3644.js:1)
    at d (runtime-es2015.25716398ef338277e502.js:1)
    at Object.0 (main-es2015.d5bb5cb8e875001c3644.js:1)
    at d (runtime-es2015.25716398ef338277e502.js:1)
    at c (runtime-es2015.25716398ef338277e502.js:1)
    at Array.a [as push] (runtime-es2015.25716398ef338277e502.js:1)
    at main-es2015.d5bb5cb8e875001c3644.js:1

Since the app works fine with a localhost build, the only thing I can think of causing the error is the differential build. But, how to fix?
Thanks
Answer: I found the solution at Git Issue 7476.
Adding the following to my polyfills.ts file was all that was needed:
import 'reflect-metadata';


Principle Component Analysis for pre-grouped variables

Question: I have a dataset that has many overlapping factors related groups of factors, and factors that we would like to investigate if there is a relationship. 57 measured factors total, in 50 individuals (lets ignore my low n...)
For instance,
1) Blood Pressure: systolic, diastolic, mean, & pulse pressure (height of BP wave)
2) Blood Flow: min, max, mean, & height for blood flow.
3) Size: Individual's weight, length, and circumference.
Each of these groups has substantial collinearity, as you may have guessed, since they are simultaneous measurements of related features. Blood flow is also related to blood pressure, and size always matters.  Of course, I have less related features thrown in the mix also, including diet, organ weights, mother's weight...
I can certainly select the 'most meaningful' factor from each group, but I dislike ignoring the potential importance of the removed factors.
My goal is Multiple Linear Regressions for areas of interest.
My question is, can I (and how) be selective about my groupings in PCA?  Looking at the component plot, the groups naturally cluster together - but in instances where they aren't as clustered as would be ideal, or a stray variable that isn't blood pressure happens to join the blood pressure cluster, what are my options?  Do I have to add all variables to PCA, or can I choose those that I would like to group?
Additionally, can someone please explain why units matters for correlations?  I was told if I change my g measurements to kg (thus changing 167 to 0.167), it would impact the coefficients/relationships found in MLR.  That doesn't logic to me.
I hope this is specific enough!  I see a lot of answers that have to account for a variety of interpretations of the question!
Use of PCA analysis to select variables for a regression analysis this question gets close to mine, but I wasn't sure what was being asked.
Answer: In principle you have a lot of freedom what to do. So yes, you can use Principal Components to summarise different subgroups of your variables. There is no fixed rule how to do this, but I think your intuition to perform PCA separately for groups of related variables (maybe representing each group by one or two of them) makes sense to me. Whether this is the best you can do is a different matter. PCA doesn't involve the $y$ and in terms of optimising prediction error methods that involve the $y$ often do better, however selecting variables not involving the $y$ avoids a bias of the resulting regression coefficients and p-values (if you're interested in them). If you reduce dimensionality and therefore information for the variable groups but you take the "stray variables" as they are (which is a legitimate thing to do in principle), you may implicitly upweight the stray variables, although I'm not sure this is a bad thing. With 50 individuals chances are you want to bring the final number of variables down to around 10 or even less, so you may have to be a bit radical. Alternatively you could look at things like Lasso.
Regarding measurement units, PCA in its raw form is based on the covariance matrix, not the correlation matrix. In this form it is obviously dependent on measurement units (this is sensible if measurement units are the same and higher variances imply higher variable importance). However PCA is these days probably more often performed on correlations, in which case the measurement units can be changed without changing the result (your PCA function should allow you to specify whether it runs on correlations or covariances).
Regarding the MLR (which I see is what the units question is actually about), the regression coefficient can be interpreted as the expected change in $y$ if a certain $x$ is changed by 1 unit assuming all other $x$ are held constant. Obviously this changes if the unit of an $x$ (or $y$) changes, however this is not a problem because MLR is affine equivariant, meaning that the regression coefficients change only accordingly to account for the measurement unit change, and the model fit is otherwise unaffected.


How can I use Java to read a file

Question: So I have this piece of code in which I want to allow the user to enter in a String of any length and it encrypts the code. To make this more than a basic project, I thought it would be cool to have a 'save' feature where the user can pickup from later on.
The problem arises here. I was going through Youtube and through a video where I learned how to create a file and write to a file. When I went to the part where I read the file (load) I saw that I need to create a variable for every single character in the file. As I will not know how many variables to make, I am stuck.
In his code (I will display it) he uses a while loop to loop through the contents of the file and using a variables he prints out its contents. My code is as follows:
import java.util.*;
public class Sep {
    private Formatter x;
    public void openfile () {
        try {
            x = new Formatter("Gogo.txt");
        }
        catch (Exception e) {
            System.out.println("You have an error mate!!");
        }
    }
    public void addStuff() {
        x.format("%s%s%s%s", "Gogo will return!!", "Stronger than ever!!", "Faster than can be seen!!", "And he is out for blood...");
        }
    public void closeFile () {
        x.close();
    }
}

As the user will be entering whatever he wants, I have no bloody clue on how many variables to make.
The youtuber has this:
import java.util.*;

public class Sep {
    private Formatter g;
    private Scanner x;
    public void openfile () {
        try {
            g = new Formatter("Gogo.txt");
            x = new Scanner(new File("gogo.txt"));
        }
        catch (Exception e) {
            System.out.println("You have an error mate!!");
        }
    }
    public void addStuff() {
        g.format("%s%s%s%s", "Gogo will return!!", "Stronger than ever!!", "Faster than can be seen!!", "And he is out for blood...");
        }
    public void readFile() {
        while(x.hasNext()) {
            String a = x.next();
            String b = x.next();
            String c = x.next();
            System.out.printf("%s %s %s\n", a,b,c);
        }
    public void closeFile () {
        x.close();
    }
}

Comment: It's also a bad idea to follow some random youtuber's advice, instead of reading [proper tutorials](https://docs.oracle.com/javase/tutorial/) which explain in depth how things work. I fear that watching a youtube video may give you a false idea that programming is *easy*, although that idea usually disappears quite quickly.
Comment: It is a bad idea to use multiple next() with one hasNext()...
Comment: If you're running in Windows, `new Formatter("Gogo.txt")` and `new Scanner(new File("gogo.txt"))` are reading and writing the same file, which is going to cause problems.  Follow Kayaman's advice and read the tutorials.
Comment: I don't really understand the question?
Comment: It would probably help to know what/how you need to use the characters. Loading an entire file of unknown size is probably a bad way to go, for instance if you only use _N_ consecutive characters at time you shouldn't load more.
Comment: It's also a bad idea to use `next()` when you need to operate on characters. Users will be ticked off if they decrypt their file and find all the white-space missing.
Comment: `Youtube` tag is hurt and shouts **use me only when you need me.**
Comment: Consider using [`java.io.FileReader`](http://docs.oracle.com/javase/8/docs/api/java/io/FileReader.html) instead of `Scanner`.
Answer: You could use an ArrayList:
ArrayList<String> al = new ArrayList<String>();
al.add(x.next);//this is in while loop

Then just print out the ArrayList:
foreach(String s : al)
    System.out.printf("%s\n", s);

How can I use Java to read a file


Can I call drupal_add_css from a block?

Question: I'm building an HTML table in a php filter in a block. Can I/is it OK if I call drupal_add_css() from the block php?
Thanks.
Answer: Although probably ok, rather than using the PHP filter, you may be interested in using

hook_block_info
hook_block_view

To define your blocks instead. Perfectly fine to use drupal_add_css there.
Eg :
<?php
drupal_add_css(drupal_get_path('module', 'custom') . '/css/custom.css', array('group' => CSS_DEFAULT, 'every_page' => TRUE));
?>

Comment: It's bad practice to use the PHP filter, as it messes with backups (can't place code in a repository), maintenance (code is stored in different areas), creates security holes. It's also been removed from D8 core. I would unless, for what ever reason, using the php filter is 100% unavoidable, it should be avoided.
Answer: instead of using hook_block_view, which implies creating the block content fully by hooked functions, i am using hook_block_view_alter like this. It maintains the capability to alter the content using Drupal's block admin pages in more user friendly way :
function font_awesome_add_css_block_view_alter(&$data, $block) {
  if (!is_object($data) && !isset($data->bid)) {
    return;
  }
  switch ($data->bid) {
    case '366':
      if (is_array($data['content'])) {
        break;
      }
      $current_content = $block['content'];
      $block['content'] = array(
        '#markup' => $current_content,
        '#attached' => array(
          'css' => array(
            'http://maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css'
          ),
        ),
      );
    break;
  }
}

Comment: PS. The drupal_add_css PHP code snippet didn't work for me. "CSS_DEFAULT, 'every_page' => TRUE));" was shown in my block's final content view

Can I call drupal_add_css from a block?


Substituir Tag por código php

Question: Olá, gostaria de saber se existe um meio de fazer via php o que o sublime text faz com os snippets. Preciso por exemplo substituir uma tag por um código pré-formatado. Tipo:
{{repete start}}

Conteúdo

{{repete end}}

<?php foreach ($noticias as $noticia): ?>
    <?= $noticia['texto'] ?>

<?php endforeach ?>

Conteúdo
Conteúdo
Conteúdo
Conteúdo
Conteúdo
(quantos existirem no banco)

É possível ser feito isso utilizando php? Minha idéia é facilitar o trabalho de integradores que utilizam um painel de administração em php que a empresa utiliza. Muito obrigado.
Comment: Não ficou muito claro o que você quer fazer. Qual é exatamente a relação entre os 3 trechos de código?
Comment: O primeiro é a tag que eu quero "criar", pra dizer que aquele bloco irá se repetir. O segundo bloco é o PHP que ele deve executar ao processar isso na página e o terceiro bloco é o output em html do que ele apresenta dessa consulta (levando em conta que a consulta ao banco e select da tabela eu já esteja fazendo acima disso).
Comment: Não é assim tão simples. O que teria o `repete start` ? Como ele saberia que era a tabela noticias ? E como saberia que o conteudo dentro do div era um `campo` da tabela e referente ao repete start ?
Comment: sim tem como e inclusive uso em meu Framework. posso da uma ideia de como fazer.
Answer: Exemplo de como fazer com PHP:
Ex:
{{ variavel }} vira <?php echo $variavel; ?>

Código PHP:
preg_replace("/({{([ a-zA-Z]*)}})/gm", "<?php echo \$${2}; ?>", $string);

Lógico que você fara um fopen para abrir um arquivo e escreve as modificações da view que você quer. Site para testar esse regex: https://regexr.com/

Substituir Tag por código php


Function $f$ which tends to $0$ but the mean $\frac 1 x \int_1^x f$ doesn't tend to $0$

Question: Is there a continuous function $f : ]1, \infty[ \to \Bbb R_{>0}$ such that $f(x) \to 0$ when $x \to +\infty$ but
$$\lim_{x \to +\infty}  \dfrac 1 x \int_1^x  f  \;\neq\; 0$$
(either the limit doesn't exist but a better example for me would be when it exists and is $>0$)?
I tried something like $f(t) = \dfrac 1 {\log\big(\log(t)\big)}$ but I'm not sure how to handle the integral. The problem seems to be when $f$ doesn't go to $0$ sufficient quickly.
Comment: There is none. The proof is a simple exercise on the X-epsilon definition of limit.
Comment: If $f(x)$ is continuous on $[1,\infty)$ then $f(1)$ has to be finite thus you cannot have $f\to \infty$ as $x\to 1$. If you instead want to consider continuous functions on $(1,\infty)$, for which it can happen, then note that if you are to ask for the limit of something then that something has to exist in the first place. For example it does not make much sense to ask what the limit of $\frac{1}{x}\int_1^x \frac{{\rm d}t}{t-1}$ is as the integral does not exist for any $x$.
Comment: This is irrelevant since you know by hypothesis, say, that $$\int_1^2f(t)dt$$ is finite.
Comment: @Did : I tried that, but I'm stuck if $f$ takes very large values when $x \to 1$, for instance $\lim_{x \to 1} f(x) = +\infty$ "very quickly".
Answer: Writing the expression as
$$\tag 1 \frac{\int_1^x f(t)\,dt}{x}$$
we can apply L'Hopital (since the denominator $\to \infty$). The ratio of derivatives is simply $f(x)/1=f(x),$ which is given to $\to 0.$ Therefore the limit of $(1)$ is $0.$
Answer: No.
If $f(x)\to 0$, then you can find an $x_0$ such that $f(x)<\varepsilon/2$ everywhere to the right of $x_0$, and then no matter how large $\int_1^{x_0} f(t)\,dt$ is, you can always push $\frac1x \int_1^x f(t)\,dt$ below $\varepsilon$ by choosing $x$ far enough to the right of $x_0$.
Of course you do need to assume that, say, $\int_1^2 f(t)\,dt$ exists (and is finite) at all. For example, if $f(t)=\frac{1}{t-1}$, then $\frac1x\int_1^xf(t)\,dt$ never exists (or is always infinite, depending on your conventions).
Comment: Thank you for your answer. But is there no problem if $f$ takes very large values when $x \to 1$, for instance $\lim_{x \to 1} f(x) = +\infty$ "very quickly"? I will think about it anyway.
Comment: @Alphonse: I've added a paragraph discussing that to the answer.
Answer: No, there is not.
Lets take $\varepsilon$ and prove that there exists $N$ s.t. for $x>N$ the mean
$M(n) =\dfrac 1 x \int_1^x  f(x)\,dx \in [-\varepsilon,\varepsilon]$
Suppose that for $x> Q~|f(x)| < \delta $. Then
$$M(2Q) = \frac12M(Q)+\frac1{2Q} \int_1^{2M}  f(x)dx\le \frac12M(Q)+\frac1{2Q} \int_1^{2Q}  \delta \,dx = \frac12M(Q)+\delta$$
Similarly
$$M(4Q) \le \frac12M(2Q)+\delta \le  \frac14M(Q)+(1+\frac12)\delta$$
and so on. So we will finally find the power $q$ such that $M(2^qQ)<\varepsilon$.


Do there exists $p$ and $q$ primes for which $p^3+1=2q^2$?

Question: Do there exists $p$ and $q$ primes for which
$p^3+1=2q^2$?
Answer: Answer:
No
Proof:
First we shall prove that $p=2$ can't be a solution.
If $p=2$ then we need to find a prime $q$ such that $9=2^3+1=2q^2$, obviously there is no such prime.
Now let us assume that there are prime solutions, we will call them $(p,q)$, therefore:
$$(p+1)(p^2-p+1)=p^3+1=2q^2$$
Therefore
$$\frac{p+1}{2}(p^2-p+1)\mid q^2$$
where $\frac{p+1}{2}\in \mathbb{N}\setminus\{1\}$ since $p$ is an odd prime.
Now let's assume that $p^2-p+1 = 1$.
In this case we get no prime solutions because the solutions to $p^2-p= 0$ are $1$ and $0$ both are not prime.
Therefore because both of the factors are in $\mathbb{N} \setminus\{1\}$ and their product divide $q^2$ where $q$ is a prime number we get:
$$\frac{p+1}{2}=q \  \land \ p^2-p+1 = q \ \Rightarrow \ p^2-p+1 = \frac{p+1}{2} \ \Rightarrow \ 2p^2-3p+1 = 0 \ \Rightarrow \ p=1 \lor p=\frac{1}{2}$$
And again we get that $p$ be is not a prime resulting in a contradiction to the assumption that there are solutions.
Answer: Suppose $p$ and $q$ are two prime numbers satisfying
$$p^3+1=2q^2.$$
Note that
$$p^3+1=(p+1)(p^2-p+1),$$
and let $d$ denote the greatest common divisor of these two factors. Then $d$ divides $3$ because
$$1\cdot(p^2-p+1)-(p-2)\cdot(p+1)=3.$$
If $d=1$ then either $p+1\leq2$ or $p^2-p+1\leq2$, both of which are clearly impossible.
If $d=3$ then $3^2$ divides $p^3+1=2q^2$ and so $q=3$. But then
$$p^3+1=2q^2=18,$$
which is again clearly impossible.


Best way to get current user purchased products

Question: I need to get purchased products by the current user (Drupal Commerce).
I use this function to reach there :
function mymodule_user_purchased_products() {
    global $user;
    $query = db_select('commerce_order', 'corder');
    $query->join('commerce_line_item', 'li', 'corder.order_id = li.order_id');
    $query->join('field_data_commerce_product', 'prod', 'li.line_item_id = prod.entity_id');
    $query->condition('corder.uid', $user->uid, '=')
          ->condition('corder.status', 'completed', '=')
          ->fields('prod', array('commerce_product_product_id'));
    $result = $query->execute();
}

But I think I forget certain things, and this solution isn't optimal.
Is it the recommended way?
Comment: Cache the results if you need or write hooks to store it in a custom table if you need to do more with the data, but if it works, then use what you have.
Comment: What's not optimal about it?
Comment: It is not a "heavy" solution? In particular in case the user would have bought numerous products? There are not ways to optimize it? If she is optimal, it's perfect ;)
Answer: One one thing that I can think of to change. Make sure you only get a single result.
$query = db_select('commerce_order', 'corder');
$query->join('commerce_line_item', 'li', 'corder.order_id = li.order_id');
$query->join('field_data_commerce_product', 'prod', 'li.line_item_id = prod.entity_id');
$query->condition('corder.uid', $user->uid, '=')
      ->condition('corder.status', 'completed', '=')
      ->addExpression('DISTINCT prod.commerce_product_product_id', 'product_id');

Using this line:
->addExpression('DISTINCT prod.commerce_product_product_id', 'product_id');

instead of:
->fields('prod', array('commerce_product_product_id'));

will insure that you only get one product_id per row in your result. By using the DISTINCT SQL Keyword, it will only allow distinct values to be returned.
Comment: Thanks nvahalik, I'm going to change this line. One thing: from what moment does it become necessary to create a custom table? Approximately, from how many products on the site for example?


Sort criteria in views: how to add custom one

Question: I have added a "node title" field.  I want to add this sort criteria to the node: the number of times the node  has been viewed by visitors in a week, descending.
If I want to add a sort criteria with PHP code and a SQL query to insert in Views module, how should I do?
ps:i have overwritten a field. i want to query the database and using the query to Sort Criteria**how to add the custom one
Comment: You don't alter the code of Views to add a new sort criteria: you create a module that implements the new criteria. Are you sure there isn't already a similar sort criteria?
Comment: yeah.i am sure,if i create a module that implements the new criteria.how do i do?
Answer: First, make sure you have Drupal's Statistics module enabled and collecting page view statistics.
In Drupal 6, you need to enable Count content views under admin/reports/settings. This will count total node views and give you total day count. Unfortunately, it does not give you a weekly view count by default.
This will give you a sort criteria for Node statistics: Total views and Node statistics: Views today.
Upon closer inspection of the day count for node views, this value is reset to 0 every 24 hours by statistics_cron. This value would prove more useful as a sort criteria if it was the most recent 24 hour's node views. So, the Node statistics: Total views would be your best bet.
NOTE: See Statistics Granularity module for week, month and year.
Comment: thank you..if i want to add a Sort criteria to views. do you know how to add it?
Comment: Yes. Edit the view. There's a section called "Sort Criteria". You will find the relevant sorting criteria under "Node statistics". You might also want to install the [Advanced Help](http://drupal.org/project/advanced_help) module to read Views documentation.
Comment: thank you, i know that. but i have overwrote a field. i want to query the database and using the query to Sort Criteria


Verificação de Versões do Browser

Question: Estou fazendo um site e gostaria de colocar uma verificação de navegadores que o usuário está utilizando.
Eu não quero que o site seja utilizado no IE 6, 7 e 8. Além de algumas versões do Firefox antigas que tem naqueles ambientes Linux.
Caso o navegador do usuário sejam alguns desses antigos quero redirecionar o usuário para uma página onde ele pode fazer o download de um navegador mais recente.
Mas estou pensando se esses navegadores antigos entendem o jQuery, porquê estava pensando em fazer uma rotina por meio dessa biblioteca.
Ou tem alguma outra maneira de fazer isso ? Eu não conheço.
Comment: Você pode utilizar tanto `JavaScript`, quanto `CSS` para fazer a verificação do browser do usuário, você também pode utilizar uma linguagem que está rodando no `back-end`, como o `PHP` por exemplo.... no seu caso aconselho utilizar `JavaScript`, pra isso também será necessário ter um certo conhecimento em `RegEx`
Answer: Use o http://modernizr.com
Adicione ao header isto:

E no final da página isto:

O endereço http://exemplo/upgrade é o local de onde irá ter os links para os navegadores novos.
Comment: Eu uso esse modernizr nos meus sites. Pelo visto não sei usar direito! uahuhauah Guilherme, é somente isso ?
Comment: Sim @DiegoSouza este método verifica o suporte a media-query, que hoje em dia tem em todos navegadores modernos, se não tiver suporte é igual a `false` então usamos `window.location` :)
Comment: Entendi, Man. Valeu, vou implementar e já retorno!
Comment: Deu certo. Eu testei no IE 5, 6 e 7. Redirecionou para uma página que estou criando agora para o usuário atualizar o navegador.
Comment: Tem um detalhe. Eu tenho um preloader num site específico aqui. Tem como essa rotina rodar até mesmo antes desse preloader carregado no window.load com jQuery ?
Comment: @DiegoSouza ele roda antes do preloader sim, só não roda antes do $.ready, recomendo você fazer assim: `if(Modernizr.mq('only all') === false) {
   window.location.href = "http://exemplo/upgrade";
} else {
    /*inicia o preloder*/
}`
Comment: Entendo. Mas os navegadores antigos entendem o jQuery ?
Comment: @DiegoSouza eu não estou entendendo, você quer rodar o preloader após o usuário baixar a nova versão ou quer que funcione em qualquer browser. Até aonde entedi você quer forçar o usuário a baixar um navegador moderno primeiro. Se é isto o "preloader" só deve rodar se `Modernizr.mq('only all')` for igual a `true`, ou seja suportar tecnologias novas :)
Comment: Não mano... esquece isso que você falou agora. Eu tenho um preloader. Quero que a rotina de verificação de browser rode antes do preloader. Beleza ? Ou seja, quando a rotina ver que o browser não é compatível, ele nem chega carregar o preloader. Mas esse preloader é carregado por $.ready, isto é, jQuery. A pergunta é: os navegadores antigos interpretam jQuery ? Entendem o $.ready ?
Comment: @DiegoSouza o que você disse foi o mesmo que eu disse, o exemplo que postei nem chega no onload e provavelmente é disparado antes do `$.ready`.

Verificação de Versões do Browser


Filter Views results by users mobile OS

Question: I'm building a mobile website with Drupal 7 and I need to filter articles displayed using Views by visitors mobile OS. If visitor is using Android phone - I would like display only articles with "Android" tag, etc. Visitors with "other" mobile OS'es will get "no results" message.
What is the best approach to accomplish this task?
Answer: I would take a look at the Context module with this add-on: Context Useragent
Answer: If you want to use Panels (or just Page Manager from ctools), you can use the Mobile Detect module if you also enable the Mobile Detect ctools sub-module.
Make your view over the content type.  Then add a pane display, and add a filter for your device term.  Add more panes as needed.
Use Page Manager to make a page.  Make variants for each of the mobile devices that you need.  Set the access options to whatever you need.  Then set the selection rule to use the mobile detect device type.  You will get a modal with a whole bunch of devices.  Configure as needed.  Then for the content, add the pane you created above.  Add additional variants as needed.
Full disclosure: I am the author/maintainer for Mobile Detect, but this is one of the scenarios I envisioned when I made this module.
Comment: is Mobile Detect module stable enough to be used in production?
Comment: I think so.  New features will mainly appear in new sub-modules.  It is being developed to support a new website we are developing, but we don't have it in a production site yet.

Filter Views results by users mobile OS


Inaccurate parameter estimates for state-space models?

Question: I'm modeling time series using dynamic linear/state-space models, and was surprised by how inaccurate the estimates of model parameters can be, even for fairly long series.
In particular, I'm generating series of length n using the second-order local linear trend model:
$\begin{align}
y_t &= \mu_t + \alpha_t & \alpha_t \sim N(0, \sigma_\alpha^2)\\
\mu_{t+1} &= \mu_t + \nu_t + \beta_t & \beta_t \sim N(0, \sigma_\beta^2)\\
\nu_{t+1} &= \nu_t + \gamma_t & \gamma_t \sim N(0, \sigma_\gamma^2)
\end{align}$

for some particular values of the the three variances $\sigma_\alpha^2, \sigma_\beta^2$, and $\sigma_\gamma^2$. Here the observed series is $y_t$, while $\mu_t$ and $\nu_t$ are unobserved state variables. I then estimate the variances using the $\texttt{dlm}$ package in R.
Here is some code:
library(dlm)

n <- 100
v <- c(0.1, 0.2, 0.3)
s <- sqrt(v)
mu <- rnorm(1)
nu <- rnorm(1)
y <- vector(mode = "numeric", length = n)
for(i in 1:n) {
    y[i] <- mu + rnorm(1, sd = s[1])
    mu <- mu + nu + rnorm(1, sd = s[2])
    nu <- nu + rnorm(1, sd = s[3])
}

my_build <- function(p) {
    dlmModPoly(order = 2, dV = p[1], dW = c(p[2], p[3]))
}
mle <- dlmMLE(y, parm = c(1, 1, 1), build = my_build, lower = c(1e-4, 1e-4, 1e-4))
print(mle$par)

(Sorry for the probably bad R code, I'm just a beginner R programmer.) It generates a $n=100$ series according to the above equations with variances equal to 0.1, 0.2, and 0.3, and then estimates the variances using the dlmMLE function.
What surprised me is how off these estimates can be, even for a series of length 100. The average absolute error is about 0.11 (so around 50%). For a series with $n=1000$, the error is still around 0.04 (so about 20%).
Is this normal? Is parameter estimation for state-space models inherently difficult and noisy and error-prone (and therefore requires very long series for accurate estimates), or am I doing something wrong?
Answer: "Is this normal?" I don't use this software, and I'm not sure what you mean by "normal," but nothing jumps out at me. A few thoughts:

Asymptotic distributions of MLE estimates have a variance term that is the reciprocal of the Fisher Information. This means, roughly, that you get wider confidence intervals when the likelihood surface is "flatter" or "less pinched" on average. This has connections with how identifiable a model is. In other words, not all SSMs are created equally. I always think about how much I could pare down a model by removing a parameter or two, and if that would make a difference.

I'm not sure how you're calculating these intervals, but it's all just food for thought.

Asymptotics only apply when your data set is large enough. Your data might not be large enough to justify these kind of confidence intervals. In this case, I'd recommend either collecting more data, or transforming the parameter space so that MLE distributions become more normal. You could start off by estimating $\log \sigma^2$ or $\log \sigma$ instead of $\sigma^2$. If you exponentiate that parameter estimate, that would give you the estimate of $\sigma^2$, by the invariance principle. This would also free you from having to specify lower bounds for your algorithm.

You're talking about percentage errors, which seems like you're interested in estimating $\sigma^2/ \mu$. You can do this with standard MLE theory, as well, using the invariance property again, and getting confidence intervals using the delta method, etc.

Try plotting profile log-likelihoods. Hold one of the three parameters fixed, simulate only one data set, and see if this surface looks flat at the top.


Normal Distribution question?

Question:
Consider tossing a fair coin 100n times, where n is geometrically distributed with mean 6. Due to a counting error, it is reported that the fraction of heads is in [0.5, 0.51]. What is the most likely value for n?

My professor calculated the value of n=3, but I have no idea how to get that. Can anyone explain ?
Comment: This question should be tagged as `[self-study]`, please also read http://stats.stackexchange.com/tags/self-study/info
Comment: As pointed out in comments to the duplicate, the meaning of this question is obscure.
Answer: First, do you know what your professor meant by "due to a counting error"? That seems like it could ruin any individual inferential step, making any argument shaky. I'm going to assume they meant something like "instead of reporting all of the summary, we report only a true portion of the summary."
The long way: we start off with a prior on $n$, that it is geometrically distributed with mean $6$. We then generate a number: $H$, the number of heads when a fair coin is flipped $100n$ times, which is a random variable with a binomial distribution $B(100n,0.5)$. From $H$, we then estimate the underlying propensity of the coin to land on heads, for which we'd use a beta distribution whose parameters are (heads+0.5, tails+0.5) if we use the Jeffreys prior.
Finally, we have something that would make sense to report as $[0.5, 0.51]$, which is presumably the credible interval or something associated with this beta distribution.
We can now calculate the likelihood for each value of $n$, and we can pick the highest one, which if your professor is correct is 3.
One might be able to use an approximation to get there faster--my attempts to jump straight to the variance of the beta distribution from knowing that the range is $[0.5, 0.51]$ got a number for $n$ considerably higher than 3, though, so it must be the case that they want the binomial distribution to be relevant.
Comment: +1 This is a valiant effort to make sense of the question.

Normal Distribution question?


Rails model directly use other class methods

Question: I am doing Rails app and i see that i could refactor my code. Just can't find how. I have many models like Company, News, Profile and many more which use Image upload. So in every class i must always copy-paste 30 rows of methods which implement always the same logic - upload_image, get_image_name, delete_image.  How is possible to do, that my Model class would automatically have the methods from somewhere else? I would like to just put to the Model - load 'GlobalMethods', or even somehow include the methds in activerecord:base to just have them for every class and i would use whenever i want. And from controller i would just leave as it is. For example - News.upload_image and it would do this same as this logic would be in original model.
Please explain with example, because i have readed more and didn't understand or it even possible.

At this moment i did:

#models/concerns/uploading.rb
module Uploading
  extend ActiveSupport::Concern

  included do
    def do_upload
        puts 'aaaaaaaaaaaaaaa'
    end
  end
end

and model:
class Company < ActiveRecord::Base
    include Uploading
end

and i get this error:

uninitialized constant Company::Uploading

My rails version: '4.2.5'
I did server restarts after every try
My application.rb file looks:
require File.expand_path('../boot', __FILE__)

require 'rails/all'

Bundler.require(*Rails.groups)

module Vca
  class Application < Rails::Application
    config.active_record.raise_in_transactional_callbacks = true
    config.autoload_paths += %W(
      #{config.root}/app/models/concerns/uploading.rb
    )
  end
end

Still the same

NameError in CompaniesController#index
uninitialized constant Company::Uploading

class Company < ActiveRecord::Base
    include Uploading  # <-- error
end

I have gem 'Spring'. I turned off server, in terminal i runned "spring stop" and started server. But it didn't solve this.
Comment: `concerns` are enabled by default since Rails 4. If you are still on Rails 3 you should load the path with concerns, take a look please on this gist example https://gist.github.com/dhh/1014971
Answer: Take a look at ActiveSupport::Concern
For example
app/models/concerns/my_concern.rb
module MyConcern
  extend ActiveSupport::Concern

  included do
    # common stuff here
  end

  class_methods do
    # define class methods here
  end
end

app/models/my_model.rb
class MyModel < ActiveRecord::Base
  include MyConcern

  # ...
end

By the way, you can refer to the model class with self in the included block and out of any instance methods, and inside the methods within the class_methods block.
Comment: gem 'rails', '4.2.5'
Comment: Have you modified `autoload_paths`? What if `include ::Uploading`?
Comment: No. i did nothing more than in example.
Comment: Please paste the full path (starts from rails root) of the file `uploading.rb`.
Comment: module Sta
  class Application < Rails::Application
    config.active_record.raise_in_transactional_callbacks = true
    config.autoload_paths += %W(
      #{config.root}/app/models/concerns/uploading.rb
    )
  end
end
Answer: You'll notice that your standard rails project includes a folder called concerns under your models folder.
Create a module in that folder, image_handling.rb
module ImageHandling
  extend ActiveSupport::Concern
  included do
    # ...(include all your common methods here)
  end
end

In your Company, News, Profile models call the concern...
class Company < ActiveReecord::Base
  include ImageHandling
  ...
end

Comment: did you stop and restart your server?
Comment: You're not using the `spring` gem, are you?  If so, you should do `spring stop` after stopping server and before restarting server.
Comment: Yes, i see this gem is listed. It was on fresh created rails project.
Comment: Is there any other way than this? I can't make it work.
Comment: Did you make any progress?  You're running development server, right? `rails s` ? And you said that before you run `rails s` you ran `spring stop` ?
Comment: Yes to everything. No progress.. I had to make it the hard way and do much repeatable code. Used much time and didn't solve it. But anyway I want to clear this out, because i plan to use this many times for more Dry and clean code.


Technique to expand polynomials and equate coefficients

Question: This question concerns my attempts to re-implement parts of this paper on developing wavelet filters. Though I don't think it is necessary to look at that paper, for full context, I'm trying to compute the contents of table II (using equation 9 and the description under the heading A Spline Variant with Less Dissimilar Lengths).
To summarize the technique, we have a trigonometric polynomial in $e^{-i\xi}$ (with real coefficients) given by the product of two factors, $H\left(\xi\right)$ and $\hat{H}\left(\xi\right)$.
These factors are defined as follows:
$$
H\left(\xi\right) = 2^{-\frac{1}{2}}\left.\sum_n h_ne^{-in\xi}\right.\qquad \hat{H}\left(\xi\right) = 2^{-\frac{1}{2}}\left.\sum_n \hat{h}_ne^{-in\xi}\right.
$$
in which the coefficients are symmetric about $n=0$, that is $h_n = h_{-n}$ and $\hat{h}_n = \hat{h}_{-n}$.
We wish to derive those factors so they have as close a number of non-zero coefficients as possible (which I know to be 9 and 7 for $h_n$ and $\hat{h}_n$ respectively for the case described below).
The polynomial we have is of a simple symmetric form (derived from equation 9 in the above reference) and is as follows (I might well have made a mistake in the preceding algebra, but I'm sure the form is correct):
Defining $B = e^{-i\xi}$
$$
H\left(\xi\right)\hat{H}\left(\xi\right) = \frac{B^{-7}}{2^8}\left[-\frac{5}{16}\left(B^{14} + 1\right) + \frac{49}{16}\left(B^{12} + B^{2}\right) - \frac{245}{16}\left(B^{10} + B^{4}\right) + \frac{1225}{16}\left(B^{8} + B^{6}\right) + 128B^{7}\right]
$$
Given this, I can define $H\left(\xi\right)$ and $\hat{H}\left(\xi\right)$ as follows:
$$
H\left(\xi\right) = B^{-4}2^{-\frac{1}{2}}\left[h_0B^4 + \sum_{n=1}^{4} h_n\left(B^{4+n} + B^{4-n}\right)\right]\\
\hat{H}\left(\xi\right) = B^{-3}2^{-\frac{1}{2}}\left[\hat{h}_0B^3 + \sum_{n=1}^{3} \hat{h}_n\left(B^{3+n} + B^{3-n}\right)\right]
$$
in which I wish to find $h_n$ and $\hat{h}_n$.
Now, I can always multiply and expand out the above and attempt to equate the coefficients by hand, but this seems long, tedious and error prone.
Is there some technique I can use to automate this task? I initially thought a matrix technique, but it's not obvious to me how. It might be really trivial, so feel free to point it out as such!
Edit: I'm pretty sure I need an additional constraint to solve this uniquely. In this case it's:
$$
\sum_n (-1)^n h_n = 0 \\
\sum_n (-1)^n \hat{h}_n = 0 \\
$$
My apologies, I've only just come to this conclusion.
Answer: It's not a full solution, but with a helpful pointer from a good friend, the following seems to be part way there...
It's easier to see the symmetry when the equations are written in the following form:
$$
H\left(\xi\right)\hat{H}\left(\xi\right) = \frac{1}{2^8}\left[-\frac{5}{16}\left(B^{7} + B{-7}\right) + \frac{49}{16}\left(B^{5} + B^{-5}\right) - \frac{245}{16}\left(B^{3} + B^{-3}\right) + \frac{1225}{16}\left(B^{1} + B^{-1}\right) + 128\right]
$$
and
$$
H\left(\xi\right) = 2^{-\frac{1}{2}}\left[h_0 + \sum_{n=1}^{4} h_n\left(B^{n} + B^{-n}\right)\right]\\
\hat{H}\left(\xi\right) = 2^{-\frac{1}{2}}\left[\hat{h}_0 + \sum_{m=1}^{3} \hat{h}_m\left(B^{m} + B^{-m}\right)\right]
$$
If we define
$$
c\left(p\right) = B^{p} - B^{-p}
$$
we can see that
$$
c\left(p\right)c\left(q\right) = c\left(p + q\right) + c\left(p - q\right)
$$
We can now write the product of $H\left(\xi\right)$ and $\hat{H}\left(\xi\right)$ neatly as
$$
H\left(\xi\right)\hat{H}\left(\xi\right) = \frac{1}{2}\left[h_0 + \left.\sum_{n=1}^{4}h_nc\left(n\right)\right.\right]\left[\hat{h}_0 + \left.\sum_{m=1}^{3}\hat{h}_mc\left(m\right)\right.\right]
$$
and expand that into a neat sum of products of $h_n$ and $\hat{h}_m$:
$$
H\left(\xi\right)\hat{H}\left(\xi\right) = \frac{1}{2}\left[h_0\left.\sum_{m=1}^{3}\hat{h}_mc\left(m\right)\right. + \hat{h}_0\left.\sum_{n=1}^{4}h_nc\left(n\right)\right. + \left.\sum_{n=1}^{4}\left.\sum_{m=1}^{3}h_n\hat{h}_m\left(c\left(n + m\right) + c\left(n - m\right)\right)\right.\right. + h_0\hat{h}_0\right]
$$
So, we're now in a position to see how the coefficients combine (remembering that $c\left(0\right) = 2$), equating them to the known coefficients of $H\left(\xi\right)\hat{H}\left(\xi\right)$:
\begin{align}
2\hat{h}_{1}h_{1} + 2\hat{h}_{2}h_{2} + 2\hat{h}_{3}h_{3} + \hat{h}_0h_0 &= 0.5\\
h_0\hat{h}_1 + \hat{h}_0h_1 + \hat{h}_{1}h_{2} + \hat{h}_{2}h_{1} + \hat{h}_{2}h_{3} + \hat{h}_{3}h_{2} + \hat{h}_{3}h_{4} &= \frac{1225}{2^{12}}\\
h_0\hat{h}_2 + \hat{h}_0h_2 + \hat{h}_{1}h_{1} + \hat{h}_{1}h_{3} + \hat{h}_{2}h_{4} + \hat{h}_{3}h_{1} &= 0\\
h_0\hat{h}_3 + \hat{h}_0h_3 + \hat{h}_{1}h_{2} + \hat{h}_{1}h_{4} + \hat{h}_{2}h_{1} &= \frac{-245}{2^{12}}\\
\hat{h}_0h_4 + \hat{h}_{1}h_{3} + \hat{h}_{2}h_{2} + \hat{h}_{3}h_{1} &= 0\\
\hat{h}_{1}h_{4} + \hat{h}_{2}h_{3} + \hat{h}_{3}h_{2} &= \frac{49}{2^{12}}\\
\hat{h}_{2}h_{4} + \hat{h}_{3}h_{3} &= 0\\
\hat{h}_{3}h_{4} &= \frac{-5}{2^{12}}
\end{align}
I think with the additional constraints:
$$
\sum_n (-1)^n h_n = 0 \\
\sum_n (-1)^n \hat{h}_n = 0 \\
$$
that should be solvable...


Find a function that makes two regions of a rectangle have a certain proportion

Question: The problem states the following: A curve $y-f(x)=0$ passes through the origin, and $R_{x}$ is the rectangle formed by the coordinate axis and the parallel lines that pass through the point $(x,f(x))$ of the curve. If the curve divides the rectangle in two regions and the area of one of them is 10 times the area of the other one,  find $f(x)$.
Excuse my awful figure but graphically I think of it this way: figure. The blue part is $\int_0^a f(x)dx$ and the purple part is 10 times the blue part, meaning $10 \int_0^a f(x)dx$. Since the total area is $ab$, the blue part + the purple part $= 11\int_0^a f(x)dx= ab$. I don't know how to proceed from here so any kind of help or hint would be appreciated.
Comment: I think you are supposed to have $b=f(a)$
Answer: hint
We look for $f (x) $ such that
$$(1+10)\int_0^xf (t)dt=xf (x) $$
(sum of two areas $=$area of the rectangle).
differentiating  gives
$$11f (x)=f (x)+xf'(x) $$
You can finish and get

$$f (x)=\lambda x^{10} $$

The other solution satisfies
$$(1+\frac {1}{10})\int_0^xf (t)dt=xf (x) $$
gives

$$f (x)=\mu x^\frac {1}{10} $$
Answer: $\int_{0}^{x}f(t) = 10\left[xf(x) - \int_{0}^{x}f(t)\right]$
$\int_{0}^{x} f(t)= \frac{10}{11}\left[xf(x)\right]$
Differentiating
$f(x) = \frac{10}{11}\left[xf'(x)+f(x)\right]$
$\frac{1}{11}f(x) = \frac{10}{11}xf'(x)$
$\frac{f'(x)}{f(x)} = \frac{1}{10x}$
$ln(f(x)) = \frac{1}{10}lnx +lnc$
$f(x) = cx^{\frac{1}{10}}$


How to Find cardinality of $|\{f|f:A \to P(A) \}|$ if $|A|=a$ (A infinite set)

Question: Let A infinite set
$|A|=a$
$B=\{x|x \in P(A)\}$
$C=\{f|f:A \to P(A)\}$
$F=\{$ Set of all the relations on $A \times B \}$
$H=\{g|g:B \to B \}$
1) Find $|C|$
2)Find $|F\times H|$
for (1) i think $|P(A)^A|= |P(A)|^{|A|}=2^a$
is that correct and how to find (2)
thanks
Comment: "All relations from A to B"? You mean relations on $A\times B$ or functions from $A$ to $B$?
Answer: Obviously $|C|=|F|$.
The number of function from one element of $B$ to all the elements of $B$ is $2^{a}$. It means that $|H|=(2^{a})^{2^{a}}$.
These are the solutions:
$$|C|=2^{a}*a$$
$$|H \times F|= (2^{a})^{2^{a}}*|F|= (2^{a})^{2^{a}+1}*a$$
These solutions consider all types of function.
Comment: the first one i understand it  $|C|=|F|=$$|A \times B|$ $= |A| * |B| = a * |P(A)| =$ $a*2^a$ . can you explain the second one  please
Comment: I modified my answer.


What's this F#m8b12b#8 chord?

Question: I often see this image in VK, OK and Facebook. I can't understand this F#m8b12b#8 chord! I know it's a taunt of a kind but does it really exist and what notes are those and how to play it on Guitar and Keyboard?
Comment: It is non-sense, this chord doesn't exist.
Comment: Note: the keyboardist on this picture is Jordan Rudess, who is mostly known for being the keyboardist of Dream Theater, a progressive metal band. This picture is just a meme reference to Jordan Rudess' tendency to play complicated songs.
Comment: Be interested to hear what it translates to, but sadly, don't think it's playable on this planet.
Comment: It's a really very basic chord. Jordan can play it with his eyes closed!
Comment: Yeh, i'm familiar woth his work in Dream Theatre.
Answer: OK, as said in my comment, this is a joke and that chord doesn't exist. But here's why:

F#m8 doesn't make sense because 8 is the octave, so it doesn't add anything to the chord.
b12 doesn't exist; the 12 is equivalent to the fifth, which is a basic chord tone, so if it should be flat, it should be a b5; however, this contradicts the F#m chord, which as a perfect fifth; there can only be one fifth; enharmonically, the b5 could be a #4 (#11), so if you wanted to add that note, it should be a #4 (#11). Note, however, that this tension is very uncommon in a minor chord.
b#8 is non-sense; is it flat or sharp or none of the two? Whatever it is, it is also non-sense because, as mentioned above, 8 is just the octave, and in a chord in doesn't make sense to alter the octave. If you want a chord tone a half step lower than the octave, then it's a major seventh; a half step up from the octave, it would be a b9;
Comment: In it just a funny way to write F#m?
http://www.scales-chords.com/chord/F%23m8b12b%238 (I don't know how accurate is this tool)
Comment: Honestly, it's probably just an F# diminished triad which is a very basic chord. This naming scheme reminds me of any Chord Identifiers on DAWs which tent to just be garbage and only approach chords from the add/no angle once it finds a small set of notes it matches to a known chord.
Comment: Wait... Are you saying `F#mb5` doesn't exist? I mean, it's just be a diminished triad, but is that naming convention actually wrong? I've seen, say, `F#majb5` before.
Comment: It's not F#m, as he said there is a flat 5th (or a sharp 4th)...
Comment: @teodozjan why is there a flat 8?
Comment: @SovereignSun I don't know I just found this tool. I'm not good at at chord theory
Comment: @AgustínLado: No, I said F#m7b12 doesn't make sense. F#mb5 is at least unconventional, and is normally called Fdim or Fo. Maybe you saw `F#maj7(b5)`?
Answer: It contains F#, A, C#, F#, F#, C
Comment: Can you explain which pitch is the "b#8" and why?
Comment: Cb# = C because # means sharp and b means flat
Comment: And which one is the "b12"?
Comment: b12 is a Gb, 12 means 5
Comment: Sharps and flats don't cancel out each other.
Comment: Oh dear, Alex G-I. Not a smart Alex...If 12 means 5, then it would be C#. And since it's an **F#** chord, it certainly wouldn't be called **Gb**!!! And even if it was b12, that would make it Fnat.
Comment: Fnat looks and sounds funny (:D

What's this F#m8b12b#8 chord?


Incrementing a UILabel in Objective-C

Question: So essentially I want the UILabel to increment every time a button is clicked. I currently have something like this:
- (IBAction) incrementCount {
    [buttonCounter = buttonCounter++]; // Increment by 1.
}

I declare button counter to be an int in the header file. Is that the right way of doing it? Furthemore, upon click, i'd like a time stamp printed as well. Is there a built-in function for fetching a time stamp? Thanks.
Answer: use:
- (IBAction) incrementCount {
    buttonCounter++;
    yourUILabel.textLabel.text = [NSString stringWithFormat:@"%i", buttonCounter];
}

You can get a current date and time using
    [NSDate date]
To get timestamp, use
    [[NSDate date] timeIntervalSince1970] * 1000;
Comment: Is it appropriate for me to define buttonCounter in my header file or should I just define it in my incrementCount method?
Comment: You need it to be persisent - if you define it in method, its value will be lost after the method execution ends. So it should be declared in header file.
Comment: Cool. That makes sense. Lastly, how would I declare its value? I tried doing it in the header method, but i'm assuming that isn't allowed. Do I simply make a setter method?

-(void) setValue {
buttonCounter = 0;
}
Comment: @property can solve all getter and setter problems. If you want to initialize values, use either init methods (in all objects) or viewDidLoad method in UIViewController.
Answer: This
[buttonCounter = buttonCounter++];

is equivalent to
[buttonCounter = buttonCounter+1];
[buttonCounter = buttonCounter];

Therefore you can change your code to
buttonCounter++;

For the timestamp you could use [NSDate date]; and a NSDateFormatter for the display.

Incrementing a UILabel in Objective-C


A complex inequality similar to triangle inequality with reversed sign

Question: If $z_1,..z_n$ are complex number, then there is a subsequence $n_i$ such that
$$\pi \left|\sum_i z_{n_i}\right| \geq \sum_k^n |z_{k}|.$$ How to prove this inequality?
Comment: There is no further information about the sequence?
Answer: Let $z_k=|z_k|e^{ia_k}$ and $S(\theta)$ be the set of all $k$ such that $\cos(a_k-\theta)>0$.
$$\left|\sum\limits_{S(\theta)}z_k\right|=\left|\sum\limits_{S(\theta)}e^{-i\theta}z_k\right| \geq Re\sum\limits_{S(\theta)}e^{-i\theta}z_k=\sum\limits_{k=1}^{n}|z_k|\min(0,\cos(a_k-\theta))$$
We choose some $\theta$ to maximize the term $\sum\limits_{k=1}^{n}|z_k|\min(0,\cos(a_k-\theta))$ By integrating it,
$$\int_{-\pi}^{\pi}\sum\limits_{k=1}^{n}|z_k|\min(0,\cos(a_k-\theta))d\theta=\sum\limits_{k=1}^{n}|z_k|\int^{a_k+\pi/2}_{a_k-\pi/2}\cos(a_k-\theta)d\theta=2\sum\limits_{k=1}^{n}|z_k|$$
So the integral average value of $\sum\limits_{k=1}^{n}|z_k|\min(0,\cos(a_k-\theta))=\frac{1}{\pi}\sum\limits_{k=1}^{n}|z_k|$, there is a $\theta_0$ such that $\sum\limits_{k=1}^{n}|z_k|\min(0,\cos(a_k-\theta_0)) \geq \frac{1}{\pi}\sum\limits_{k=1}^{n}|z_k|$. Hence we choose the subset $S(\theta_0)$.
Comment: But can someone explains the intuitive meaning of the proof? I just copy this from the book and I find it so amazing.


Is there any way to use multiple precompiled headers simultaneously with Clang?

Question: I am playing around with a clang++ command line in order to learn how precompiled headers work.  I've got something like this:
clang++ [several lines of options] sourcefile.cpp -o sourcefile.o -include durr.h -include hurr.h

where the two headers included via the command line have been precompiled into corresponding .h.pch files.
If I "-include" just one of the two headers, compilation succeeds and is faster than it is when I include neither, in the normal fashion for precompiled headers.  But when I include both (as above), I get this error:
clang: warning: precompiled header 'hurr.h.pch' was ignored because '-include hurr.h' is not first '-include'

Is there any way (not necessarily using -include) to use multiple .h.pch precompiled header files to speed compilation of one .cpp file?  I understand that such a feature would be seriously complicated by the tendency of the preprocessor to cause headers to affect one another (even if only via include guards).  I don't really expect what I want to be supported, now that I've thought about it a little.  But I'm trying to confirm here.  The above error message is suggestive but not comprehensive, and the Clang user manual didn't seem to tell me the answer....
Answer: It turns out there is:  Clang supports "chained" PCH files, which is a feature that allows one PCH to represent an extension of another one.  If the latter is included during some later compilation, then both it and the PCH that it depends on will be used to speed compilation.  I think.
Something like this might produce an ordinary PCH:
clang++ -x c++-header header1.h -o header1.h.pch

And, if I'm understanding correctly (questionable), then something like this would produce a chained PCH that would extend header1.h.pch:
clang++ -x c++-header header2.h -o header2.h.pch -include-pch header1.h.pch

And then that chain of two PCH files can be used to speed compilation like so:
clang++ source.cpp -o source.o -include-pch header2.h.pch

(The parent PCH does not need to be mentioned in the command; header2.h.pch already knows where to find it I think.)
I haven't found any way to explicitly demand this sort of "chaining" via the command line.  Simply including a PCH when compiling another PCH seems to produce a chained PCH...  probably.  My evidence that it does is mainly that in cases where header2.h actually includes header1.h, this technique seems to produce a small header2.h.pch and a large header1.h.pch, even though one would expect that if chaining weren't happening then header2.h.pch would generally be larger than header1.h.pch, since it contains at least as much information.  This seems to match what I understand the purpose of PCH chaining to be:  It saves resources by storing a dependent PCH's duplicate information as a cheap reference to the contents of another PCH.
My casual exploration suggests that a dependent PCH may itself have another one depending on it, extending the chain to three or more steps, though I'm not certain of this.  When I tried to extend a chain involving real code by something like fifteen or twenty links, the PCH file sizes eventually blew up in what appeared to be an erroneous way, approximately doubling with each step.  This eventually produced 300 MB PCH files for headers that, if compiled into PCHs without any attempt at chaining, would produce files smaller than 6 MB in size.  This happened in Clang 3.6.something, and in Clang 3.7.0.  I imagine it's a bug but who knows.  I gave up on my exploration before reaching the point where I cared to try to pin it down and report it.  And maybe the PCH chains aren't intended to ever grow very long anyway.  This feature doesn't seem to be something people normally use....
Regardless, there seemed to be no way to do what I really wanted:  mixing any two arbitrary PCHs, as long as they didn't directly conflict with one another, regardless of how they had been created.  Chaining only allows two PCHs to be used together if one depends on the other.  I had been interested in speeding compilation by making a PCH for each header in a project and then mixing groups of PCHs together during compilation as appropriate.  But accomplishing this with chained PCHs seems to require making a tree of PCH files in which more than one PCH may correspond to a single header.  I actually attempted to generate such a thing automatically, and seemed to succeed...  but the above-mentioned "error" (if error it was) bogged me down, and to the extent that I did succeed, the time savings were not impressive enough to warrant continuing.
There is also some kind of "module" system in Clang that may be relevant here.  But I have the impression that trying to exploit this to achieve the effect I want, if it could even be successful at all, would probably require me to change my source code to something special, and maybe to something non-standard.  I didn't look into it much though, so maybe not.  But anyway I guess standard C++ will probably get modules eventually and then all of this mess will (I hope) become a thing of the past.
GCC did not seem to support anything related to what I wanted, incidentally.


Fivestar appears on content type, but can't vote

Question: I have problem with Fivestars module, (Drupal7).
It is configured in field and appears on content type page, but cannot vote
(like voting is disabled - when inspecting with firebug, i see no Javascript activity over stars, and no any possible javascript conflict.)
Permissions are set correctly.
What in the world could cause this ?
(it seems more-less like plug-and-play module :D )
Answer: When adding the FiveStar field,

If you choose "Rated while viewing" , that means all users can rate the node (with permissions) can rate the node. This is ideal to allow users to rate how well the article was writtem etc).
If you choose "rated while editing", it will make the rating field disabled (static field) for other users than the node author. This is ideal for review nodes to allow the reviewer to leave their ratings while making the node or any other entity.
Comment: I know, and i have rate while viewing, but one is not able to vote. I checked the module on vanilla, and it worked. When i filled my database with content types etc, it stopped working. It is some kind of conflict but i have no clue
Comment: check for the permissions that is if a user is granted the permission to vote.
Answer: If you have checked the permission and chose "rated while viewing" correctly you must check the "Allow users to vote on their own content." option in the edit section of your field as well. it lets you vote for your own content.
Answer: You should enable "users can vote for their own materials" (sorry, if translation is somewhat inaccurate).
That would be in /admin/structure/types/manage/YOUR_CONTENT_TYPE/fields/field_vote
My fivestar field is called "vote", thus "field_vote" at the end.
Answer: Make sure the "Allow voting on the entity" is enabled in the Field: Rating displays field within the View.


Let $f$ be a harmonic function on $\Bbb{D}$ defined as poisson integral of a complex measure $\mu$ on $\Bbb{T}$.

Question: Let $\mu$ be a complex measure on $\Bbb{T}$ and $f:\Bbb{D}\to\Bbb{C}$ be the harmonic function defined as poisson integral of $\mu$ i.e. $$f_r(\theta)=f(re^{i\theta}):=\int P_r(\theta-t)\ d\mu(t)$$ where $P_r$ denotes the Poisson Kernel defined by the formula $P_r(\theta)=\text{Re}\left(\frac{1+re^{i\theta}}{1-re^{i\theta}}\right)$
We have to prove that $\lim\limits_{r\to1}\lVert f_r\rVert_1=\lVert\mu\rVert$
$\lVert f_r\rVert_1=\frac{1}{2\pi}\int\limits_{-\pi}^{\pi} |f_r(\theta)|\ d\theta$
$=\frac{1}{2\pi}\int\limits_{-\pi}^\pi \left|\int\limits_{-\pi}^\pi P_r(\theta-t)\ d\mu(t)\right|\ d\theta$
$\le \frac{1}{2\pi}\int\limits_{-\pi}^\pi \int\limits_{-\pi}^\pi P_r(\theta-t)\ d\theta\ d|\mu|(t)$
$=\int\limits_{\pi}^\pi d|\mu|(t)$
$=|\mu|(\Bbb{T})=\lVert \mu\rVert$
This implies $\lim\limits_{r\to 1}\lVert f_r\rVert_1\le\lVert\mu\rVert$
Now I want to prove the converse inequality. I know that from Fatou's theorem
$$\lim\limits_{r\to1} f_r(\theta)=\tilde{f}(\theta)\ \text{for almost every }\theta$$
where $\tilde{f}\in L^1(\Bbb{T})$ is the derivative of $\mu$ with respect to the normalized Lebesgue measure i.e. $d\mu=\frac{1}{2\pi}\tilde{f}\ d\theta+d\mu_s$ where $\mu_s$ is singular.
I think from this, somehow I need to establish the other inequality. Can anyone help me with an idea to finish the proof? Thanks for your help in advance.
Answer: Let $\psi \in C^0(\mathbb{T})$. Suppose we can show that $\int_{\mathbb{T}}{f_r(\theta)\psi(\theta)d\theta} \rightarrow 2\pi\int_{\mathbb{T}}{\psi d\mu}$. Then, as continuous linear forms on $C^0(\mathbb{T})$, $\frac{1}{2\pi}f_r(\theta) d\theta \rightarrow d\mu$, so for the operator norm, $\|d\mu\| \leq \liminf_{r \rightarrow 1} \|\frac{1}{2\pi}f_r(\theta)d\theta\|$, which is the inequaily we need, ie $\|\mu\| \leq \liminf_{r \rightarrow 1} \|f_r\|_1$.
The convergence statement that we need is linear wrt $\psi$ and linear wrt $\mu$, so it's enough to prove it when $\psi$ and $\mu$ are nonnegative.
Then $$\int_{\mathbb{T}}{f_r(\theta)\psi(\theta)d\theta}=\int_{\mathbb{T}^2}{P_r(x-y)\psi(x)dxd\mu(y)}=\int_{\mathbb{T}}{\int_{\mathbb{T}}{P_r(x)\psi(x+y)dx}d\mu(y)}.$$
For all $y \in \mathbb{T}$ and $0<r <1$, as $P_r$ is non-negative, $\left|\int_{\mathbb{T}}{P_r(x)\psi(x+y)dx}\right| \leq \|\psi\|_{\infty}\int_{\mathbb{T}}{P_r(x)dx} \leq 2\pi\|\psi\|_{\infty}$.
So, by dominated convergence, we just need to show that for almost all $y$, $\int_{\mathbb{T}}{P_r(x)\psi(x+y)dx} \rightarrow 2\pi\psi(y)$.
But this integral is $\int_{\mathbb{T}}{P_r(x-y)\psi(x)dx}=\int_{\mathbb{T}}{P_r(y-x)\psi(x)dx}=g(re^{iy})$, where $g$ is the Poisson integral of $\psi(\theta)d\theta$. The conclusion then follows from Fatou's theorem, as in your post (we don't actually need it, there's an elementary argument showing that convergence holds for all $y$).


Internet Explorer browser issue while click shift + mouse-left-click , the text automatically get highlighted

Question: I have render html table with multiple select option. while I was clicked shift + mouse-left-click , td element text automatically gets highlighted in ie( Internet Explorer) browser only(chrome, firefox, safari are working fine ). Can you please help me how to resolve this issue.
Thanks
Comment: add your code js fiddle
Answer: use below code working fine.
<code>document.onselectstart = function() { return false; }
document.onmousedown = function() { return false; }
</code>
Thanks