How can I add relative path to a pdf file link in drupal menu

Question: I have created menu link for a pdf file. I can use a full path like "http://website/sites/all/myfiles/file.pdf", but if I try to put a relative link such as "sites/all/myfiles/file.pdf" it does not work. If anyone has idea please tell me.
Answer: The thing with the menu system is that what you are typing is not a relative path, but an internal Drupal URL.
Since what you are after is not a Drupal path, but instead a static file server outside of Drupal by your webserver your options are limited.

You can write the full url like you tried yourself
You can create a module/theme where you can make this possible, either by adding the extra link or creating a drupal path that redirects to the static file.

Of these, I personally think that a an absolute path is the lessor of evils, unless you need to do this a lot of times.
Answer: Just use the Menu Token module. Copy your absolute PDF url to your path textfield and replace the servername with [site:url]. Also make sure the uses tokens checkbox is activated and save your menu item... In combination with the Menu Attributes module you could even link your PDF's to a blank browser tab/window if you like so.
Comment: This works great, except on my Drupal 6 installation I had to use `[site-url]` rather than `[site:url]`.  I have Menu Token 6.x-1.0-alpha2+0-dev and Token 6.x-1.19 installed.
Answer: Drupal uses "clean URLs" so when you're on the node/123 page and you are visualizing a link such as:
PDF file

Your browser will interpret it as "node/123/sites/all/myfiles/file.pdf" which won't work. You have to put a "/" at the beginning of the URL:
PDF file

Of course, if your site is in a subdirectory, you need to append it; the safest way is to use l():
<?php echo l('PDF file', 'sites/all/myfiles/file.pdf'); ?>

Edit Dic, 18: use l() as per kiamlaluno advice.
Comment: The correct way is to output a Drupal URL is to use `url()`; the function always output the correct URL, independently from Drupal using clean URLs (or not), or Drupal being installed in a sub-directory of the server root directory (or not). Actually, in such cases you should use `l()`, which outputs the `` tag for a Drupal URL.
Comment: Thanks, I wasn't sure you could use `l()` without a Drupal internal path ;)
Answer:
Create a new content type (e.g. "file download")
Give it a field URL (a link, or a regular text field)
Override the template file used in your theme (e.g. node--file-download.tpl.php)
In this file, put the PHP code to load the field with the URL of file, and then put the following code:
Header("Location: file_address");

Create a pattern in the Pathauto module for this kind of content type (e.g. "file/download/name" or "download/file_id")
Then, you can put it in the menu without problems

I bet there's an easier way, but this should also do the work. It should be double considered in a matter of security.
Comment: Thanks for advice. I also used like
Create new content

And add a code any of following

OR

I just used menu link to the content and this content redirects to my pdf file.
but I have about 100s of pdf. For which I need to create 100s of contents. So I am searchinhg for any other solution which is easy and safety for my site.
Comment: So maybe use module Pages? Try creating:
path : http://localhost:8888/drupal/download_file/%file_name
variant_type :  http response.
and limit it to folder with those 100 files.. This seems to be easier.
Answer: Just use the Pathologic module, and your relative links will work just fine.
Comment: Pathlogic only works on node content as a filter.  It would not work for menu items
Answer: You can also use Menu HTML module together with Special Menu Items module
. This will allow you to place anchor pointing to you file as Menu link title, and nolink tag as menu path.
Just take a look at the screenshot:


One istio-ingressgateway and multiple TLS gateways

Question: Brief of the problem:

If I try to attach multiple TLS gateways (using the same certificate)
to one ingressgateway, only one TLS will work. (The last applied)
Attaching multiple non-TLS gateways to the same ingressgateway works ok.

Error messages:
Domain 1 (ok):
✗ curl -I https://integration.domain.com
HTTP/2 200
server: envoy
[...]

