Why does tomcat like deleting my context.xml file?

Question: I'm developing a web-based Java application at work and (obviously) have to run it locally during development. I've figured out the Tomcat docs and have a suitable context.xml file in /etc/tomcat6/Catalina/localhost/ but every so often, Tomcat decides to delete it! Which means I have to put it back and restart Tomcat.
Why does it do this? I have searched the Tomcat docs about it and am none the wiser.
(Oh yes: it's not actually called context.xml but owners.xml as that's the HTTP path prefix for this application.)
Update
I've now seen Tomcat delete the file whilst Tomcat was running. I think I need to file a bug...
Comment: Have this problem to. Seems like when you replace your war it causes undeployment of the app which causes deletion of the context file. I don't have a work-around but would love to have one which is more convenient than reloadable=false http://stackoverflow.com/questions/4032773/why-does-tomcat-replace-context-xml-on-redeploy
Answer: Quick summary: there are several conditions (like changing the war file, deleting the webapp or replacing it with new content) under which Tomcat will undeploy the context, including removing the context file.
Details:
Whether Tomcat does or doesn't do autoDeployment (means checking for changes in your .xml descriptor as well as checking changes in the webapp directory) is driven by:

server.xml located in $CATALINA_HOME/conf/server.xml section:
<Host name="localhost" appBase="webapps" unpackWARs="true" autoDeploy="true" xmlValidation="false" xmlNamespaceAware="false">

You can also set this property in your context file overloading the value

Quoting the doc for cases when autoDeploy=true may cause removal of your context file:

Deleting a WAR file will trigger an undeploy of the application with the removal of any associated expanded directory, context file and work directory.
Deleting a directory will trigger an undeploy of the application with the removal of any associated context file and work directory.
Updating a WAR file will trigger an undeploy of the application with the removal of any associated expanded directory, context file and work directory.
Updating a directory (not the directory contents) will trigger an undeploy of the application with the removal of any associated context file and work directory.

Exhaustive details: http://tomcat.apache.org/tomcat-6.0-doc/config/host.html#Automatic%20Application%20Deployment
Comment: That's simply not true. The original answer contained (and still does) short summary of what you can find under the link. Without the link the answer still make perfect sense and together with the link you can find details.
Comment: This is not a complete answer - see http://serverfault.com/faq#deletion
Comment: :) please help yourself (seems the syntax highlighting works slightly different than in stackoverflow which deleted part of the answer before)
Comment: The thing is that if you just add a link, the target of the link may disappear, making the answer useless. That's why serverfault.com encourages you to post the actual answer instead of just the link. And when I commented, the rest of the text wasn't visible. I'd still recommend actually posting a more complete response rather than a brief summary of the link.
Comment: But I didn't plan to be offensive so sorry if it sounded like that :) I'm not much into this web, just was solving the same and wanted to share.
Comment: Of course it's entirely true that I misread the half sentence that was visible at the time, what with being human.
Comment: So we are all good :) I'll add details from the link as adviced. Cheers
Comment: Ah. Thanks. That makes a twisted kind of sense. I would call this feature mis-designed or at the very least, a hidden side-effect.
Comment: It might sound a bit weird for apps outside of appBase directory, but for the case where you deploy war to appBase directory and the context file gets deployed to the $CATALINA_HOMEconf/Catalina/localhost automatically it makes sense to delete it when you remove the war file for example ...
Answer: If you don't want autoDeploy feature, in production environments for instance, you may consider the following attributes in the conf/Catalina/localhost context file :

autoDeploy="false"
and deployXML="false"

autoDeploy="false" may not work alone because application context.xml (in META-INF) can override server.xml settings of autoDeploy.

The application's META-INF/context.xml will be used in development environment, with autoDeploy
The conf/Catalina/localhost context in production, without autoDeploy.

