Countable sets?

Question:
Determine whether each of these sets is countable or uncountable. For those that are countably infinite, exhibit a one-to-one correspondence between the set of positive integers and that set.
1) Integers not divisible by $3$.
2) Integers divisible by $5$ but not by $7$.

I figured out the first one so it was $3k+1$ or $3k+2$ but the second one has thrown me for a loop I was thinking it could be something like $5k$ but that will give me everything divisible by $5$ and $7$, can't figure out what to do about the not divisible by $7$.
Both are countable since I could go though and count the numbers that meet the requirements or am I wrong?
Comment: Does it mean that the set of multiples or non-multiples of any natural number is always countable?
Comment: Yes. That is correct, except for non multiples of 1.
Comment: I would say set of non-multiples of $1$ is countable, as it is the empty set; it is just not countably infinite. You have to be very careful when talking about countability to check whether the person speaking treats finite sets as countable, because this is very common in the literature.
Answer: They are both indeed countable. for the second one, you can use the fact that all numbers divisible by $5$ and $7$ are divisible by $35$, so the set is equivalent to
"Integers divisible by $5$ but not by $35$".
Also, for the first part of the question (simply "are they countable?"), you can simply show that they're an infinite set, and that they're a subset of the integers. This immediately pins them as having cardinality $\aleph_0$.
EDIT: There's a fairly easy (though not very elegant) definition in terms of recursion:
$$a_1=5$$
$$a_2=10$$
$$a_3=15$$
$$a_4=20$$
$$a_5=25$$
$$a_6=30$$
$$a_n=a_{n-6}+35, n>6$$
The fact that you're listing them as $a_n$ implies bijection to $\mathbb{N}$. The first sequence works similarly.
Comment: $a_1=1,a_2=2,a_n=a_{n-2}+3,n>2$. The idea is that you have a bunch of arithmetic sequences with the same increment, as you've noticed. So set up all your initial terms, then just set up the recursion to increment all of them. Since none of them were divisible by $3$ originally, adding $3$ keeps it that way.
Comment: Oh so the $a_n$ implies bijection the book wasn't very clear on that. This book isn't the greatest with how the course is structured. So my answer for 1 isn't correct since I have two functions? Should they be more like $3a_{n-2}+1, n > 3$
Comment: Thank you that makes so much sense now.
Comment: @LF4 to be clear your initial formulation was still correct. defining $a_{2n+1}=3n+1, a_{2n+2}=3n+2, n\geq 0$ generates the same sequence.
Answer: If $a$ and $b$ are relatively prime, then the numbers divisible by $a$ but not by $b$ belong to the set $$\{\text{lcm}(a,b)k+a,\text{lcm}(a,b)k+2a, \ldots, \text{lcm}(a,b)k+(b-1)a : k \in \mathbb{Z}\}$$
Comment: Strictly speaking, the questions asks for a bijection between the _positive integers_ and the set.
Answer: First of all, both are countable since they are a subsets of the integer which is countable.
Also the $3k + 1$ and $3k + 2$ that you mention does not exactly answer the question since the question asks for a bijection between the desired set and the positive integers. I will provide a bijection between the nonnegative integers and the desired set. You then just shift by one to get it between the positive integers.
For the first one, consider the function
$f(k) = \begin{cases}
1 & \quad k = 0 \\
2 & \quad k = 2 \\
3t + 1 & \quad k \neq 0,2 \text{ and } k = 4t \\
3(-t) + 1 & \quad k \neq 0,2 \text{ and } k = 4t + 1 \\
3(t) + 2 & \quad k \neq 0,2 \text{ and } k = 4t + 2 \\
3(-t) + 2 & \quad k \neq 0,2 \text{ and } k = 4t +  3
\end{cases}$
This is a bijection between the nonnegative integers and the set of all integers not divisible by $3$.
For the other one, note that by a similar argument as for $3$, you can find a bijection between the set of all positive integers and numbers that are not divisible by $7$. Let $g$ be this bijection. The numbers that are divisible by $5$ but not divisible by $7$ take for the form $5k$ where 7 does not divide $k$. Hence $5g(k)$ is the desired bijection between the positive integers and the set of integers divisible by $5$ but not $7$.
Answer: Hint: On constructing the mapping $f(k)$: you want to include a term $5k$ to ensure divisibility by 5. You also want to skip every multiple of $35.$ This involves $k/35,$ but not quite.
Answer: There is a trivial way to get an explicit bijection $f_A$ between $\mathbb{N}$ and any infinite subset $A$ of $\mathbb{N}$, namely
$$
f_A(0) = \min (A)\\
f_A(k+1) = \min (A \setminus \{ f(0), \ldots, f(k)\})
$$
So in your case you can do the following. Let $B \subseteq \mathbb{Z}$ be infinite. Write $B$ as the union of a set $N$ of negative integers and a set $P$ of nonnegative integers. Assuming both of these are infinite, define
$$
g(2k) = f_{P}(k)\\
g(2k+1) = -f_{-N}(k)
$$
Then $g$ will be the desired bijection between $\mathbb{N}$ and $B$. As you can see you do not need a formula for the elements of the set $B$, you only need to know the sets $N$ and $P$ are infinite to construct a specific bijection in this way. By some small modifications you could also handle the case where one of $N$ or $P$ is finite.

Countable sets?


CNAME not resolving

Question: I've got a domain (example.com) registered with godaddy and pointed to nameservers hosted by linode. I've got a multisite WordPress install on linode (blogs.com) and I want to point the domain to a subdomain of the wordpress install (example.com -> example.blogs.com).
The subdomain of the wordpress install works fine - DNS can find it and I can browse to it.  in the linode's DNS manager I've set up a CNAME to make the pointer I referenced above.
Whois shows that the linode nameservers are set for the domain, but DNS can't find any nameserver for example.com.
Am I missing a step, or do I have something misconfigured?
EDIT 1
The answer section of the dig request using one of linode's nameservers is
;; ->>HEADER<<- opcode: QUERY, status: REFUSED, id: 44359
;; flags: qr rd; QUERY: 1, ANSWER: 0, AUTHORITY: 0, ADDITIONAL: 0

The answer section from the dig using my host's nameserver is
;; ->>HEADER<<- opcode: QUERY, status: SERVFAIL, id: 16379
;; flags: qr rd ra; QUERY: 1, ANSWER: 0, AUTHORITY: 0, ADDITIONAL: 0