Domain 2 (bad):
✗ curl -vI https://staging.domain.com
* Rebuilt URL to: https://staging.domain.com/
*   Trying 184.108.40.206...
* TCP_NODELAY set
* Connected to staging.domain.com (35.x.x.x) port 443 (#0)
* ALPN, offering h2
* ALPN, offering http/1.1
* Cipher selection: ALL:!EXPORT:!EXPORT40:!EXPORT56:!aNULL:!LOW:!RC4:@STRENGTH
* successfully set certificate verify locations:
*   CAfile: /etc/ssl/certs/ca-certificates.crt
  CApath: /etc/ssl/certs
* TLSv1.2 (OUT), TLS header, Certificate Status (22):
* TLSv1.2 (OUT), TLS handshake, Client hello (1):
* Unknown SSL protocol error in connection to staging.domain.com:443
* Curl_http_done: called premature == 1
* stopped the pause stream!
* Closing connection 0
curl: (35) Unknown SSL protocol error in connection to staging.domain.com:443

Facts:
I have a wildcard TLS cert (lets say '*.domain.com') I've put in a secret with:
kubectl create -n istio-system secret tls istio-ingressgateway-certs --key tls.key --cert tls.crt

I have the default istio-ingressgateway attached to a static IP:
apiVersion: v1
kind: Service
metadata:
  name: istio-ingressgateway
  namespace: istio-system
  annotations:
  labels:
    chart: gateways-1.0.0
    release: istio
    heritage: Tiller
    app: istio-ingressgateway
    istio: ingressgateway
spec:
  loadBalancerIP: "35.x.x.x"
  type: LoadBalancer
  selector:
    app: istio-ingressgateway
    istio: ingressgateway
[...]

Then I have two gateways in different namespaces, for two domains included on the TLS wildcard (staging.domain.com, integration.domain.com):
staging:
apiVersion: networking.istio.io/v1alpha3
kind: Gateway
metadata:
  name: domain-web-gateway
  namespace: staging
spec:
  selector:
    istio: ingressgateway # use Istio default gateway implementation
  servers:
  - port:
      number: 443
      name: https
      protocol: HTTPS
    tls:
      mode: SIMPLE
      serverCertificate: /etc/istio/ingressgateway-certs/tls.crt
      privateKey: /etc/istio/ingressgateway-certs/tls.key
    hosts:
    - "staging.domain.com"
  - port:
      number: 80
      name: http
      protocol: HTTP
    hosts:
    - "staging.domain.com"

integration:
apiVersion: networking.istio.io/v1alpha3
kind: Gateway
metadata:
  name: domain-web-gateway
  namespace: integration
spec:
  selector:
    istio: ingressgateway # use Istio default gateway implementation
  servers:
  - port:
      number: 443
      name: https
      protocol: HTTPS
    tls:
      mode: SIMPLE
      serverCertificate: /etc/istio/ingressgateway-certs/tls.crt
      privateKey: /etc/istio/ingressgateway-certs/tls.key
    hosts:
    - "integration.domain.com"
  - port:
      number: 80
      name: http
      protocol: HTTP
    hosts:
    - "integration.domain.com"

Answer: The problem is that you are using the same name (https) for port 443 in two Gateways managed by the same workload (selector). They need to have unique names. This restriction is documented here.
You can fix it by just changing the name of your second Gateway, for example:
apiVersion: networking.istio.io/v1alpha3
kind: Gateway
metadata:
  name: domain-web-gateway
  namespace: integration
spec:
  selector:
    istio: ingressgateway # use Istio default gateway implementation
  servers:
  - port:
      number: 443
      name: https-integration
      protocol: HTTPS
    tls:
      mode: SIMPLE
      serverCertificate: /etc/istio/ingressgateway-certs/tls.crt
      privateKey: /etc/istio/ingressgateway-certs/tls.key
    hosts:
    - "integration.domain.com"
  - port:
      number: 80
      name: http
      protocol: HTTP
    hosts:
    - "integration.domain.com"

Comment: Yes, the docs are continuously evolving. preliminary.istio.io always contains the latest doc, which will move to istio.io at the next release. The doc that I referenced was also recently added to istio.io (https://istio.io/help/ops/traffic-management/deploy-guidelines/#configuring-multiple-tls-hosts-in-a-gateway), but I referenced the preliminary version because I think it is more clearly explained there.
Comment: @singh I think this is the issue you are having: https://istio.io/docs/ops/troubleshooting/network-issues/#404-errors-occur-when-multiple-gateways-configured-with-same-tls-certificate
Comment: Ouh! Didn't know the 'preliminary' Istio section. Seems like docs are evolving quite quickly this days and sometimes lack some coherence (or are conflicting or outdated) I'll test this now. Thanks!
Comment: I'm getting the suspicion that you can't use '-' on port names.  When I named the ports as staging-https and integration-https I got this nasty error:

2018-10-10T13:40:01.856397Z error buildGatewayRoutes: could not find server for routeName https.443.staging-https, have map[http.80:[port: hosts:"integration.domain.com"  port: hosts:"staging.domain.com" ]]
Comment: But now I used 'httpsint' and 'httpssec' and everything is good :)
Comment: @FrankB In fact, I am curious about the behavior when I have multi TLS gateway enabled at the same time. If i enable two TLS gateway with same port but targeting different hostname, when a connection is coming, will it try to validate the SSL in the first option, and try to match the hostname? How about when the first match failed with match condition, and will it start to match with the second gateway TLS context and hostname? Does it mean multiple TLS handshake or something?
Comment: If the server has a TLS certificate matching the incoming request, it uses the gateway configured with that certificate. You need to be careful with wildcard certificates which can cause browser problems, but otherwise it's straightforward. https://preliminary.istio.io/docs/tasks/traffic-management/secure-ingress/#configure-a-tls-ingress-gateway-for-multiple-hosts https://preliminary.istio.io/help/ops/traffic-management/deploy-guidelines/#browser-problem-when-multiple-gateways-configured-with-same-tls-certificate
Comment: @FrankB
I ran into similar problem in accessing different services in same browser. Because I use a wildcard certificate. Can you point me to the details why it happens and workaround if any ?
Thanks In advance.


Prove the following $A \setminus (B\setminus C) = (A\setminus B)\cap (A \cup C)$

Question: I want to prove the following so I decide to rewrite the RHS
$$A \setminus (B\setminus C) = (A\setminus B)\cap (A \cup C)$$
$$
A\setminus(B\setminus C) = A\setminus (B \cap C^c) = A\cap (B\cap C^c)^c = A\cap(B^c\cup C) = (A\cap B^c)\cup(A\cap C)
$$
there is way that $(A\cap B^c)\cup(A\cap C)\rightarrow (A\setminus B)\cup(A\cap C) = (A\setminus B)\cap (A \cup C)$?
 thanks.
EDIT

LHS:
$$x\in A \vee x\in A\cap C \rightarrow x\in A \wedge x\in C$$
RHS:
$$x\in A \wedge x\in A\cup C \rightarrow x\in A \vee x\in C$$
how it can help me?
Answer: Suppose $A=B=C=\{1\}$.
$B\setminus C=\{1\}\setminus\{1\}=\emptyset$.
$A\setminus(B\setminus C)=\{1\}\setminus\emptyset=\{1\}$.
$A\setminus B=\{1\}\setminus\{1\}=\emptyset$.
$A\cup C=\{1\}\cup\{1\}=\{1\}$.
$(A\setminus B)\cap(A\cup C)=\emptyset\cap\{1\}=\emptyset$.
$A\setminus(B\setminus C)=\{1\}\ne\emptyset=(A\setminus B)\cap(A\cup C)$.
That's why you have trouble proving it.
You could have found this counterexample by drawing the Venn diagram, and observing that the equality fails when some element is in all three sets.
Alternatively, you could simplify the right side: $A\setminus B\subseteq A$ and $A\subseteq A\cup C$, so $A\setminus B\subseteq A\cup C$, so $(A\setminus B)\cap(A\cup C)=A\setminus B$, so the alleged identity simplifies to$$A\setminus(B\setminus C)=A\setminus  B$$which, if true, would mean that $C$ has nothing to do with it. Seems unlikely. If you specialize by setting $C=B$, you get  the alleged identity$$A=A\setminus B$$which is blatantly false.


Make the checkbox non editable by the user but editable programmatically

Question: and I want to restrict the user from changing it. I should be able to change it programmatically but not by the user.
I have tried, editable, clickable out did not work.
How should it be done?
 <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:baselineAligned="false"
        android:paddingLeft="8dip"
        android:paddingRight="8dip">

        <androidx.appcompat.widget.AppCompatCheckBox
            android:id="@+id/flight_origin_date"
            style="@style/InputCheckBox"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:text="@string/new_order_flight_origin_date"
            android:visibility="visible"
            android:layout_weight="1"
            android:layout_marginBottom="0dp"
            app:buttonTint="@color/i6_teal" />

    </LinearLayout>

Answer: Please set following two fields to false in androidx.appcompat.widget.AppCompatCheckBox

android:clickable="false"
android:focusable="false"

Comment: but that also stops me from editing it programatically. I want to just stop the user from changing it but allow the change programatically
Comment: In program, you can set the values to `true`
Comment: Wherever you need to enable it , just enable it from programmatically, and where you want to disable it, just set the both values to `false`
Answer: You can simply use an ImageView instead of checkbox, with two different sources, the first image will be a non-checked checkbox image and the second would be a checked-checkbox image, based on your state you can show either, as in if you want to programmatically check the check-box, just switch to the checked-checkbox image and vice-versa, similarly you can update the variables inside by simply switching image sources.


If $\int_1^\infty f(x) x^n dx=0$ for all $n>1$, is $f=0$?

Question: For a continuous function $f$, if
$$
\int_1^\infty f(x) x^n dx =0
$$
For all integers $n>1$, is it true that $f=0$? Here, $\int_1^\infty f(x) \text d x = 0$ means $\lim_{A \to \infty} \int_1^A f(x)\text dx =0$.
By looking at the real and imaginary parts, we can assume $f$ is real. If $f$ has compact support, then approximating $f$ with Stone-Weierstrass shows that $\int f^2=0$ so $f=0$. If $f$ stops changing signs outside an interval $[1,a]$, then $\int_1^a f(x) (x/a)^n \to 0$ by the DCT, and the rest of the integral must diverge, contradicting the assumption, so the sets where $f$ is positive or negative must be unbounded.
The problem is that the approximation theorems I know only apply in compact domains, so integrating to infinity makes it more complicated. The fact that I do not know if $f$ is bounded also complicates matters, I know that if $f$ were decaying better than $e^{-x}$ this would be more tractable since I could just cut off at some point. So far, I am coming up empty. Is it true that $f = 0$ or is there some counterexample?
Comment: Check this: https://www.mathcounterexamples.net/a-nonzero-continuous-map-orthogonal-to-all-polynomials/
Comment: Does it help to make the change of variables $u=1/x$? That solves the problem of the unbounded domain at least....
Comment: Perhaps you can find a counter-example piece-wise, by adding thin spikes in $[k,k+1].$ Given a function $f_{N},$ zero outside $[1,M],$ which works for $n=2,\dots,N,$ add $N+2$ spikes such that $\int_{M}^{M+N+2} f_{N+1}(x)x^n=0$ for $n=2,\dots,N$ and $$\int_{M}^{M+N+2} f_{N+1}(x)x^{N+1}\,dx=-\int_{1}^{M} f_{N}(x)x^{N+1}\,dx.$$ You have to keep the spiked bounded low, so I'm not sure this will work.
Answer: I am going to rewrite the answer provided by Yalikesifulei in the comments for my own sake, since I was not expecting there to be a counterexample.
Let $g(x) = e^{-x}e^{ix}$ so that $|g(x)| = e^{-x}$ and therefore $\int_0^\infty x^n g(x) \text dx$ converges absolutely. Integration by parts with $u= x^n \Rightarrow \text d u = n x^{n-1} \text dx$ and $\text dv = e^{(-1+i)x} \text d x \Rightarrow v = (-1+i)^{-1}e^{(-1+i)x} $ yields
\begin{align}
I_n &:= \int_0^\infty x^n e^{(-1+i)x} \text dx = \frac{x^n}{-1+i}e^{(-1+i)x}|_0^\infty +\frac n{1-i}\int_0^\infty x^{n-1}e^{(-1+i)x}
\text dx
\\
&= \frac{n}{1-i} I_{n-1}
\end{align}
Because $I_0 = \int_0^\infty e^{(-1+i)x} \text d x = \frac 1{1-i}$, we assume that $I_n = \frac{n!}{(1-i)^{n+1}}$ for some $n$ so that $I_{n+1} = \frac{n+1}{(1-i)} \frac{n!}{(1-i)^{n+1}} = \frac{(n+1)!}{(1-i)^{(n+1)+1}}$ and induction establishes this identity for all $n$. In particular, because $1-i = \sqrt{2}e^{-i \pi/4}$, we have
\begin{align}
\int_0^\infty x^n e^{-x} \sin(x) \text d x &= \Im\left(\int_0^\infty x^n e^{-x} (\cos(x) + i \sin(x))\text d x \right)
\\
&= \Im(I_n) =  2^{-(n+1)/2}n! \Im \left( e^{i \frac \pi 4(n+1)}\right)
\\
&= 2^{-(n+1)/2}n! \sin\left(\frac \pi 4(n+1)\right)
\end{align}
If $n= 4m + 3$ for any $m \in \Bbb N$ then $\frac \pi 4(n+1) = (m+1) \pi$ forces the above to vanish, so, putting $f(x) = \sin((x-1)^{1/4})e^{-(x-1)^{1/4}}$ gives:
\begin{align}
\int_1^\infty u^m f(u) \text ds &\overbrace{=}^{s = u - 1}
\sum_{k = 0}^m \binom mk \int_0^\infty s^k \sin(s^{1/4}) e^{-s^{1/4}} \text d s
\\
&\overbrace{=}^{s=x^4, \text ds = 4x^3 \text d x}4\sum_{k = 0}^m \binom mk\int_0^\infty x^{4k +3} \sin(x)e^{-x} \text d x = 0
\end{align}
Hence such a non-zero $f$ exists and, furthermore, it is analytic on $(1, \infty)$


Finding family of $g$ functions with algebraic property

Question: Consider the family of functions $g$ that satisfy the following conditions over a certain field or algebra:
$$ g(uv, w) =g(u,w) g(v,w) $$
over any elements $u, v, w$ of the given field or algebra
How does one determine or characterise this family of functions?
In the particular case that the family of function is analytic and the field is Abelian,
$$g(u,v)= \sum_{m,n} a_{m,n}u^m v^n $$
 I get the following nilpotent condition on coefficients:
$$ \sum_{p+q=m} a_{p,n} a_{q,n} = a_{m,n}  $$
for all m and n
I'm not sure how to interpret this condition other than it seems to be its own square
Comment: Maybe one should first determine the class of functions $f$ for which $f(uv) = f(u)f(v)$. See here: https://math.stackexchange.com/questions/43964/if-fxy-fxfy-then-show-that-fx-xt-for-some-t
Comment: So, if the field is $\mathbb R$ and the functions $g(\cdot,w)$ are supposed to be continuous for every $w$, then the general solution is $g(u,w) = u_w^{f(w)}$, where $f$ is an arbitrary function of $w$ and $u_w$ is either $|u|$ or $u$, depending on $w$.
Answer: The argument $w$ is merely an index. It's more instructive to write this as
$$g_w(uv) =g_w(u) g_w(v) $$
Then we see that $g$ is just an arbitrary indexed family of homomorphisms of the multiplicative semigroup.
Comment: @ams That's hopeless in general. We need to pick a specific algebra to have any hope of characterizing them.
Comment: But the question was how to characterize these.
Comment: Sure, Matt. Even for $\mathbb R$ this is hopeless. With some more constraints though it is possible in special cases (see my comment(s)).
Comment: it is interesting that the $w$ does not play a major part, the $g$ function is an attempt to find all binary functions that satisfy distributive property with multiplication, and your argument is pointing to it being equivalent to homomorphic property


Adding language file in joomla 1.5

Question: I've mentioned my component name in menu in sys.ini file.  I've mentioned this on xml file also, but the language file didnt change in Joomla 1.5
language/en-GB/en-GB.com_examsmsstaff.sys.ini
COM_EXAM="Exam"

Xml file
<languages folder="admin">
    <language tag="en-GB">language/en-GB/en-GB.com_examsmsstaff.sys.ini</language>
</languages>

Answer: Joomla is pretty fussy about naming conventions.  take the .sys. out of the file name and you should see it working (assuming that your component is installed and working as com_examsmsstaff)
Answer: .sys.ini files only work in Joomla 1.6 and above.  If you're looking to name menu items, place the code into a file named .menu.ini.
For instance, your file above would be:
en-GB.com_examsmsstaff.menu.ini

Adding language file in joomla 1.5


Interpreting a regression equation with summation notaion

Question: I am definitely more of an applied statistician than one with a strong background in the specific mathematical notation.  I'd like to recreate a model I ran across in a paper, and though I understand how to do nonlinear regression (in this case, negative binomial), I'm not sure about how to interpret the following equation that was given as the model for the relationship:
$$ln(Q_{it}) = \beta_1 +\sum_{\theta} (\beta_\theta ln(P_{it}) * storetype_{\theta,i} )) + \sum_{\pi} (\beta_\pi ID_{\pi,i}) + \sum_\delta (\beta_\delta Region_{\delta,i} * endcap_{it}) + \beta_2 radio_{it} + \epsilon_i + \gamma_t$$
for item i in time period t.
It's obviously a demand equation.  I understand the general structure of regression equations, but am unsure how to translate the presence of the summations.  There are multiple coefficients for each of the independent variables, and there seems to be a hierarchical structure of some sort.  I haven't been able to find any formal examples of this structure in my searches and I want to make sure I understand what's going on before I proceed.  Thanks for any help you can provide.
Comment: Aren't the summations going over the "i" as well? So you would have for instance something as $\beta_1*stereotype_1+\beta_2+stereotype_2$ written as $\sum_{i=1}^2 beta_i*stereotype_i$
Comment: No, the summations appear as I have written them . . .
Answer: Let's say the equation were:
$$ln(Q_{it}) = \beta_0 + \sum_{\theta} \beta_\theta \ln(P_{it}) \mathit{Storetype}_{\theta,i}  + \epsilon_{it} $$
And imagine $\theta \in \{ 1,2,3\}$ hence the above regression equation would simply be:
$$ln(Q_{it}) = \beta_0 +\beta_1 \ln(P_{it}) \mathit{Storetype}_{1,i}+ \beta_2 \ln(P_{it}) \mathit{Storetype}_{2,i}+ \beta_3 \ln(P_{it})\mathit{Storetype}_{3,i}  + \epsilon_{it} $$
That is, you'd be estimating a different coefficient $\beta_\theta$ for each possible value of $\theta$. The summation is just a more compact way to write the regression model.
But what is $\mathit{Storetype}_{\theta,i}$?
You'll have to read the paper to know for sure, but I'd guess that $\mathit{Storetype}_{\theta,i}$ is an indicator variable:
$$ \mathit{Storetype}_{\theta,i} = \left\{ \begin{array}{ll} 1& \text{if observation $i$ is storetype $\theta$} \\ 0 & \text{otherwise}  \end{array} \right. $$
And then you'd be estimating a different elasticity $\beta_{\theta}$ for each storetype $\theta$. But that's just a guess.
Comment: So, given an item type i at a time t, it could be present in each of the different storetypes but has a different demand relationship depending on the storetype?  Am I saying that correctly?  And yes, storetype is an indicator variable.
Comment: Hmmm... generally with indicator variables, you have something like for any observation $i$ you have$\sum_\theta \mathit{Storetype}_{i,\theta} = 1$. For any $i$, only one of the Storetype indicator variables would be true. As I said though, you really have to look carefully at how they're defining each variable. I'm making educated guesses.
Comment: That makes sense in the context of the expanded equation you provided in your example.  If it's not present, the zero will wipe out the influence of that particular coefficient and the only coefficient that will impact the result is the storetype = 1 for item i.
Comment: @mmmm Exactly! With indicator variables, that's generally the idea.
Comment: Thanks for helping me put that together.  As a final question, and maybe I should make it's own question, but what is the general term for the type of model where there are different coefficients in play for different variables?  Is this a fixed/random effects sort of model?  I'm just not familiar enough with interpreting things from this end to know what I'm looking at.


Distribution symmetry proof

Question: I have three dependent random variables $X,Y,Z$ and a well-behaved function $g:\mathbb{R}^2\to\mathbb{R}$. Suppose that the random vector $(X,Y)$ has the same distribution as the random vector $(Y,X)$, meaning that $P(X\leq x,Y\leq y)=P(Y\leq x,X\leq y)$, for every $x,y\in\mathbb{R}$.
How can I prove that the random vectors $(g(X,Z),g(Y,Z))$ and $(g(Y,Z),g(X,Z))$ have the same distribution?
That is, I want to prove that $P(g(X,Z)\leq t,g(Y,Z)\leq u)=P(g(Y,Z)\leq t,g(X,Z)\leq u)$ for every $t,u\in\mathbb{R}$. This result seems kind of intuitive to me, and I thought about conditioning on $Z$, but can't figure out the complete argument.
Comment: Welcome to the site ! If you have a follow up question it is best that you make a new post. On stackexchange we try to have one question per post.
Comment: Sorry! I removed the follow-up and posted a new question: https://math.stackexchange.com/questions/4617933/distribution-symmetry-given-some-information
Answer: Welcome to Math Stack Exchange!
It seems that we need $Z$ to be independent of $(X,Y)$ if we want the result to hold. Otherwise, we get a counter-example by letting $g(u,v)=u-v$, $Z=X$ and $Y$ such that $Y-X$ is not constant equal to $0$ but having the same law as $X$.
When $Z$ is independent of $(X,Y)$, define $h_z(u)=g(u,z)$. Then for each Borel subsets $A$ and $B$ of the real line,
\begin{align}
\mathbb P(g(X,Z)\in A,g(Y,Z)\in B)&=\int_{\mathbb R}\mathbb P(g(X,z)\in A,g(Y,z)\in B)d\mathbb P_Z(z)\\
&=\int_{\mathbb R}\mathbb P( X \in h_z^{-1}(A),Y\in h_z^{-1}(B))d\mathbb P_Z(z)\\
&=\int_{\mathbb R}\mathbb P( Y \in h_z^{-1}(A),X\in h_z^{-1}(B))d\mathbb P_Z(z)\\
&=\mathbb P(g(X,Z)\in B,g(Y,Z)\in A).
\end{align}
Comment: Thank you very much, Davide! I edited the question and posted a follow-up. Would you please take a look? Thanks again.
Comment: I will have a look at your new question, which is also interesting. Usually on this website, a common practice is to post followup-up questions as a new question.

Distribution symmetry proof


How to get authoritative answers from nslookup?

Question:
Why is it "Non-authoritative"? Even when I look for yahoo.com ip with ns3.yahoo.com I get Non-authoritative answer.
Why does a yahoo server keep stackoverflow's ip? From where do I get stackoverflow's ip if not from ns3.yahoo.com?
Comment: Without getting into the details about how DNS works I'll simply say that in order to get an authoritative answer you need to query the name server(s) that is/are authoritative for the domain/name you're querying. Yahoo's name serves are not authoritative for the stackoverflow.com DNS namespace.
Comment: Nice answer -- why is it in the comments, and not in the answers?
Answer: You should have a look at how DNS works: http://en.wikipedia.org/wiki/Domain_Name_System.
Every domain is managed by authoritative name servers, and Yahoo server are not the authoritative ones for the stackoverflow.com domain; what's happening here is, when you ask them for info about a domain they are not authoritative for, they in turn ask the authoritative servers, and return their answer to you; thus, the answer you get for your query is non authoritative, because Yahoo's DNS servers are only relaying it to you from other servers, they are not the ones which actually manage that domain.
In order to find the authoritative name servers for a domain, you should perform a NS query:
> set query=ns
> stackoverflow.com

stackoverflow.com       nameserver = cf-dns02.stackoverflow.com
stackoverflow.com       nameserver = cf-dns01.stackoverflow.com

If you ask one of those servers, you'll get an authoritative answer.
Comment: I got an authoritative answer from cf-dns01.stackoverflow.com: http://i.imgur.com/0ITDNjx.png
Comment: http://i.snag.gy/CFBFf.jpg
Comment: From [Wireshark Lab: DNS v6.01](http://people.cs.umass.edu/~arun/453/labs/Wireshark_DNS.pdf): `However, nslookup also indicates that the answer is "non-authoritative," meaning that this answer came from the cache of some server rather than from an authoritative MIT DNS server`
Comment: http://i.snag.gy/aF2Gn.jpg
Comment: it's still Non-authoritative...


Dispatch a class method

Question: Given the below piece of code how do you correctly dispatch a class method:
>>> class A:
...     def a(self):
...         pass
...     def b(self):
...         pass
...     c = a
...     dispatch_map = { 'a' : a, 'b' : b }
...     def dispatch(self, arg):
...         self.dispatch_map[arg]()   # Fail: unbound method!
>>> A().c
<bound method A.a of <__main__.A object at 0x100550210>>
>>> A().dispatch_map['a']
<function a at 0x10054acf8>

Why is c a bound method, whereas dispatch_map['a'] is an unbound method.
This is simple with plain functions, and is a common idiom for a select/case replacement, what is the correct way to do this with class methods?
Answer: You can only bind a method when there is an instance to bind to. Your dispatch map builds the map with just the class instead.
Build the map in __init__:
def __init__(self):
    self.dispatch_map = { 'a' : self.a, 'b' : self.b }

or bind the methods explicitly in your dispatch() method:
def dispatch(self, arg):
    bound = self.dispatch_map[arg].__get__(self, type(self))
    bound()

This uses the descriptor protocol to bind the method, which is what normally happens when a method is looked up on an instance.
Comment: Thank you, I like the later approach being more memory efficient, especially if you have a large number of instances. Shame it's so unreadable.

Dispatch a class method


problem of setting audit rules: Syscall name unknown: stime

Question: I am setting audit rules in /etc/audit/audit.rules.
As the requirement : The audit system should be configured to audit all administrative, privileged, and security actions.
So I add one line into /etc/audit/auditd.rules:
-a exit,always -S stime -S acct -S reboot -S swapon

However, after I restart audit.d by service auditd  restart:
There is error comeout:
Stopping auditd:                                           [  OK  ]
Starting auditd:                                           [  OK  ]
Syscall name unknown: stime
There was an error in line 14 of /etc/audit/audit.rules

It seems stime can't be recognized.
Could anybody help me to find out what is wrong with my added rule? Thanks a lot!
Answer: By chance are you running 64 bit?  You might need to qualify the architecture.
So -a exit,always -F arch=b32 -S stime
Let me know.
Comment: Don't forget you can check if an audit is in a certain architecture by running the ausyscall stime x86_64 OR ausyscall stime i686
Answer: Shouldn't you add this to /etc/audit/audit.rules instead?
Comment: I'm sorry, in fact, I add it into /etc/audit/audit.rules. But I didn't say clearly in the question.
Answer: Got the same on Alpine (64-bit), had to do:
-a exit,always -F arch=b64 -S stime


Is possible (or responsible) to fit a univarite multiresponse nonlinear model?

Question: I have a colleague that wants to fit a nonlinear model to the independent variables X (X is an n x k matrix) and the dependent variables Y (Y is an n x 1 matrix).  The difficulty is that each row of Y could be from one of two different "types" of data, T1 and T2.
There are two different functional relationships between X and the two data types, but the functional relationship between X and the T1 data uses a subset of the parameters that the functional relationship between X and T2 does.
In the past, the nonlinear model between X1 and the T1 was fit and then the parameters fit in that first regression were fixed for the nonlinear regression between the X2 (note that this is a different set of observations) and T2 data.
My colleague is curious what happens if we fit the X1 , T1 data and the X2, T2 simultaneously (remember that T1 and T2 are different "types" of data with different scales and X1 and X2 are non-overlapping data sets).  Is there a standard way to approach this problem?  I think that I could standardized the residuals  or something like that, however I don't really understand the theoretical justification for that and I feel that I could be making some massive error.
Answer: As I understand each $Y$ has type $T_{1}$ or $T_{2}$ and it is no row where two types are given simultaneously. Conseuqnently it is no theoretical grounds for assuming correlation (or some other kind of dependence) between errors in $X_{1},T_{1}$ and $X_{2},T_{2}$ models. Hence simultaneous estimation will give the same results.
Simultaneous estimations are reasonable when random components (usually errors) of estimated equations are dependend in some way (for example correlated) as it makes combinated log-likelihood function to be differerent from simple summ of marginal log-likelihood functions of each model.
For example suppose the model:
$\begin{cases}y_{1i}=\beta_{0}+\beta_{1}x_{1i}+\beta_{2}x_{2i}+\epsilon_{1i}\\
y_{2i}=\alpha_{0}+\alpha_{1}x_{1i}+\alpha_{2}x_{3i}+\epsilon_{2i}\end{cases}, \epsilon_{1*},\epsilon_{2*}\sim N(\begin{bmatrix}\mu_{1}\\\mu_{2}\end{bmatrix},\begin{bmatrix}\rho_{1}&\rho_{0}\\ \rho_{0}&\rho_{2}\end{bmatrix})$
Then if $\rho_{0}=0$ constistent estimates could be achieved without simultaneous estimation because log-likelihood function will be simple the summe of log-likelihood functions of univariate normal distributions. But if $\rho_{0}\ne0$ then log-likelihood function will be based on bivariate normal distributio, so it will have the different form and hence the different maximum that results in different outcome parameter vector. But in your case it is no such $i$ that both $y_{1i}$ or $y_{2i}$ (no matter how complicated your functional form, only how it meets the random component that is disturbance matters) observed simultaneously that is why I think it is no reason for simultaneous estimation. However more deep look at estimated equations unlikely, but maybe will give me some reasons to advice you simlultaneous estimation, but it is extremely unlikely as your case seems to have no dependence between random components of estimated equations.
Comment: However, in this case, the two models share three parameters, B(0), B(1) and B(2), which would suggest that there may be correlation between errors.  (I think!)


Why doesn't my custom entity work in an entity reference field?

Question: I've got a custom entity with bundles that I want to be able to use in an entity reference field in a different entity.  So, I've got an the content entity for my entity type:
<code>/**
 * Defines the Redacted teaser entity.
 *
 * @ingroup redacted
 *
 * @ContentEntityType(
 *   id = "redacted_teaser",
 *   label = @Translation("Redacted teaser"),
 *   bundle_entity_type = "redacted_teaser_bundle",
 *   bundle_label = @Translation("Content type"),
 *   handlers = {
 *     "view_builder" = "Drupal\Core\Entity\EntityViewBuilder",
 *     "list_builder" = "Drupal\redacted\RedactedTeaserListBuilder",
 *     "views_data" = "Drupal\redacted\Entity\RedactedTeaserViewsData",
 *
 *     "form" = {
 *       "default" = "Drupal\redacted\Entity\Form\RedactedTeaserForm",
 *       "add" = "Drupal\redacted\Entity\Form\RedactedTeaserForm",
 *       "edit" = "Drupal\redacted\Entity\Form\RedactedTeaserForm",
 *       "delete" = "Drupal\redacted\Entity\Form\RedactedTeaserDeleteForm",
 *     },
 *     "access" = "Drupal\redacted\RedactedTeaserAccessControlHandler",
 *     "translation" = "Drupal\node\NodeTranslationHandler",
 *   },
 *   base_table = "redacted_teaser",
 *   admin_permission = "administer RedactedTeaser entity",
 *   translatable = FALSE,
 *   entity_keys = {
 *     "id" = "id",
 *     "uuid" = "uuid",
 *     "bundle" = "type",
 *     "langcode" = "langcode",
 *     "user_id" = "user_id",
 *     "created" = "created",
 *     "changed" = "changed",
 *   },
 *   links = {
 *     "canonical" = "/admin/redacted_teaser/{redacted_teaser}",
 *     "edit-form" = "/admin/redacted_teaser/{redacted_teaser}/edit",
 *     "delete-form" = "/admin/redacted_teaser/{redacted_teaser}/delete"
 *   },
 *   field_ui_base_route = "entity.redacted_teaser_bundle.edit_form",
 * )
 */
</code>
And the config entity for my bundles:
<code>/**
 * Defines the Redacted teaser bundle entity.
 *
 * @ConfigEntityType(
 *   id = "redacted_teaser_bundle",
 *   label = @Translation("Redacted teaser bundle"),
 *   bundle_of = "redacted_teaser",
 *   handlers = {
 *     "list_builder" = "Drupal\redacted\RedactedTeaserBundleListBuilder",
 *     "form" = {
 *       "add" = "Drupal\redacted\Form\RedactedTeaserBundleForm",
 *       "edit" = "Drupal\redacted\Form\RedactedTeaserBundleForm",
 *       "delete" = "Drupal\redacted\Form\RedactedTeaserBundleDeleteForm",
 *       "default" = "Drupal\redacted\Entity\Form\RedactedTeaserForm"
 *     }
 *   },
 *   config_prefix = "redacted_teaser_bundle",
 *   admin_permission = "administer site configuration",
 *   entity_keys = {
 *     "id" = "id",
 *     "label" = "label",
 *     "uuid" = "uuid"
 *   },
 *   links = {
 *     "canonical" = "/admin/structure/redacted_teaser_bundle/{redacted_teaser_bundle}",
 *     "edit-form" = "/admin/structure/redacted_teaser_bundle/{redacted_teaser_bundle}/edit",
 *     "delete-form" = "/admin/structure/redacted_teaser_bundle/{redacted_teaser_bundle}/delete",
 *     "collection" = "/admin/structure/visibility_group"
 *   }
 * )
 */
</code>
I then try to use that in an entity reference field in another entity:
<code>->setSetting('target_type', 'redacted_teaser')
</code>
But when I go to create an instance of this entity, the reference field isn't getting any of my bundle instances.
I've also try adding an entity reference field to a content type in the UI.  The field settings recognize my defined bundles when I'm setting up the field, but when I go to create a node of that content type the entity reference field doesn't pick up any of my bundles instances there, either.  I've compared my annotations to those in Node and NodeType and don't see that I'm missing anything.  I've also stepped through with Xdebug, and I can see that when my create form loads, it's getting "redacted_teaser" as the expected type for the reference field.
Everything else about my entity and bundles works just as expected.
Comment: can you clarify "isn't getting any bundle instances"? what exactly doesn't it show and where? Can you include the classname and parent class in the code example?
Comment: In the edit form for the entity where I want to reference my custom entity, nothing shows up when I start entering characters in the autocomplete field.  Ditto for a regular content type entity reference field (created in /admin/structure/types) that tries to use my custom entity.  In both cases, I can use node as the target type and things work fine.
Comment: I used drupal console to generate both classes, the only mods to that are in the annotations.
Answer: You have no label key, so autocomplete doesn't know what to search for.
Comment: Thank you!  Especially for pointing out why autocomplete wasn't working.


Tauri and shared postgres instance

Question: I'm currently developing an app where it is necessary for the frontend to communicate with a PostgreSQL database. I'm using the postgres package to do the PostgreSQL work on the Rust side.
Since I'm using Tauri here, I was building commands to create the connection and delivering data to the user when it's requested.
My problem here is, that I cannot share the PostgreSQL Client between the commands. I know that there is some sort of tauri::State but that cannot handle the client.
Is there a way to share the postgres::Client instance between multiple commands?
My current code looks something like this:
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]

use postgres::Client;

struct ClientState(Option<Client>);

#[tauri::command]
fn connect(client_state: tauri::State<ClientState>) { ... }

fn main() {
    tauri::Builder::default()
        .manage(ClientState(None))
        .invoke_handler(tauri::generate_handler![connect])
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}

I want the code to share the instance of the client
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]