deployXML attribute documentation attribute documentation is worth reading (§ Standard Implementation).
Exhaustive autoDeploy user case, and when context is removed : i.e. application undeployed, user case is documented can be found here.
Answer: Cant answer the Why bit.
However, This link states you can stop this by setting the autoDeploy="false" in server.xml
Comment: Under tomcat7 autoDeploy="false" makes no difference :(
Answer: I honestly dont know what the reasoning behind Tomcat doing this is but try adding the following XML attribute to your context element
reloadable="false"

So your context could look something like this:
<Context path="/" docBase="/some/path/name" reloadable="false">

</Context>

This should keep Tomcat from deleting the file
Comment: Unfortunately, that makes development harder as I would have to restart Tomcat after each build.
Comment: checkout jrebel to help with this in development: http://zeroturnaround.com/jrebel/
Answer: I realize this is an old thread, but I thought I would share what I found to fix this problem...
I had been having the exact same issue with my context.xml file for my desktop version of tomcat getting clobbered every time that I would deploy a new copy of the war file for my application.
The problem was due to the fact that I was making changes to this file directly on the filesystem. What fixed the problem was to edit the context.xml file via my Eclipse editor. Inside of
my Eclipse, there's a "servers" project that once you expand it, you can see a handful of files, such as context.xml and server.xml. It appears that if you modify the files from here
instead of going out to the filesystem, your changes are kept.
I found this solution in the following thread:
https://www.liferay.com/community/forums/-/message_boards/message/16511799
I hope this helps someone else!
-StephenS
Answer: The general issue as described by the title is covered by Re-deploy from war without deleting context which is still an open issue at this time.
There is an acknowledged distinction between re-deploy which does not delete the context, and deploy after un-deploy where the un-deploy deletes the context. The documentation was out of date, and the manager GUI still does not support re-deploy.
Answer: Sometimes it is necesary have different values for app in the server, for example a path to store uploaded files.
In developer environment mabe we have something like this:
<?xml version="1.0" encoding="UTF-8"?>
<Context antiJARLocking="true" path="/ParkMeServer" allowCasualMultipartParsing="true" reloadable="false">
     <Parameter name="rutaTrabajo" value="C:\Larry\Proyectos\app\rutaTrabajoxx" override="true"/>
</Context>

But in server the path is different:
<?xml version="1.0" encoding="UTF-8"?>
<Context antiJARLocking="true" path="/ParkMeServer" allowCasualMultipartParsing="true" >
     <Parameter name="rutaTrabajo" value="/usr/share/App/rutaTrabajo" override="true"/>
</Context>

I also have the same problem, tomcat deleting the context.xml( meapp.xml ) from conf/Catalina/localhost
To solve I use context.xml.default, in the same path I create a file called context.xml.default and inside a put config I want to held:
 cat context.xml.default
<?xml version="1.0" encoding="UTF-8"?>
<Context antiJARLocking="true" path="/ParkMeServer" allowCasualMultipartParsing="true" >
     <Parameter name="rutaTrabajo" value="/usr/share/ParkiMeApp/rutaTrabajo" override="true"/>
</Context>

So ,when redeploying then app, the confir parameteres still there.


How to multiply two sinusoids with the same frequencies but are out of phase without the use of complex numbers.

Question: So as a part of my extended essay I am looking into the importance of complex numbers in signal processing. I am in high school, but I cannot seem to figure out how to multiply two sinsoids together without the use of complex numbers. There has to be a way. Here is the two that I am trying to multiply,
$$3\cos\left(\omega t + \frac{\pi}{4}\right) \times 0.5 \cos \left(\omega t - \frac{3\pi}{8} \right)$$
Can someone please help me out?
Answer: You can use the identity:
$$\cos A \cos B = \frac{1}{2}[\cos (A + B) + \cos (A - B)]$$
Comment: Hi I used that identity and got, 1.5cos(5pi/8)+1.5cos(2wt-pi/8). I am not sure what to do from here. I want in the end the new sinusoid to be represented in the form of Mcos(wt+theta).
Comment: 1.5cos(5pi/8) is a constant and evaluate to -0.5740....
Comment: How does this help? Even then how do I get rid of the 2wt?
Comment: So you will get your sinusoid in the form of $A + M\cos(2\omega t+\theta)$. The form of $M\cos(\omega t+\theta)$ cannot be attained, at least without the use of complex numbers.
Comment: alright thank you so much!  I did not know that. If you use complex numbers you can get the answer in the same frequency.


Prove the identity $x^n = \sum^{n}_{k=0}S_{n,k}(x)_k$

Question:
Prove the following identity: $$x^n = \sum^{n}_{k=0}S_{n,k}(x)_k \space \space \space\space\space\space\space\space\space\space\space\space\space (n \geq 0)$$.

We are talking clearly about Stirling numbers of the second kind here. I don't know what exactly $(x)_k$ means, but in my script I have something defined like this:
$$x_0 := 1$$
$$(x)_n := x(x-1)(x-2)\ldots(x-n+1) = \sum_{k=0}^{n}(-1)^{n+k}s_{n,k}x^k$$
Any ideas about what it exactly talks about and how can I prove this problem?
Answer: That is trivial to prove by assuming that $x$ is a non-negative integer. Assume that $|A|=n$ and $|B|=x$.
The LHS counts the number of functions $f:A\to B$. The RHS counts the number of functions from $A$ to $B$, according to the size of $f(A)$, since the Stirling number $S_{n,k}$ accounts for the number of ways for partitioning $A$ in $k$ pieces.
On the other hand, if two polynomials agree on $\mathbb{N}$, they agree on $\mathbb{R}$, too, and that proves the identity in the general case.
Comment: Can you please open this up a bit, I didn't exactly understood what's going on here. Plus, what exactly is $(x)_k$? And you are talking if $x$ is a positive number, what happens if it is negative?
Comment: A non-negative integer is a natural number. $(x)_k$ is a Pochhammer symbol, you know its definition.
Comment: @JackD'Aurizio Okay, I understood the concept of Pochhammer symbol. But, I still have a hard time grasping the second paragraph of the solution, regarding the LHS and RHS of the identity. Can you elaborate it a bit more?
Comment: @portal: simply, $x^n$ is a polynomial, and $\sum_{k=0}^{n}{n\brace k}(x)_k$ is a polynomial, too. The first part of the proof gives that these polynomials agree on $\mathbb{N}$, hence they agree everywhere.
Comment: @JackD'Aurizio Yes, what you try to do makes sense, if they agree on NN they will agree everywhere. But, I don't see how LHS counts the number of functions $f:A→B$, I mean what kind of function is surjective or? I know that the Stirling number accounts for the number of ways to partition nn objects into $k$ pieces, but what does it mean to count the number of functions from $A$ to $B$ according to the size of $f(A)$?
Answer: $(x)_k$ can be expressed as $\frac{x!}{(k-1)!} = \binom{x}{k}k!$
To distribute $n$ distinct objects into $x$ distinct boxes with empty boxes allowed, we have $$x^n \space \text{ways}$$
Or we could choose $k$ boxes to distribute the $n$ objects into with no empty boxes allowed, from $k=0$ to $k=n$
To choose the $k$ boxes we have $\binom{x}{k}$ ways.
To distribute $n$ objects into the $k$ boxes with no empty boxes allowed, we have:
$$k!S_{n,k} \space \text{ways}$$
Therefore, the number of ways to $n$ distinct objects into $x$ distinct boxes with empty boxes allowed, we have:
$$x^n = \sum^{n}_{k=0}\binom{x}{k}k!S_{n,k} $$
Comment: What if $x\not\in\mathbb{Z}$?
Comment: On the other hand, both sides of the original identity are polynomials in $x$. See the last part of my answer.
Comment: The combinatorial approach only works for $x \in \mathbb{Z}$. So I guess it only proves the identity for $x,n \in \mathbb{Z}$
Comment: I didn't totally understood why we need the $k!$ in $k!S_{n,k}$. Isn't the definition of Stirling numbers of the second kind enough, which says that number of ways to partition a set of $n$ objects into $k$ non-empty subsets.
Comment: @Nicholas I second portal here. I didn't get it too.
Comment: For sirling numbers, it involves distribution into identical boxes, the $k!$ is required since we are dealing with distinct boxes in this case.
Comment: @Nicholas Okay, and one more question, as you have said Stirling numbers count the distribution with no empty boxes allowed, so we go over all the possible Stirling numbers, which counts distributions with no empty boxes, and you conclude that it is the same as counting distributions with empty boxes allowed.
Comment: The initial distribution allowed empty boxes. What we were attempting to do was to split this into the cases where the objects were only distributed into a limited number of $k$ boxes, $k =0,1,2,3 \dots n$. When we are trying to distribute into only $2$ boxes for example, we must then ensure that none of the $2$ boxes are empty otherwise there will be an overlap with the case where we distribute into $1$ box.
Comment: So, $\sum^{n}_{k=0}\binom{x}{k}$  part gives us the number of partitioning $n$ elements into $k$ boxes, which clearly includes the empty boxes too, and $S_{n,k}$ is enough to show that we can distribute $n$ objects into $k$ partitions. But, you have $k!$, which is the combination of all boxes. Clearly, I don't understand the meaning of distinct and identical boxes. Perhaps, an example?
Comment: @portal Let's say we have objects $a,b,c$. If we were to distribute them into two identical boxes, then $(a)(b,c)$ would be the same as $(b,c)(a)$. Now, if we were distribute them into two distinct boxes, say, box $A$ and $B$, $A:(a)$ $B:(b,c)$ would not be the same as $A:(b,c)$ $B:(a)$
Answer: This also has a straightforward algebraic proof for $x=q$ with $q$ an integer which then extends to $q$ a complex number.
Recall the combinatorial  species  of  set
partitions which is given by
$$\mathfrak{P}(\mathcal{U}\mathfrak{P}_{\ge 1}(\mathcal{Z})),$$
producing the generating function
$$\exp(u(\exp(z)-1))$$
and in particular
$${n\brace k}
= n! [z^n] \frac{(\exp(z)-1)^k}{k!}.$$
Now we have
$$q^n =
\frac{n!}{2\pi i} \int_{|z|=\epsilon} \frac{1}{z^{n+1}} \exp(qz) \; dz
\\ = \frac{n!}{2\pi i} \int_{|z|=\epsilon} \frac{1}{z^{n+1}}
\sum_{p=0}^q {q\choose p} (\exp(z)-1)^p\; dz
\\ = \frac{n!}{2\pi i} \int_{|z|=\epsilon} \frac{1}{z^{n+1}}
\sum_{p=0}^q {q\choose p} \times p! \times \frac{(\exp(z)-1)^p}{p!}\; dz.$$
Extracting the coefficient we obtain
$$\sum_{p=0}^q {q\choose p} \times p! \times {n\brace p}.$$
But $${q\choose p} \times p! = q^{\underline{p}}$$
and we have the claim.
Answer: See http://faculty.kfupm.edu.sa/ICS/malalla/Teaching/ICS253/TextBook/Apps_Ch6.pdf
page 102 on the pdf gives a nice explanation
The falling-factorial $x_k$ represents the number one-to-one functions from a $x$-set to a $k$-set
$S_{n,k}$ represents the number of $k$ sized partitions of n
So, we have $x_k$ $k$ sized partitions, and $S_{n,k}$ ways to organize these $k$ sized partitions
Answer: This identity can be proven by induction on $n$. The base case is trivial $x^0 = 1 = S_{0,0}(x)_0$. For the induction case we have
\begin{align}
\sum_{k=0}^{n+1}S_{n+1,k}(x)_k &= \sum_{k=0}^{n+1}(S_{n,k-1}+k S_{n,k})(x)_k\\
&=\sum_{k=0}^{n+1}S_{n,k-1}(x)_k + \sum_{k=0}^{n+1}k S_{n,k}(x)_k\\
&=\sum_{k=0}^{n}S_{n,k}(x)_{k+1} + \sum_{k=0}^{n}k S_{n,k}(x)_k\\
&=\sum_{k=0}^{n}(x-k)S_{n,k}(x)_{k} + \sum_{k=0}^{n}k S_{n,k}(x)_k\\
&=x \sum_{k=0}^{n}S_{n,k}(x)_{k}.
\end{align}
Then by the induction hypothesis we obtain $\sum_{k=0}^{n+1}S_{n+1,k}(x)_k = x^{n+1}$.


Does nginx cache my responses?

Question: I'm using Symfony2 with nginx as http server (I don't know much about reverse proxies, I just installed it and didn't touch anything), without Apache nor Varnish.
I need to know whether nginx is caching the responses I send with the correct headers, like public, max-age, and s-max-age, or I have to add something else to the stack, like Varnish.
I have read somewhere that if you add Varnish, you will have to add yet something else, for gzip compression. So it would be nginx -> Varnish -> ???
So is nginx caching? How can I check that? I did grep cache on the nginx logs and found nothing.
Answer: To use nginx caching you should configure it.

http://nginx.org/r/fastcgi_cache_path
http://nginx.org/r/proxy_cache_path

You do not need Varnish unless ESI is required.

Does nginx cache my responses?


Lavaan don't work with libgfortran.so.4, should I file a bugreport?

Question: Working on Solus Linux I get following error:
Error in dyn.load(file, DLLpath = DLLpath, ...) :
  unable to load shared object '/home/aaron/R/x86_64-solus-linux-gnu-library/3.4/quadprog/libs/quadprog.so':
  libgfortran.so.3: cannot open shared object file: No such file or directory

when I try to install lavaan. Stated here: R v3.4.0-2 unable to find libgfortran.so.3 on Arch this is due to the most recent version of gcc which upgrades gfortran which updates libgfortran.so.3 to libgfortran.so.4.
Now I could install a old version of gcc (but I have no idea to do that under Solus) or I could ask the Developer (Yves Rosseel) of lavaan to add suppourt to the newest gfortran version and file a bu report?
What would you do?
Comment: File a bug report.
Answer: After I filed a bug report, it turns out that Yves Rossell has the most recent version of libgfortran.so.4 (and only this version). So it's clearly not that lavaan is not up to date. Actually I wasn't. I just had to reinstall some dependencies of lavaan:
install.packages("pbivnorm")
install.packages("mnormt")
install.packages("numDeriv")
install.packages("quadprog")

Thanks Yves.
Answer: in the meanwhile you can link the libraries and create libgfortran.so.3 as an alias of libgfortran.so.4
here's how to do it: https://www.bibliotechzw.com/blog/solved-how-to-create-aliases-in-ubuntu-16-via-the-commandline/
Comment: This is not a good idea. There is  good reason why the version vwas increased. The versions are NOT compatible. The version number was increased to avoid linking a wrong incompatible inadvertently.


What is the probability that $n$ random points in $d$ dimensions are linearly separable?

Question: Given $n$ data points, each with $d$ features, $n/2$ are labeled as $0$, the other $n/2$ are labeled as $1$. Each feature takes a value from $[0,1]$ randomly (uniform distribution). What's the probability that there exists a hyperplane  that can split the two classes?
Let's consider the easiest case first, i.e. $d = 1$.
Comment: @gung I think the word "hyperplane" unambiguously implies "flatness", that's why I edited the title to say "linearly separable". Clearly *any* dataset without duplicates can is in principle nonlinearly separable.
Comment: This is a really interesting question. I think this might be able to be reformulated in terms of whether or not the convex hulls of the two classes of points intersect or not - though I don't know if that makes the problem more straightforward or not.
Comment: @gung IMHO "flat hyperplane" is a pleonasm. If you argue that "hyperplane" can be curved, then "flat" can also be curved (in an appropriate metric).
Comment: For $d=1$ we have $n$ random points on the real line to which we randomly assign class labels. The data are going to be separable iff all 0 labels are below all 1 labels, or vice versa. So it's 2 combinations out of $n\choose {n/2}$.
Comment: @DonWalpola Treating the convex hulls is surely correct, but turns the question much harder than it already is. Linear separability is much more tractable.
Comment: This will clearly be a function of the relative magnitudes of $n$ & $d$. Consider the easiest case w/ $d=1$, if $n=2$, then w/ truly continuous data (ie, no rounding to any decimal place), the probability they can be linearly separated is $1$. OTOH, $\lim n\to \infty\ \ \text{Pr(linearly separable)} \to 0$.
Comment: You should also clarify if the hyperplane needs to be 'flat' (or if it could be, say, a parabola in a $2d$-type situation). It seems to me that the question strongly implies flatness, but this should probably be stated explicitly.
Comment: @amoeba, what appears curved isn't necessarily curved in actuality (see: [Why is polynomial regression considered a special case of multiple linear regression?](https://stats.stackexchange.com/a/92087/7290)). This is also the nature of the kernel trick (see: [1](https://stats.stackexchange.com/a/2500/); [2](https://stats.stackexchange.com/a/153134/), & [3](https://en.wikipedia.org/wiki/Kernel_method#/media/File:Kernel_trick_idea.svg)). I don't think it would be overly lawyerly to call those resulting separating hyperplanes 'linear'. I still think it should be stated explicitly.
Comment: @Amoeba The case $d=2$ is instructive. We need only count the number of separating hyperplanes when all $2n$ points are in general position.  There will be between $n$ and $2n$ of them.  For $n\gt 2,$ the value of $2n$ is attainable. $n$ is the result when the points form a convex polygon. The integrals to compute the probability distributions look intractable and uninteresting: what is most interesting is that these bounds are independent of how the points are distributed. There are similar results for higher $d.$ The case $2^d \gg 2n$ admits a special analysis, too.
Answer: Assuming no duplicates exist in the data.
If $n\leq d+1$, the probability is $\text{Pr}=1$.
For other combinations of $(n,d)$, see the following plot:

I generated this plot simulating input and output data as specified in the OP. Linear separability was defined as failure of convergence in a logistic regression model, due to the Hauck-Donner effect.
We can see the probability decreases for increasing $n$. In fact, we could fit a model relating $n, d$ to $p$, and this was the result:
$$P(n,d)={
  1
  \over
  {1 + e^
    {-(5.82944-4.58261\times n + 1.37271 \times d -0.0235785 \times n \times d)}
  }
}$$

Code for the plot (in Julia):
using GLM

ds = 10; #number of dimensions to be investigated
ns = 100 #number of examples to be investigated
niter = 1000; #number of iterations per d per n
P = niter * ones(Int64, ds, ns); #starting the number of successes

for d in 1:ds
    for n in (d+1):ns
        p = 0 #0 hits
        for i in 1:niter
            println("Dimensions: $d; Samples: $n; Iteration: $i;")
            try #we will try to catch errors in the logistic glm, these are due to perfect separability
                X = hcat(rand((n,d)), ones(n)); #sampling from uniform plus intercept
                Y = sample(0:1, n)  #sampling a binary outcome
                glm(X, Y, Binomial(), LogitLink())
            catch
                p = p+1 #if we catch an error, increase the count
            end
        end
        P[d,n] = p
    end
end

using Plots

gui(heatmap(P./niter, xlabel = "Number of Samples", ylabel = "Number of Dimensions", title = "Probability of linear separability"))

Code for the model relating $(n,d)$ to $p$ (in Julia):
probs = P./niter
N = transpose(repmat(1:ns, 1, ds))
D = repmat(1:ds, 1, ns)

fit = glm(hcat(log.(N[:]), D[:], N[:].*D[:], ones(ds*ns)), probs[:], Binomial(), LogitLink())
coef(fit)
#4-element Array{Float64,1}:
# -4.58261
#  1.37271
# -0.0235785
#  5.82944

gui(heatmap(reshape(predict(fit), ds, ns), xlabel = "Number of Samples", ylabel = "Number of Dimensions", title = "Fit of probability of linear separability"))

Comment: +1. Why log(n) and not n? The yellow-black boundary looks like a straight line to me on the top figure, but appears bent on the second figure. Is it maybe because of the log(n)? Not sure.
Comment: @amoeba I changed it. I also included the interaction, because it could explain the gradual broadening of the border between $p=1$ and $p=0$ (which was the reason I had tried the logarithm before).
Answer: This is related to Cover's theorem.
A nice summary by Emin Orhan is given here.
Ps: I would post this in a comment but don't have enough reputation.


MX Record not working

Question: I'm almost done configuring my nameservers for my domain. Everything works fine website responding...but My MX record don't seem to be working, and I tried a lot of things. I created a cname with subdomain pop and smtp an MX record with webhost4life.com has a host name (but I have no idea if it should be that host) i did try mail.webhost4life.com but nothing seem to be working. If you compare intoDNS.com datahex.ca and myhaccpplan.com (which the MX is working) maybe you could help me figure out what i'm doing wrong here.
I'm configuring my nameserver on zoneedit.com.
thanks.
Answer: Make sure that mail server MX record is referring has A record, CNAME is not enough. This is important but I do no remember why. Here is an example:
<code>$ORIGIN example.com.
@       IN SOA  dns0.yourisp.com. zone.yourisp.com. 1308717736 21600 7200 1209600 10800
@       IN NS   dns1.yourisp.com.
@       IN NS   dns2.yourisp.com.
@       IN MX   10 mail.example.com.
mail    IN A    192.168.1.200
...
</code>
Also, make sure there is corresponding PTR record that resolves IP addres to the name of your mail server. This is not directly related to your problem, but it is important for successful mail delivery.
<code>$ORIGIN 1.168.192.IN-ADDR.ARPA.
@       IN  SOA     dns0.yourisp.com. zone.yourisp.com. 2011041900 3h 15m 3w 3h
@       IN  NS      dns1.yourisp.com.
@       IN  NS      dns2.yourisp.com.
200     IN  PTR     mail.example.com.
...
</code>
Once you have your mail working consider adding SPF record.
Comment: `CNAME`s do _not_ work if used for domains in `MX` records, contrary to the false claim above.  The loop prevention algorithm specified by the SMTP standard _breaks_ if the SMTP Relay client system is a fallback mail exchanger but the name used for it in `MX` records is an alias via a `CNAME` resource record.
Comment: CNAMEs will work for MX Record entries, they are just not RFC compliant.
Comment: Thank you for the quick answer, here is my setup.. I can receive emails on datahex.ca but i can't send email from datahex.ca :

@ IN MX 7200 10 mail.datahex.ca
mail IN A 7200 (22.214.171.124)
50 IN PTR 7200 mail.datahex.ca
@       IN  NS      ns8.zoneedit.com.
@       IN  NS      ns4.zoneedit.com
Comment: is the IP suppose to be my Public IP ? in this case I put the address that is working for other domain...

MX Record not working


HTML widgets in Jupyter R Notebook

Question: Im unable to display HTML widgets in Jupyter Notebooks when using R (works when using python). For example none of the plotly charts work in Jupyter R notebook. Is there any solution for this?
library(plotly)
set.seed(100)
d <- diamonds[sample(nrow(diamonds), 1000), ]
plot_ly(d, x = carat, y = price, text = paste("Clarity: ", clarity),
        mode = "markers", color = carat, size = carat)

The code executes but no graph is displayed
Comment: you should save the widget out and use an `iframe` to read it back in (or write a wrapper that does that for you and emits the proper HTML for a notebook). or just use RStudio and forget the notebook nonsense :-)
Answer: You need to make a call to embed_notebook (see the examples here).
So change your code to:
library(plotly)
set.seed(100)
d <- diamonds[sample(nrow(diamonds), 1000), ]
myPlot <- plot_ly(d, x = carat, y = price, text = paste("Clarity: ", clarity),
        mode = "markers", color = carat, size = carat)