Same response in the status field if I specify CNAME or just accept the standard A query.
I do not have an A record for that example.com on the linode nameservers; do I need to set that up?
This is a fairly recent change - a few hours ago, so maybe I'm just being impatient? The nameserver changes made at the same time came through pretty quickly. I figured that the CNAME entry would be simultaneous with that; am I wrong in that expectation?
Comment: Work backwards a little. First ensure the A record that your CNAME points to works first. Fix that and your CNAME should also work.
Answer: Technically what you're asking for is invalid.  CNAME conflicts with all other records (with a special exception for DNSSEC records), thus having CNAME xxxxx conflicts with the SOA, MX, NS etc records for the domain.  My guess is that the reason the domain resolves when you use an A there and fails when you use CNAME is because the DNS server enforces those restrictions and is unable to process your zone file.
Furthermore, based on your response to @xwincftwx's question, it's not clear that getting CNAME to work would do what you want in the first place.  A CNAME pointing to an A record is exactly the same as an A record in the first place.  The CNAME is handled entirely internally by the DNS system and the web browser only sees the IP address.  In your test with an A record (let's say 126.96.36.199), the browser connected to 22.214.171.124 and asked it for the website example.com.  If that server isn't configured to serve a website for example.com it typically serves a default site (in this case blogs.com).
If you got your domain to work as a CNAME, the browser would ask for the IP address of example.com.  DNS would see that it is a CNAME, look up example.blogs.com and return 18.104.22.168.  The browser would connect to 22.214.171.124 and ask it for example.com just as it did when it was an A record.
If you want people going to example.com to be redirected to example.blogs.com then you'll need to set up a basic web server that receives connections to example.com and sends a 301 permanent redirect to the browser to tell it go to example.blogs.com
Comment: very cogent explanation of what's going on; thanks!
Answer: You cannot use a CNAME for the root record in a zone file (this is prohibited per RFC 1034, read section 3.6.2). You'll need to put in an A record instead that points to the same IP as the target of your CNAME rule.
Answer: What is the output of dig example.com? If your know your nameserver's IP you can force dig to use your nameserver (dig @nameserver-ip example.com). If this works, your nameserver is not used for example.com. When did you assign the linode nameservers? Those changes can take time. Especially if your ISP's DNS server caches results...
Comment: If some changes came through, all of them should have come through. I'm not sure about the need for an A record. My mistake with a CNAME record was the missing tailing ".". So `@ IN CNAME example.blogs.com.`. But the SERVFAIL does not seem right (as well as "REFUSED"). The SERVFAIL problem is mentiond [here](www.linuxquestions.org/questions/linux-server-73/bind9-dig-x-returns-status-servfail-643191/c), the REFUSED problems also points to wrong configuration of the nameserver. As if you were not allowed to query.
Answer: Just looks like that your nameserver isnt running.
Can you check if you name server is running.
ps -aux | grep named
If your nameserver is not running.. start it and check again.
If it isnt started after you started it.. please post the named information of /var/log/daemon and /var/log/messages
grep named /var/log/messages
grep named /var/log/daemon
Perhaps it is a misconfiguration in your zone file.
if your nameserver IS RUNNING, please check your named.conf if your zone accept all incomming traffic.
It is not required to include A records of example.com in your zone file but it is recommended to do for DNS checks and whois checks.
Comment: I should have been more explicit; I'm using Linode's nameservers (ns[1-4].linode.com) and their DNS manager. Their servers are running, the zone files pass a check and have the trailing "." Moreover, when I do add an 'A' record for example.com, nslookup finds it within 15 minutes. Of course then example.com is pointed to blogs.com, not example.blogs.com.

CNAME not resolving


Ahah helper alwas getting error, but on other page no error

Question: I have forms with Ahah helper. When I tried to fill the form, it always getting this error:
warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'A' not found or invalid function name in xxx\includes\form.inc on line 378.

A = name of function, but that function is exist
xxx = location of drupal
Line 378 is:
$form = call_user_func_array(isset($callback) ? $callback : $form_id, $args);

At page_new_init, there is no error at all. But, at page_initedit there's always error. This is the .module code:
$items['new/init/1'] = array(
    'title' => 'Add new',
    'type' => MENU_LOCAL_TASK, //MENU_NORMAL_ITEM,
    'page callback' =>'page_new_init',
'access arguments' => array('new'),
);

$items['new/editinit'] = array(
    'title' => 'Edit',
    'type' => MENU_CALLBACK, //MENU_NORMAL_ITEM,
    'page callback' =>'page_initedit',
'access arguments' => array('new'),
'file' => 'act.edit.inc',
);

And this is the form on function "page_new_init":
function page_new_init(){
  global $user;

 $output .= drupal_get_form('form_new_add2',$id,$codeact);

  return $output;
}

function form_new_add2(){
  global $user;

    $form = array();
    ahah_helper_register($form, $form_state);
    drupal_add_js("sites/all/modules/act/javascript/jss.js");

    $form['input']['account'] = array(
    '#type' => 'textfield',
    '#title' => t('Account Code'),
    '#size' => 60,
    '#default_value' => $account,
    '#required' => TRUE,
    '#autocomplete_path' =>'compose/code',
    '#ahah' => array(
        'event'   => 'change',
        'path'    => ahah_helper_path(array('input')),
        'wrapper' => 'input-wrapper',
        'method' => 'replace',
        'progress' => 'throbber',
    ),

    $form['input']['access_code'] = array(
    '#type' => 'select',
    '#title' => t('Access Code'),
    //'#required' => TRUE,
    '#default_value' => $access_code,
    '#options' => opt_accesscode(),
    );

  return $output;
}

And this is the other function "page_initedit":
function page_initedit(){
  global $user;

 $output .= drupal_get_form('form_initedit',$id,$codeact);

  return $output;
}

function form_initedit(){
  global $user;

    $form = array();
    ahah_helper_register($form, $form_state);
    drupal_add_js("sites/all/modules/act/javascript/jss.js");

    $form['input']['account'] = array(
    '#type' => 'textfield',
    '#title' => t('Account Code'),
    '#size' => 60,
    '#default_value' => $account,
    '#required' => TRUE,
    '#autocomplete_path' =>'compose/code',
    '#ahah' => array(
        'event'   => 'change',
        'path'    => ahah_helper_path(array('input')),
        'wrapper' => 'input-wrapper',
        'method' => 'replace',
        'progress' => 'throbber',
    ),

    $form['input']['access_code'] = array(
    '#type' => 'select',
    '#title' => t('Access Code'),
    //'#required' => TRUE,
    '#default_value' => $access_code,
    '#options' => opt_accesscode(),
    );

  return $output;
}

On "page_new_init", there is no error at all, Ahah helper works fine. But on "page_initedit" the error comes up:
warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'form_initedit' not found or invalid function name in drupal\includes\form.inc on line 378.

What should I do?
Answer: In .module file, I have to load .inc file. That's what I forgot! :(
include_once(drupal_get_path('module', 'act') .'/act.edit.inc');


How to explain null hypothesis testing using Bayesian terms?

Question: Imagine someone who knows Bayesian statistics but has never heard of null hypothesis significance testing. How would one best explain NHST by using Bayesian analogies?
Searching through the archives I found a nice answer to a related question, which led me to the idea to describe NHST as something like a posterior predictive check, but with a "null hypothesis" pseudo-posterior that is a Dirac $\delta$ density about $H_0$. Does that make sense, or does anyone have a better comparison?
Comment: If the parameter has a continuous prior, I would have thought a Bayesian might think that the posterior probability of a point null hypothesis (such as $H_0: \mu=0$) is zero; having a prior and then a posterior distribution putting a point of probability at a particular point might seem strange
Comment: Casella and Berger's (1987) Comment on the Berger and Delampedy (BD) paper is also well worth a read, as Casella and Berger disagree with a number of BD's arguments.  @Durden I think that you would struggle to explain significance testing using Bayesian posterior probabilities for the following reason. Informally, P-values are used to address the question: Is the data (statistically) consistent with the null hypothesis?  In contrast, posterior probabilities can be regarded as Bayesian answers to the question: Given two hypotheses, what is the relative plausibility of each?
Comment: I'd start by explaining the idea that parameters of frequentist probability distributions are not seen as random and therefore don't come with a prior distribution. I don't think that somebody who at this point only knows Bayesian statistics needs "Bayesian analogies" to have a non-Bayesian concept explained.
Comment: Different questions deserve different answers. There are not just different schools here (Frequentist and Bayesian), these are different questions so naturally answers can differ widely. Since p-values are absolute measures of consistency between the data and a single hypothesis whereas posterior probabilities are measures of relative plausibility, I think it would be difficult to explain significance testing to a Bayesian using posterior probabilities of hypotheses. Any observed linkages depend critically on the particular hypotheses involved.
Comment: Andrew Gelman is a respected Bayesian with the article:
Gelman, Andrew. "Commentary: P values and statistical practice." Epidemiology 24.1 (2013): 69-72.  http://stat.columbia.edu/~gelman/research/published/pvalues3.pdf Disclosure: I have not had an opportunity to read this reference yet.
Comment: @krkeane it appears the article Gelman is discussion, [by Greenland and Poole](https://doi.org/10.1097/EDE.0b013e3182785741), is more along the lines of what I was looking for.
Comment: That's why I cautiously labeled it pseudo-posterior, since it isn't actually $p(\theta|\{\text{data}\})$, but rather some adhoc competitor to what the data actually said.
Comment: There is a good paper by Berger and Delampady is Statistical Science about this. All very formal; nothing "pseudo" about it. There are indeed many applications where there is large prior probability in a small neighborhood of zero: gene expression, ESP and other paranormal studies, certain safety signals in drug studies, bio equivalent formulations, tests for market efficiency in finance, etc.
Comment: "Informally, P-values are used to address the question: Is the data (statistically) consistent with the null hypothesis?" @GrahamBornholt Aren't prior/posterior predictive checks addressing the same (or at least very similar) question?
Comment: Would you describe what you mean by "prior/posterior predictive check"?
Comment: In a PPC you use your model $p(y,\theta)$ to simulate data, by drawing parameter values from your prior $p(\theta)$ and then plugging them into your likelihood $p(y|\theta)$. For each draw you generate a test statistic, and finally you compare the distribution of this statistic with the one statistic calculated from your actual data (the result might [look like this](https://avehtari.github.io/masterclass/slides_ppc.pdf#page=15)).
Comment: In this process, the spread of the data comes from both the prior and the likelihood. If the prior was only a Dirac density $\delta(\theta - \theta_0)$, then wouldn't we have something similar to a $H_0$ "generating" other data, which is implied by the meaning of the p-value?
Comment: I see some similarity. Hopefully a Bayesian statistician will respond to your question.
Comment: Seems to me that you should define "null hypothesis significance testing". It might mean Neyman–Pearsonian hypothesis testing, which is really like decision theory, or it might mean (neo-) Fisherian significance testing which is a little closer to the Bayesian approach because it deals with the evidential content of the data.
Comment: @Durden - Greenland and Poole is reference #1 in Gelman paper. I'm happy your search was fruitful. Regards,
Answer: Null hypothesis significance testing, NHST, is expressing an observed effect in terms of a probabilistic comparison with the hypothesis of an absence of the effect. An observation is statistically significant if there is a clear distinction in the support of the data for absence versus presence of an effect.
An example of performing NHST with Bayesian techniques can be the following:
Imagine there is a lady that claims that she can taste whether the tea or the milk was first added to the cup. We would like to test that claim by having her perform a blind taste test.
We test the ability of the lady, by presenting her 100 cups of tea where she has to guess whether it was tea or milk first and we record the number of correct guesses. Let's for simplicity assume that the probability of a correct guess is symmetric (independent from whether the cup was tea first or milk first).
Say that based on prior information we know that there is a probability of 0.99 to have a person that can't taste anything (the null hypothesis), and a probability of 0.01 probability that a person can taste something and the ability of this person will follow a uniform distribution.
$$\begin{array}{RL}
H_0:&p=0.5\\
H_a:&p\sim U(0.5,1)
\end{array}$$
We have the following likelihoods as function of the number of heads:
$$\begin{array}{rcl}
\mathcal{L}(H_0,k) &=& {n \choose k} 0.5^n\\
\mathcal{L}(H_a,k) &=& \int_{0.5}^1 2 {n \choose k} p^{k}(1-p)^{n-k} dp
\end{array}$$
and a likelihood ratio (where we can compute the denominator with as the incomplete beta function)
$$
\Lambda = \frac{\mathcal{L}(H_0,k)}{
\mathcal{L}(H_a,k)} = \frac{1}{2^{n+1}\int_{0.5}^1  p^{k}(1-p)^{n-k} dp}$$
and posterior odds as function of $k$
$$
\frac{P(H_0;k)}{P(H_a;k)} = \frac{P(H_0)}{P(H_a)} \frac{\mathcal{L}(H_0,k)}{
\mathcal{L}(H_a,k)}
$$
will look like

If for example the lady has two thirds (67) of the tea cups guessed correctly, then this indicates an effect that she can have more than half guessed correctly. But it is not significant. The null hypothesis is just as likely as the alternative hypothesis (odds ratio around one or even slightly above it).

The classical null hypothesis significance testing is not using these priors and are using instead probability statements based on a fiducial distribution or p-value.
Those statements are independent from a prior distribution (but not on prior information, e.g. assumptions about the model describing the likelihood function), and they only regard the likelihood of the null hypothesis and aim to make this a small value in order to declare a test statistically significant.
In a way the NHST has an implicit Bayesian reasoning and assumes that data that does not support the null hypothesis is supporting instead some alternative, but unknown, alternative hypothesis. Neyman and Pearson make this more explicit by defining the fiducial distribution or p-values (which can be computed in different ways) based on a specfic alternative hypothesis.

Possibly a more simple way to regard statistical significance, and how I interpret Fisher's approach to it, is that the fiducial distribution has a probability density concentrated in a small region (and in a Bayesian analysis one could use the posterior distribution in place of the fiducial distribution).
An effect is statistically significant if the highest density region (or some other region) of a certain large amount, say 95%, does not include the parameter value relating to a zero/null effect.
Expressions of statistical significance are useful when people make point estimates. A point estimate could for instance be the maximum of the posterior distribution. But such point estimate alone does not give an indication of the entire posterior and of the difference of the estimate with other hypotheses. If we give a point estimate along with a region, then we can have a better idea about the information that the data contains about a particular parameter/hypothesis.
Comment: @Alexis the range of parameters that corresponds to a null hypothesis (absence of effect) might differ based on the context. Yet, the principle is everytime very much the same and revolves around whether or not the data/experiment is not only supporting a specic observed effect, but also at the same time represents bad support for other effects (such as the null). An experiment that supports some effect and at the same time as well supports the null hypothesis is not very useful.
Comment: Very interesting answer. Can you maybe explain a bit more waht you mean by  "fiducial distribution". Also there should be a critical value $\Lambda_\alpha$, for a p-value of $\alpha$, from which we could infer a prior such that the posterior $P(H_0) \leq \alpha$. I'd love to see this "implicit" prior of the classical approach.
Comment: @LukasLohse I agree that I should do something more with these distributions and I am contemplating a big revision. Explaining the fiducial distribution more indepth might be very nice since it was Fisher's attempt of mimicking Bayesian inference and this NHST is a good opportunity to make the connectioms between all sorts of analysis. I hope it will make the answer better.
Comment: "…comparison with the hypothesis of an absence of the effect…" What about the null hypotheses $\text{H}_{0}\text{: }\theta \le c$,  $\text{H}_{0}\text{: }\theta \ge c$, and  $\text{H}_{0}\text{: }|\theta| \ge c$?
Comment: Thank you!. "An experiment that supports some effect and at the same time as well supports the null hypothesis is not very useful." If I understand this , I think I quite disagree: relevance testing combines inference on a null of no effect, with inference on an effect at least *so* big in order to (1) directly counter confirmation bias as routine in tests, (2) explicitly integrate power into conclusions, and (3) explicitly integrate effect size (the  "*so* big" part) into conclusions. That's pretty useful.
Comment: @Alexis relevance testing just has a different null hypothesis. The story remains the same that an experiment is not very useful when the confidence interval covers a range such large such that you can not make a clear statistical/probabilistic distinction between different hypothetical values of interest. See also [Did my university class choose wrong $H_0$?](https://stats.stackexchange.com/a/602491/164061).
Answer:
...the idea to describe NHST as something like a posterior predictive check, but with a "null hypothesis" pseudo-posterior that is a Dirac $\delta$ density about $H_0$. Does that make sense...?

Yes. I'm not sure whether to call NHST a prior or posterior predictive check, but it is fair to see it as a form of model check. That said, a Bayesian PPC is often used to check "Is my model large enough yet, or do I need to add more nuance?" By contrast, you could says classical NHST is typically used to check "Is my model small enough yet to match the capacity of my sample size / study design, or should I simplify it further because (especially without believing in an informative prior) I just don't have enough data to estimate some parameters with adequate precision?"
Ultimately, the usual scientific reason for running a NHST is to answer the question "Is my sample size large enough to rule out sampling variation as being a major concern?" We deliberately set up a too-simple straw-man model, under which the effect we hope to learn about (say, a difference in means between treatment and control groups) isn't a true effect in the population, but could show up as an apparent effect in finite samples: $\mu_1=\mu_2$, but $\bar{x}_1\neq\bar{x}_2$.
If our sample is small, this "PPC" might lead us to conclude: "Even though we don't believe this straw-man model, the data aren't inconsistent with it. Let's design our next experiment to collect more data, so that we can rule out sampling variation as a reason to disbelieve our results."
But if our sample is large enough, we should see that the too-simple model $\mu_1=\mu_2$ typically leads to datasets that don't look like our actual sample. Then we can say, "OK, sampling variation isn't a major concern here. Now we can focus on all the other concerns: Was there random assignment? Are the measurements valid for the construct we are trying to study? etc."

Perhaps it's worth framing this a 2nd way too:
From the Bayesian point of view, a point prior often makes no sense. If your prior puts all its weight on a single $\theta$ value, the posterior will be the same, so there's no point in collecting data at all. In this sense, classical NHST is not the same as using data to update your prior probabilities for $H_0$ and $H_A$ into posterior probabilities, because it starts with a point prior solely on $H_0$. But since Bayesian methods are largely meant for updating priors into posteriors, NHST seems like nonsense to many Bayesians.
However, if you're a Bayesian who is willing to run a PPC, you are willing to admit your prior might be wrong. Maybe your initial prior is your first attempt at pinning down your beliefs on this topic, and you run the PPC to see if your prior beliefs lead to an adequately realistic model that generates adequately realistic data. If they do, you'll keep using your prior. If they don't, it might convince you that your initial prior was inadequate, and you'll revise your prior (again, NOT the same thing as updating from a prior to a posterior).
In that sense, the purpose of NHST is similar to a PPC attempting to find convincing evidence that a prior of "no effect" is unreasonable. You might not actually hold such a prior yourself, but some readers or reviewers might. By reporting a NHST, you hope to tell them: "If we had started with a simple prior of 'no effect,' a PPC would have told us that our prior was inadequate" (if you reject $H_0$), or "...was not inadequate" (if you fail to reject $H_0$).

In either case, NHST is not meant as an answer to the Bayesian's usual question "Which values of $\theta$ should I believe in?" NHST is about the study design, not really about $\theta$ itself. The Greenland & Poole article mentioned in the comments does a nice job of trying to frame p-values in more Bayesian ways, but I don't know how useful that is, because (outside of PPCs) Bayesian methods are simply tackling a very different question than NHST is.


get distance from dragged element to other related element

Question: I might have a very specific question about jQuery's draggable() in combination with css.
I have lots of divs in my body which are all draggable:
for(var i = 0; i < 150; i++) {
        var randomleft = Math.floor(Math.random()*1000);
        var randomtop = Math.floor(Math.random()*1000);
        var appenditem = '

'
        $('body').append(appenditem);
        cubes.push($('#cube'+i));
    }

$('div').draggable();

So far so good.
Then I have a fixed
 in my body at a specific position, lets say: top: 50px; left: 50px;
What I would like to do is trigger the event handler on dragstop and get the distance between the currently dragged div on dragstop to the fixed div.
For example on dragend a div is dragged to: top: 500px; left: 40px then I would like to have the values: +450 and -10 because the div was top: +450px and -10px from  #fixed.
How can I do this, and especially the negative value.
Thanks in advance
Comment: Do you need to take in consideration the `#fixed` height and width?
Comment: @RokoC.Buljan yes but all divs have to same size so I can simply add that value
Comment: oh, ok than, I did it without that detail, just add that math as you desire. Take a look at my demo, hope will help
Answer: LIVE DEMO
jQuery(function($) {

   var allCubes  = '',
       $fixed    = $('#fixed'),
       fixedOffs = $fixed.offset();

    for(var i = 0; i < 150; i++) {
        var randomleft = Math.floor(Math.random()*1000),
            randomtop  = Math.floor(Math.random()*1000);
        allCubes += '

';
    }

    $('body').append(allCubes); // Outside loop! (60% more performance)

    $('[id^="cube"]').draggable({
        stop: function(ev, ui){
            var pos = ui.position; // or use ui.offset if you need document related position
            // var orgPos = ui.originalPosition; // if you need it
            alert(
               ( pos.left - fixedOffs.left )+' \n '+
               ( pos.top  - fixedOffs.top  )
            );
        }
    });

});

Comment: thank you very much for this. Works like a charm. Didnt know that performance thing, im not that into debugging!
Comment: You're welcome! I did some tests long ago, appending with jQ elements 1 by 1 inside a for loop. 60% slower than doing it once outside the loop (appending only once the created string). If your elements is not going to change positions, getting your fixed offset once it's also faster. `fixedOffs` is now an object with accessible `top` and `left` property names.
Comment: and if we are at that topic. why did you use two variables for `$('#fixed').offset()`. Does it have performance reasons too?
Answer: As you're using jQuery, all you need is the offset() of your fixed element. The draggable ui object in the stop callback provides this information as well, the rest is simple math:
// assuming the stop callback of draggable()
stop: function( event, ui ) {
    var fixedOffset = $("#fixed").offset();

    return {
        top: ui.offset.top - fixedOffset.top,
        left: ui.offset.left - fixedOffset.left,
    }
}

With the values of your example this function would return an object literal with the following values: { top: 450, left: -10 }
Comment: sorry but how, or where can I catch this value? could you please edit your answer with a log or alert. That would be great!
Comment: @supersize did you happen to look at the code (and the return statement)? It's all there…


With two different random seeds for binary classification, I have the exact same result for GLM and QDA, what gives?

Question: With a binary classification analysis, I find myself with the exact same accuracy, recall and specificity for both a qda and glm model.
When I apply the same random seed to both classification models I get the same results, same when I apply a different random seed to each.
Anyone know why that is?
here's a reprex
   library(caret)

set.seed(73, sample.kind = "Rounding")

sonar_index <- createDataPartition(Sonar$Class, times = 1, p= 0.2, list = F)
sonar_train <- Sonar[-sonar_index,]
sonar_test <- Sonar[sonar_index,]

#glm
set.seed(73, sample.kind = "Rounding")

sonar_ctrl <- trainControl(method="cv", summaryFunction=twoClassSummary, classProbs=T,
                           savePredictions = T)

sonar_glm <- train(Class ~ V13 + V25, data = sonar_train, method = "glm", trControl = sonar_ctrl)

cm_sonar_glm <- confusionMatrix(predict(sonar_glm, sonar_test), sonar_test$Class)

results_glm <- tibble(model = "GLM",
                      accuracy = cm_sonar_glm$overall["Accuracy"],
                      sensitivity = cm_sonar_glm$byClass["Sensitivity"],
                      specificity = cm_sonar_glm$byClass["Specificity"],
                      f1_score = F_meas(predict(sonar_glm, sonar_test), sonar_test$Class))

#QDA
set.seed(73, sample.kind = "Rounding")

sonar_ctrl <- trainControl(method="cv", summaryFunction=twoClassSummary, classProbs=T,
                           savePredictions = T)

sonar_qda <- train(Class ~ V13 + V25, data = sonar_train, method = "qda", trControl = sonar_ctrl)

cm_sonar_qda <- confusionMatrix(predict(sonar_qda, sonar_test), sonar_test$Class)

results_qda <- tibble(model = "QDA",
                      accuracy = cm_sonar_qda$overall["Accuracy"],
                      sensitivity = cm_sonar_qda$byClass["Sensitivity"],
                      specificity = cm_sonar_qda$byClass["Specificity"],
                      f1_score = F_meas(predict(sonar_qda, sonar_test), sonar_test$Class))

The tables don't have the same result but with the exact same code structure like the one above, on my dataset it comes out as exactly the same
Comment: Thank you for being willing to help,
I edited my question with a reprex
Comment: my first guess is your measure of performance is not very good - e.g. proportion of correct guesses is usually a bad metric. better to use Bernoulli log likelihood
Comment: there's a bug see ```cm_sonar_qda <- confusionMatrix(predict(sonar_glm, sonar_test), sonar_test$Class)```
Comment: also ```cars_index``` is used but I have no idea where that came from
Comment: I apologize, I initially tried with the mtcars dataset, it should work now.
Comment: can you share the code used to run the training for both models? I think it's very unlikely
Answer: Never a good thing to repeat the same chunk of code twice. So if we train on accuracy, we set up like what you did:
library(mlbench)
library(caret)

data(Sonar)
set.seed(73, sample.kind = "Rounding")

sonar_index <- createDataPartition(Sonar$Class, times = 1, p= 0.2, list = F)
sonar_train <- Sonar[-sonar_index,]
sonar_test <- Sonar[sonar_index,]

Methods = c("glm","qda")

wrap up the test in a function:
res = lapply(Methods,function(i){

ctrl <- trainControl(method="cv", classProbs=T,
                           savePredictions = T)

fit <- train(Class ~ V13 + V25,
 data = sonar_train, method = i, trControl = ctrl)

cm = confusionMatrix(predict(fit, sonar_test), sonar_test$Class)

results_glm <- data.frame(model = i,
                accuracy = cm$overall["Accuracy"],
                sensitivity = cm$byClass["Sensitivity"],
             specificity = cm$byClass["Specificity"],
             f1_score = F_meas(predict(fit, sonar_test),
                        sonar_test$Class))

return(results_glm)
})

And I get the following results:
[[1]]
         model  accuracy sensitivity specificity  f1_score
Accuracy   glm 0.6511628   0.7391304        0.55 0.6938776

[[2]]
         model  accuracy sensitivity specificity f1_score
Accuracy   qda 0.5813953   0.6956522        0.45     0.64

Comment: Thank you for the tip on the function! I'll definitely use it. However, even when I apply your function to my dataset I still get the exact same results for everything. Is there a mathematical explanation behind this?
Comment: what is the accuracy you are getting? and is your dataset imbalanced, like do you have 90% of one label
Comment: 0.904 accuracy and the dataset is not imbalanced, aprox. 70-30
Comment: you have to check out why those that are predicted wrongly always fail in both models. it could be that they have some extreme values or some reason that leads to that
Comment: hey it's really hard to tell without seeing the data. And obviously you can see from the example above, it really depends on your data
Comment: I can share the data with you if you want, I found out that the results are not the same when the division for test and training is not 0.20. But I think it wouldn't be wise to do that


How to get PSGet up and running from scratch

Question: On a new build machine with PowerShell 5.0, how do I configure PSGet so it actually just works?
I think it needs me to tell it what package provider I want and then what repository? And I'm behind a proxy, too, so that complicates things.
When I installed NuGet into Visual Studio, it just worked immediately against nuget.org, but with PowerShellGet its like there's no default setup.
Answer: I think someone forgot that Install-PackageProvider needs -Proxy and that's scuppered the whole thing for millions of people.


InfoWindow Scroll doesn't work in iOS

Question: I have an app in Cordova, and I use the element InfoWindow.
In Android, the scroll works correctly, but in iOS, it doesn´t work.
I have read about it but I didn´t get the solution.
I tried to use the css with some properties like overflow-y: auto;, but didn´t work.
How can I fix it? Thank you!
Comment: If you share what you have tried so far (by adding your code to the question) and the reading you have done you will improve your question and may find more help with be forthcoming.
Answer: Try to apply this css in iOS instead:

-webkit-overflow-scrolling: touch;

I hope it will help.

InfoWindow Scroll doesn't work in iOS


Git push error pre-receive hook declined

Question: I have run gitlabhq rails server on virtual machine, following 1-6 steps from this tutorial https://github.com/gitlabhq/gitlab-recipes/blob/master/install/centos/README.md and starts rails server executing command sudo -u git -H bundle exec rails s -e production. After that I created user, using admin tools and created new project under this user. Then I'm trying to push the existing project to this repo as always. But in the last step, git push origin master fails with the error

[remote rejected] master -> master (pre-receive hook declined)

Additional info:
1) I haven't activated user (project owner) via email activation link, because I haven't configured post service on server-side and I didn't find instructions how to do that in this manual.
2) Gitlab server generates tips how to push project to repo and there is not repositories/ in path. I mean it generates git@mygitlabhost:user/repo.git instead of git@mygitlabhost:repositories/user/repo.git which is correct.
3) When i tried to debug it, I opened pre-receive script inside repo on server and tried to output variables (there is 3 of them): refs = ARGF.read, key_id  = ENV['GL_ID'] and repo_path = Dir.pwd and found, that key_id is always empty. Maybe the problem is here... If so, please give me suggestions on how to fix that. Thanks
Comment: I swear, there is at least 1 person in every software development team that wakes up everyday and think how to make other developers' lives much harder.
Comment: It looks like there's a very popular answer that must work for most people. In my case, however, the same message was received from Git*Hub* when there were accidentally another push already in progress from another machine when trying to push.
Comment: You cannot do anything from your end. Just check with repository admin for the new push policies they have incorporated. It could be because they have implemented policy like commit comment must include something special for example it should include Jira ticket number in comment or similar to this.
Comment: I just encountered this issue as well.  For me, the resolution was in how my branch was named.  The server administrator (our DevOps person) had added a check on the branch name format and I was failing this check.  Once I renamed my branch locally then the new branch push worked fine.
Comment: In my case I got this error because of trying to push large files to github. So I added .angular/ to the .gitignore file. This resolved my issue.
Answer: GitLab by default marks master branch as protected (See part Protecting your code in https://about.gitlab.com/2014/11/26/keeping-your-code-protected/ why). If so in your case, then this can help:

Open your project > Settings > Repository and go to "Protected branches", find "master" branch into the list and click "Unprotect" and try again.

via https://gitlab.com/gitlab-com/support-forum/issues/40
For version 8.11 and above how-to here: https://docs.gitlab.com/ee/user/project/protected_branches.html#restricting-push-and-merge-access-to-certain-users
Comment: UI has changed a bit: After project "Settings", click "Repository" tab. Then "Protected Branches"
Comment: Since `GitLab 8.11` the options has changed a bit, check the details [here](https://docs.gitlab.com/ee/user/project/protected_branches.html)
Comment: i removed unprotected but what will happen now ? anyone else in the world can work on this repo ?
Comment: So I was having the same problem OP had and this solution worked for me, thanks! But now I'm wondering, why? I've been using gitlab for a while and all of a sudden I have do this? What changed?
Comment: facing same issue. Here I'm not even able to push other branch as well. I'm pushing it first time though.
Comment: Nope. Anyone from people, who have access to your repo can push (and push with "force" flag to replace) into any of your unprotected branches. Replace master by another set of commits, for example, which means a loose a commit history.
Comment: Why do GitLab protect `master` branch by default?
Comment: Because you can loose everything by untidy actions.
Comment: If you don't want to unprotect `master`, you can also toggle `Allowed to force push` so it remains protected but users with push rights can use `git push --force origin master`.
Comment: Besides the protected branches, there are also branch rules and push rules that can cause the pre-receive hook declined message.
Comment: The template can be changed to avoid this in `https:///admin/application_settings/repository`
Comment: In my case I got this error because of trying to push large files to github. So I added .angular/ to the .gitignore file. This resolved my issue.
Answer: In my case, my team lead to created a repo(repo was empty) and assign me as developer so when I pushed to the code directly to master the error I was facing ! [remote rejected] master -> master (pre-receive hook declined) So how it was fixed that he assigned to me as maintainer so I was able to push the code directly to the master.
Comment: How do I do that?
Comment: Ask the repo owner to give you the right to the maintainer

Alternative:
Ask repo owner to push something/Readme.md in master then you can push the code, if you are still facing the issue you have to push code with `-f` command, full command would be `git push origin master -f`.
Comment: I created my own repo, then I tried to push on the main branch to init (following the initial readme of Gitlab), it didn't work until I unprotected the main branch. Something is sill unclear.
Answer:
Following resolved problem in my local machine:

A. First, ensure that you are using the correct log on details to connect to Bitbucket Server (ie. a username/password/SSH key that belongs to you)
B. Then, ensure that the name/email address is correctly set in your local Git configuration: Set your local Git configuration for the account that you are trying to push under (the check asserts that you are the person who committed the files)
    * Note that this is case sensitive, both for name and email address
    * It is also space sensitive - some company accounts have extra spaces/characters in their name eg. "Contractor/ space space(LDN)".  You must include the same number of spaces in your configuration as on Bitbucket Server.  Check this in Notepad if stuck.
C. If you were using the wrong account, simply switch your account credentials (username/password/SSH key) and try pushing again.
D. Else, if your local configuration incorrect you will need to amend it

For MAC

open -a TextEdit.app ~/.gitconfig
NOTE: You will have to fix up the old commits that you were trying to push.

Amend your last commit:
> git commit --amend --reset-author

<save and quit the commit file text editor that opens, if Vim then
:wq to save and quit>

Try re-pushing your commits:
> git push

Answer: Seems the problem is with some services, like sidekiq. Running sudo -u git -H bundle exec rake gitlab:check RAILS_ENV=production outputs all the problems with config.
Comment: I had the problem with GitLab, just had to restart.
Comment: In my case I got this error because of trying to push large files to github. So I added .angular/ to the .gitignore file. This resolved my issue.
Answer: This is because Master branch is protected, Here are the steps to clear this error.

Create a branch in your master branch git checkout -b new-branch-name
Push the new branch git push --set-upstream origin new-branch-name
Now remotely merge the branch into master.
Once merged, reset the local master branch git reset --soft HEAD~1
Finally git pull
Comment: Not the right solution. It'll display the same error as master.
Answer: this worked for me.
In the latest version of GitLab you can find it under:
Your GitLab project > Settings > Repository > Protected Branches
One or both of the settings (Allowed to merge / push) set it to: Developers + Maintainers or make the person Maintainer.
https://gitlab.com/gitlab-org/gitlab-recipes/-/issues/27
Answer: ihave followed the instruction of heroku logs img https://devcenter.heroku.com/articles/buildpacks#detection-failure  ( use cmd: heroku logs -> show your error)
then do the cmd: "heroku buildpacks:clear". finally, it worked for me!
Answer: Might not be the case, but this was the solution to my "pre-receive hook declined" error:
There are some repositories that only allow modifications through Pull Request. This means that you have to

Create a new branch taking as base the branch that you want to push your changes to.
Commit and push your changes to the new branch.
Open a Pull Request to merge your branch with the original one.
Answer: Go to Project settings --> Hooks --> (Under) Pre-receive hooks
Disable
cp require issue reference in commits
Answer: You need to add your ssh key to your git account,if it throws error then delete previous ssh key and create a new ssh key then add.
Comment: That didn't help. :( Tested on both accounts - root and myuser on vm and local machine resp.
Comment: check git remote -v, your git repo is added or not ?
Comment: 'git remote -v' outputs:
origin git@mygitlabhost:repositories/user/repo.git (fetch)
origin git@mygitlabhost:repositories/user/repo.git (push)
Comment: If you're using hosted gitlab, the problem is likely on their side.   Just try again a few minutes later.
Comment: Answers like given here should get an extra negative penalty cause there is no reason whatsoever given WHY this would work or how SSH is related to the problem stated.
Answer: You might not have developer access to the project or master branch. You need dev access to push new work up.
New work meaning new branches and commits.
Answer: I stumbled across the same error using BitBucket. I had a local Git repo I wanted to back up online, so I created a new repository from my BitBucket account (using the web interface).
After running git remote add origin email@example.com:StatMarianne/.git, I ran git push origin master to no avail (I typically don't use the -u option with git push because I don't mind typing up the full repo and branch names when pushing and pulling).
The error read:
remote: You're not allowed to write to this repository.
To bitbucket.org:StatMarianne/.git
 ! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'firstname.lastname@example.com:StatMarianne/.git'

But my local branch did get successfully pushed when I ran git push -u origin master (following strictly BitBucket's instructions).
I find it surprising, since -u (--set-upstream) should only "add upstream (tracking) reference..." Anyhow.
Answer: If you are facing issue like
! [remote rejected] master -> master (pre-receive hook declined)
its beacuse master is protected, you can do 2 steps
To remove the protection, follow these steps –

Go to project Settings.

Click on Repository tab.

Open Protected Branches.

Find your master branch and click on Unprotect.

Or else
We can switch branches from master to main

git checkout -b main

git branch -D master

git push heroku main

Happy Hacking!!!
Answer: Despite the question is specific to gitlab, but similar errors can happen on github, depending how it is set up (usually Github Enterprise).
You need to familiarize yourself with the following concepts:

pre-receive hooks
organization webhooks
Webhooks

Webhooks are more commonly understood than other two items.
The Pre-receive hooks

are scripts that run on the GitHub Enterprise server
to enforce policy. When a push occurs, each script runs in an
isolated
environment
to determine whether the push is accepted or rejected.

Organization webhooks:
Webhook events are also sent from your repository to your "organization webhooks". more info.
These are set up in your github enterprise. They are specific to the version of the github enterprise.
You may have no visibility because of your access limitations (developer, maintainer, admin, etc).
Comment: Why the negative vote? This is an undocumented new behaviour that needs to be out there for community.
Answer: I solved this issue by changing remote 'origin' url from http to git protocol in .git/config
Answer: I had the same problem while working with Bitbucket.
On push, the error was 'The commit message doesn't match the regex **".
Got to 'Settings' > 'Hooks' > Enable 'Yet another commit checker' option.
And it started working!!
Comment: If you have a new question, please ask it by clicking the [Ask Question](https://stackoverflow.com/questions/ask) button. Include a link to this question if it helps provide context. - [From Review](/review/late-answers/30350770)
Answer: I recently faced this issue on Gitlab and none of the above solutions worked for me.
Finally what I realized was that the public key was deployed on the repository by my colleague who had left the company and his account was disabled a few weeks later. This caused the key deployed by him rendered unusable, even though it wasn't his personal key.
I deleted the key and re-uploaded the same one and it worked. Permanent solution is to create a service account and upload keys using that account.
Quoting from the Gitlab documentation.

All deploy keys are associated to an account. Since the permissions for an account can change, this might lead to scenarios where a deploy key that was working is suddenly unable to push to a protected branch.
Answer: Please try:
git push -u origin master

If you still aren't able to push successfully, Make a new branch or choose another one and Push on the new Branch
Answer: I've experienced that just because of AWS breakage.
To exclude this just check if the message contains something similar to
<title>504 Gateway Time-out</title>
So if you haven't done anything suspicious before and just started to see this - it may be just server timeouts.
Answer: TL;DR Rename project and copy all the changes over.

I tried almost all answers on this page.
In the end I fixed it by doing this:

Renaming my project to project-tmp
Cloning the project again to project
Manually moving all my changes from project-tmp to project (and not copying over the .git-folder obviously).
git add .
git commit -m 'Blah blah'
git push

That worked!

Why this worked?
My theory is, that somewhere in some commit (or something) there was a bad piece of settings that screwed it up.
Git LFS
Another thing, that I did, was that I setup git lfs. I'm not sure if that was important or not.
Answer: For me two possible cases:

The branch is protected and you do not have the right to push (see the role of your git user)
Allowed to force push is disabled on this branch and you maybe you are trying to force push.
Answer: solution:

you need to remove .lock file, yarn.lock or package-lock.json file, for safety you can move this file another folder
then, git add .
git commit -m 'update'
git push heroku main
Answer: for me this happened because of the previous pending commints which were not meeting certain criteria's. after below command it worked for me
git reset --hard commitId
(commit id of the successful commit before unsucessful ones)
Answer: I had the same problem going around for a while, in my case I was working in a group and had cloned the repository but created it in a separate repository. Two things happened
1.- The repository was created privately.
2.- The repository had not been assigned the necessary permissions to upload to it remotely.
You can check if you are working just create a new public repository and change the path of the remote one this way you can test it.
in my case as I was working in a group just change my url to the creator repository and that's it, push and it worked perfectly, I hope I can help you.
git remote set-url origin https://github.com// <-- URL
git push -u origin main
Answer: Only specific people or groups have write access means Branch is restricted.

If you are using Bitbucket follow bellow steps:

Login in your Bitbucket Account.
Select Your Repository
Click On Repository Settings
Click On Branch restrictions
All restricted branch will be list click Edit
You can add your user in Only specific people or groups have write access section

7. Click on Save button
8. Again try to push
Answer: In my case the gitlab service was down when I got this error - this happened on 07-07-2023
Answer: I've faced the same issue, this is because I am pushing my code directly in the master branch, and I don't have rights for this. So I push my code in a new branch and after that, I created a pull request to merge with master.
Answer: Please check if JIRA status in "In Development".
For me , it was not , when i changed jira status to "In Development", it worked for me.


Konva - Unable to completely destroy stage in react when unmounting component

Question: I am using the Konva API directly in my react componen, and it works perfectly.
I only have one big problem.
The problem is that when the component that contains the ref container is unmounted the react app crashes, saying that staging has no container anymore.
I have tried to call destroy on the stage when the component unmounts, it enters that method but it still crashes.
So basically, from what i understand, calling destroy on stage from within the react component does not destroy the stage from the DOM.
Could anyone help with this issue?
EDIT: adding code snippet
    export default class ReactComp extends Component {
     renderKonva(container) {

     var stage = new Konva.Stage({
       container: container,
       width: 500,
       height: 350
     });
     var layer = new Konva.Layer();
     var rect = new Konva.Rect({
      stroke: '#155DA4',
      strokeWidth: 2,
      fill: '#fff',
      width: 190,
      height: 190,
      shadowColor: 'black',
      shadowBlur: 10,
      shadowOffset: [10, 10],
      shadowOpacity: 0.2,
      cornerRadius: 2,
      opacity: 0.75,
      visible: true
     });
     layer.add(rect);
     stage.add(layer);
    }

    render() {
      return (

 this.renderKonva(ref)}>

      )
    }

So whenever this component unmounts i get the error:
"Uncaught Stage has no container. A container is required."
Also, i have tried calling destroy on the stage, but i still get the same error. Also, even if i create and destroy the stage in renderKonva, and in essence i will have nothing displayed, because stage was once created it throws the same error.
Comment: Please see creating a [mcve], so we can see your issue and reproduce it.
Comment: Sorry, we need to see your code to help you solve your problem.
Comment: Thank you for your replies, i have added some code, hope this helps
Answer: renderKonva is a callbackRef. From the docs:

React will call the ref callback with the DOM element when the component mounts, and call it with null when it unmounts.

That means, when it unmounts container is undefined.
So,
export default class ReactComp extends Component {
 constructor(props){
  super(props)
  this.stage = null;
 }

 renderKonva(container) {
  if (!container) {
    this.stage.destroy();
    return;
  }

  var stage = new Konva.Stage({
   container: container,
   width: 500,
   height: 350
  });

  this.stage = stage;
  ...
 }

}


Como usar pseudo nomes com CONCAT e MySQL?

Question: Uma questão sobre MySQL pede que o resultado saia nessa formato de resposta.

Ao terminar minha solução através de uma consulta feita em MySQL, encontro o seguinte problema.
Abaixo um primeiro exemplo de solução da minha consulta que Funciona
SELECT CONCAT('There are a total of ' , COUNT(name),' ', occupation ) FROM OCCUPATIONS GROUP BY occupation ORDER BY COUNT(name) ASC ;
Abaixo um segundo exemplo de solução da minha consulta que Não Funciona

SELECT CONCAT('There are a total of ' , COUNT(name) AS numb,' ', occupation ) FROM OCCUPATIONS GROUP BY occupation ORDER BY numb ASC ;`

O problema em questão é que eu gostaria de renomear o COUNT(name) para numb através de um 'aliase' ou um pseudo nome, mas me deparo com esse erro.
ERROR 1583 (42000) at line 3: Incorrect parameters in the call to native function 'concat'

Seria possível contornar esse problema, ou seja, é possível o uso de pseudo nomes dentro da função CONCAT?
Answer: Não é possível, e neste caso nem faz sentido. Imaginei inicialmente que iria usar o dado para mais alguma coisa, como não vai seria completamente desnecessário dar nome para o resultado da expressão usada na concatenação.
Não faz sentido não querer repetição porque a sintaxe pede a repetição.
Answer: De acordo com o standard não é possível usar aliases na mesma instrução de SELECT na qual eles são criados. Uma solução passa por usar um sub-query.
O standard informa que a sequência de execução das instruções é a seguinte:
1. FROM
2. WHERE
3. GROUP BY
4. HAVING
5. SELECT
6. ORDER BY
7. TOP

O que explica, por exemplo, porque é que é possível utilizar um alias na cláusula ORDER BY.
Comment: Sempre que uso alguma função de agregação costumo dar nomes pra eles, nesse caso é para não repetir o "COUNT(name)" na  parte do GROUP BY.
Comment: Neste caso a solução passa por usar uma sub-query para calcular o total, após isto, poderá utilizar o alias tanto no SELECT como no GROUP BY


Are normal operator with positive self-adjoint part boundedly invertible?

Question: Consider an unbounded normal operator $A$ with domain $\mathcal{D}(A)$ on a Hilbert space $\mathcal{H}$, i.e. its adjoint $A^*$ satisfies $\mathcal{D}(A^*)=\mathcal{D}(A)$ and, for all $x\in\mathcal{D}(A)$, $\|Ax\|=\|A^*x\|$. We can thus define its self-adjoint and skew-adjoint parts:
\begin{equation}
\mathrm{Re}\,A=\frac{A+A^*}{2},\qquad\mathrm{Im}\,A=\frac{A-A^*}{2\mathrm{i}},
\end{equation}
both being self-adjoint operators with domain $\mathcal{D}(A)$.
Now, suppose that one of them (say, $\mathrm{Re}\,A$) is a strictly positive operator, thus implying that its spectrum is contained in $[\epsilon,\infty)$ for some $\epsilon>0$ and, consequently, it admits a bounded inverse $(\mathrm{Re}\,A)^{-1}\in\mathcal{B}(\mathcal{H})$. Can we state that $A$ admits a bounded inverse $A^{-1}$ as well? (Equivalently, is $0$ an element of the resolvent set of $A$?)
Comment: What have you tried?
Comment: I've checked that $A$ is injective (it comes as an immediate consequence of the invertibility of $\mathrm{Re}\,A$) but I have not managed to show that the inverse is bounded. A possibility would be to show that $A$ is surjective; the closed graph theorem would then imply that the inverse is bounded.
Comment: Also: using the relation $\mathrm{Ker}\,A^*=(\mathrm{Ran}\,A)^\perp$, and the fact that $A^*$ is injective as well, one shows that $\mathrm{Ran}\,A$ is dense in $\mathcal{H}$, so that $A^{-1}$ exists and it is densely defined. However, this still does not show that $A^{-1}$ is bounded unless we assume $\mathrm{Ran}\,A$ to be a closed subspace of $\mathcal{H}$; only in such a case, the closed graph theorem does imply the claim.
Answer: This should be the answer. Since $A$ is normal, it is closed. A closed operator admits a bounded inverse if and only if there is $c>0$ such that, for all $x,y\in\mathcal{D}(A)$,
$$
\|Ax\|\geq c\|x\|,\qquad \|A^*y\|\geq c\|y\|;
$$
see e.g. J. Derezinski, Unbounded linear operators, Theorem 3.3.2. Now, if $\mathrm{Re}\,A$ is strictly positive, i.e. $\langle x,\mathrm{Re}\,Ax\rangle\geq c\|x\|^2$, then
$$
|\langle x,Ax\rangle|\geq c\|x\|^2,\qquad|\langle x,A^*x\rangle|\geq c\|x\|^2
$$
and therefore both conditions hold, since e.g.
$$
\|x\|\|Ax\|\geq|\langle x,Ax\rangle|\geq c\|x\|^2.
$$


Signing an encrypted PDF document with PDFBox 2.0.0

Question: I try to sign an encrypted PDF document for which the signature is allowed.
This document : Encrypted PDF document
With the PDFBox 2.0.0 sample code : CreateSignature.java
But I got this exception :
<code>Exception in thread "main" java.lang.NullPointerException
    at org.apache.pdfbox.pdmodel.encryption.StandardSecurityHandler.computeRevisionNumber(StandardSecurityHandler.java:131)
    at org.apache.pdfbox.pdmodel.encryption.StandardSecurityHandler.prepareDocumentForEncryption(StandardSecurityHandler.java:335)
    at org.apache.pdfbox.pdfwriter.COSWriter.write(COSWriter.java:1254)
    at org.apache.pdfbox.pdmodel.PDDocument.saveIncremental(PDDocument.java:966)
    at principal.CreateSignature.signDetached(CreateSignature.java:179)
    at principal.CreateSignature.signDetached(CreateSignature.java:154)
    at principal.CreateSignature.main(CreateSignature.java:334)
</code>
I don't know the pass of the document but signing is allowed :

What should I do for sign this document?
Comment: Indeed, I can reproduce the problem. After some debugging it looks to me like the PDFBox signing code has not been developed or tested for encrypted files. You may want to open an issue in the Apache PDFBox Jira. For the time being you might want to remove the password protection in a first step and only thereafter sign.
Answer: This has been fixed in PDFBox 2.0 RC3 (released today), please try it.
While the answer by Gleb is well-meant, it is not correct, due to the reasons I've written in the issue:
https://issues.apache.org/jira/browse/PDFBOX-2729
The solution has the problem that it reads and saves the file first, so it is no longer the same before signing. Another problem is that we must encrypt with the same method than initially done, and with the same encryption key. For AES256, this (internal) encryption key has a random component, even if the user provides the same keys to the API.
Comment: It works like a charm ! I just have a problem with bouncycastle provider. Please check https://issues.apache.org/jira/browse/PDFBOX-3311. Thank you !
Answer: Here is my solution for this:
When you load your pdf file, check if it is protected, load it with Owner password and reset all security.
<code>         ...
        this.document = PDDocument.load(pdf, ownerPassword);
        document.setAllSecurityToBeRemoved(true);
        ...
</code>
To make document protected again you should create new StandartProtectionPolicy with old passwords and premissions, save document, and then load it with password, sign it and save it again.
<code>    .....
    StandardProtectionPolicy policy = new StandertProtectionPolicy(ownerPassword, userPassword, accessPremission)
       doc.protect(policy);
       doc.save(signedFile);
       doc.close();
       doc = PDDocument.load(signedFile, policy.getOwnerPassword());
       doc.protect(policy);
       ....
       doc.addSignature(signature, this, options);
</code>
This works for me.
Comment: I'm not sure that this is always correct... I'll write my thoughts in PDFBOX-2729 when I know enough. It isn't easy, because even if Adobe Reader accepts the file, it still doesn't mean that it is correct :-(
Comment: You should be able to sign an encrypted PDF file without unlock it.
Comment: @CyrilBremaud, Yes, but it seems like a pdfbox issue. This work-around helps with encrypted, but not signed files, and fails when you need to sign encrypted document for second time.
Comment: @CyrilBremaud why should one be able to sign an encrypted file without decrypting it? The signature itself (except the /Contents string) is encrypted, so a key is needed. See PDFBOX-3173 which has files where the signature is encrypted.


Inequality $\prod_{k=1}^n (1+a_k) \ge (n+1)^n \prod_{k=1}^n a_k.$

Question: For non-negative $a_k$, $k =1,2,\dots,n$ such that $a_1+a_2+\dots+a_n=1$, then
$$\prod_{k=1}^n (1+a_k) \ge (n+1)^n \prod_{k=1}^n a_k.$$
I used induction but it became complicated. A detailed answer will be appreciated.
Comment: If you're afraid of "complicated", you might not understand some answers.
Comment: Apply the AM-GM inequality to $1+a_k = a_1 + \ldots + a_n + a_k$. Compare https://artofproblemsolving.com/community/c6h1212085p6012361 for a similar inequality  where the same approach is used.
Comment: so what do you want to prove? Is there any order on $a_k$?
Comment: @Alex i want to prove inequality
Comment: Have you tried to transform the products into sums via logarithms?
Comment: @ProfessorVector Right  sir ji you are right
Comment: That's why it's not a bad idea to give some context, and information about what you tried, and where you failed. I may think Jensen's inequality would be the most natural and simple way, but if you've never heard of convexity/concavity or derivatives, you may think otherwise.
Comment: @MartinR  thankyou sir ji. i done it
Answer: Inspired by Real numbers inequality on AoPS: Let $S = \sum_{k=1}^n a_k$ and $P = \prod_{k=1}^n a_k$. Then, using the AM-GM inequality,
$$
 \prod_{i=1}^n(1+a_i) = \prod_{i=1}^n(S+a_i) \ge \prod_{i=1}^n \bigl( (n+1)\sqrt[n+1]{P a_i}\bigr) = (n+1)^n P \, .
$$
Answer: Let $ n $ be a positive integer. We have : $$ \prod_{k=1}^{n}{\left(1+\frac{1}{a_{k}}\right)}=\sum_{k=0}^{n}{\sum_{1\leq i_{1}<\cdots <i_{k}\leq n}{\frac{1}{a_{i_{1}}\cdots a_{i_{k}}}}} $$
Given some $ k\in\mathbb{N} $, using AM-GM inequality, we have : $$ \frac{1}{\binom{n}{k}}\sum_{1\leq i_{1}<\cdots <i_{k}\leq n}{\frac{1}{a_{i_{1}}\cdots a_{i_{k}}}}\geq \left(\prod_{1\leq i_{1}<\cdots <i_{k}\leq n}{\frac{1}{a_{i_{1}}\cdots a_{i_{k}}}}\right)^{\frac{1}{\binom{n}{k}}}=\left(\prod_{k=1}^{n}{\frac{1}{a_{k}}}\right)^{\frac{\binom{n-1}{k-1}}{\binom{n}{k}}}=\left(\prod_{k=1}^{n}{\frac{1}{a_{k}}}\right)^{\frac{k}{n}} $$
Using AM-GM again, we have $ \left(\prod\limits_{k=1}^{n}{a_{k}}\right)^{\frac{1}{n}}\leq\frac{1}{n}\sum\limits_{k=1}^{n}{a_{k}}=\frac{1}{n} $, and hence : $$ \left(\prod_{k=1}^{n}{\frac{1}{a_{k}}}\right)^{\frac{1}{n}}\geq n $$
Thus : $$ \sum_{1\leq i_{1}<\cdots <i_{k}\leq n}{\frac{1}{a_{i_{1}}\cdots a_{i_{k}}}}\geq\binom{n}{k}n^{k} $$
Hence : $$ \prod_{k=1}^{n}{\left(1+\frac{1}{a_{k}}\right)}\geq\sum_{k=0}^{n}{\binom{n}{k}n^{k}}=\left(n+1\right)^{n} $$
Answer: This is the solution if $0<a_k<1$.
LHS is $P_1 = e^{\log P_1} = e^{ \sum_{k=1}^{n} \log (1+a_k)} \geq e^{\sum_{k=1}^{n} (a_k - \frac{a_k^2}{2})} = e^{\frac{1}{2}}$
This inequality is due to Taylor series expansion for $0<x:$
$$
x-\frac{x^2}{2}< \log(1+x) <x
$$
and the fact that $0<a_k^2 < a_k <1$.
RHS can be rewritten as
$$
(n+1)^n \prod_k a_k = e^{\sum_{k=1}^{n}\log ((n+1)^n a_k)} = e^{\sum_{k=1}^{n}\log b_k} < 1
$$
where $b_k = (n+1) a_k$, and, since $0<a_k<1, \log b_k <0$
Putting these all together, RHS $<$ LHS
Comment: The inequality is met with equality when each $a_k=\frac{1}{n}$ so the conclusion of a strict inequality $RHS<e \times 1 < LHS$ cannot be correct, unless RHS means something other than 'right hand side' of $\prod_{k=1}^n (1+a_k) \ge (n+1)^n \prod_{k=1}^n a_k$ and/or LHS means something other than the "left hand side" of that inequality
Comment: @user8675309: The first estimate is already wrong, because $\log(1+x) \le x$ for all real numbers $x$.
Comment: Sorry, but I still don't get it. Why is $b_k = (n+1) a_k < 1$ for all $k$?
Comment: Thankyou sir for your help .  I also solve using Am-gm inequality
Comment: @MartinR see the edit
Comment: $\log b_k < 0$ would only hold if $(n+1)a_k < 1$, which need not be true. Also (as @user8675309 pointed out above) *equality* holds with $a_k = 1/n$, so a proof demonstrating strict inequality cannot be correct.
Comment: @MartinR that's what I start the solution with, that it's for $0<a_k<1$
Comment: As Martin pointed out, the equality case $ a_i = \frac{1}{n}$ leads to errors in your solution, like $b_k = (n+1)/ n < 1 $.
Answer: For a simple answer only using $\text{AM}\geq \text{GM}$:
consider dividing each side by $\big(\prod_{k=1}^n a_k\big)$  and re-writing the desired inequality as
$\prod_{k=1}^n \big(1+\frac{1}{a_k}\big) \geq \big(n+1\big)^n$
now take nth roots to see this is equivalent to
$\Big(\prod_{k=1}^n \big(1+\frac{1}{a_k}\big)\Big)^\frac{1}{n} $
$\geq \big(\prod_{k=1}^n\frac{1}{a_k}\big)^\frac{1}{n} +\big(\prod_{k=1}^n 1\big)^\frac{1}{n} $
$ \geq \frac{1}{\frac{1}{n}}+1$
$=n +1$
where the first inequality comes from superadditivity of the geometric mean (which may be proven with a one-liner using $\text{AM}\geq \text{GM}$ ) and the second inequality comes from observing $\frac{1}{n}\geq \big(\prod_{k=1}^n a_k\big)^\frac{1}{n}$ which holds from $\text{AM}\geq \text{GM}$, and then inverting.
The original inequality is met with equality iff $\frac{1}{n} = a_1 = a_2=...=a_n$


How to test Singleton class that has a static dependency

Question: I have a Singleton class that uses the thread-safe Singleton pattern from Jon Skeet as seen in the TekPub video. The class represents a cached list of reference data for dropdowns in an MVC 3 UI.
To get the list data the class calls a static method on a static class in my DAL.
Now I'm moving into testing an I want to implement an interface on my DAL class but obviously cannot because it is static and has only one static method so there's no interface to create. So I want to remove the static implementation so I can do the interface.
By doing so I can't call the method statically from the reference class and because the reference class is a singleton with a private ctor I can't inject the interface. How do I get around this? How do I get my interface into the reference class so that I can have DI and I can successfully test it with a mock?
Here is my DAL class in current form
public static class ListItemRepository {

    public static List<ReferenceDTO> All() {
        List<ReferenceDTO> fullList;
        ... /// populate list
        return fullList;
    }
}

This is what I want it to look like
public interface IListItemRepository {
    List<ReferenceDTO> All();
}

public class ListItemRepository : IListItemRepository {

    public List<ReferenceDTO> All() {
        List<ReferenceDTO> fullList;
        ... /// populate list
        return fullList;
    }
}

And here is my singleton reference class, the call to the static method is in the CheckRefresh call
public sealed class ListItemReference {

    private static readonly Lazy<ListItemReference> instance =
        new Lazy<ListItemReference>(() => new ListItemReference(), true);

    private const int RefreshInterval = 60;
    private List<ReferenceDTO> cache;
    private DateTime nextRefreshDate = DateTime.MinValue;

    public static ListItemReference Instance {
        get { return instance.Value; }
    }

    public List<SelectListDTO> SelectList {
        get {
            var lst = GetSelectList();
            lst = ReferenceHelper.AddDefaultItemToList(lst);
            return lst;
        }
    }

    private ListItemReference() { }

    public ReferenceDTO GetByID(int id) {
        CheckRefresh();
        return cache.Find(item => item.ID == id);
    }

    public void InvalidateCache() {
        nextRefreshDate = DateTime.MinValue;
    }

    private List<SelectListDTO> GetSelectList() {
        CheckRefresh();
        var lst = new List<SelectListDTO>(cache.Count + 1);
        cache.ForEach(item => lst.Add(new SelectListDTO { ID = item.ID, Name = item.Name }));
        return lst;
    }

    private void CheckRefresh() {
        if (DateTime.Now <= nextRefreshDate) return;
        cache = ListItemRepository.All(); // Here is the call to the static class method
        nextRefreshDate = DateTime.Now.AddSeconds(RefreshInterval);
    }
    }
}

Answer: You can use the singleton based on instance(not based on static), for which you can declare interface like this.
public interface IListItemRepository
{
    List<ReferenceDTO> All();
}

public class ListItemRepository : IListItemRepository
{
    static IListItemRepository _current = new ListItemRepository();

    public static IListItemRepository Current
    {
        get { return _current; }
    }

    public static void SetCurrent(IListItemRepository listItemRepository)
    {
        _current = listItemRepository;
    }

    public List<ReferenceDTO> All()
    {
        .....
    }
}

Now, you can mock IListItemRepository to test.
    public void Test()
    {
        //arrange
        //If Moq framework is used,
        var expected = new List<ReferneceDTO>{new ReferneceDTO()};

        var mock = new Mock<IListItemRepository>();
        mock.Setup(x=>x.All()).Returns(expected);

        ListItemRepository.SetCurrent(mock.Object);

        //act
        var result = ListItemRepository.Current.All();

        //Assert
        Assert.IsSame(expected, result);
    }

Comment: Where is `Mock`coming from? I assume a framework but I mean which one?
Comment: Oh. It means any mock object. You can use any mocking framework(Moq/RhinoMock...) or hand coded mock class.
Comment: This has actually worked. I don't know why I didn't think of it before but I was using a static repository and it wasn't thread safe. By using your example and my thread safe code I got it. I still can't inject `IListItemRepository` into the caching reference class but it lets me use the interface with the repository and then I took the same approach with the reference class :-) awesome thanks!!
Comment: Could you give me more information about why you cannot inject the interface into the caching?
Comment: Private ctor on a thread safe class basically. In this series of videos http://tekpub.com/productions/cspatterns Jon Skeet shows how using what we think are singleton classes aren't true singletons. He compares several methods and show how each one fail. Then he shows the pattern I have in my question using the `Lazy` and a private constructor and it provides a true singleton class. I've already looked into some of the DI frameworks and their methods that are supposed to provide a singleton are using the failed strategies that Jon demonstrated.
Comment: @AlfalfaStrange: There is something that I do not know about singlenton pattern. It sounds like that the singleton we understand may not be true on some extreme case. I hope you can resolve it.
Answer: One way to test it would be if you refactor your ListItemReference by adding extra property:
public sealed class ListItemReference {
    ...
    public Func<List<ReferenceDTO>> References = () => ListItemRepository.All();
    ...
    private void CheckRefresh() {
        if (DateTime.Now <= nextRefreshDate) return;
        cache = References();
        nextRefreshDate = DateTime.Now.AddSeconds(RefreshInterval);
    }
}

And then in your test you could do:
ListItemReference listReferences = new ListItemReference();
listReferences.References = () => new List<ReferenceDTO>(); //here you can return any mock data

Of course it's just temporary solution and I would recommend getting rid of statics by using IoC/DI.
Answer: Which DI framework are you using?  Depending on your answer, IOC container should be able to handle single-instancing so that you don't have to implement your own singleton pattern in the caching class.  In your code you would treat everything as instanced classes, but in your DI framework mappings you would be able to specify that only one instance of the cache class should ever be created.
Comment: I haven't implemented an IoC framework yet, I was considering Ninject but the documentation and lack of up to date tutorials is horrible. Castle Windsor has a great tutorial so I was considering that one because it shows me how to fix the controllers. I'm still struggling over how to build the DI into the solution (where to put the root, how to reference, etc). Would love to see a good sample of DI in an NTier app
Comment: I'm not an expert on DI myself, but I believe that every major DI framework will support singleton instancing.

Autofac:  http://code.google.com/p/autofac/wiki/InstanceScope
Unity:  http://msdn.microsoft.com/en-us/library/ff660864%28v=pandp.20%29.aspx
Ninject:  http://blog.bobcravens.com/2010/03/ninject-life-cycle-management-or-scoping/
StructureMap:  http://abstractcode.com/abstractblog/archive/2010/06/13/structuremap-part-2-ndash-instance-lifecycles.aspx
Comment: That makes sense, but since I can't see *how* it's handling it, I feel *safer* with my thread-safe class with the Lazy instancing :-)
Comment: How = by being the central point where instances of the object are created.  It could either create a new instance each time or use some sort of registry or similar pattern to ensure single instancing.  Some DI frameworks will let you specify an existing instance as the singleton instance of choice.  Still, if you want to embrace DI and be able to supply testable mocks, you will probably want to avoid creating your own static singleton instances and "have faith" in the DI framework.
Comment: I would if I hadn't watched Jon Skeet's video on TekPub where he proves that all the locking/volitile/sync patterns that most people use to try to create a *real* singleton all fail at that. And then he showed how to do it and it never fails. So I'm sure you can see where I struggle with that :-) I've read the docs on Ninject and see that it doesn't implement true singleton, I'm looking into the rest :-)


Behavior of char pointer

Question: I am really confused about the following:
char *list = malloc(sizeof(char));

list[0] = 'a';
list[1] = 'b';
printf("%s\n", list);

My expectation was some kind of undefined behavior, because list has only memory for 1 char "object".
But the actual output is ab. Why can I access list[1] when list only has allocated memory for one char?
Comment: You shouldn't have any expectation from undefined behavior. Its every act is deceptive.
Comment: "Undefined behavior" means anything can happen as far as the Standard is concerned. Something is actually happening so that should meet your expectations. :)
Comment: compiler aligns data segment.I bet to this cause.
Answer: As per your memory allocation of sizeof(char) bytes (and considering the allocation is success),
  list[1] = 'b';

is out-of-bound access, which invokes undefined behavior. There can be no expectation from a program causing UB. It can do anything, absolutely anything.
That said,

sizeof(char) is defined (guranteed) to be 1 in C standard.
Check for the success of malloc() before using the return value. Otherwise, the first access, list[0] itself will invoke UB as you'll end up dereferencing an invalid pointer (i.e., accessing invalid memory)
Passing a pointer to a non-null-terminated char array as argument to %s also invokes UB.
Comment: ..non-null-terminated...   and all that stuff is wrong
Comment: char b[]="jyumj";
printf("%s",b);       workin
Comment: @АлексейНеудачин so you think `b` is not null-terminated, i'm afraid, you're wrong.
Comment: how about to type non workin ex
Comment: yea it's null-terminated

Behavior of char pointer


Example illustrating the importance of Hamel bases for description of additive functions

Question: Can anyone please explain and show (step by step) that how $ f \big( f ( x ) \big) = x $ in the following example?

One can show that for any Hamel basis $ H $ there exists a bijection $ \varphi : [ 0 , 1 ] \to H $. If we set $ \varphi ( t ) = h _ t $, then $ H = \{ h _ t | t \in [ 0 , 1 ] \} $. This observation leads to constructions of additive functions having interesting properties.
Example. Let $ f : \mathbb R \to \mathbb R $ be the additive function determined by the function $ s : H \to \mathbb R $ defined by:
$$ s ( h _ t ) =
\begin {cases}
h _ t & \text {if } t \in \left[ 0 , \frac 1 2 \right] \\
- h _ t & \text {if } t \in \left( \frac 1 2 , 1 \right] \text .
\end{cases} $$
Then it is easy to check that $ f \big( f ( x ) \big) = x $ for any $ x \in \mathbb R $.

Also, please explain and show (step by step) that how $ f \big( f ( x ) \big) = f ( x ) $ in the following example?

Another interesting example of a discontinuous additive function is obtained by considering the function $ s : H \to \mathbb R $ defined by
$$ s ( h _ t ) =
\begin {cases}
h _ t & \text {if } t \in \left[ 0 , \frac 1 2 \right] \\
0 & \text {if } t \in \left( \frac 1 2 , 1 \right] \text .
\end{cases} $$
Then $ f \big( f ( x ) \big) = f ( x ) $ for any $ x \in \mathbb R $.

I was unable to do it and I am completely clueless.
Comment: Check that the equations hold for $x\in H$ by using $f(x)=s(x)$ for $x\in H$ and then note that the additive extension is unique.
Comment: Do you understand how $f$ is constructed in the first place? Because once you do, showing that $f(f(x)) = x$ is indeed easy to check.
Comment: i am sorry but i could not follow you
Comment: well no....could you please help ?
Answer: For the first one, for all $h_t\in H$ we have
\begin{align}
f(f(h_t)) = f(s(h_t)) &=
\begin{cases} f(h_t) & t\le \frac 1 2 \\ f(-h_t) & t>\frac 1 2\end{cases} \\
&=
\begin{cases} s(h_t) & t\le \frac 1 2 \\ -s(h_t) & t>\frac 1 2\end{cases} \\
&=
\begin{cases} h_t & t\le \frac 1 2 \\ -(-h_t) & t>\frac 1 2\end{cases} \\
&= h_t.
\end{align}
Since $f(f(x))=x$ on a Hamel basis and both $f\circ f$ and $\operatorname{id}_{\mathbb R}$ are additive, it also holds on all of $\mathbb R$.
For the second one, for all $h_t\in H$ we have
\begin{align}
f(f(h_t)) = f(s(h_t)) &=
\begin{cases} f(h_t) & t\le \frac 1 2 \\ f(0) & t>\frac 1 2\end{cases} \\
&=
\begin{cases} s(h_t) & t\le \frac 1 2 \\ 0 & t>\frac 1 2\end{cases} \\
&=
\begin{cases} h_t & t\le \frac 1 2 \\ 0 & t>\frac 1 2\end{cases} \\
&= s(h_t) = f(h_t).
\end{align}
Since $f(f(x))=f(x)$ on a Hamel basis and both $f\circ f$ and $f$ are additive, it also holds on all of $\mathbb R$.

In reply to questions raised in the comments:

Since $t\in[0,1]$ anyway, we do indeed have $t\in[0,\tfrac 1 2]$ equivalent to $t\le \tfrac 1 2$ and $t\in(\tfrac 1 2,1]$ equivalent to $t>\tfrac 1 2$, I just prefer writing it that way.
The map $\operatorname{id}_{\mathbb R}\colon \mathbb R\to\mathbb R$ is the identity map on $\mathbb R$, it satisfies $\operatorname{id}_{\mathbb R}(x)=x$ for all $x\in\mathbb R$.
I can't recommend a book on Hamel bases, I just picked up what I needed to answer your question.
Whenever you have two additive functions $\varphi,\psi\colon\mathbb R\to\mathbb R$ that agree on some Hamel basis $H\subseteq\mathbb R$, that is $\varphi(h)=\psi(h)$ for all $h\in H$. It follows that $\varphi(x)=\psi(x)$ for all $x\in\mathbb R$, since any map $H\to\mathbb R$ has a unique additive extension to $\mathbb R$.
$f$ being additive means that $f(x+y)=f(x)+f(y)$ for all $x,y\in\mathbb R$. In particular for $x=y=0$ you get $f(0)=f(0)+f(0)$ so $f(0)=0$ and for $y=-x$ you get $f(0)=f(x)+f(-x)$, so $f(-x)=-f(x)$ ($f$ is odd). That is what I used to get things like $f(-h_t)=-f(h_t)=-s(h_t)$.
Comment: I replied to your questions in an edit.
Comment: also, by $t \leq \frac{1}{2}$ do you mean $t \in [0, \frac{1}{2}]$ ??
Comment: could you please tell that what do mean by $\operatorname{id}_{\mathbb R}$ ?
Comment: also, if you don't mind, could you please tell me that where did you learn these all concepts of Hamel basis by recommending me a book for the same ?
Comment: Could you please explain in a bit detail the last statements of both the proofs ? I coudnt understand that how you concluded $f(f(x))=f(x)$ holds for R ??
Comment: is it correct if i write $f(−ht)=−f(ht)=−s(ht)$ (since $f(t)$ is additive and odd) in reference to the first proof ??
Comment: Thank you very much...i owe you for your help !
Comment: Sir, if possible could you please answer the following question asked by me on logarithmic Cauchy functional equations. It would be highly helpful to me. Thank  you.                                      https://math.stackexchange.com/questions/3860102/solution-of-the-logarithmic-cauchy-equation


Sample Standard Deviation - Did my teacher make a mistake (hypothesis testing)?

Question: I first posted this one MSE, but it was pointed out to me that this site might be more suited for these types of questions (which is probably why this question wasn't answered for about 11 hours) over there.
So we have the following data about a research:
Group 1:
$n_1 = 10$
$\mu \bar{x}_1 = 433$
$ \sigma \bar{x}_1 = 65$
Group 2:
$n_2 = 12$
$ \mu \bar{x}_2 = 367$
$ \sigma \bar{x}_2 = 84$
Hypotheses:
$H_0: \mu _v = \mu _1 - \mu _2 =0$
$H_1: \mu _v \neq 0$
My teacher then made the following calculations, which I quite frankly don't understand at all:
$ \sigma_v = \sqrt{\sigma_x^2 + \sigma_y^2}$, so:
$ \sigma _v = (\sqrt{\dfrac{ \sigma \bar{x}_1}{\sqrt{n_1}}})^2 + (\sqrt{\dfrac{ \sigma \bar{x}_2}{\sqrt{n_2}}})^2 =... \approx 32        $ , so we can reject $H_0$
My complaints and confusion:

In his calculation he uses $\sigma {x} = \dfrac{\sigma \bar{x}}{\sqrt{n}}$, but I've always seen the formula: $\sigma \bar{x} = \dfrac{\sigma_x}{\sqrt{n}}$. Isn't his calculation just plain incorrect?
When we have the (I'm assuming wrong) $\sigma _v$, why can we immediately reject $H_0$? I think there are some steps (which I don't understand) missing.

EDIT:
Also, now that I think about it, isn't $\mu \bar{x}$ redundant, since $\bar{x}$ is already the sample mean? Or is there a difference between the two?
My answer:
$ \mu _v = 0$
$ \sigma_v = \sqrt{(\sigma \bar{x_1} \times \sqrt{n_1})^2 + (\sigma \bar{x}_2 \times \sqrt{n_2})^2} \approx 356$
$P (X \geq 66 | \mu = 0 , \sigma = 356) \approx 0.426$
$ 0.426 > \dfrac{1}{2} \alpha $ , so the nullhypothesis holds.
ps - Keep in mind this is rudimentary hypothesis testing, not anything advanced. We've only been taught the binomial distribution and the normal distributions. Quite frankly, I have no idea what z-scores or t-scores (and such) are and mentioning them in your answer is not needed (since we never discussed them and he probably doesn't know what they are himself, since he isn't a statistics teacher. He didn't assume we knew t-tests when we tackled the hypothesis).
Comment: This question is now redundant. My statistics teacher sent me an answer saying that I was correct and he was wrong.
Comment: You should explain what those variables are to improve your question.
Comment: I meant he said we were both wrong but 'because' of him (he didn't want to make it too complicated so he just divided by n).
Answer: This was originally a comment but my edit of it grew too long; I guess it's an answer now.
It's critical to carefully distinguish between sample quantities (like $\bar{x}$ or $s_x$) and population quantities (like $\mu_x$ or $\sigma_x$). The notation you have there seems to muddle them together with abandon and you have little hope of understanding what you're doing from there. Hypotheses are about population quantities. The inference is based on sample quantities. It looks like your teacher is trying to do a two-sample t-test; there are many teaching resources online that explain how to set them up and do them.
Comment: I don't really understand what you mean by the comment in italics, what I have done from 'there' (whatever there might be) is written under **My answer**. My teacher does exactly the same and *I understand* what he does, my question only is why he used a wrong form of the formule **he taught me** Also, the two-sample t-test is significantly different from what we've both done, so.. (besides, we are doing very basic hypothesis testing, no t-tests etc.)
Comment: The notation is so confusing it's very difficult to tell *what* you're testing; the two-sample-t was my guess based on what I could work out. You're welcome to try to clarify or give more details. That you don't understand what you're doing is clear from the question. My point was that the confusion is unlikely to be properly resolvable without better notation, because the notation will *lead you into errors you won't even realize you're making*. There's good reason why you are having trouble.


not able to save file in files/myuploads folder in drupal 6

Question: I want to upload a file inside the sites/default/files/myuploads folder. But I am not able to. Actually I am not able to upload the file to any of the folder inside sites/default/files/myuploads.
Here is my code:
<code>$validators = array('file_validate_extensions' => array('se', 'SE'));

$file = file_save_upload('fname',$validators, 'public://myuploads', FILE_EXISTS_REPLACE);

if ($file) {
 $fid = $file->fid;
 $doc_url = file_create_url($file->uri);
 //Set the status of the uploaded file.
 $file->status = FILE_STATUS_PERMANENT;

//other code...
}
</code>
The upload will work fine if I just give public://. So it will be in the sites/default/files folder. And when I print the $file, in that the ["destination"] => "sites/default/files/./test.se"
How can I do this? Any idea how I can upload into the myuploads folder ?
Answer:
Verify the write permission for "myuploads" folders.
Change the $validators variable like this:
$validators = array('file_validate_extensions' => array('se SE'));


confusion related to the dual of SVM

Question: I have a confusion related to the dual of SVM
In the main objective function I have:
$$\mathcal{L}(w,b,\xi,\alpha,r)=\frac{1}{2}||w||^2 +C\sum\limits_i \xi_i -\sum\limits_i \alpha_i\{ y^{(i)}(w^T x^{(i)}+ b) - 1 +\xi_i \} -\sum\limits_i r_i\xi_i$$
Now to solve the dual of this objective function, I will minimize with respect to the primal variables first to get:
$$w=\sum \alpha_i y^{(i)} x^{(i)} \\ \sum \alpha_i y^{(i)}=0 \\ \alpha_i = c - r_i \quad \forall i $$
I didn't get how substituting the value of $w$ in the lagrangian will give me:
$$-\frac{1}{2}\sum\limits_{i,j}\alpha_i\alpha_jy^{(i)}y^{(j)}{x^{(i)}}^Tx^{(j)}$$
Where did the minus sign come from in the above?
I got the other terms by substituting the remaining terms. But I didn't get the above term how it came to give me:
$$\max\limits_{\alpha \ge 0} \mathcal{L}(\alpha) = \sum\limits_i \alpha_i - \frac{1}{2}\sum\limits_{i,j} \alpha_i \alpha_j y^{(i)} y^{(j)} {x^{(i)}}^T x^{(j)} \\ \text{such that}\quad \sum\limits_i \alpha_i y^{(i)}=0 \\ 0 \le\alpha\le c \quad \forall i$$
Answer: Rearranging the Lagrangian, you have a term of  $-w^T \left(\sum_i \alpha_i y^{(i)}x^{(i)}\right)$ which is $-||w||^2$. Thus, you have a value of $-\frac{1}{2}||w||^2$. Substitute the value of $w$ back in to get the result.
Comment: Here is the step-by-step derivation of the regression case https://stats.stackexchange.com/questions/578076/derivation-of-the-svm-regression-problem

confusion related to the dual of SVM


Backup in SQL Azure very slow

Question: I'm currently working on an SQL Database backup strategy in advance of porting our application to Azure. Currently we are using a SQL Server maintenance task to run a backup of our on-premise database  once every 15 minutes with a 1 hour retention (thus retaining 4 local copies). We also run a 24 hour backup which gets pushed into Amazon S3.
Now in Azure, I've so far managed to institute a backup of the primary database (to another sql server instance) using the following T-SQL:
<code>CREATE DATABASE targetserver.backupName AS COPY OF sourceserver.sourceName
</code>
The source database is approximately 3GB in size and is expanding around 5-10% per month. The problem I'm having is that the copy process is painfully slow! I initiated a copy over 30 minutes ago and it's still running! This means that adopting a 15 minute backup schedule seems untenable in Azure.
So I'm wondering if I can qualify a few things with other users:

Is it normal for a 3GB backup to take over 30 minutes (and counting) to replicate to another server instance?
Should I keep the backups on the same server as the source? I'm very nervous as a few clicks in the Azure portal could wipe out a lot of critical data! I know this is a 'black swan' event but I just wouldn't feel easy having everything running in a single server instance.
Is there a quicker way to backup an SQL Azure Database? I've taken a look at the Red-Gate but it seems expensive to do sub daily incremental backups.

Any thoughts on this would be much appreciated!
I should add that I am happy to rethink my backup strategy entirely to be more Azure friendly. The key thing is mitigation against administrator error, e.g. dropping a load of important data due to a clumsy statement (the shorter the backup intervals the better) and a 24 hour backup pushed into a different storage method, e.g. blob container.
UPDATE ------
I cancelled the initial backup request after waiting 1 hour and re-initiated. The second backup completed in 5 minutes. I've now gone back to Red-Gate to take a look at their hosted backup solution.
Comment: Yes, from my experience with SQL-Azure it is normal for a 3GB backup to take about 30 minutes to replicate to another server instance.
Comment: The database has been in COPYING state for 1 hour now, is that still normal?
Answer: How long copy database takes to run depends not only on the size of the data, but also how many transactions are being run on it at the time, so this option may not be tenable in your situation.  Now that you have a backup DB you can test this for yourself by making a backup of your backup and see how long that takes.
Your other option is to export a .bacpac file and store it in blob storage.  There are libraries for this but I don't have the reference to hand.  This will also be a much cheaper option.  I'm pretty sure this is what Red Gate are doing under the covers of their service.
Comment: You're right, under the surface we make use of the Microsoft Import/Export service. This is the same functionality that you see in the Azure Portal.

Microsoft did a pretty comprehensive run through of all the backup options for SQL Azure recently http://blogs.msdn.com/b/windows_azure_technical_support_wats_team/archive/2013/03/04/different-ways-to-backup-your-windows-azure-sql-database.aspx

I work for Red Gate and develop the solution :)
Comment: Thanks knightpfhor. As I understand it, exporting to .bacpac does not produce a transactionally consistent backup. What Redgate do is run a CREATE DATABASE ... AS COPY OF ... and export to .bacpac from there. They also allow you to directly export to .bacpac which is much faster but without any guarantee of being transactionally consistent. For now I'm going with the Redgate solution as they're handling all the scheduling for us so we can focus on other areas. We can create 4 backups per day for USD 40 per month + the cost of having another db in Azure.
Comment: That's all exactly correct.  It's the trying to keep transactionally consistent that means the copy database runs slow if you have transactions on your DB.
Comment: Be careful with that cost calculation, as I understand it the minimum charge for a DB is one day which resets at midnight UTC. So if you run 4 backups with CREATE DATABASE...AS COPY OF... You'll pay for 4 extra databases. If you create one of those at 23:59 UTC you'll end up paying for yet another.
Comment: That's interesting! I assumed we would only be charged for one additional db as the backup only exists momentarily and is then deleted once the .bacpac file is created, I didn't know it's per every new instance created. Richard, if multiple backups are being run in a day why not continuously overwrite the same database to save cost for the user?

Backup in SQL Azure very slow