use postgres::Client;

struct ClientState(Option<Client>);

#[tauri::command]
fn connect(client_state: tauri::State<ClientState>) {
    // initialize the client
}

#[tauri::command]
fn exists_user(id: &str, client_state: tauri::State<ClientState>) -> bool {
    // check if a user with the given id exists for example
}

fn main() {
    tauri::Builder::default()
        .manage(ClientState(None))
        .invoke_handler(tauri::generate_handler![connect, exists_user])
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}

Answer: Hopefully I am not too late for your use-case. I am building the exact same pattern that you are, and I had the same problem. I indeed ended up using tauri::State.
Firstly, my original application uses sqlx::PgConnection and a bunch of async stuff, but I tested with postgres and it should actually end up simpler.
After much trial and error, I now instantiate my global structs like this:
struct DbConnection {
    client: Mutex<Option<Client>>
}

Afterwards, you can use your client like this:
#[tauri::command]
fn exec(
    connection: State<DbConnection>,
    sql: &str
) -> u64 {
    let mut binding = connection.client.lock().unwrap();
    let client = binding.as_mut().unwrap();
    // You can start using your `postgres::Client` here
    let result = client.execute(sql, &[]).unwrap();
    return result;

Of course, this doesn't work without initialization. I prefer to not actually initialize the connection at start up, but use a separate function to do it.
I use core::default for setting default values in .manage(), that will never be used, but are useful for going on with the initialization:
    tauri::Builder::default()
        .manage(DbConnection {
            client: Default::default()
        })
        ...

and then in a function, that is actually another tauri command:
#[tauri::command]
fn init(connection: State<DbConnection>) -> Result<(), String> {
    *connection.client.lock().unwrap() = Some(Client::connect("host=localhost user=postgres", NoTls).unwrap());
}

I wrote all this in my app, to see if it works, and it connected correctly, but I didn't test any actual sql. You can see my app here, for further inspiration.

Tauri and shared postgres instance


Questions about how to adjust p.value by FDR

Question: I am adjusting a group of p-value by FDR in R. For example
 p.value= c(0.01,0.02,0.03,0.04,0.5,0.8,0.9)

I see some papers used the following function.
p.adjust(p.value,method = "fdr",n=length(p.value))

But I think FDR is used to control the numbers of false positive. Thus, the adjustment object is the p value less than 0.05? There is no need to adjust the negative (p>0.05)?
May I adjust the p.value like the following function?
p.value_n=p.value[p.value<0.05]
p.adjust(p.value_n,method = "fdr",n=length(p.value_n))

I am not sure my thought is right or wrong?
Any insight would be greatly appreciated!
Comment: You may not adjust the p-value like that. Your thought is wrong. By dropping the non-significant tests, you are pretending you never performed them at all. The FDR correction is less aggressive, leading to more false discoveries.
Answer: You're right that FDR is used to control the numbers of false positive.
But it changes also p-values that are greater than 0.05. However, after applying FDR adjustment, p-value never drops, it can remain the same as before adjustment or rise. Therefore p-values greater than 0.05 will remain greater than 0.05.
This may suggest that one can safely drop p-values greater than 0.05 in his/her calculation, but it is not true. This is because number of conducted tests (number of obtained p-values) is crucial for FDR (and any other p-value correction method).
Imagine you have only one significant p-value, say p=0.01, in your study. In first scenario it is one of three obtained p-values. In second it is one of thousand. In first case you have 3 tests with 5% probability of type-I error each, in second you have 1000 of them. Your conclusions about "corrected" significance should be quite different, right?
Answer: Thanks a lot for your reply!
I still have some questions about multiple hypothesis test.
Situation 1: We have 1000 p-values, all of them are less than 0.0 5. We may say there are 50 false positive (1000*0.05) in these p-values.
Situation 2: We have 1000 p-values, all of them are greater than 0.05. Can we still say there are 50 false positive in the p-values. Apparently, it is unreasonable. Because there are not positive in these p-values.
Multiple hypothesis test is used to control false positive. So the premise is that we must have positive. Together, I think the adjustment object is the p values those are less than 0.05, not all the p-values including p-values >0.05. I am not sure my though is wrong or right? Any insight would be greatly appreciated!


How do I set the POST headers of Play! 2.0 webservice query?

Question: I am building a webservice request that submits some data to a 3rd party service we use:
val promise = WS.url("http://example.com/api/xxx/testers?api_key=%s" format(prefineryAPIKey)).post(requestBody)
val data = promise.value.get.body

The variable requestBody is XML content and I need to send this post with "Content-Type: text/xml". How do I set that inside the webservice? Does it work like Play!'s result by chaining .as("text/xml")?
Thanks
Answer: Found it! I had to dig around the API docs and decrypt some of the compiler errors, but basically the above will look like:
val promise = WS
  .url("http://example.com/api/xxx/testers?api_key=%s" format(prefineryAPIKey))
  .withHeaders("Content-Type" -> "text/xml")
  .post(requestBody)

When you call WS you are putting together a WSRequestHolder. The docs for WSRequest are here:
http://www.playframework.org/documentation/api/2.0/scala/index.html#play.api.libs.ws.WS$$WSRequestHolder


Is Not There Any Solution to run Node.JS Code from Chrome?

Question: I wrote a code by using "puppeteer" in Node.Js. I could run the code from CMD of windows and also terminal of PHPStorm. But I need to build a user-interface for my code to let the user select some parameters. I could not prepare a UI by designing an HTML web page because browser (I mean Javascript) could not send and execute Commands to CMD to run my code (written in Node.JS). As you know Chrome and other browsers does not permit to do that for security reasons.
I have 3 questions:

Node.JS has a module, named "node-CMD". Could I disable security settings of chrome to allow me to use javascript to run commands by using "node-cmd"?
If I could not change the chrome setting, what other solutions are available for running Node.JS code (beside CMD of windows or Terminal of PHPStorm )
Does defining a new web server with customized settings on my PC helps my problem? I am asking because of this comment by Harry Parker.

regards
Comment: You do it the same way you want to run PHP code from Chrome or any browser - by writing a web server. Nodejs may be javascript but that does not mean the browser can run it. From the browser's point of view nodejs is the same as C++ or Java or PHP or Python
Comment: "*let the user select some parameters*" - why does that need a UI? cli arguments should suffice, no?
Comment: Maybe [`page.exposeFunction()`](https://github.com/puppeteer/puppeteer/blob/main/docs/api.md#pageexposefunctionname-puppeteerfunction) can help?
Answer: You cannot execute any commands from browser. You can setup a local server, set up a front end that will allow to you issue some command and send a request to the backend which will then execute given command. Keep in mind that it will execute command on the server, so you cannot execute command on someone else's computer this way.
Express is a pretty popular module for creating a server in Node.js.
You can also create an electron app if you want to create an app - it's like a browser, but with access to file system and everything else you can access in Node.js
Comment: At first thanks for your answer. You mean if I build a UI by using electron,  i could use "node-cmd" to run my Node.JS codes, am I right?
Comment: Yes, you should be able to require() any module you like


Boa práticas ao criar elementos com jQuery

Question: Quando tenho necessidade de criar elementos no DOM através do jQuery, eu costumo utilizar a seguinte síntaxe:
$('
').addClass('minha-div').attr({id: 'id-da-div'});

Porém, o que geralmente vejo nos tutorias pela internet é um pouco diferente.
Geralmente é:
$('

').addClass('minha-div').attr({id: 'id-da-div'});

Ou:
$('

');

Gostaria de saber se, pelo fato de eu não fechar a div no primeiro exemplo, poderia haver algum problema (até hoje funcionou corretamente) e se isso é uma má prática.
Eu devo criar os atributos pelas funções do jQuery (como no primeiro e segundo exemplo) ou devo "escrevê-lo" diretamente no argumento onde passo o seletor (terceiro exemplo)?
Answer: Você deve sim fechar a div:

"To ensure cross-platform compatibility, the snippet must be well-formed. Tags that can contain other elements should be paired with a closing tag"
  http://api.jquery.com/jQuery/#jQuery2

Quanto a segunda pergunta, acho que tanto faz. Se não for constantes eu prefiro utilizar do primeiro jeito. Parece que o último é mais rápido (http://jsperf.com/jquery-element-creationyay/19)
Comment: Para a segunda pergunta, pessoalmente eu acho mais elegante e prático através de um JSON (dois primeiros exemplos) do que uma string gigante, não indentável e possivelmente de difícil interpretação.
Comment: obrigado! você tirou todas as minhas dúvidas.
Answer: Você também pode utilizar da seguinte forma:
$('
', {
    id: 'minhaDiv',
    class: 'minhaClasse',
    'outro-atributo': 'meuValor'
}).appendTo('body');

Sempre uso assim, funciona perfeitamente!
Comment: Eu nunca havia usado essa sintaxe até uns meses atrás. Pessoalmente eu achei um pouco mais complicada do que quando já se tem o elemento criado no DOM, mas é questão de se acostumar.
Comment: Essa passagem de objetos no segundo parâmetro ficou bem melhor do que qualquer um dos meus exemplos. Assim que possível, vou refatorar os meus códigos :)
Comment: Muito bacana. Assim `$('', {html: 'conteúdo da div'})` você escreve dentro dela!


Bayesian optimization on a polynomial regression as the surrogate model

Question: My understanding of Bayesian optimization is that it is generally used in conjunction with Gaussian process (GP) as the surrogate model. Because GP inherently produces an uncertainty of estimate, the acquisition function of expected improvement (EI) can take that into account the uncertainity and strike a balance between exploration and exploitation.
If we were to use a (2nd order) polynomial regression model as the surrogate, as what is normally used in response surface methodology (RSM), is it possible to still use expected improvement as the acquisition function? If so, what is the method to obtain an uncertainty of estimate at any point from a 2nd order polynomial model in order to calculate the EI?
Comment: You could use a GP with a covariance such as the [polynomial kernel](https://en.wikipedia.org/wiki/Polynomial_kernel) or you could do [Bayesian linear regression](https://en.wikipedia.org/wiki/Bayesian_linear_regression).
Comment: Thanks for the suggestion! However, is it correct to say it's not possible to get an uncertainty estimate from a standard polynomial regression model?
Answer: g g already answered this in their comment, but since this led to a further question in the comments, I will try to clarify this further.
A Gaussian process is equivalent to Bayesian linear regression with the inputs mapped into some high-dimensional space such that the dot product of two mapped inputs corresponds to the kernel function applied to the original inputs. See Rasmussen & Williams for a detailed exploration of how the Bayesian linear regression 'weight-space view' and the 'function-space view' are equivalent: https://gaussianprocess.org/gpml/chapters/RW.pdf
What this means for your purposes here is what you are trying to do is equivalent to fitting a Gaussian process with a polynomial kernel. You could therefore fit a Gaussian process with a degree-2 polynomial kernel to generate your uncertainty estimates, and that would be equivalent. Alternatively, you could use Bayesian linear regression. To make this more concrete, let's say you have two input variables, $x_1$ and $x_2$, so that each input datapoint $x_i$ has the associated vector $x_i = [x_{i_1},x_{i_2}]$. If using a 2nd degree polynomial, you can now map each input datapoint to the following $z_i$ (I would standardize your data first...):
$z_i = [x^2_{i_1}, x^2_{i_2},  x_{i_1}x_{i_2}, x_{i_1}, x_{i_2}]$
and fit the mapped input data to a linear model using Bayesian linear regression (e.g. in scikit-learn -- the scikit-learn implementation of Bayesian linear regression will calculate the uncertainty on each prediction for you), and use this to generate your uncertainty values. Polynomial regression is just linear regression with polynomial basis functions.
The two approaches (GP with a polynomial kernel, or Bayesian linear regression with polynomial basis functions) are equivalent. Which one to use depends on whether you have a small number of datapoints in a high dimensional input space (in this case a GP with a polynomial kernel will be faster), or whether you have a large number of datapoints in a low dimensional input space (in this case, performing a matrix decomposition on the kernel matrix will be expensive, so use Bayesian linear regression).
Comment: Thank you for your answer! That was very helpful


login page permission has changed suspiciously

Question: I have developed a website with php and apache server on linux centos
I am not professional on security issues and I think some folks try to hack my website
first please advice me which security things I should follow
but my problem:
tonight as I tried to login firebug showed it tries to load login.php for serveral times but a file error occurs (I think a permanent move or something....)
anyway when I checked the login.php file in linux I have noticed the file permission has been changed and all x (execution) flags has been removed.
could it be the work of a hacker? what should I do to prevent such happening.
I changed chown to root, and also set chmod of all files from 775 to 755
please give more
Answer: In a situation like this, the first thing I would do is check the Apache log files. There should be an access_log as well as an error_log file(s). It should give you a clue as to possibly the source and what was done, if anything.
The logs are usually found in:

/etc/httpd/log/

The second thing I would do, if you think the script was changed, is to compare it for differences with a backup copy (that you know is secure and has not been tampered with).
Answer: Boot from a CentOS installation LiveCD.  Determine the harddrive installation location or $ROOT and if it is already mounted.  Pass $ROOT to the following command.
`rpm  --root $ROOT --query --verify --all`

which is the same as
`rpm --root $ROOT -qva`

will verify all packages installed via yum/rpm.  If a binary, say httpd is different than what was installed, then somebody has root.  The catch is that rpm verify does not verify anything installed outside of rpm/yum.  So if you download a module and install manually or a cgi script not installed via rpm, then it will not find changes to those files.  Even if you only installed via rpm and it finds everything ok, that does not find compromise via misuse.
Examples of misuse:

send a password over http instead of https.
Do not choose a strong password for ssh.
Use login credentials for ftp instead of using sftp.
Comment: @voretaq7  of course nothing can be trusted on the harddrive, that is why a boot from LiveMedia is necessary, preferably containing all the rpm packages.  Not hard with 64GigaByte USB sticks.  If not predownloaded, the rpms can be downloaded in the live session. Further, i addressed the second concern about installations outside of rpm starting with "The catch is ...."
Comment: If you read the man page for `rpm` you will find the following in the section about `--root`: "Use the system rooted at *DIRECTORY* for all operations. Note that this means the database will be read or modified under *DIRECTORY*". That means you'll be using the RPM metadata from the (compromised) `--root` in your example above (i.e. "trusting the compromised system's metadata"). If you intend to use RPM data from the CD you've left out a bunch of steps...
Comment: @voretaq7  The canonical answer does not give specific information for quick forensic analysis of a RedHat derived machine.  However, it recommends attempting to find out the cause of break-in because restoring from backup will probably just make the system vulnerable to attack yet again.  Yes, steps were left out, such as using --dbpath but this is not necessarily a compromise yet.  It could very well be a restoration of selinux context, not a hacking attempt.
Comment: Log files can be compromised too and if my answer is voted down, so should checking that answer.
Comment: On a compromised host you cannot trust ***anything***, including the RPM checksums that would be used in this verification. (You've wisely chosen not to use the `rpm` binary from the compromised host, but unless you have all of the packages available on your CD you still need to reference potentially compromised data (the RPM manifests) on the hard drive.) You also can't verify that something *not* managed by RPM wasn't installed, removed, or modified...


Highcharts plotbands different per category

Question: I am attempting to create the following chart:

However I can't seem to get the plotbands to work in this way; right now, they fill the entire axis:
I am not sure if I should use annotations instead, but so far I haven't gotten it to work. What can I try next?

Highcharts.chart('container',{
            credits: {
                enabled: false
            },
            title: {
                text: "hello world",
                style: {
                    visibility: 'hidden'
                }
            },
            chart: {
                type: 'line',
                width: 400,
            },
            legend: {
                enabled: false
            },
            exporting: {
                enabled: true,
                allowHTML:true,
                chartOptions: {
                    chart: {
                        marginLeft: 175,
                        marginRight: 175
                    },
                    plotOptions: {
                        line: {
                            dataLabels: {
                                style: {
                                    fontSize: 14

                                },
                                verticalAlign: "top",
                                useHTML: true
                            }
                        }
                    }
                }
            },
            yAxis: {
                startOnTick: false,
                endOnTick: false,
                gridLineWidth: 2,
                tickWidth: 2,
                tickLength: 20,
                plotBands: [{
                    color: 'rgba(231, 23, 60, 0.5)', // Color value
                    from: 5, // Start of the plot band
                    to: 6.2 // End of the plot band
                },
                {
                    color: 'rgba(53, 101, 237, 0.5)', // Color value
                    from: 1, // Start of the plot band
                    to: 3 // End of the plot band
                }
                ],
                title: {
                    align: 'high',
                    offset: -40,
                    text: 'mmol/L',
                    style: {
                        fontWeight: "bold",
                        fontSize: 15
                    },
                    rotation: 0,
                    y: -20
                },
                min: 0,
                max: 7,
                labels: {
                    x: -10,
                    y: -3,
                    formatter: function () {
                        if (this.value != 0) {
                            if (this.value < 8) {

                                return this.value;
                            }
                        }
                    },
                    style: {
                        fontWeight: "400",
                        lineHight: "20",
                        padding: "0",
                        fontSize: "13"
                    }
                }

            },

    annotations: [{
        shapes: [{
            point: '0',
            type: 'circle',
            r: 10
        }, {
            point: '3',
            type: 'rect',
            width: 20,
            height: 20,
            x: -10,
            y: -25
        }, {
            fill: 'none',
            stroke: 'red',
            strokeWidth: 3,
            type: 'path',
            points: ['0', '1', {
                x: 6,
                y: 195,
                xAxis: 0,
                yAxis: 0
            }],
            markerEnd: 'arrow'
        }],
        labels: [{
            point: {
                x: 6,
                y: 195,
                xAxis: 0,
                yAxis: 0
            }
        }]
    }],
            xAxis: {
                gridLineColor: 'transparent',
                accessibility: {
                    rangeDescription: 'Range: 2010 to 2020'
                },
                categories: [2018, 2019]
            },
            plotOptions: {
                line: {
                    dataLabels: {
                        style: {
                            fontSize: 14

                        },
                        verticalAlign: "top",
                        useHTML: true,
                        format: '
{y}
mmol/L
'

                    }
                }
            },
            series: [{
                name: '',
                color: "black",
                data: [5.4, 3],
                showInLegend: false,
                dataLabels: {
                    enabled: true,
                    useHTML: true,
                }
            }],
        });

Answer: This kind of plotBand shape is not possible from the API level, but you can simulate it in several ways. Example configurations:

SVG Renderer:
  chart: {
    events: {
      render() {
        const chart = this;

        if (chart.rects) {
          chart.rects = chart.rects.destroy();
        }

        chart.rects = chart.renderer.g('rects').attr({
          zIndex: 1
        }).add();

        let x = chart.xAxis[0].toPixels(1),
          y = chart.yAxis[0].toPixels(4),
          width = chart.xAxis[0].toPixels(2) - chart.xAxis[0].toPixels(1),
          height = chart.yAxis[0].toPixels(2) - chart.yAxis[0].toPixels(4);

        chart.rect = chart.renderer.rect(x, y, width, height)
          .attr({
            fill: 'grey'
          }).add(chart.rects)

        chart.rect = chart.renderer.rect(chart.xAxis[0].toPixels(3), y, width, height)
          .attr({
            fill: 'grey'
          }).add(chart.rects)
      }
    }
  },

Demo:
https://jsfiddle.net/BlackLabel/wst607ub/
API Reference:
https://api.highcharts.com/class-reference/Highcharts.SVGRenderer

Annotations:
 annotations: [{
  draggable: false,
    shapes: [{
      points: [{
                x: 1,
                y: 2,
                xAxis: 0, // xAxis reference used, use xAxis value
                yAxis: 0  // yAxis reference used, use xAxis value
            }, {
                x: 2,
                y: 2,
                xAxis: 0,
                yAxis: 0
            }, {
                x: 2,
                y: 4,
                xAxis: 0,
                yAxis: 0
            }, {
                x: 1,
                y: 4,
                xAxis: 0,
                yAxis: 0
            }],
      type: 'path'
    }]
  }]

Demo:
https://jsfiddle.net/BlackLabel/uvxzp6o7/
API Reference:
https://api.highcharts.com/highcharts/annotations

Polygon series:
  series: [{
    name: 'Polygons',
    type: 'polygon',
    color: 'grey',
    showInLegend: false,
    enableMouseTracking: false,
    states: {
      inactive: {
        opacity: 1,
      },
    },
    data: [
      [1, 2],
      [2, 2],
      [2, 4],
      [1, 4],
      null, // allows multiple polygons
      [3, 2],
      [4, 2],
      [4, 4],
      [3, 4],
    ]
  }]

Demo:
https://jsfiddle.net/BlackLabel/4n7ep3k2/
API Reference:
https://api.highcharts.com/highcharts/series.polygon

Take note that annotations and polygon series require the module to be included.


Is there any way to disable at least TLS 1.0 in GCE HTTPS Load Balancer?

Question: I'm trying to pass the Trustwave pci DSS scan but i can't because it fails in "TLSv1.0 supported" and i think the problem is in GCE HTTPS loadbalancer that enables TLSv 1.0, 1.1 and 1.2 by default (https://cloud.google.com/compute/docs/load-balancing/http/#tls_support).
I have tested my instances locally with openssl and with cipherscan (https://github.com/jvehent/cipherscan) and in either one i was only able to get connection using TLSv1.2 ciphers.
It i try to use the same tools using the public ip of GCE HTTS Load Balancer i can connect using TLSv1,TLSv1.1,TLSv1.2.
Comment: You might be able to use GCE Network Load Balancers instead, for forwarding the TCP packets directly to your instances; this means your HTTPS client would be handshaking directly with your application, and thus would use the TLSv1.2 ciphers.  On the downside, you might not get the same per-request balancing behavior.
Comment: @Castaglia is it possible to post your comment as an answer, so others can benefit from it.
Comment: @George Ok, done.
Comment: Your best option will be to dispute this finding and submit your Risk Mitigation & Migration Plan, which will grant you an EXCEPTION to this finding until June 30th, 2018. You'll get another 14 months to deal with this issue. I submitted one and was granted an exception within a couple hours. The reasoning was for supporting IE9/10 on Win7, which does not support TLS 1.1 or 1.2 by default; support can only be configured manually in the browser, which no one will do. A significant enough percentage of our customers are still using those browsers on that OS, so we'd lose their business.
Answer: For anyone stumbling on this ; it is now possible to define an SSL-policy that can be applied to the target-https-proxies created by a GCE HTTPS load balancer.
The following command allow to create a policy that, to my knowledge, would had met the requirement for the mentioned Trustwave pci DSS scan in OP question.
$ gcloud beta compute ssl-policies create pci_dss_ssl_policy \
  --profile MODERN --min-tls-version 1.2

List the existing target-https-proxies with :
$ gcloud beta compute target-https-proxies list

Apply the created policy to a given target-https-proxies with :
$ gcloud beta compute target-https-proxies update \
  NAME_OF_HTTPS_TARGET --ssl-policy pci_dss_ssl_policy

For further reference, the ssl-policies is your friend.  E.g. if one want to further restrict the policy using a custom list of cipher.
Comment: Thanks! I did the same using Google Cloud Console and it had `0` effect on the ssl policies.. After doing it with gcloud commands you provided above, everything worked perfectly! `sslscan` showed the difference :+1:
Answer: You might be able to use GCE Network Load Balancers instead, for forwarding the TCP packets directly to your instances; this means your HTTPS client would be handshaking directly with your application, and thus would use the TLSv1.2 ciphers. On the downside, you might not get the same per-request balancing behavior.
Hope this helps!
Comment: The most significant difference in the load balancing behavior is that the TCP balancing can only balance between VMs in a single region. HTTP/HTTPS/SSL balancing can balance between VMs in different regions.
Comment: Anyone who needs high availability should not do this, as @kasperd noted with the limitation to a single region.
Comment: @danemacmillan You could always setup a separate TCP balancer in each region and use a DNS server with awareness of location of the users and health of the load balancers to direct users. But some would say that is re-inventing the wheel.


If the conductor went missing post-rehearsal....?

Question: I know that the Kronos Quartet do not use a conductor, and a lot of "modern classical" music doesn't use one.  For example, I don't think I've ever seen a conductor at a performance of a Steve Reich piece.  However, such examples involve a pre-planned performance without a conductor.
I'm aware of what a conductor does but I'm interested in what would happen if the conductor disappeared (after rehearsals) and could not be replaced.
How would removing the conductor post-rehearsal audibly affect a professional performance?
Would it just be a bit looser, or would it just become impossible for the concert to go ahead?  Would it be easier for "standards" that the players would likely know better?
Comment: I reckon, in most cases, that the conductor has done >90% of his work prior to the concert, in rehearsals, so any set of decent players would be capable of performing the piece well conductorless. Or at least with the orchestra leader giving cues. Perhaps more than 'ready, steady, go'. And, yes, well-known pieces would go even better. With the dots to follow, it's not that difficult. If several complete strangers can play together, in perfect harmony, in jazz pieces, without a rehearsal...
Comment: This happens from time to time - usually when the conductor is taken ill.  Last time I was at a concert where this happened - Carmen (fully staged), if I remember correctly - another conductor stepped in to fill the gap.
Comment: See related question [here](https://music.stackexchange.com/q/40228/2600). Of course ensembles so small as a string quartet never need a conductor. As I wrote in my answer there a big romantic orchestra (worse even: with chorus) is hardly imaginable without conductor for anything else than well-rehearsed or very short encore pieces. Transmission time of sound is big enough to become noticable and not everybody may have the bow of the concert master in clear view.
Answer: Particularly in a large ensemble or when a performance occurs in a highly reverberant space, the conductor is especially helpful in keeping the ensemble together. Sound from one part of an orchestra or choir can reach other parts of the orchestra or choir at different times -- enough so to throw off the timing or at least create confusion or uncertainty.
The more experience the musicians have, the more ways there are around this problem (watching bow strokes, timing the echo, finding nearby instruments to cue off of), but a conductor gives the entire ensemble a common point of reference.
Comment: Back of the envelope calculation: in a typical orchestra pit, sound takes about a 32nd note at 120bpm 4/4 (Moderato–Allegretto–Allegro moderato) to travel between the furthest points. That's more than enough to make throw off at least the microtiming, if not to make the whole thing fall apart altogether.
Comment: I guess you meant 'cue'. If they're in a queue, they'll never catch up!
Answer: It depends on the size of the ensemble and the level of their playing and the quality of the conductor but mostly on the type of music being played. It's impossible to generalize, but the worst case result could be that the concert would be impossible to perform. The best case result would be if the concert sounded better without the conductor. Or the result could be anywhere in between: playable but with a loss of quality, playable with a replacement conductor etc.
Chamber ensembles (and, since you mentioned them, particularly string quartets) almost never use a conductor.
Comment: Thank you for the answer and the point re string quartets.  It seems I've misremembered something about Kronos being different (maybe amplification?) or misattributed something I've read about another group to Kronos.
Answer: Watch an established string quartet start a piece.  They breathe together, give each other a sort of mutual upbeat...   Or maybe the first violin (or whoever carries the main opening melody) 'leads' a bit more blatantly.
In a larger orchestra (whatever its Socialist philosophy) someone - generally the concertmaster - HAS to lead.  In effect he becomes the conductor.
They'll get through it.  If it's a familiar piece, they might get through it very well.


$\exp_q^{-1}(\exp_p(tX)) = \exp_q^{-1}(p)+t\Gamma_{p\to q}(X)+O(t^2)$ as $t\to 0$?

Question: Let $(M,g)$ be a Riemannian manifold with induced metric $d$ and injectivity radius $r>0$. Let $p, q$ be two points in $M$ such that $d(p,q)<r$. It is easy to see that $p$ and $q$ can be connected by an unique minimizing geodesic $\gamma=\{\gamma(t):0\le t\le 1 \}$ with $\gamma(0)=p$ and $\gamma(1)=q$. Denote by $\Gamma_{p\to q}:T_p(M)\to T_q(M)$ the parallel transport along the geodesic $\gamma$ from $p$ to $q$.

My question is: for a tangent vector $X\in T_p(M)$, does the following holds
  $$\exp_q^{-1}(\exp_p(tX)) = \exp_q^{-1}(p)+t\Gamma_{p\to q}(X)+O(t^2), \quad t\to 0?$$

Any comments or hints will be appreciated. TIA.
Answer: It does not hold : On $2$-dimensional unit sphere, consider two points of $\frac{\pi}{2}$ distance. And parallel vector field on the geodesic between two points is perpendicular to the geodesic (cf. Parallel transportion for Alexandrov space with curvature bounded below - Petrunin) :
When $M=\mathbb{S}^2,\ |p-q|=\frac{\pi}{2}$, then $c$ is unit speed
geodesic from $p$ to $q$. Assume that $X(t)$ is a unit parallel
vector field along $c(t)$ s.t. $X(0)\perp c'(0)$.
Then $$A=0,\ B=\exp_p^{-1}\ q,\ C=\exp_p^{-1}\ \exp_q\ tX(\pi/2)$$ is
a triangle in $T_pM$ s.t. $\angle\ BAC = t$.
When $A,\ B,\ C'$ is triangle with $\angle\ ABC'=\pi/2$ and
$|B-C'|=t$, then we find $|C-C'|$ : By cosine law, \begin{align*}
|C-C'|^2&=t^2+(\pi\ \sin\ \frac{t}{2})^2-2t(\pi \ \sin\
\frac{t}{2})\cos\ \frac{t}{2} \\& =( t-\pi\ \sin\ \frac{t}{2})^2+ O(t^4)
\\ |C-C'| &=t-\pi\ \sin\ \frac{t}{2}+ O(t^2)\end{align*}
Comment: How does your example negate that equality? Can you explain more? Thanks...
Comment: I think I understand your exmaple and it is really a good counterexample. But I derive the last two equations in your answer as $$|C-C'|^2 = (t- \frac{\pi}{2} \sin t)^2 + (\frac{\pi}{2} - \frac{\pi}{2} \cos t)^2 = t^2 - \pi t \sin t + \frac{\pi^2}{2} (1-\cos t) = (1-\pi+ \frac{\pi^2}{4}) t^2 + O(t^4),$$ $$|C-C'| = (1-\frac{\pi}{2}) t + O(t^2).$$ But, anyway, this negate that equality in my question. Thanks.


Question about Fitch style natural deduction

Question: So I have a proof in which i have derived both ~P and (P v Q). My current objective is to extract the Q as I need it for another part of the proof. It seems obvious to me that if I have ~P true and (P v Q) true, then Q is necessarily true. However, to get Q I would need to use the disjunction elimination rule, and I am unsure of how to insert that into my proof to get the desired result (Q). Any help would be appreciated
Answer: Indeed $\neg P$ and $P\vee Q$ do entail $Q$ by rule of Disjunctive Syllogism.
This derived rule may be proven using the fundamental rules of Disjunction Elimination and Explosion (aka. ex falso quodlibet).
A contradiction may be derived when assuming $P$, since $\neg P$ is a premise, and $Q$ may be derived from that contradiction, since anything may.
Also $Q$ is trivially derived when assuming $Q$; it is what was assumed.
And from $\neg P, P\vdash Q$ and $Q\vdash Q$ we may infer $\neg P,P\vee Q\vdash Q$ ...
$$\def\fitch#1#2{\quad\begin{array}{|l}#1\\\hline#2\end{array}}\fitch{~~1.~\neg P\\~~2.~P\vee Q}{\fitch{~~3.~P}{~~4.~\bot\hspace{10ex}{\neg}\mathsf E~1,3\\~~5.~Q\hspace{10ex}\mathsf{X}~4}\\\fitch{~~6.~Q}{}\\~~7.~Q\hspace{14ex}{\vee}\mathsf E~2,3{-}5,6{-}6}$$


Using delta method to get confidence intervals for multinomial logit?

Question: I am working with some choice modeling data and am interested in trying to potentially use the delta method with the multinomial logit model that I'm analyzing the data with. Here's an example:
First, I uploaded some data in R:
# First upload and format the data
cbc.df <- read.csv("http://goo.gl/5xQObB",
                   colClasses = c(seat = "factor", price = "factor",
                                  choice="integer"))
cbc.df$eng <- factor(cbc.df$eng, levels=c("gas", "hyb", "elec"))
cbc.df$carpool <- factor(cbc.df$carpool, levels=c("yes", "no"))
summary(cbc.df)

Format data for mlogit package depending on version:
if (packageVersion("mlogit") < "1.1") {
  # for mlogit up through 1.0.3
  cbc.mlogit <- mlogit.data(data=cbc.df, choice="choice", shape="long",
                            varying=3:6, alt.levels=paste("pos", 1:3),
                            id.var="resp.id")
} else {
  # for mlogit starting with version 1.1
  library(dfidx)      # install if needed

  # add a column with unique question numbers, as needed in mlogit 1.1+
  cbc.df$chid <- rep(1:(nrow(cbc.df)/3), each=3)

  # shape the data for mlogit
  cbc.mlogit <- dfidx(cbc.df, choice="choice",
                      idx=list(c("chid", "resp.id"), "alt" ))
}

I think fit a basic multinomial logit model:
# fit the models
library(mlogit)
m1 <- mlogit(choice ~ 0 + seat + cargo + eng + price, data = cbc.mlogit)

Next, I want to predict the probability of making a choice given different combinations of the predictors. I found this function to do that:
# Predicting shares
predict.mnl <- function(model, data) {
  # Function for predicting shares from a multinomial logit model
  # model: mlogit object returned by mlogit()
  # data: a data frame containing the set of designs for which you want to
  #       predict shares.  Same format at the data used to estimate model.
  data.model <- model.matrix(update(model$formula, 0 ~ .), data = data)[ , -1]
  utility <- data.model%*%model$coef
  share <- exp(utility)/sum(exp(utility))
  cbind(share, data)
}

So then I generated some combinations of predictors to generate predictions for:
> # and set up attributes needed later
> attrib <- list(seat  = c("6", "7", "8"),
+                cargo = c("2ft", "3ft"),
+                eng   = c("gas", "hyb", "elec"),
+                price = c("30", "35", "40"))
>
>
>
> (new.data <- expand.grid(attrib)[c(8, 1, 3, 41, 49, 26), ]) # find attrib at top
   seat cargo  eng price
8     7   2ft  hyb    30
1     6   2ft  gas    30
3     8   2ft  gas    30
41    7   3ft  gas    40
49    6   2ft elec    40
26    7   2ft  hyb    35

And finally, get the predictions for these combinations:
> predict.mnl(m1, new.data)
        share seat cargo  eng price
8  0.11273356    7   2ft  hyb    30
1  0.43336911    6   2ft  gas    30
3  0.31917819    8   2ft  gas    30
41 0.07281396    7   3ft  gas    40
49 0.01669280    6   2ft elec    40
26 0.04521237    7   2ft  hyb    35

This share variable is great, but what I'm really wanting is something like a 95% CI for it and I've heard that the delta method could potentially help. I just think that knowing that the first combination has an 11% share is meaningless without knowing the variability in the estimate.
Can anyone help?
Comment: Can I ask did you solve this issue using mlogit and the delta method?
Answer: Sort of not answering your question, but the brms R package covers the multinomial model. E.g. like this brm(bf(y | trials(size)  ~ 1, muy2 ~ x), data = mydata, family = multinomial(), prior = myprior) (see e.g. here). The great thing - assuming you are happy with a Bayesian approach - is that you can then get predictions based on each MCMC sample.
One of the reasons why this gets a lot easier in a Bayesian context is that if you have MCMC samples for some parameters, then to get MCMC samples for some transformation (including adding, subtracting, multiplying etc. the parameters) just requires you to calculate the transformation for each MCMC sample. Then, voilà, you've got pseudo-random samples for the transformation. If you then want to predict for new data, you just draw pseudo-random samples from the outcome distribution for each of the samples from the combination of parameters.
In short, what I'm suggesting is that reflecting uncertainties gets a lot easier, if you take a Bayesian approach. You don't need to derive any results about delta-methods etc., but of course this comes with the downside of people potentially criticizing your prior choices and MCMC sampling taking a bit longer than fitting a model using maximum likelihood.
Comment: Thanks for the response. I know *nothing* about Bayesian stats (except for Bayes' theorem) but it's good to know that it's a possibility in case I can't resolve my problem within a Frequentist framework.


How can I separate my custom config files from default config files provided?

Question: In a server with several packages installed (nginx, php, etc) and configured with .conf files how can I avoid problems with updates that introduce new config parameters? Currently whenever I update, my old config is renamed or overwritten and I have to manually merge the two, which can be tedious.
I develop with SublimeText2 and like how it has Settings - Default and Settings - User separate so I can override settings that I actually want to modify and leave everything else default. Is there a way I could easily do something like this with the packages I install?
Btw, I'm using CentOS 6.
Answer: Use a configuration management system like puppet to make sure your conf files are in sync with the "master version".  Or you could possibly try making your custom conf files immutable after you have them setup how you like (using the chattr +i filename command).
Answer: A big config management system is good, but if you want something lighter weight one of the old-style local source-code management systems (RCS, SCCS) does fine for me.
I put my config files under RCS - it requires nothing more than the tool installing, and for tidiness' sake, mkdir ./RCS in any directory where a config file exists - and I've got the ability to roll back any change made to a config file, or to roll back to any previous version, and a set of logs to tell me what changes I made, when, and why.
That said, though, most yum updates shouldn't overwrite your config files; instead, a new candidate foo.conf.rpmnew should appear.  If this isn't happening for you, you might want to look into why.


Why is CSS ignoring these styles for a specific list element?

Question: I have a pretty straight-forward navigation menu, and I'm trying to style one item differently than the others. However, only the background is applied while other things like border radius and link color are not.
This is the menu:

Page1

Page2

Page3

Extra

These are the generic menu list styles:
.menu ul{ margin:0px; padding:0px;}
.menu ul li{ float:left; background:url(../images/sprator.png) right top no-repeat; padding-right:1px;}
.menu ul li a{display:block; padding:0px 23px; font-size:12px; font-family:Arial, Helvetica, sans-serif; color:#fff; line-height:46px; text-decoration:none; text-transform:uppercase;}
.menu ul li a:hover{ display:block;background: #b04141; /* Old browsers */
background: -moz-linear-gradient(top, #b04141 0%, #c35151 39%, #c35151 62%, #c35151 100%); /* FF3.6+ */
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#b04141), color-stop(39%,#c35151), color-stop(62%,#c35151), color-stop(100%,#c35151)); /* Chrome,Safari4+ */
background: -webkit-linear-gradient(top, #b04141 0%,#c35151 39%,#c35151 62%,#c35151 100%); /* Chrome10+,Safari5.1+ */
background: -o-linear-gradient(top, #b04141 0%,#c35151 39%,#c35151 62%,#c35151 100%); /* Opera 11.10+ */
background: -ms-linear-gradient(top, #b04141 0%,#c35151 39%,#c35151 62%,#c35151 100%); /* IE10+ */
background: linear-gradient(top, #b04141 0%,#c35151 39%,#c35151 62%,#c35151 100%); /* W3C */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#b04141', endColorstr='#c35151',GradientType=0 ); /* IE6-9 */}

And this is what I'm trying to apply to the extra nav element:
.extranav a{
    height:46px;
    color:#FF0000;
    line-height:46px;
    display:block;
    background: #206818; /* Old browsers */
    background: -moz-linear-gradient(top, #024A00 0%, #206818 39%, #347C2C 62%, #3E8636 100%); /* FF3.6+ */
    background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#024A00), color-stop(39%,#206818), color-stop(62%,#347C2C), color-stop(100%,#3E8636)); /* Chrome,Safari4+ */
    background: -webkit-linear-gradient(top, #024A00 0%,#206818 39%,#347C2C 62%,#3E8636 100%); /* Chrome10+,Safari5.1+ */
    background: -o-linear-gradient(top, #024A00 0%, #206818 39%, #347C2C 62%, #3E8636 100%); /* Opera 11.10+ */
    background: -ms-linear-gradient(top, #024A00 0%, #206818 39%, #347C2C 62%, #3E8636 100%); /* IE10+ */
    background: linear-gradient(top, #024A00 0%, #206818 39%, #347C2C 62%, #3E8636 100%); /* W3C */
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#024A00', endColorstr='#3E8636',GradientType=0 ); /* IE6-9 */}
    -moz-border-radius: 0px 0px 10px 0px;
        -webkit-border-radius:0px 0px 10px 0px;
        -khtml-border-radius: 0px 0px 10px 0px;
        border-radius:0px 0px 10px 0px;
}

The background properties are applied properly, while other things like link color and border radius are not. Why is this happening and how do I fix it?
Fiddle: http://jsfiddle.net/68Vb6/
Comment: have you tried to make your selector more specific? (.menu ul li.extranav a)
Answer: The border radius is not part of the style, you have a } that ends the style block before it.
Change this line:
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#024A00', endColorstr='#3E8636',GradientType=0 ); /* IE6-9 */}

to:
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#024A00', endColorstr='#3E8636',GradientType=0 ); /* IE6-9 */

The .menu ul li a selector is more specific than the .extranav a selector, so the settings in the first rule will take precedence. Change the selector to .menu ul li.extranav a to make it more specific.
Comment: Indeed. That fixes that issue, thanks. Still don't understand why the color property isn't applied though, any ideas on that?
Comment: @robert: Check in a tool like Firebug or IE Developer Tools which color style is actually applied. There may be some other rule that interfers.


if chords are not only linked to the major scale, then why scales at all?

Question: I have been playing guitar for years now and I thought I -at least- knew music theory basics... I was told a long time ago that chords were built upon scales notes
yet I stumbled upon this question that states chords are build but upon intervals
Is it correct to say that all common chords are built using the major scales?
then :

how are scales (and solos) related to the chords of a song ?
is it that the only way to play melodies accordingly is to relate on chords notes ?

thanks in advance for the time you'll spend on this question
Comment: First words from the top answer there: "good question, but your assertion is entirely incorrect". So, why do you give it so much credence?
Comment: Please define what you mean by "building a chord". In what situation do you build a chord, for what purpose, what do you take as input when starting to build a chord, and what is the output of the chord building. Do you mean, getting a chord symbol like "E7" and figuring out which notes you should play? Or do you mean, "I think I need a chord here but I don't know what notes I would want to put in it and therefore of course I have no idea what the _chord symbol_ for it would be until after I've selected the notes..." and then you start building the chord i.e. selecting notes for it?
Comment: one example : https://www.edmprod.com/different-chord-types/ so I am tempted to think that ALL chords are based on the major scale, then I wonder, why not the other scales, mino, penta, orientals lidian, myxolidian and stuff..I try to figure the link here..Also I try to understand why all chords are not based on the major scale (from the other SE question)
Comment: Do you mean that for any chord i.e. combination of three or more notes, there should exist a major scale that contains those notes? That obviously cannot be true. Take the dim7 chord as a counter-example https://en.wikipedia.org/wiki/Diminished_seventh_chord    Or do you mean, "which scale does a chord imply?"
Comment: I'd really like to know what the confusion is about here. StackExchange is not doing its job very well if it adds confusion. The linked question feels messy as well and somehow I get the impression that the OP and the answerers did not really understand each other. What does it mean that a chord is "built upon" or "drawn from" something?
Answer: That original question was based on erroneous assumptions. Most of the answers refer to it being questionable.
For starters, there are many, many different scales, the well-loved major being only one.
Scales are our way to label notes - to pigeon-hole them. It's what humans do, and like to do! It could be argued that chords can be made from notes of any scale - they actually are. Especially the chromatic scale, which happens to contain all the notes western music uses (except those bent by guitarists!).
It just happens that with chords, the notes involved can be seen as having intervals between them, so it's one way to establish how certain chords are spelled. As in Dm has a m3 and P5, or Cm7 has m3, P5 and m7 (all calculated from the root).
From what you've stated, we can't get a Cm chord from the C major scale notes - we can from the C minor scale notes, though.
Not all chords can in fact be made up from diatonic notes. C diminished 7 only has one note from C major. It also can't be made from the Cm scale.
On to your question. A piece in, say, key C major will have most of its chords made up from the diatonic C notes. There will be times, though, when other notes need to be used, and that will probably mean using other chords. If there's an A♭ note in the melody, an Fm chord will fit. If it's a G♯, then it could be that C+ is leading to an F chord, so Caug. will fit.
However, with less complex tunes, the diatonic notes will fit the diatonic chords, and vice versa. When I have to solo in B♭, my first thoughts are based in the B♭ major scale notes. If it was a B♭ Blues, I'd be thinking in terms of the two B♭ blues scale notes.
Appertaining to your last question, have a look at many songs. Notice that any bar with a particular chord being played in it will most likely have at least a couple of those same notes in the melody. It's pretty straightforward - the chords fit the melody line, and the melody line fits the chords. That happens most of the time - if it didn't something would sound wrong! I'm not saying that in a bar of C the only notes that will fit will be C E and G, but generally speaking, at least one of those notes will be in the bar - often in a prominent place - 1st or 3rd beats, for instance.
Comment: ok, that brings some light to my poor brain, the issue here is that I try to apply rigid major scale chord building patterns (I ii iii IV V vi vii°) on top of my 20 years experience in intuitive solo playing ... trying to bridge everything together
Answer: A lot of musicians - particularly ones who deal in the sort of music which can usefully have chord symbols (C, Dm, E7, Bm7♭5, E♭maj7♯11 etc.) written above it - base their 'theory' on chord=scale equivalence.  See a C major chord, play notes fron the scale of C major.  See a C minor chord, play the C minor scale.  See E♭maj7♯11 - heck, play E♭ pentatonic, that fits ANYTHING :-) (Though you might like to investigate E♭ Lydian too.)
No, it isn't all based on the major scale.   Maybe, early in your learning, you were shown the chords that ARE built from the major scale.  There are other ones too!
I could go on.  But don't just look at the question you quoted:
Is it correct to say that all common chords are built using the major scales?
look at the answers too.


Otimizar código SQL

Question: gostaria de saber se a uma maneira de eu conseguir otimizar esse código sql (mysql) que eu fiz, a pesquisa está muito lenta, demorando demais pra trazer os campos selecionados, já fiz alguns teste mas continua na mesma.
SELECT
rc470.cod_item as 'Código do Produto',
r0200.descr_item as 'Descrição',
GROUP_CONCAT(DISTINCT rc470.cst_icms) as 'CSTs'

FROM rc470
INNER JOIN r0200
ON rc470.cod_item = r0200.cod_item

GROUP BY rc470.cod_item
HAVING COUNT(DISTINCT cst_icms) >= 2;

Esse código faz uma pesquisa em duas tabela, agrupando os resultados de rc470.cod_item e rc470.cst_icms, onde ele só exibirá apenas os cod_item com mais de um cts_icms diferente e o inner join pra buscar a descrição do produto na tabela r0200 que tem o mesmo cód_item com a tabela rc470.
Espero ter sido claro
Obrigado
Comment: Remove o `DISTINCT` do Group_Concat, isso afeta a performace e é desnecessário
Comment: Desconfio que a lentidão seja causada pelo `group_concat` e `distinct`, vc pode justificar o uso deles? também coloca a estrutura das tabelas, talvez seja possível escrever a consulta de outra forma.
Comment: Se você fizer só `SELECT * FROM FROM rc470
INNER JOIN r0200
ON rc470.cod_item = r0200.cod_item`, quantas linhas voltam e quanto tempo demora a consulta? Você tem uma restrição de chave estrangeira nessa coluna `cod_item`? `cod_item` é a chave primária de alguma das tabelas?
Comment: eu uso o GROUP_CONCAT (DISTINCT coluna) pra ele mostrar apenas os valores diferentes e agrupar os iguais, vou tentar exemplificar melhor com imagens amanhã que terei acesso ao banco, mas obrigado pela dica pessoal.
Answer: Existem algumas maneiras de otimizar a consulta:
Você pode adicionar índices nas colunas usadas nas cláusulas JOIN, GROUP BY e HAVING. Isso pode ajudar a acelerar a consulta, pois permitirá que o banco de dados faça buscas mais rápidas nas tabelas envolvidas. Por exemplo:
CREATE INDEX idx_cod_item ON rc470 (cod_item);
CREATE INDEX idx_descr_item ON r0200 (descr_item);

Você pode revisar a estrutura das tabelas e ver se há alguma forma de simplificar a consulta. Por exemplo, se a tabela rc470 possui muitas linhas com o mesmo cod_item, mas diferentes cst_icms, talvez seja mais eficiente dividir esses dados em duas tabelas: uma para os cod_item e outra para os cst_icms. Dessa forma, a consulta ficaria mais simples e o banco de dados teria menos trabalho para processá-la.
Você pode usar a função EXPLAIN para ver como o banco de dados está processando a consulta. Isso pode ajudar a identificar problemas de desempenho e sugerir maneiras de otimizar a consulta. Por exemplo:
EXPLAIN SELECT
rc470.cod_item as 'Código do Produto',
r0200.descr_item as 'Descrição',
GROUP_CONCAT(DISTINCT rc470.cst_icms) as 'CSTs'

FROM rc470
INNER JOIN r0200
ON rc470.cod_item = r0200.cod_item

GROUP BY rc470.cod_item
HAVING COUNT(DISTINCT cst_icms) >= 2;

Você pode usar a função LIMIT para limitar o número de linhas retornadas pela consulta. Isso pode ser útil se você só precisa de uma pequena parte dos dados e não precisa de todas as linhas da tabela. Por exemplo:
SELECT
rc470.cod_item as 'Código do Produto',
r0200.descr_item as 'Descrição',
GROUP_CONCAT(DISTINCT rc470.cst_icms) as 'CSTs'

FROM rc470
INNER JOIN r0200
ON rc470.cod_item = r0200.cod_item

GROUP BY rc470.cod_item
HAVING COUNT(DISTINCT cst_icms) >= 2
LIMIT 1000;

Você pode usar a função SELECT INTO OUTFILE para salvar os resultados da consulta.

Otimizar código SQL


How do I apply loop into node twig template?

Question: This is code I am using.

{{ content.field_article_main_content[0] }}

{{ content.field_article_main_content[1] }}

How can I change that code to make it loop over content.field_article_main_content?
Answer: I would use code similar to the following one.

  {% for key, item in content.field_article_main_content %}
    {% if key == 0 %}

{{ content.field_article_main_content[key] }}

    {% else %}

{{ content.field_article_main_content[key] }}

    {% endif %}
  {% endfor %}

If it happens that some values of key start with #, then I would use the following code.

  {% for key, item in content.field_article_main_content if key|first != '#' %}
    {% if key == 0 %}

{{ content.field_article_main_content[key] }}

    {% else %}

{{ content.field_article_main_content[key] }}

    {% endif %}
  {% endfor %}


What is Bootstrapping in statistics? How can I use it to determine error in the mean, variance, kurtosis and skewness of a data set?

Question: From what I understood from searching randomly is that it has something to do with resampling. What does this resampling mean? Is it selecting random data from a distribution or is it getting data from somewhere else?
Comment: I think you should google a bit more....
Answer: Bootstrapping, very briefly, means that you repeatedly resample (with replacement) from the data you have and compute a statistic on each sample. Then you combine the statistics
However, many entire books have been written on bootstrapping.
Comment: I'll add that Efron and Tibshirani's book is marvelously written and great fun to read.
Comment: There is some ambiguity in this answer: exactly what is being "combined" at the end?  Samples?  "Estimated" statistics? (Don't you really mean *compute* instead of *estimate*?) In any case, *how* would the combination be done and for what purpose?


How to write a function for different sample sizes to do same task

Question: I have written some functions in R with different sample sizes and will like to have an anova fit for each of the sample sizes. Please can anyone help me as to how to write a code that does it once for each one of them? ns represents the different sample sizes.
ns=c(16,18,22,30)
x=rnorm(ns/2,2,5)
y=rnorm(ns/2,0,1)
yy=c(y,x)
xx=c(rep(0,ns/2),rep(1,ns/2))
fitt=lm(yy~xx)
anova(fitt)
(ns/2-1)*var(x)+(ns/2-1)*var(y))/((2*ns/2)-2)

Comment: What is exactly the output you are looking for? The whole `anova` or some parts of it? Also, what does this line do and do you need its output too? `(ns/2-1)*var(x)+(ns/2-1)*var(y))/((2*ns/2)-2)`. Please post a desired output
Comment: Alright please take out the last statement but what I want is the anova(fitt) for 16, that for 18 and so on up to 30, writing a program to do it once rather than one after the other.
Answer: Something like that?
loopAnovafunc <- function(temp) {
  x <- rnorm(temp/2,2,5)
  y <- rnorm(temp/2,0,1)
  yy <- c(y,x)
  xx <- c(rep(0,temp/2),rep(1,temp/2))
  fitt <- lm(yy~xx)
  anova(fitt)
}

ns <- c(16,18,22,30)
lapply(ns, loopAnovafunc)

Comment: Thanks David but can you please explain the last part of the output