embed_notebook(myPlot)

HTML widgets in Jupyter R Notebook


If P and Q can never be true, are they still "necessary" and "sufficient" for each other?

Question: If we are given that propositions P and Q can never be true, is it still accurate to say that P and Q are necessary and sufficient for each other, and why?
I am conflicted here, as the statement P iff Q is true here and I have learned that this also means P and Q are necessary and sufficient for each other (for context, I have learnt that P is necessary for Q if P must be true to conclude Q is true, and that P is sufficient for Q if Q must be true to conclude that P is true); however, it seems counterintuitive to stipulate conditions for propositions being true (by deeming other propositions as necessary or sufficient for them) if these are never relevant to the situation, as these propositions are always false anyway.
I would appreciate an answer grounded in an explanation of necessity and sufficiency.
Comment: "*it seems counterintuitive to stipulate conditions...*"  Are you comfortable with vacuously true statements?  This is just more of the same as that.
Comment: @JMoravitz thanks for the reply; so is it the case that notions of necessity and sufficiency apply to the statement P⇒Q when both these are false? Would you be able to explain how this is the case from the definitions of necessity and sufficiency? (I am not seeing them apply here)
Comment: I think your difficulty hinges on your use of the word "relevance". In the everyday logic of mathematics, we don't care about relevance, we just care about mathematical facts: if $P$ and $Q$ are both false, they are equivalent. There are [modal logics](https://en.wikipedia.org/wiki/Modal_logic) which attempt to model notions like relevance and necessity which we often use to qualify statements that we make in natural language. These logics are very interesting, but much harder to work with than the everyday logic of mathematics.
Answer: Clearly, $$(¬P∧¬Q)\implies (\lnot P↔\lnot Q);$$ by contrapositive, $$(¬P↔¬Q)\implies(P↔Q).$$ So, by transitivity, $$(¬P∧¬Q)\implies(P↔Q);$$ that is, $$(¬P∧¬Q)→(P↔Q)$$ is a tautology. After all, P ↔ Q ($P$ and $Q$ necessary and sufficient for each other) just means that $P$ and $Q$ have the same truth value (in this case, 'false').

it seems counterintuitive to stipulate impossible—thus, irrelevant—propositions as conditions for propositions being true

But a contradiction $\bot$ within a conditional statement is not an irrelevant condition, since it is meaningful to truth evaluation:

$⊥$ is a sufficient condition for $P\quad\equiv\quad\top$
$⊥$ is a necessary condition for $P\quad\equiv\quad\lnot P;$

in order to truthfully assert that 'pigs can fly' is a necessary condition for  $P,$ $P$ must be something false; on the other hand, whatever $P$ stands for, the assertion that 'pigs can fly' is a sufficient condition for $P$ is certainly a redundancy. Like vacuous truth, these assertions are perhaps surprising but not really counterintuitive, so I may be misunderstanding your point.
Comment: @RW_123: yes, this can be proved constructively (and the proof is simpler): if you have $\lnot P$, $\lnot Q$ and $P$, you can infer $\bot$ and then infer $Q$ by *ex falso quodlibet*, so $(\lnot P \land \lnot Q) \to (P \to Q)$. Swapping $P$ and $Q$ you get $(\lnot P \land \lnot Q) \to (Q \to P)$, so $(\lnot P \lnot Q) \to (P \leftrightarrow Q)$
Comment: Can't this be proven constructively to show it's valid in more than just classical logic? Also, don't you think necessary and sufficient conditions deal more with *strict* implication? We don't want random a co-incidence between $A$ and $B$ to constitute that $A$ is necessary and sufficient for $B$.
Answer: In mathematics, "P is necessary for Q" is defined as meaning "it is impossible for P to be false and Q to be true." If both P and Q are totally impossible, then it's certainly impossible for P to be false and Q to be true, so we say that P is necessary for Q.
Likewise, in mathematics, "P is sufficient for Q" is defined as meaning "it is impossible for P to be true and Q to be false." If both P and Q are totally impossible, then it's certainly impossible for P to be true and Q to be false, so we say that P is sufficient for Q.
These conclusions may be at odds with the everyday meanings of the words "necessary" and "sufficient." However, when we're writing about math, we use the mathematical definitions of these words, not the everyday meanings.
Comment: This is the answer I was composing in my head while staring at the page. Very well stated. To reiterate: the everyday meanings of *necessary* and *sufficient* break down when you start to talk about impossible situations.
Comment: How are the everyday and mathematical meanings of 'necessary' and 'sufficient' actually discrepant?
Comment: @ryang Well, I think that most people would agree that walking to the moon and walking to Mars are both totally impossible, yet most people would disagree with the sentences "in order to walk to Mars, it is sufficient to walk to the moon" and "in order to walk to the moon, it is necessary to walk to Mars." On the other hand, if P = "I am going to walk to the moon" and Q = "I am going to walk to Mars," by the mathematical meanings, P and Q are necessary and sufficient conditions for each other. These two ways of looking at things seem to be at odds with each other.
Comment: All that being said, it's not clear that there really is a discrepancy between the two notions, which is why I wrote "may be at odds" instead of "are at odds."
Comment: @TannerSwett Thanks for elaborating! I am reminded of this [discrepancy](https://math.stackexchange.com/a/4404801/21813): in mathematics, 'only if' means `implies`, whereas in everyday English that phrase strongly (and not unreasonably) suggests 'just if', i.e., `if and only if`.
Answer:
If $P$ and $Q$ can never be true, are they still "necessary" and
"sufficient" for each other?

The "can never be true" is distracting. In propositional logic, we don't make predictions about the future. We talk about what is true (present tense). Change it to:

If $P$ and $Q$ are both false, are they "necessary" and
"sufficient" for each other?

Then the answer would be, yes.
Truth Table for $P\iff Q$

See line 4 where $P$ and $Q$ are both false.


How to adapt HDImass of posterior predicted distributions

Question: how to adapt the HDImass of posterior predicted distributions for linear regression in JAGS? I am most content with John Kruschke's R-script Jags-Ymet-Xmet-MRobustPredict.R. I would like to change the default HDImass of 0.95 into 0.9. I applied HPDinterval(mcmcCoda,prob=.9) to generate tables of lower and upper limits, but this code does not change graphs or summaryInfo.
Han Diesfeldt
Comment: Check https://stats.stackexchange.com/questions/240749/how-to-find-95-credible-interval/240777#240777 for general discussion. The software question is off-topic in here, s you can learn from https://stats.stackexchange.com/help/on-topic
Answer: To compute or display the HDI, the scripts call the function HDIofMCMC() which is defined in DBDA2E-utilities.R. An argument of HDIofMCMC is credMass (i.e., the mass of the credibility interval), which defaults to 0.95. You can change it to 0.90 by specifying credMass=0.90. The plotPost() function calls the HDIofMCMC() function, and is designed with the same argument. For example, inside Jags-Ymet-Xmet..., find the relevant calls to plotPost() and include another argument in plotPost, namely, credMass=0.90.
Comment: thanks for the fast reply. I think I have expressed myself unclearly. If I add credMass =.80 in plotPost, it shows the 80% HDI in the plot. It works perfectly fine. But I would like to change the HDI in the summary statistics output (mean, median, mode of posterior etc.)  from .95 to .80. I thought this summary statistics output relies on HDIofMCMC. But changing credMass there does not work.
Comment: In Jags-Ymet-Xnom2grp-MrobustHet.R, find every instance of summarizePost() and include the additional argument credMass=0.80
Comment: That worked, thank you very much. What does the HDIofMCMC() function actually do then? What about the BEST package, when would you recommend its use over the scripts from DBDA2Eprograms?
Comment: Hi John, I am using Jags-Ymet-Xnom2grp-MrobustHet. No matter to what value I change credMass in HDIofMCMC = function( sampleVec , credMass=0.95) in DBDA2E-utilities, the summary output remains the same. adding the argument in plotPost works. Any idea?
Comment: plotPost calls HDIofMCMC with an explicit default of 0.95, so you have to set credMass in plotPost


What distribution does the mean of a random sample from a Uniform distribution follow?

Question: For example, let $X_1,\cdots,X_n$ be a random sample from $f(x|\theta)=1,\theta-1/2 < x < \theta +1/2$.
Clearly, $X_i \sim U(\theta-1/2 , \theta +1/2)$. Some intuition would suggest that $\bar{X}\sim f(x|\theta)=1,\theta-1/2 < x < \theta +1/2$. However, I do not think that this is actually correct. What distribution would $\bar{X}$ follow?
Comment: Please see the central limit theorem: lots here on that!
Comment: Up to a factor of $\theta/n$ and a shift by $-n/2,$ both of which are readily understandable and computable, it's the distribution described (in great detail, with no approximation) at https://stats.stackexchange.com/questions/41467.
Comment: I followed the link by whuber and it is his usual absolutely esquisite and thorough answer! There should be a **Hall of Fame** for answers like that. Come to think of it, it is probably distributed throughout this site: lots of seriously heavy hitters here and all I can do is marvel, from the cheap seats, at what they produce!
Comment: One last comment. Whenever I see an astonishingly good answer here, I am reminded of a line from **Butch Cassidy and the Sundance Kid**: "Who *are* these guys?"
Comment: @whuber both the question and your answer are fantastic on that link- thank you for sharing!
Comment: @EdV I was hoping to find a known distribution for the mean, non-asymptotically; however, I am beginning to doubt there's a generic answer. Is there an answer for this example, at least?
Comment: @EdV Honestly. I hope to one day be able to write an answer $1/5$th as great as that one
Answer: First, you might want to look at Wikipedia on Irwin-Hall distribution.
Unless $n$ is very small $A = \bar X =
\frac{1}{n}\sum_{i=1}^{n} X_i,$ where
$X_i$ are independently $\mathsf{Unif}(\theta-.5,\theta+.5)$ has $A \stackrel{aprx}{\sim}\mathsf{Norm}(\mu = \theta, \sigma = 1/\sqrt{12n}).$
[The approximation is quite good for $n \ge 10.$ In fact, in the early days of computation when it was expensive to do operations other than pain arithmetic, a common way to simulate a standard normal random variable was to evaluate $Z = \sum_{1=1}^{12} X_i - 6,$ where $X_i$ were generated as independently standard uniform.]
The following simulation in R uses a million samples of size $n = 12$ with $\theta = 5.$
set.seed(2020)  # for reproducibility
m = 10^6;  n = 12;  th = 5
a = replicate(m, mean(runif(n, th-.5,th+.5)))
mean(a);  sd(a); 1/sqrt(12*n)
[1] 5.000153      # aprx 5
[1] 0.08339642    # aprx 1/12
[1] 0.08333333    # 1/12

Thus the mean and standard deviations are consistent
with the results of the Central Limit Theorem.
In R, the Shapiro-Wilk normality test is limited to
5000 observations. We show results for the first 5000
simulated sample means. Those observations are consistent with a normal distribution.
shapiro.test(a[1:5000])

    Shapiro-Wilk normality test

data:  a[1:5000]
W = 0.99979, p-value = 0.9257

The histogram below compares the simulated distribution of $\bar X$ with the PDF of $\mathsf{Norm}(\mu=5, \sigma=1/12).$
hdr = "Simulated Dist'n of Means of Uniform Samples: n = 12"
hist(a, br=30, prob=T, col="skyblue2", main=hdr)
 curve(dnorm(x, 5, 1/sqrt(12*n)), add=T, lwd=2)
 abline(v=5+c(-1,1)*1.96/sqrt(12*n), col="red")

This suggests that $$P\left(-1.96 < \frac{\bar X - \theta}{1/\sqrt{12n}} < 1.96\right) = 0.95,$$ so that a very good approximate 95% confidence interval for $\theta$ is of the form $(\bar X \pm 1.96/\sqrt{12n}).$
Comment: (1) I'm old enough to remember using it. (2) Mention: penultimate parag [here](https://www.johndcook.com/blog/2009/02/12/sums-of-uniform-random-values/). (3) Temporarily separated from my older simulation books, but method often mentioned. (4) Method can't produce values beyond $\pm 6.$ When computing logs and exponentials became cheap, it was replaced by the [Box-Muller](https://en.wikipedia.org/wiki/Box%E2%80%93Muller_transform#Tails_truncation) method.which gives values roughly btw $\pm 6.67.$ (5) R now uses Wichura's rational aprx to std norm quantile fcn,: accurate to double precision,
Comment: Do you know a reference where that approximation to the normal was used?
Comment: References: The method to sum 12 standard uniform random variables and subract 6 (among others) is discussed and extended in Thomas, Luk, Leung & Villasenor, ACM V39, Nr4, [Article 11, Sect 2.2.2](https://www.doc.ic.ac.uk/~wl/papers/07/csur07dt.pdf). It is a problem is several applied probability books, including Suess (2010), Springer: Problem 2.15 p48, (The Box-Muller method is discussed there in Sect. 2.5 p36-38.)
Comment: I did not expect to find such a lovely relationship between the sum of uniform random variables and the standard normal distribution. This is fantastic- thank you!
Answer: No, it's not uniform. Intuitively, you would expect that the uncertainty over $\bar X$ decreases as $n$ increases. Also the central limit theorem suggests, as $n$ increases, the distribution approaches normal distribution. Which means, you'll have a peak around $\theta$, and it's going to narrow down as $n\rightarrow\infty$.
For a simple counter-example, if $n=2$, $\bar X$ is going to have triangular distribution, with its center at $\theta$, with the same limits.
Comment: @Edison whuber's post give a detailed answer on your query for the general case. and Bruce's answer exemplifies the implications of CLT to your case very well. I was lazy enough to answer for the general case since it wasn't directly asked in your question, but was nearly sure that the general case was answered before in this forum (of course with some volume of explanation inside it) however couldn't spotted it. This is a counter-example for your original question :)
Comment: I see. By applying CLT, we get that $\bar{X}$ is asymptotically normal. I was hoping to find some function of the sample that is a pivotal quantity, but I guess I cannot use $\bar{X}$
Comment: Does this example's mean follow a known distribution, non-asymptotically?
Comment: I appreciate the counter-example and your effort. Thank you!
Answer: The Irwin-Hall distribution is the distribution of a sum of $n$ uniform random variables. Therefore, an analytic expression for the density of the mean of $n$ uniform random variables is
$$\frac{1}{n!} \sum_{k=0}^n (-1)^k \binom{n}{k} (x-k)_+^{n-1}$$
By shifting this expression, you get the density of yours.
Comment: Thank you for sharing this. I appreciate it!
Answer: This is one case where using Fourier transforms makes for simple solutions.  Your density function is $\mathrm{rect}(\theta)$ with its Fourier transform $\mathrm{sinc}(f)$ (where $\mathrm{sinc}(f)=\frac{\sin \pi f}{\pi f}$ with the obvious continuation $\mathrm{sinc}(0)=1$).  Adding $n$ variables with that distribution leads to convolving the distribution $n$ times with itself (and dividing by $n$), so the resulting distribution has the Fourier transform $\bigl(\mathrm{sinc}(f)\bigr)^n\over n$.  Doing the inverse transform then delivers
$$\int_{-\infty}^\infty \cos(2\pi f\theta){\bigl(\mathrm{sinc}(f)\bigr)^n\over n}\,\mathrm{d}f$$.  In contrast to the piece-wise defined function in the $\theta$ domain, this is a single expression and thus properties like the moments of the function can be derived from this representation through the Fourier domain.
Comment: Thank you for sharing a unique explanation. Love seeing the different ways that can explain certain concepts.


php - reduzir tamanho de imagem

Question: Criei este codigo de upload de imagens.
Mas sabendo que certa gente pode por imagens de 2000x1000, 5mb
Gostaria de reduzir isso para algo mt menor.
E inserir no meu codigo, como poderei fazer?
Comment: Alguem possivelmente poderia ajudar?
Comment: http://php.net/manual/pt_BR/features.file-upload.php
Answer: Dá uma olhada nesse video:
https://www.youtube.com/watch?v=GBMXmDBXK7M Ele fala sobre como redimensionar imagens, elas ficam menores ao serem redimensionadas, você pode deixá-las do tamanho que desejar e você também pode limitar o tamanho da imagem, assim por exemplo:
<code>$tamanhoPermitido = 1024 * 1024;

$tamanho = $_FILES['file']['size'];

if ($tamanho > $tamanhoPermitido) {?>
   O tamanho do arquivo enviado é maior que o limite!

                <?php }?>
</code>
OBS: cara, o amigo acima está tentando te ajudar e é assim que você responde?

Citação

<code>@hugocsl .. continuo na mesma, pois pretendo é ajudinha a desenvolver e a explicar um codigo de reducao de tamanho. Voces dão-me respostas tortas e... sem sentido para a minha questão.
</code>
Assim que o pessoal não vai te ajudar mesmo.

php - reduzir tamanho de imagem


How do I add a simple form to the node edit page?

Question: I've spent a grand total of 8 hours trying to solve this problem. The form needs to be separate from the node edit form so I can't use the form_alter hook. It needs a separate submit button. It only needs to appear on admin screens ... I've tried overriding page.tpl.php (the one used by me admin theme, seven) with no luck. See the code below ... absolutely nothing happens. When I add html into the page.tpl.php file (located in my modules folder), the html does not appear.
<code>/**
 * Implements hook_theme_registry_alter()
**/
function my_module_theme_registry_alter(&$theme_registry) {
  $mod_path = drupal_get_path('module', 'my_module');
  $theme_registry_copy = $theme_registry;       // munge on a copy
  _theme_process_registry($theme_registry_copy, 'phptemplate', 'theme_engine', 'seven', $mod_path);
  $theme_registry += array_diff_key($theme_registry_copy, $theme_registry);
  $hooks = array('node');
  foreach ($hooks as $h) {
    _my_module_insert_after_first_element($theme_registry[$h]['theme paths'], $mod_path);
  }
}
/**
 * Helper function for re-ordering arrays (needed by theme_registry_alter)
*/
function _my_module_insert_after_first_element(&$a, $element) {
  if(is_array($a)) {
    $first_element = array_shift($a);
    array_unshift($a, $first_element, $element);
  }
}
</code>
Also, I realize I can create forms the drupal way with the form hook (and page call backs). I've had success creating forms and showing them on custom urls, but I can't seem to programatically add the forms on pages I want, such as the node edit pages. If I could figure out how to do that, it would be preferable to just adding an html form into the template folder.
Comment: The node edit page _is_ a form, and HTML won't let you nest a form within a form...what are you trying to accomplish exactly?
Comment: Yeah, I would like to display it outside the form, technically below the form so the two forms are siblings. The reason why it needs to be a seperate form is because it is essentially notifying my module of an update to the page. I can't have the module be notified every time the page is updated (because tiny edits need to be ignored, so I couldn't use a hook for when the page updates) but I need to implement a way of manually notifying the module that edits are made.
Answer: It sounds like you want to let the author notify your module of significant changes to a node.  Another approach you could take is to add a field to your node type, such as "field_change_notification" (boolean/checkbox) ... then look to check if the author selected the checkbox in hook_node_presave.  You can even set it back to unchecked so they can again notify your module on the next update.
<code>function HOOK_node_presave($node){
  if ($node->type == 'article'){
    if ($node->field_change_notification['und'][0]['value']){
      drupal_set_message('A change has been made...');
      $node->field_change_notification['und'][0]['value'] = 0;
    }
  }
}
</code>


Eclipse Tomcat log files

Question: I find the similar question - answer
But it doesn't help any.
Near .metadata I didn't find any files *.log.
May be Tomcat when run from Eclipse doesn't write log files?
Thanks.
Comment: To configure this inside of eclipse, view the discussion here:
http://stackoverflow.com/questions/2233053/where-can-i-view-tomcat-log-files-in-eclipse
Comment: Please select the answer which worked for you.
Answer: Look in workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\logs
Source: Logging output in Eclipse WTP server
Answer: Yes. If you want the logs like those for a default Tomcat 6 installation started using startup.bat, you need to add the following JVM arguments:
-Dcatalina.base="C:\Tomcat6"
-Dcatalina.home="C:\Tomcat6"
-Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager
-Djava.util.logging.config.file="C:\Tomcat6\conf\logging.properties"

Also add C:\Tomcat6\bin and C:\Tomcat6\lib to the classpath if necessary
Answer: Go to server view --> double click on server --> In Overview tab you will find server locations click on this to extend part --> In this part you will find server path --> In server path you will find logs folder In that folders log files will be available

Eclipse Tomcat log files


Permission for anonymous user

Question: I got custom registration form under /user/register URL but anonymous user gets denied access what type of permissions should I set.
 I tried:
 requirements:
   _permission: 'access content'

and
requirements:
   _permission: 'none'

or I deleted it completly but it didn't help.
Answer: 'access content' should be good in general, check it under "people/permissions" to seem if also anonymous users have right to "access content".
You can also declare:
_access: 'TRUE'

In this case you don't need the permission part, this one should definitely work!
Comment: It should be 'TRUE' as string
Comment: It is working. I accidentialy might have turn off access content for anonymous users. Thanks for feedback.
Comment: True: even tho without string it's also working, string shall be used in all cases.
Answer: The above answer did not work until I added the quote marks around TRUE. See the following YAML example placed in my_module.routing.yml
my.module:
    path: '/my-module'
    defaults:
      _controller: '\Drupal\my_module\Controller\MyModuleController::connection'
    requirements:
      _access: 'TRUE'

Answer: The most correct way is use the _persmission as following:
custom_module.add:
  path: '/tools/add'
  defaults:
    _title: 'Add new tools'
    _controller: '\Drupal\custom_module\Controller\ToolsInputPage::render'
  requirements:
    _permission: 'access content'

Answer: Try this.

  requirements:
    _role: 'authenticated'

or use the User service.

  requirements:
    _user_is_logged_in: 'TRUE'

Permission for anonymous user


SBT forces file system locking, even on distributed file systems

Question: I intended to run an extensive test suite that uses SBT on our university high performance computing cluster (it uses the Lustre file system).
Since I have very basic user privileges, I was only able to try installing manually and installing by extracting the tarball.
Even with -Dsbt.boot.lock=false, I get the following stack trace:
java.io.IOException: Function not implemented
    at sun.nio.ch.FileDispatcherImpl.lock0(Native Method)
    at sun.nio.ch.FileDispatcherImpl.lock(FileDispatcherImpl.java:89)
    at sun.nio.ch.FileChannelImpl.tryLock(FileChannelImpl.java:1024)
    at java.nio.channels.FileChannel.tryLock(FileChannel.java:1154)
    at xsbt.boot.Locks$GlobalLock.withChannel$1(Locks.scala:86)
    at xsbt.boot.Locks$GlobalLock.xsbt$boot$Locks$GlobalLock$$withChannelRetries$1(Locks.scala:78)
    at xsbt.boot.Locks$GlobalLock$$anonfun$withFileLock$1.apply(Locks.scala:97)
    at xsbt.boot.Using$.withResource(Using.scala:10)
    at xsbt.boot.Using$.apply(Using.scala:9)
    at xsbt.boot.Locks$GlobalLock.ignoringDeadlockAvoided(Locks.scala:58)
    at xsbt.boot.Locks$GlobalLock.withLock(Locks.scala:48)
    at xsbt.boot.Locks$.apply0(Locks.scala:31)
    at xsbt.boot.Locks$.apply(Locks.scala:28)
    at xsbt.boot.Launch.locked(Launch.scala:238)
    at xsbt.boot.Launch.app(Launch.scala:147)
    at xsbt.boot.Launch.app(Launch.scala:145)
    at xsbt.boot.Launch$.run(Launch.scala:102)
    at xsbt.boot.Launch$$anonfun$apply$1.apply(Launch.scala:35)
    at xsbt.boot.Launch$.launch(Launch.scala:117)
    at xsbt.boot.Launch$.apply(Launch.scala:18)
    at xsbt.boot.Boot$.runImpl(Boot.scala:41)
    at xsbt.boot.Boot$.main(Boot.scala:17)
    at xsbt.boot.Boot.main(Boot.scala)
Error during sbt execution: java.io.IOException: Function not implemented

The issue is that parallel distributed file systems such as Lustre and NFS do not implement lock0, but SBT seems to rely on it.
Not being able to run my test suite on a high performance cluster is a huge disadvantage, as it takes at least 6 hours to run the test suite on my Intel i5, 7200 rpm HDD laptop (which is my only alternative). I do not have access to any file system other than the distributed file system, so putting the boot directory elsewhere is not an option.
I had intended to submit this as an issue on GitHub, but the community guidelines indicate that posting a question on StackOverflow is a better option for this particular kind of issue.
I ended up running the tests overnight on my laptop, but I am not very pleased with this. Unless this is fixed, I will not be able to continue using SBT for my research on actor based testing.
Comment: > I had intended to submit this as an issue on GitHub, but the community guidelines indicate that posting a question on StackOverflow is a better option for this particular kind of issue.

Feel free to open Github issues for feature requests and bug reports. There's now a case for this - https://github.com/sbt/sbt/issues/2222
Answer: You need to mount the client with -o flock in order to enable distributed locking.


Using JdbcMetadataStore Along with s3-inbound-streaming-channel-adapter

Question: We are reading files from S3 bucket using Streaming Inbound Channel Adapter referring at https://github.com/spring-projects/spring-integration-aws
In order to avoiding duplicate file reading across instances I am planning to use
JdbcMetadataStore. So the question is can we use S3PersistentAcceptOnceFileListFilter with JdbcMetadataStore ? (we don't have/want to use AWS MetadataStore)
Answer: The answer is "yes" you can use JdbcMetadataStore based on a shared RDBMS for the mentioned S3PersistentAcceptOnceFileListFilter to avoid file reading duplication on several instance of your application.


knockoutjs button click event doesn't fire

Question: I'm building HTML from data which is returned from ajax, it's looking good when I view the source, but for some reason the click event doesn't fire.
This is how I'm creating the markup:
$.ajax({
                    type: "POST",
                    url: "/webservices/WebService.asmx/GetData",
                    contentType: "application/json; charset=utf-8",
                    data: "{'orderId': " + JSON.stringify(order.OrderId) + "}",
                    dataType: "json",
                    success: function (data) {
                        if (data) {
                            if (data.d.length > 1) {
                                $.each(data, function () {
                                    $.each(this, function (k, v) {
                                        var temp2 = "<input type='button' class='btn' data-bind='value: " + v.TeacherId + ", click: $root.downloadImage' />";
                                        $(".downloadButtons").append(temp2);
                                    });
                                });
                                $("#selectOrderPackagePopup").modal("show");
                            }
                        }
                    },
                    error: function (n) {
                        alert('Error');
                    }
                });

Then I'm able to see the buttons in the modal popup, and this is the generated source:

The click event is this one:
self.downloadImage = function () {
                if (order) {
                    var url = "DownloadImage.aspx?orderId=" + order.id;
                    window.location = url;
                }
            };

I'm not able to fire the click event.
Comment: Possible duplicate of [Get dynamically inserted HTML to work with knockoutjs](http://stackoverflow.com/questions/10826482/get-dynamically-inserted-html-to-work-with-knockoutjs)
Comment: Have you solved your question?
Answer: You need to call ko.applyBindings after you have added the buttons to the DOM. Place it in your ajax success callback, e.g below the $("#selectOrderPackagePopup").modal("show"); line.


How do I render a table with a checkbox on each row?

Question: In Drupal 7, I could achieve this using the following code.
<code>$form['table'] = array(
  '#type' => 'tableselect',
  '#header' => $header,
  '#options' => $options,
  '#empty' => t('No data')
);
</code>
This doesn't work anymore in Drupal 8. I just want a page similar to the one at /admin/people. What's the correct way in Drupal 8?
Comment: You can look at his they rendered the /admin/people page
Comment: I think admin/people is a view, in Drupal 8. The OP is asking what is the code that they should use in Drupal 8, and that is equivalent for the Drupal 7 code shown in the question.
Answer: The form element type "tableselect" is available in Drupal 8

Description: A table created with a far left column of radios or
  checkboxes. Build the table headings and columns with the #headers
  property, and the rows with the #options property.

https://api.drupal.org/api/drupal/developer%21topics%21forms_api_reference.html/8#tableselect
More info on "Adding checkboxes to a table" can be found in the handbook documentation here: https://www.drupal.org/node/945102
Comment: it doesn't work! i tried this:'#type' => 'tableselect',
      '#header' => $header,
      '#options' => $rows,
      '#multiple' => TRUE,
      '#empty' => $this->t('No data .'),
      ); but the result is empty
Comment: i did read the documentary carefully and tried it many times. Please note it worked perfectly in the Drupal 7. i spent many hours trying to find an example in the Drupal 8 source code and failed to find any module using the tableselect render.
Comment: @benson, I suspect it will be an error in your code and not in the core API. Please check the above handbook link and verify your implementation is correct.
Answer: I spent many hours to figure this out and hope my code will help someone to save time.
I am using Drupal 8 version
I was working on some same sort of code where I wanted to output a listing of nodes after form submit and the listing should have checkbox in each row. Below is the sample code. Please modify as per your requirements.
<code>$form['mytable'] = array(
    '#type' => 'table',
    '#title' => 'List of Nodes',
    '#header' => ["Checkbox","Title","Author"],
);

$nids = \Drupal::entityQuery('node')
        ->condition('status', 1)
        ->execute();
$nodes = \Drupal\node\Entity\Node::loadMultiple($nids);
$nids = array_keys($nodes);

// Add input fields in table cells.
$i=0;
foreach($nids as $nid)
{

  $node = \Drupal\node\Entity\Node::load($nid);
  $contenttitle=$node->title->value;
  $receivername = $node->getOwner()->getDisplayName();
  \Drupal::entityManager()->getStorage('node')->resetCache(array($nid));

    $form['mytable'][$i][''] = array(
                                        '#type' => 'checkbox',
                                        '#return_value' => $nid,
                                    );

    $form['mytable'][$i]['Title'] = array(
                                        '#type' => 'label',
                                        '#title' => t($contenttitle),
                                    );
    $form['mytable'][$i]['Author'] = array(
                                        '#type' => 'label',
                                        '#title' => t($receivername),
                                    );
    $i++;
}
// Add a submit button that handles the submission of the form.
$form['actions']['submit'] = [
                                '#type' => 'submit',
                                '#value' => $this->t('Submit'),
                            ];
return $form;
</code>
below is the output example
Comment: It looks like you are loading the node twice. Once with all of the nodes, and again inside the loop
Answer: You may be missing that the keys of header and respective keys of option should be same. Either both indexed or both associative.
I face same issue having index key in header and associative key in option which gives empty table.
https://www.drupal.org/node/945102  code will work


Exchange 2016 - Unable to Send As for Mail Public Folder

Question: Exchange 2016 using Outlook 2016 client
Created a new Public Folder titled
Mail-enabled the public folder:
Enable-MailPublicFolder -Identity "\PublicFolder"

Added Send As permissions.
Add-ADPermission PublicFolder -User domain\jsmith -Extendedrights "Send As"

Added permissions to receive mail.
Add-PublicFolderClientPermission -identity "\PublicFolder" -User Anonymous -AccessRights CreateItems

Set Hidden from address lists false:
Enable-MailPublicFolder -Identity "\PublicFolder" -HiddenFromAddressListsEnabled $False

The user jsmith is an owner of this public folder. He can add the public folder and the public folder can receive emails but nobody is able to "Send As" the public folder.
Under EAC I have verified that the public folder exists, permissions are in place, and the folder is mail-enabled.
I have tried disabling Mail Settings and re-enabling. I am also completely unable to select "PublicFolder" in my "From" field in OWA. It gives no option to enter a custom name and also doesn't have an option for the PublicFolder. I did add it to my Favorites.
The user receives the message "This message could not be sent. Try sending the message again later, or contact your network administrator. You do not have the permission to send the message on behalf of the specified user. Error is [0x80070005-0x0004dc-0x000524]."
The user has both Send As and Send on Behalf Of permissions.
The issue has lasted more than 24 hours so I am fairly certain that it is not a replication issue.
Comment: Cross posting: http://stackoverflow.com/questions/39537188/exchange-2016-unable-to-send-as-on-mail-public-folder/40652983#40652983
Answer: "The user has both Send As and Send on Behalf Of permissions. "
First, you need to set one or the other. Not both. Therefore remove one.
Does the public folder appear in the GAL? If so, that is how you populate the From field. You cannot just type the address in. If it doesn't appear in the GAL then you need to wait for it to do so. Outlook in cached mode will use the OAB, so you could force the OAB to update
get-offlineaddressbook | update-offlineaddressbook
Wait half an hour then force the client to download the OAB from the Send/Receive menu.
Comment: It started working when I enabled and then disabled "Automatically updated email addresses based on the email address policy applied to this recipient." Although I think that has nothing to do with the issue and it was merely a coincidence of replication that led to it working suddenly.

Currently it is working with the user having both Send As and Send on Behalf Of. Why would it need to be one or the other?
Comment: If you have both set, then you have no way of controlling which one is actually used. Therefore you need to decide which one you want and then set the permission. They are not the same.

Your setting change probably forced an update within Exchange, which is why it started working.


why jquery mouseover on dropdown options doesn't work on Chrome/Webkit?

Question: I'm writing a simple code to display some description as user hovers over a dropdown options. But no luck with getting it to work in Chrome. Is there anything I'm doing wrong?
<code>$('#dropdown option').mouseover(function (e) {
    $('.option-desciption').show();
    console.log('test');
});
</code>
Answer: Did you try this one :
<code>$('#dropdown').on("mouseover", function (e) {
    $('.option-desciption').show();
    console.log('test');
});
</code>
http://api.jquery.com/mouseover/


Does the 7th of iiø7 in minor need to be prepared even used in a sequence?

Question: I am writing a descending 5th sequence in minor and want to use a iiø7 (half diminished NOT diminished chord) instead of a ii° at the cadence. My textbook says in the chapter on supertonic 7th chord harmony that the 7th is usually prepared from the previous chord. Does this advice become null and void if the iiø7 is used in a sequence?
In a descending sequence of diatonic triads usually ^1 will come in the VI chord prior to the iiø7 chord but in past chapters before the sequences part "Harmony and voice leading" say the preparation of the 7th in supertonic chords must come in the same voice which might not be possible depending on the soprano one might choose. So my question is that since a sequence allows us to do all kinds of things otherwise discouraged or forbidden (like double leading tones and root position diminished triads) then shouldn't it be that such a strict preparation of the 7th in the iiø7 be unnecessary in the same voice as otherwise instructed in my book and we should see the sequence as overriding this requirement.
Comment: Please edit to tell us about the whole sequence!
Comment: @Dekka no only the ii°7
Comment: Could you include a score showing what are you trying to do?
Comment: yes correct, I have not yet got to fully diminished chords yet
Comment: Does the sequence use sevenths in general? I'm not sure I get the book's point about preparing the seventh. Maybe there's a distinction between "usually" and "must."
Comment: Are you also using a 7th chord for the previous chord?
Comment: Do you want to use ii°7 (fully diminished) or ii half-diminished 7? This is important because, assuming the previous chord is VI (e.g. an Ab chord in C minor) and has all chord tones in it, the 7th of ii half-diminished 7 has already been prepared, while the 7th of ii°7 has not. ii°7 does risk being confused with vii°7, though, so resolve ii°7 carefully.
Comment: Is `ii°7` really the best description? In `C` that would be `D F Ab Cb`. Preparing that diminished seventh on an altered tonic seems tricky. What previous chord will have also been using a _chord tone_ of altered tonic? Enharmonically that chord is just a `viio7` chord.
Comment: @MichaelCurtis Note, he's talking about minor. So, e.g., in A minor, B D F Ab. I still wanna know where it's coming from...
Comment: @AndyBonner, but the mode doesn't matter regarding a lowered tonic versus a leading tone. It's just as questionable in minor. I do agree, the actual sequence would be helpful to hear. There might be a misunderstanding.
Comment: Echoing @user1079505's comment, I am not sure I understand the question.  By "descending 5th sequence" I presume you mean that the preceding chord is a VI chord.  Is this correct?  If so, is the problem that the third of the VI chord is a minor second above the seventh of the seventh of the ii°7 chord?
Comment: You say that "In a descending sequence of diatonic triads usually ^1 will come in the VI chord prior to the ii°7 chord" - you *do* really mean ii half-diminished 7 instead of ii°7, right?
Answer: In real life you can do whatever you want.
The only time you can't do what you like is when emulating some well defined style or procedure, or taking a test. etc.

My textbook says in the chapter on supertonic 7th chord harmony that the 7th is usually prepared from the previous chord.

The key word is "usually."
The textbook is giving you latitude. "Usually" the seventh is prepared. That means sometimes it is not prepared.
In such cases my attitude is this: write the passage several ways using various types of relative motion.
I think it's good to follow whatever the lessons asks, try alternatives, then examine the reason for using one or another treatment.

Does this advice become null and void if the iiø7 is used in a sequence?

This seem worth addressing separately.
You're now moving beyond the specific lesson about preparing the seventh in the supertonic seventh chord. You should bring in other sources, like counterpoint or figured bass texts, to understand the principles involved and develop a broader view.
Historically, preparing suspensions comes out of counterpoint. So, IMO, it makes sense to understand the process in terms of intervals rather than Roman numeral chords. From that perspective the only question is whether the tone is dissonant with the bass. If it is, prepare the dissonance. Whatever the chord might be in Roman numeral analysis is irrelevant.
I think you can extend the same idea to dissonance preparation in sequences. I've never seen a source that makes a distinction between sequential or non-sequential passages. Again, the idea in strict counterpoint seems simply to prepare any dissonance in any type of passage.
Comment: And "do what you want" is obviously not my answer. I address both following the lesson of the textbook and an explanation, historically, why the suspension treatment does not depend on chord type.
Comment: @Aaron write your own answer that focuses on the _unnamed_ textbook. IMO the particular book doesn't matter. The textbook is just a point of departure. The OP's concern - IMO - is how to handle prepared dissonances.
Comment: What's the reason for the down vote?
Comment: "Do what you want" is your second sentence. If it's not your answer, then either remove it altogether (what I'd like to see), or at least move it to the end. And while you make vague references to history, your answer never directly addresses whether that history expects the preparation of the seventh in this scenario.
Comment: "Do what you want" isn't an answer, and OP isn't asking the question of making aesthetic, which is what this post addresses. OP is trying to understand the history and reasoning behind the rules and guidelines laid out in Aldwell and Schachter.
Comment: You don't tell me to remove stuff from my answers. You got your single down vote.
Comment: It's not an order — my apologies that it read that way — just a suggestion, along with an alternative.
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/134377/discussion-between-aaron-and-michael-curtis).
Comment: The only thing that is relevant is if the tone is dissonant with the bass? A V in its inversions has many dissonances against the bass yet there is no mention of the need for preparing any of those in my textbook
Comment: @Armani. Yes, suspensions are in relation to the bass. Also, remember what I wrote about sticking to a textbook's lessons. You're jumping from a textbook lesson about preparing the seventh of `ii7` and trying to apply something of that particular point to sequential passages generally, or to the inversions of `V`, and then saying the textbook doesn't explain how to handle those other situations. If you stick with _only one textbook_, I think just stick to only it's lessons. If you want to expand on those lessons, you _must get other appropriate textbooks and compare them._
Comment: About preparing dissonances in the inversions of `V`. I assume you mean `V7`, because the only dissonant inversion of plain triad `V` is the P4 in `V6/4`. Keep in mind a prepared suspension is not the only way to account from the dissonances of `V7` and its inversions. Passing tones and neighbor motions are other ways to get the various dissonances.
Comment: Yes sorry I meant V7... V43 and V42 have dissonances against the bass which do not need to be prepared
Comment: Right. `I V4/3 I` would have the dissonant `^5` as a held tone while the other voiced moved as neighbor motions. `V V4/2 I6` would make held tones `^5 ^7` dissonant to the bass in a bass passing motion. I just mean that preparation/suspension isn't the only way to introduce dissonances with smooth voice leading.
Answer: Preparation is melodically smooth.  Non-preparation is more melodically dramatic.  If you leap to a dissonant note, it will stand out.   Make sure that's what you want.
Comment: Yes I understand that but sequences kind of overide things a bit as far as I can see so that might make leaping into the dissonance less of a problem
Comment: +1 for _positively_ stating what really guides the choice. It's about melodic line not chords.
Comment: Do something once, it's wrong.  Do it twice, it's a sequence!


Delete folders from GCS using Java API

Question: I'm trying to delete a folder in GCS with the following code, I need to delete a folder inside a folder with all of it's containing data.
Storage storage = CredentialsProvider.getStorageService();
Page<Blob> blobs = storage.list("pdf",
                Storage.BlobListOption.prefix("parent_folder/folder_to_delete"),
                Storage.BlobListOption.currentDirectory());

for (Blob blob : blobs.iterateAll()) {
      System.out.println(blob.getName());
      storage.delete(blob.getBlobId());
}

This code prints all the folders within the folder_to_delete folder but not removing anything. Do we have other approach to delete a folder?
Answer: Because folders does not exist, you can't delete a folder.
A folder is a human representation of path separated by /. Remove all the object in the same path (i.e. folder) the folder will disappear.
More detail here on the "folders"

Delete folders from GCS using Java API


Erro em API WEB com flask

Question: Iniciei meu estudo de API WEB tentando criar uma API Pokedex, Quando tentei criar a função de buscar pokemon pelo numero surgiu o seguinte erro:
"json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)"
appPokedex:
from flask import Flask, jsonify
app = Flask(__name__)

@app.route('/podekex', methods=['GET'])
def pokedex():
    return jsonify({
        'pokedex':[
            {
                'numero': 1,
                'nome':'bulbasuar',
                'type':('grass','poison')
            },
            {
                'numero': 2,
                'nome':'ivysuar',
                'type':('grass','poison')
            },
            {
                'numero': 3,
                'nome':'venusuar',
                'type':('grass','poison')
            },
            {
                'numero': 4,
                'nome':'charmander',
                'type':('fire')
           },
           {
                'numero': 5,
                'nome':'charmeleon',
                'type':('fire')
           },
           {
                'numero': 6,
                'nome':'charizard',
                'type':('fire','flying')
           },
           {
                'numero': 7,
                'nome':'squirtle',
                'type':('water')
           },
           {
                'numero': 8,
                'nome':'wartortle',
                'type':('water')
           },
           {
                'numero': 9,
                'nome':'blastoise',
                'type':('water')
            },
          ]
       })

@app.route('/<int:numero>', methods=['GET'])
def getNome(numero):
    p = pokedex()
    for pokemon in p['pokedex']:
        if pokemon['numero'] == numero:
            return jsonify(pokemon)

if __name__ == '__main__':
    app.run(port=80)

clientPokedex:
import requests as req

url_pokedex = "http://127.0.0.1/podekex"

pokedex = req.api.get(url_pokedex).json()
print(pokedex)

url_busca_num = "http://127.0.0.1/1"
pokemon = req.api.get(url_busca_num).json()
print(pokemon)

ERRO:
Traceback (most recent call last):
  File "c:\Users\EmersonCarbonaro\OneDrive\Documentos\Estudo\Faculdade\terceiro_semestre\aplicações_distribuidas\aula_07\estudo\pokedex\clientPokedex.py", line 9, in <module>
    pokemon = req.api.get(url_busca_num).json()
  File "C:\Users\Emerson Carbonaro\AppData\Local\Programs\Python\Python36-32\lib\site-packages\requests\models.py", line 892, in json
    return complexjson.loads(self.text, **kwargs)
  File "C:\Users\Emerson Carbonaro\AppData\Local\Programs\Python\Python36-32\lib\json\__init__.py", line 354, in loads
    return _default_decoder.decode(s)
  File "C:\Users\Emerson Carbonaro\AppData\Local\Programs\Python\Python36-32\lib\json\decoder.py", line 339, in decode
     obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Users\Emerson Carbonaro\AppData\Local\Programs\Python\Python36-32\lib\json\decoder.py", line 357, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

Answer: Lembre-se de que json nada mais é do que uma string.
Quando você chama p = pokedex(), está botando em p o que a sua função pokedex retorna, que é uma Response do flask com data sendo uma string em formato json, e não um dicionário Python.
Você pode iterar sobre um dicionário se transformar o json em um dicionário:
import json
...
p = json.loads(pokedex().data)

Mas talvez uma solução melhor seja ter a pokedex como um dicionário em seu escopo global, e chamar jsonify nesse dicionário dentro da função pokedex.

Erro em API WEB com flask


Why isn't there a continuously differentiable injection into a lower dimensional space?

Question: How to show that a continuously differentiable function $f:\mathbb{R}^{n}\to \mathbb{R}^m$ can't be a 1-1 when $n>m$? This is an exercise in Spivak's "Calculus on manifolds".
I can solve the problem in the case $m=1$. To see this, note that the result is obvious if the first partial derivative $D_1 f(x)=0$ for all $x$ as then $f$ will be independent of the first variable. Otherwise there exists $a\in \mathbb{R}^n$ s.t. $D_1 f(a)\not=0$. Put $g:A\to \mathbb{R}^n, g(x)=(f(x),x_2, \ldots, x_n)$ (with $x=(x_1,\ldots, x_n)$). Now the Jacobian
$$
g'(x) = \left[
          \begin{array}{cc}
             D_1 f(x) & 0 \\
             0        & I_{n-1}
          \end{array}
        \right]
$$
so that $\text{det}\, g'(a)=D_1 f(a)\not=0$. By the Inverse Function Theorem we have an open set $B\subseteq A$ s.t. $g:B\to g(B)$ is bijective with a differentiable inverse. In particular, $g(B)$ is open.
Pick any $g(b)=(f(b),b_2,\ldots, b_n)\in g(B)$. Since $g(B)$ is open there exists $\varepsilon > 0$ such that  $(f(b), b_2, \ldots, b_n+\varepsilon) \in g(B)$. Thus we can find $b'\in B$ s.t. $g(b')=(f(b), b_2, \ldots, b_n+\varepsilon)$. By the definition of $g$, $f(b')=f(b)$ with $b'$ and $b$ differing in the last coordinate. Thus $f$ isn't injective.
However, I cannot generalize this argument to higher dimenssions.
Comment: This is exercise 2.37, for more reference see [this post](https://math.stackexchange.com/questions/3414426/spivak-calculus-on-manifolds-problem-2-37-b).
Answer: Let $k\leq m$ be the maximum rank of $f'(x)$ when  $x$ runs through $\mathbb R^n$ and $a\in \mathbb R^n$ be a point where the maximum is attained: $rank(f'(a))=k$.
We will have  $rank(f'(u))=k$ for all $u$ in some open neighbourhood  $U$ of $a$ [obtained by  choosing a non-zero $k\times k$ minor of $f'(a)$].
The constant rank theorem will then assure us that locally near $a$ the map $f$ looks like $  (x_1,...,x_n) \mapsto  (x_1,...,x_k,0,...,0)$ and is thus not injective since $n\gt k$ (because $n\gt m\geq k$)
Edit
Here is a 13-line proof of the constant rank theorem, written by a high-quality contributor to this site: @Pierre-Yves Gaillard
Comment: [This link](http://www.iecn.u-nancy.fr/~gaillapy/DIVERS/Constant-rank-theorem/constant-rank-theorem-110320a.pdf) in the answer is now broken.
Comment: Dear KPK, I'll be very happy if someone else gives a solution more to your taste. But I suspect that it would amount to reproving the constant rank theorem in a special case.  By the way, that's exactly what you did for $m=1$! Indeed (in your notation)   $(f\circ g^{-1})(f(x),x_2,...,x_n)=f(x)$ can be rewritten as $(f\circ g^{-1})(y_1,y_2,...,y_n)=y_1$. In other words,  up to the coordinate change effected by your ingeniously constructed $g$, the map $f$ is simply projection on the first factor.
Comment: Dear KPK, I have added (in an Edit to my answer) a link to an incredibly short proof of the constant rank theorem. I think it would be a worthwhile investment to read the proof or at least to remember the precise statement.
Comment: Thx for the answer I'm not really familiar with the constant rank theorem. The book doesn't mention it either so I wait if someone comes up with a more elementary solution.
Comment: Perhaps that's the idea of the whole exercise. In the book this problem comes right after the Inverse Function Theorem. There's an a)-part about the case $n=2$, $m=1$ (construction of $g$ is given as a hint) and b)-part asks the general result. I wonder what the precise statetements of the constant rank theorem might be and whether it would be difficult to prove in this special case?
Comment: Thank you for the link as well as for all the other help. I red the proof altough I'm not 100 percent sure if I understood all the details on first reading; have to look that again some other day:) Anyway, I believe I can now at least answer to my original question. Somehow the idea of arguing using the rank had escaped me.
Answer: Here's another answer which probably uses machinery you don't have, but has the advantage of working in the topological category.
First, recall the Borsuk-Ulam theorem:

If $g:S^n\rightarrow \mathbb{R}^n$ is continuous, then there is a point $p \in S^n$ such that $g(p) = g(-p)$.

In particular, there are no continuous injective maps from $S^n$ to $\mathbb{R}^n$.
Now, suppose $f:\mathbb{R}^n\rightarrow \mathbb{R}^m$ is continuous and injective.  Let $i:\mathbb{R}^m\rightarrow \mathbb{R}^{n-1}$ be the canonical inclusion.
Then $i\circ f:\mathbb{R}^n\rightarrow \mathbb{R}^{n-1}$ is continuous.  Now, restricting $i\circ f$ to $S^{n-1}\subseteq \mathbb{R}^n$ gives a map $i\circ f|_{S^{n-1}}:S^{n-1}\rightarrow \mathbb{R}^{n-1}$.
By Borsuk-Ulam, this new map cannot be injective.  Since $i$ is injective, this means $f$ cannot be injective either.
Comment: Borsuk Ulam is true for $n\ge 2$ right?
Comment: @Mex:  It's true for $n\geq 0$.
Comment: could you help me to solve this one with out borsuk ulam? show $C^{\infty}$ function from $\mathbb{R}^2$ to $\mathbb{R}$ can not be injective?
Comment: @Mex:  In the $C^\infty$ case, I'd suggest Georges's proof above mine.
Answer: I don't have a full solution for the general case, myself, but I can boil it down to a simpler problem which I feel may have a more elementary solution.
Firstly, I believe you miscalculated the top row of $g'$.
In the $m=1$ case, it comes out to:
$$
  g'(x)
  =
  \left[
    \begin{array}{c|ccc}
      D_1 f(x) & D_2 f(x) & \dots & D_n f(x) \\ \hline
      0 & & I_{n-1} & \\
    \end{array}
  \right]
$$
The determinant still comes out to be $\det(g'(x)) = D_1 f(x)$.
In the general case, $g'$ becomes
$$
  g'(x)
  =
  \left[
    \begin{array}{ccc|ccc}
      D_1 f^1(x) & \dots & D_m f^1(x) & D_{m+1} f^1(x) & \dots & D_n f^1(x) \\
      \vdots & \ddots & \vdots & \vdots & \ddots & \vdots \\
      D_1 f^m(x) & \dots & D_m f^m(x) & D_{m+1} f^m(x) & \dots & D_n f^m(x) \\ \hline
      & 0 & & & I_{n-m} & \\
    \end{array}
  \right]
$$
The determinant then becomes
$$
  \det(g'(x))
  =
  \left|
    \begin{array}{ccc}
      D_1 f^1(x) & \dots & D_m f^1(x) \\
      \vdots & \ddots & \vdots \\
      D_1 f^m(x) & \dots & D_m f^m(x) \\
    \end{array}
  \right|
$$
As before, this determinant cannot be nonzero anywhere, or else you can apply the inverse function theorem again, to show that $f$ is not 1-1. Therefore it remains to be shown that if this determinant is zero everywhere, $f$ cannot be 1-1.
It seems intuitively clear to me that that $(f^1, \dots, f^m)$ should fail to be 1-1, and therefore so will $f$, but I'm having difficulties showing it using the earlier results from Spivak.
To be clear, I claim that the general case boils down to: if $f: \mathbb{R}^n \rightarrow \mathbb{R}^n$ is continuously differentiable and satisfies $\det(f'(x)) = 0$ for all $x$, then $f$ is not 1-1.
Comment: If we are able to show that $f^1,...,f^m$ all fail to be 1-1, what is the argument we can use to show that $f$ is not 1-1?  These component functions are continuously differentiable maps from $\Bbb R^n$ to $\Bbb R$, so we can apply the OP's work above.
Comment: Not sure. Maybe consider the "level curves" (level surfaces?) of the f^i, in some not ill-chosen point, and then show that they intersect in more than one point? (Of course, this is just a re-statement of your question.)
Comment: Hmm okay.  There are definitely counterexamples for $m > n$.  I'll think about it.


DatePicker and chrome issue

Question: So I have just come across this issue.
I am using the JQuery UI to have a datepicker which "maps" to a readonly textbox:
$(document).ready(function ()
            {
                var dateFormatStr = 'yy/mm/dd';
                $('#DateOfBirth').datepicker({
                    dateFormat: dateFormatStr,
                    minDate: '-100Y',
                    maxDate: '-18Y',
                    changeMonth: true,
                    changeYear: true
                });

                $('#DateOfBirth').attr('readonly', 'readonly');
});

And in the View, this is what I am doing to bind it:
@Html.LabelFor(m => m.DateOfBirth)
@Html.EditorFor(m => m.DateOfBirth, new { @readonly = "readonly" })

This works fine in IE.
In Chrome however, not so much. It gives its own definition of the date picker control and you can see the jquery control behind it! And when you try to set the value, it fails to do so.
is there a reason why chrome is acting weird? I am guessing this is because the EditorFor is binding the DateOfBirth property which is of type DateTime.
Is there a way to stop this behaviour? I believe I had issues when I was using a TextBoxFor instead and had to use the EditorFor.
Many thanks
Answer: I don't see any Id with your EditorFor statement.
@Html.EditorFor(m => m.DateOfBirth, new { id="DateOfBirth", @readonly = "readonly" })

Don't know if that's the issue, I worked on the datepicker control yesterday and I had no issues.  Unfortunately, I can't make much sense of what you describe as weird behaviour in Chrome.
Comment: I'll try the Id thing but that isn't really the issue. Try pulling up chrome with somewhat the same View/VM and I am sure you will see the issue.

DatePicker and chrome issue


como pegar uma substring de tamanho n que se repete

Question: Tenho a seguinte entrada:
aaisndiaunwioun    test|test saiudb8iuyb aiwbu diby tab fiubaw palavragrande|palavragrande asibtiubi

Como fazer o algoritmo retornar test e palavragrande apenas se estiver escrito igual antes e depois do index do simbolo |
Fiz isso mas obviamente não deu certo
while (s1.indexOf("|") != -1) {
        for (int i = 1; i < 25; i++) {
            for (int j = 1; j < 25; j++) {
                String teste1 = s1.substring(s1.indexOf("|") + 1, s1.indexOf("|") + i);
                String teste2 = s1.substring(s1.indexOf("|") - j, s1.indexOf("|"));
                if (teste1.equals(teste2)) {
                    System.out.println(teste1);
                    char[] s1char = s1.toCharArray();
                    s1char[s1.indexOf("|")] = 'a';
                    s1 = String.valueOf(s1char);
                    System.out.println(s1);
                    System.out.println(s1.indexOf("|"));
                }

            }

Comment: É padrão ? Tem sempre espaços antes de pois de `test|test` ?
Comment: nao, pode ocorrer de ser qualquer carácter alfanumérico ex: assatest|test    awe
Comment: Caso seja `assatest|test awe` não seria valida ?
Comment: eu preciso q nesse caso ele retorne `test`, na minha ideia seria um comparação char a char pra cima e pra baixo a partir do simbolo `|` ate achar um char diferente
Comment: Não podes simplesmente fazer assim: https://repl.it/repls/DismalUnselfishProfile
Comment: acho que não, quando vc dá de exemplo `aaaa|aabaa` na teoria eles são iguais até o 2 `a` se comparado a partir do simbolo `|` pra frente e pra trás. E o retorno pra mim tem q ser a string q foi verificada no caso acima `aa`
Answer: Você pode usar o indexOf("") para coincidir a sentença inteira:
public class Teste {

    private static final String CONST = "aaisndiaunwioun    test|test saiudb8iuyb aiwbu diby tab fiubaw palavragrande|palavragrande asibtiubi";

    public static void main(String[] args) {

        if(CONST.indexOf("test|test") >= 0) {
            System.out.println("test");
        }

        if(CONST.indexOf("palavragrande|palavragrande") >= 0) {
            System.out.println("palavragrande");
        }
    }
}

Caso as sentenças "test|test" ou "palavragrande|palavragrande" não existam o indexOf("") retornará -1.

EDIT
Com os comentários abaixo entendi que não era isso o que queria.
Refiz a resposta mas vou deixar o conteúdo original de exemplo.
Segue a resposta correta:
public class Teste {

    private static final String CONST = "aaisndiaunwioun    test|test saiudb8iuyb aiwbu diby tab fiubaw palavragrande|palavragrande asibtiubi";

    public static void main(String[] args) {

        int ultimaPosicaoDoPipe = 0;
        while(CONST.indexOf("|", ultimaPosicaoDoPipe) >= 0) {

            final int posicaoAtualDoPipe = CONST.indexOf("|", ultimaPosicaoDoPipe);
            final String palavraAntesDoPipe = getPalavraAntesDoPipe(ultimaPosicaoDoPipe, posicaoAtualDoPipe);
            final String palavraDepoisDoPipe = getPalavraDepoisDoPipe(posicaoAtualDoPipe);

            if(palavraAntesDoPipe.equals(palavraDepoisDoPipe)) {
                System.out.println(palavraAntesDoPipe);
            }

            ultimaPosicaoDoPipe = posicaoAtualDoPipe + 1;
        }
    }

    private static String getPalavraAntesDoPipe(final int ultimaPosicaoDoPipe, final int posicaoAtualDoPipe) {
        String palavraAntesDoPipe = CONST.substring(ultimaPosicaoDoPipe, posicaoAtualDoPipe);
        palavraAntesDoPipe = palavraAntesDoPipe.substring(palavraAntesDoPipe.lastIndexOf(" ") + 1);
        return palavraAntesDoPipe;
    }

    private static String getPalavraDepoisDoPipe(final int posicaoAtualDoPipe) {
        String palavraDepoisDoPipe = CONST.substring(posicaoAtualDoPipe + 1);
        palavraDepoisDoPipe = palavraDepoisDoPipe.substring(0, palavraDepoisDoPipe.indexOf(" "));
        return palavraDepoisDoPipe;
    }
}

Explicação:
O caractere pipe (|) é procurado em loop através da sobrecarga do método indexOf() que recebe um segundo parâmetro que informa a partir de qual index ele deve procurar o pipe.
A partir daí, os métodos getPalavraAntesDoPipe() e getPalavraDepoisDoPipe() retornam as palavras antes e depois do pipe (como é de se imaginar :p).
Nada muito complexo, apenas uso dos métodos da classe String.
Comment: acho q me expressei errado, as palavras test e palavragrande foram somente exemplos, eu imagino palavras aleatórias mas seguindo o padrão de ter o simbolo `|` no meio
Comment: Você saberá quais palavras tem que procurar? Ou vai procurar pelo pipe (`|`) e encontrar as palavras antes e depois?
Comment: eu vou procura-las pelo pipe `|` elas serão randomicas
Comment: @unkbr atualizei a resposta. Poderia ver se agora atende, por favor?! :D


Finite set in $\mathbb{R}^{2}$ is not open

Question: If we have a finite set $A$ in $\mathbb{R}^{2}$ I am trying to show it is not open using the standard Euclidean metric.
Two strategies come to mind shown as attempt 1 and attempt 2 below:
Attempt 1:
I need to show that not every point is an interior point. Let $A = \{a_{1},a_{2},\dots,a_{n}\}$ be a finite set. Then let $\alpha = \min\{d(x_{i},x_{j}): i \neq j, x_{i}, x_{j} \in A\}$.
Then consider $0<r\leq \alpha$. Then $B(x_{i},r) \cap A = \{x_{i}\}$. But does this intersection also contain the point $\{x_{i}+r\}$? since we are taking the minimum distance between the points (if $r = \alpha$).
If that's the case then $B(x_{i},r) \not \subset A$.
Then I think we can obtain a contradiction, but am a bit stuck.
Attempt 2:
If I can show that in $\mathbb{R}^{2}$ a singleton set is not open, then I can construct a finite set as a union on singleton sets and this will then also not be open.
Edited due to comments: Assume A is non-empty but finite.
Comment: ok, strictly speaking one should add that $A$ is not empty. Then, one way of reasoning is contrapositively (think: what's the cardinality of an open ball of positive radius).
Comment: @peek-a-boo Good catch, thanks.
Comment: For singletons see https://math.stackexchange.com/q/1459067/399263
Comment: Any (non-empty) open ball must be infinite.
Answer: Suppose to the contrary that the non-empty, finite set $A$ is open. Then given $a \in A$ there must be a radius $r>0$ such that $B(a,r) \subseteq A$. But $B(a,r)$ is infinite, and therefore cannot be a subset of a finite set.  Contradiction.
Answer: Your first attempt is close but not quite right. You need to show that no ball centered at $x_i$ is contained entirely in $A$. To do this, consider $B(x_i, r)$ for some $r > 0$, and show that you can find some point in $B(x_i, r)$ that isn't in $A$, no matter what $r$ is.
Comment: @learningmathematics Your proof should be for **any** $r >0$. By restricting it to $r < \alpha$ your argument is still a bit incomplete. Note a ball $B(x_i,r)$ will contain infinitely many points for any $r>0$ but your set is finite, so...
Comment: I'll try it here: Let $r > 0$ and let $\alpha =\min\{d(x_{i},x_{j}):i\neq j x_{i}. x_{j} \in A\}$. Choose $r < \alpha$ Then consider $B(x_{i}, r)$. This contains points in the ball that aren't in A? I don't think this is quite correct though still
Comment: @Anurag Thanks, I will try and amend it. I need to practice my logic of negating statements!


Read content of another app through my app

Question: I have been searching the same problem for days. But unable to get any hint for that.
I need to create an app like voodoo app, which shows its custom layout only on specific pages of different apps like flipkart,etc.
Now, till this time, i have found options of using AccessebilityService and MediaProjection classes for the same. But i am stuck, how can i know programmatically, that Flipkart's Product Detail Page is visible so that i can display my app's custom view over it like Voodoo app does.
Any suggestions?
Answer: What you want to do is the following.
Using accessibility services track incoming events.  Then you want to track TYPE_WINDOW_CONTENT_CHANGED events, and detect when the window content matches what you'd expect.
@Override
public void onAccessibilityEvent(AccessibilityEvent e) {

    switch (e.getEventType()) {
        case AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED:  {
            if (isFlipkartProdcutDetailPage(getRootInActiveWindow()) {
                doStuff()
            }
        }
    }
}
public boolean isFlipkartProductDetailPage(AccessibilityNodeInfo nodeInfo) {
    //Use the node info tree to identify the proper content.
    //For now we'll just log it to logcat.
    Log.w("TAG", toStringHierarchy(nodeInfo, 0));
}

private String toStringHierarchy(AccessibilityNodeInfo info, int depth) {
    if (info == null) return "";

    String result = "|";
    for (int i = 0; i < depth; i++) {
        result += "  ";
    }

    result += info.toString();

    for (int i = 0; i < info.getChildCount(); i++) {
        result += "\n" + toStringHierarchy(info.getChild(i), depth + 1);
    }

    return result;
}

Comment: @PraneetKumar can you please share code exactly how you are tracking Flipkart Product Detail page ? How you are tracking when user first time opening product detail page and when user is coming from onPause() to onResume() because in both cases different events will be called?


Avoiding MISRA warnings, generating automated code from embedded coder

Question: I would like to know if it is possible to avoid MISRA warning 10.1, 13.2 and 12.6 after generating a code from Simulink model using embedded code (or is it possible to generate a code with a way around?).
e.g (the generated code)
if (A)
{;}

At if(A) statements there is a MISRA violation.
Is it possible to generated code with embedded coder like
if (A !=0)
{;}

Comment: You should only get a warning for 13.2 from that code. If your tool whines about anything else, it is broken.
Comment: yes thats true, I am tring to find out if its possible to avoid that warning. thats to configure the embedded coder to generate the code   without the warning
Comment: I'm assuming that "A" is of a boolean type?  Can you not tell/config your analyser that that type is boolean?
Answer: I was having difficulty generating this type of construct if (A) without using a Boolean type in which case there is no violation of rule 13.2.
Without a Boolean type, I get something along these lines:
if (A > 1) {
    ...}
I was using the R2015b release. It will be good if you can share an example model that generates this type of code.
Also, all the listed rules (10.1, 12.6, 13.2) are recommended and not obligatory as per the MISRA AC AGC standard (Guidelines for the application of MISRA-C: 2004 in the context of automatic code generation).
So compliance to those rules is dependent on the criticality of your application.
Even in the latest MISRA 2012 standard where these rules have been reclassified, they are still classified as advisory in the context of generated code.
For general information on MISRA compliance of generated code this is a great reference:
http://www.mathworks.com/solutions/automotive/standards/misra-c.html
or
http://www.mathworks.com/solutions/aerospace-defense/standards/misra-c.html


Eventos do mouse (ao passar em um elemento x) Jquery

Question: Bem, estou com problemas com o mouseenter().
ele só dispara o evento se eu clicar, preciso que ao passar dentro de um elemento(div) ele dispare o evento.
Como estou fazendo:
                        $('#<?php echo $x?>').mouseenter(function(){
                            $('#<?php echo $x?>').popover('show');
                        });

Quando eu clico dispara,mais na verdade preciso que ele dispare ao passar o mouse.
Answer: O ideal é que você utiliza o método mouseover na verdade, neste caso lá no seu PHP ficaria da seguinte forma:
$('#<?php echo $x?>').mouseover(function(){
    $('#<?php echo $x?>').popover('show');
});

Para ter certeza que o evento está sendo atrelado corretamente você pode inserir um alerta no item para que uma mensagem seja disparada na tela:
$('#<?php echo $x?>').mouseover(function(){
    $('#<?php echo $x?>').popover('show');
    alert("Mouse sobre o elemento: <?php echo $x?>"));
});

Caso tenha mais dificuldades, poste na sua pergunta o conteúdo final do seu html e js, pois se dessa foram ainda não funcionar, o problema provavelmente passará a ser outro.
Answer: O evento que você quer é o .mouseover().
Qualquer coisa de uma olhada na documentação dele, link