correlation analysis for big data set

Question: I am doing a pairwise correlation for 20,000 genes. I used the rcorr function in Hmisc package. Then, I extracted the pvalues and correlation coefficient values from the result object. I applied FDR correction for the pvalues and did not get a significant gene below the 0.05 cutoff. However, almost 80 % of the genes have strong correlation coefficients(>= 0.9).
The structure of my data and the code I used are simulated below. If my data and code are correct, I wonder why I did not get a single correlated gene after FDR correction, while most genes show a strong correlation?
set.seed(1)
    A <- data.frame(rnorm(100),
                    rnorm(100),
                    rnorm(100),
                    rnorm(100),
                    rnorm(100))
    row.names(A) <- paste0("G_", 1:100)
    colnames(A) <- paste0("S_", 1:5)

    set.seed(42)
    B <- data.frame(rnorm(100),
                    rnorm(100),
                    rnorm(100),
                    rnorm(100),
                    rnorm(100))
    row.names(B) <- paste0("I_", 1:100)
    colnames(B) <- paste0("S_", 1:5)

    library(dplyr)
    library(Hmisc)
    library(reshape2)
## Bind the rows
    all <-bind_rows(A, B)
    ## Correlation as transposed matrix
    result <- rcorr(as.matrix(t(all)))
    hist(result$P,br=100)
    ath.p <- round(result$P,3)
## Extract the top right block of the matrix
    ath.pp <- ath.p[1:100, 101:200]
    cor <- melt(as.matrix(ath.pp))
    p.adj <- p.adjust(cor$value, method = "BH")
    ath.data <- cbind(cor,p.adj)
    at <- ath.data %>% filter(value >=0.05)

## Correlation coff
    ath.r <- round(result$r,3)
## Extract the top right block of the matrix
   ath.rr <- ath.r[1:100, 101:200]
   cor.r <- melt(as.matrix(ath.rr))

Comment: I tried to address the issue in the post below. Quite honestly... the above code you have, will give you a all null hypothesis.. so you need to provide context about your data
Answer: This part of the code is quite problematic:
ath.p <- round(result$P,3)

If you have a p-value < 0.001 it gets rounded to zero.. which would be grossly wrong.
round(1e-04,3)
[1] 0

It should not affect your result that there's no significance. However, looking at the code, note that you are doing a correlation between matrices and not a pairwise comparison.
What exactly are these two matrices and why would you expect a correlation between the genes from two different group of samples? You need to provide this context in your question!!!!!
Below I can use an example dataset, and the pairwise correlation within a sample will show p.values that pass the adjustment. The correlation between samples, because they are not related in any sense, should show much much lesser:
library(Hmisc)
library(multtest)
library(reshape2)
library(dplyr)
data(golub)

mat = golub
rownames(mat) = paste0("G",1:nrow(mat))
#split the samples up randomly
m1 = mat[,seq(1,ncol(mat),2)]
m2 = mat[,seq(2,ncol(mat),2)]

test = rcorr(t(rbind(m1,m2)))

n = nrow(m1)

If we look at the pairwise comparison within the sample, I am sure you get p-values that pass the FDR (i excluded the self correlation here):
results = melt(test$r[1:n,1:n],value.name ="pcc") %>%
filter(Var1!=Var2)%>%
left_join(melt(test$P[1:n,1:n],value.name ="p"),by=c("Var1","Var2"))

If you look at the histogram of p values, you see an enrichment of low p-values, indicating this will pass the FDR (as it deviates from an all null hypothesis). This plot is missing from your actual data:
hist(results$p,br=100)

table(p.adjust(results$p,"BH")<0.05)

  FALSE    TRUE
9258610   46940

Now if we look at the correlation between the matrices:
results = melt(test$r[1:n,(n+1):(2*n)],value.name ="pcc") %>%
left_join(melt(test$P[1:n,(n+1):(2*n)],value.name ="p"),by=c("Var1","Var2"))

head(results)
  Var1 Var2         pcc         p
1   G1   G1  0.28368867 0.2391968
2   G2   G1  0.11289293 0.6454033
3   G3   G1 -0.03138222 0.8985162
4   G4   G1 -0.11531721 0.6382801
5   G5   G1 -0.11807959 0.6302003
6   G6   G1 -0.10628946 0.6649551

hist(results$p,br=100)

You can appreciate that there are less enrichment in smaller p-values, and of course if you do FDR, you get less:
table(p.adjust(results$p,"BH")<0.05)

  FALSE    TRUE
9308363     238

Comment: I am satisfied with your detailed explanations! Basically, I am doing this analysis to get an idea if genes of two tissues in the same patients(T2D) show correlation or not? Doing the same analysis for other patients (patients with kidney diseases or hypertension ) and compare correlated genes in a network graph. Therefore, the gene correlation exists in the two tissues of the three different disease state can be compared. I really would like to get some advice if this is the wrong way to go. Thank you!
Comment: Ok yes if they are the same patients, different tissues, it make sense. The issue is do you have enough samples to make this correlation
Comment: Yes, that is the issue! However, how many samples it should be to satisfy the assumption? I have 6-10 samples.   Thanks!
Comment: might be too little considering you are testing 20000x20000. Suggest you try to narrow down to like 3000 genes. for one you can eliminate genes that are expressed in 1 tissue and not the other
Comment: If I may ask one more time here,  how you advise me to extract those 238 significant genes from the matrix test$r[1:n,(n+1):(2*n)] for heatmap and network plot?. Some lines of codes would be pretty much helpful! Thank you!
Comment: Hi @DowithR, i am afraid that's a different question altogether. You can try posting it as another question,using the example I have. Have I answered your question above?
Comment: If I could able to extract those 238 significant genes from the matrix test$r[1:n,(n+1):(2*n)], then the heatmap and other staff I can do it. Thanks!
Comment: try ```sig = droplevels(results[p.adjust(results$p,"BH")<0.05,]) ; results %>% filter(Var1 %in% sig$Var1 & Var2 %in% sig$Var2) %>% recast(Var1 ~ Var2,data=.,measure.var="pcc")```
Comment: Thank you so much!

correlation analysis for big data set


On the method of computing integrals

Question: Question
Let $\mathcal{B}$ be the entire Borel set of $\mathbb{R}$. And let $\chi_E$ be the indicator function of the set $E$.
$(X, m, \mu)$; measure space, map $f: X \to \mathbb{R}$; measurable.
For $A \in \mathcal{B}$, we define
$$
\lambda(A) = \mu(f^{-1}(A)).
$$
When $g = \chi_E$, $E \in \mathcal{B}$, the following equation transformation holds:
$$
\int_{\mathbb{R}} \chi_E\ d\lambda = \lambda(E) = \mu(f^{-1}(E)) \overset{?}{=} \int_{X} \chi_E \circ f\ d\mu.
$$
Why is the third equal sign valid?
What I know
$\chi_E \circ f = \chi_E(f)$,
$\int_{X} \chi_E \circ f\ d\mu = \mu((\chi_E \circ f) \cap X)$.
Answer: $\chi_E \circ f$ is not exactly $\chi_E(f)$, as the input set of $\chi_E$ is $\mathbb{R}$. Moreover, your formula $\int_{X} \chi_E \circ f\ d\mu = \mu((\chi_E \circ f) \cap X)$ doesn't make sense as $(\chi_E \circ f) \cap X$ is not a set as $(\chi_E \circ f)$ is a function and not a set.
More precisely, $\chi_E \circ f$ is a function from $\mathbb{R}$ to $\mathbb{R}$ defined by
$$\forall x \in \mathbb{R}, \quad (\chi_E \circ f) (x) = \chi_E(f(x)).$$
Therefore we can see that $(\chi_E \circ f)= \chi_{f^{-1}(E)}$. Indeed, for $x \in \mathbb{R}$,
$$\begin{array}{lll}
 (\chi_E \circ f) (x) &=& \chi_E(f(x)) \\
&=& \left\{\begin{array}{lll}1 &\text{si }f(x) \in E \\ 0 &\text{otherwise} \end{array} \right. \\
&=& \left\{\begin{array}{lll}1 &\text{si }x \in f^{-1}(E) \\ 0 &\text{otherwise} \end{array} \right. \\
&=& \chi_{f^{-1}(E)}(x)
\end{array}$$
Therefore we get
$$\mu(f^{-1}(E)) = \displaystyle\int_X \chi_{f^{-1}(E)} d\mu = \displaystyle\int_X \chi_E \circ f d\mu.$$
Comment: Thank you for letting us know about the mistake! I understood.

On the method of computing integrals


Can we describe nicely all the rational numbers of the form $x^{2}-xy+y^{2}$?

Question: Let $\zeta$ be a primitive cubic root of unity, i.e., $\zeta$ is a complex number such that $\zeta^{3}=1$ and $\zeta\neq1$.
Let us consider the Galois extension $\mathbb{Q}(\zeta)/\mathbb{Q}$ (the Eisenstein field) and the norm map given by
\begin{equation}
N(a+b\zeta)=a^{2}-ab+b^{2},
\end{equation}
where $a$ and $b$ are rational numbers.
Since the norm defines a homomorphism on the multiplicative groups $\mathbb{Q}(\zeta)^{\times}\to\mathbb{Q}^{\times}$, we know already that the image will be a multiplicative subgroup of $\mathbb{Q}^{\times}$. Can we describe this group nicely?
I've tried putting some values and trying to figure out the form of this group inside $\mathbb{Q}^{\times}$, but I can't really see a pattern going on. Taking primes $p\equiv 2\pmod3$, we can see that this norm map is not surjective, but I don't know the group $\mathbb{Q}^{\times}$ really well to know its subgroup structure.
I'd guess that Global Class Field Theory gives an answer to this question, but I don't know much about it.
Thanks for any help or references.
Comment: Since this is a quadratic form, the elements of the group are completely determined by Hasse-Minkowski principle: as long as there are $p$-adic solutions to $x^2-xy+y^2 = a$ for each $p$ (and a real solution), then there is a rational one.  In this case I believe it amounts to "$a > 0$ and no prime of the form $3k+2$ occurs to an odd power in $a$".
Comment: @Shoutre Just consider the homogeneous equation $f(x,y) - az^2 = 0$ where $z$ is a third variable.
Comment: what exactly is a norm map? Is it "just a homomorphism" from the extension field to the base field? I've never seen this before. Thanks!
Comment: If $L$ is a finite extension of $\mathbb{Q}$, you can the norm of an element $x\in L^{\times}$ as $N_{L}(x)=\prod \sigma(x)$, where $\sigma$ varies through the field automorphisms $L\to L$. If the extension is "well-behaved" in a certain sense (Galois extensions), then there are $[L\colon K]$ such automorphisms. In $\mathbb{Q}(\zeta)=\{a+b\zeta\}$ the automorphisms are given by $\varphi_{1}\colon \zeta\to\zeta$ and $\varphi_{2}\colon \zeta\to\zeta^{2}$. So, we have $N(a+b\zeta)=(a+b\zeta)(a+b\zeta^{2})$, which gives the question homomorphism when you use $\zeta^{2}=-1-\zeta$
Comment: Thanks for your comment. I was looking for some argument (ideally) that would cover also higher degree fields, where the norms are no longer quadratic forms, but I guess this is a difficult problem in general. Thanks, though.
Comment: @Shoutre, that is super interesting. How does such a construction come up naturally?
Comment: @Erick Wong Wait a minute, Hasse Minkowsky only applies to f(x,y)=0, right? So if we let this $a$, it looks like it is no longer a quadratic form.
Comment: @Siddharth Bhat Galois theory.
Comment: @Shoutre - which part? I've done some undergrad level Galois Theory and I haven't seen this before
Comment: @SiddharthBhat I think it is a standard topic in field/Galois theory. It is useful for many things. For example, $3$ cannot be written as a product of two non-invertible elements in $\mathbb{Z}[i]$, since $3=(a+bi)(c+di)$ would imply (applying norms) that $3^{2}=(a^{2}+b^{2})(c^{2}+d^{2})$ for integers $a,b,c,d$, which you can easily verify it is not possible. The fact that invertible elements in $\mathbb{Z}[i]$ are the guys with norm $= 1$ is also a good exercise.
Answer: The idea is to reduce the problem to integer arithmetic. Since $\mathbb Q(\zeta)$ is the field of fractions of $\mathbb Z[\zeta]$, we can write $$x+y\zeta = \frac{a+b\zeta}{c+d\zeta}$$
where $x,y\in\mathbb Q$ and $a,b,c,d\in \mathbb Z$, and where the numerator and the denominator on the right hand side are coprime. Here we are using the fact that $\mathbb Q(\zeta)$ has class number $1$.
In particular, $\frac mn\in\mathbb Q^\times$ (written in lowest terms) is a norm from $\mathbb Q(\zeta)^\times$ if and only if $m,n$ are both norms from $\mathbb Z[\zeta]$.
We can calculate using quadratic reciprocity that a prime $p$ is a norm from $\mathbb Z[\zeta]$ if and only if $p=3$ or $p\equiv 1 \pmod 3$. It follows that $$n = p_1^{e_1}\cdots p_k^{e_k}$$
is a norm from $\mathbb Z[\zeta]$ if and only if $e_i$ is even whenever $p_i\equiv 2\pmod 3$. (Note that all norms are positive in this case.)
We deduce that the image $N(\mathbb Q(\zeta)^\times)$ is the subgroup of $\mathbb Q^\times$ generated by $$\{p:p\equiv 1\pmod 3\}\cup\{3\}\cup\{p^2 : p\equiv 2\pmod 3\}.$$

To illustrate the difficulty of generalising this when $K$ does not have class number $1$, neither $2$ nor $3$ are norms from $\mathbb Z[\sqrt{-5}]$, but $$\frac 32 = \frac 64 =N\left(\frac{1+\sqrt{-5}}2\right) .$$
We can get around this by considering factorisation of ideals. Let $K$ be a number field, and let $x\in K^\times$. Write
$$(x) = \frac{\mathfrak a}{\mathfrak b},$$
where $\mathfrak{a,b}$ are coprime ideals of $\mathcal O_K$. Since $\frac{\mathfrak a}{\mathfrak b}$ is principal, both $\mathfrak a$ and $\mathfrak b$ lie in the same class of the ideal class group. In particular, we can find some integral ideal $\mathfrak c$ such that $\mathfrak{ac}$ and $\mathfrak {bc}$ are both principal.
Hence,
$$|N(x)| = \frac{N(\mathfrak a)}{N(\mathfrak b)}=\frac{N(\mathfrak {ac})}{N(\mathfrak {bc})}=\frac{|N(a)|}{|N(b)|},$$ for some $a,b\in\mathcal O_K$.
It follows that the image $|N(K^\times)|\subset \mathbb Q_{>0}^\times$ is generated by the elements of $\mathbb Z$ which are norms from $\mathcal O_K$. There should be some way to sort out the issue with signs.
Answer: In dealing with rational values of rational binary quadratic forms, I think that it's much simpler to use Hasse's norm principle for cyclic extensions in place of the Minkowski-Hasse principle for quadratic forms suggested by @Erik Wong (but of course both principles come from CFT). Everything is known « in a nice way » according to the following process :
Diagonalizing the quadratic form if necessary, we are led to solve the equation $a = x^2+ dy^2$ in $\mathbf Q$, where $d$ is a given square free rational number, or equivalently to solve the normic equation $a = N(\alpha)$, where $N$ denotes the norm map from $K = \mathbf Q(\sqrt –d) $ to $\mathbf Q$. Hasse's principle asserts that $a$ is a global norm in $K/\mathbf Q$ iff $a$ is a norm in all the local extensions $K_v/\mathbf Q_{p}$, where $\mathbf Q_{p}$ is the field of $p$-adic numbers (resp. $\mathbf R$) if $p$ is a finite (resp. the infinite) prime, and $K_v$ is the completion of $K$ at a prime $v$ above $p$. The local condition at $v$ is equivalent to $(a, d)_p$ = 1, where $(a, d)_p$ is the Hilbert symbol at $p$ (which generalizes the Legendre symbol), and this latter criterion is effective in the sense that we have explicit formulae for the Hilbert symbol, and moreover we need to compute only a finite number of them. All this is explained in great detail e.g. in chapters II and III of Serre's « A Course in Arithmetic ». Note that we don't need to suppose that the class number of K is 1 as in the case treated by @Mathmo123.
Going a step further, we can ask for integral values of integral binary quadratic forms, as e.g. in the questions posted by  @Henry and @Kieren MacMillan. This is  genuine arithmetic, which needs CFT over the quadratic field $K$, and no longer above $\mathbf Q$ alone.. See e.g. D. Cox's  book « Primes of the form $x^2 + ny^2 »$.


modulus of continuity

Question: the Hölder $\rho$-continuity is defined as
$$|f(x)-f(y)| \leq K_1 |x-y|^\rho.$$
I'm doing a research problem right now and might need the following condition
$$K_2 |x-y|^\rho\leq|f(x)-f(y)| \leq K_1 |x-y|^\rho,$$
where both $K_1$ and  $K_2$ are constants.
My question is, is it a high requirement to assume the left hand side of above condition?
Answer: If $\rho<1$ there are no such functions!
Assumme $f:\Bbb R\to \Bbb R$ and $|x-y|^{1/2}\le|f(x)-f(y)|$. Say $f(0)=0$. Now for every $x>0$ either $f(x)\ge x^{1/2}$ or $f(x)\le-x^{1/2}$. By continuity, wlog $$f(x)\ge x^{1/2}\quad(x>0).$$
Fix $x>0$ for a second. If we had $f(x+y)\le f(x)-y^{1/2}$ for every $y>0$ then large $y$ would contradict the previous inequality. So $$f(x+y)\ge x^{1/2}+y^{1/2}\quad(x,y>0).$$By induction $$f\left(\sum_{j=1}^nx_j\right)\ge\sum_{j=1}^nx_j^{1/2}\quad(x_j>0).$$Now $1=\sum_{j=1}^n1/n$ implies that $f(1)=\infty$.

Similarly there is no $f:[0,1]\to\Bbb R$ such that $|x-y|^{1/2}\le|f(x)-f(y)|\le c|x-y|^{1/2}$. As before we can assume that $f(x)\ge x^{1/2}$. Now above we needed large $y$ to get a contradiction from $f(x+y)\le f(x)-y^{1/2}$. Under our current assummptions this inequality implies $f(x+y)\le cx^{1/2}-y^{1/2}$, giving a bound on how large $y$ has to be to get that contradiction; if $x>0$ is small enough then we get a contradiction from $y=1-x$. If I did the sums correctly it seems to me that we have $$f(x+y)\ge x^{1/2}+y^{1/2}\quad(x,y>0,x+y<\delta)$$where $\delta=1/(1+(c-1)^2)$. This leads to $f(\delta)=\infty$ as before.
Answer: Your question is very vague and depending on the context, you will get different answers. I think it is reasonable to make such an assumption to derive a technical result. At the very least, it is a starting point towards understanding and deriving properties of the problem you are working on. Later, you can try relaxing this assumption.
For what it is worth, I will mention one well-known example where such a condition is imposed in the theoretical analysis of an algorithm, namely the convergence of gradient descent for convex, differentiable functions.
In particular assume that you want to minimize $f(x)$, $x \in \mathbb R^n$, where $f$ is convex, differentiable function. One possibility is to use the gradient descent algorithm. Under suitable choices of the step-size, the algorithm then can be shown to converge at a linear rate, if the gradient of $f$ is Lipschitz with constant L>0, i.e.
$$\vert\vert \nabla f(x) - \nabla f(y) \vert \vert_2 \leq L \vert\vert  x-y\vert\vert_2$$
OTOH, the convergence can be shown to be exponentially fast, when $f$ is also strongly convex with modulus $m>0$ ($m<L$). This is equivalent to the following condition:
$$m \vert\vert  x-y\vert\vert_2 \leq \vert\vert \nabla f(x) - \nabla f(y) \vert \vert_2 \leq L \vert\vert  x-y\vert\vert_2$$
So this is an example where a requirement like the one you stated is used in the theoretical analysis of an algorithm.
Comment: Thank you for your detailed response. I'm trying to prove some convergence rate. If I only assume the primitive Holder $\rho$ continuity, I can show the upper bound. But if I hope to show the lower bound as well, I need the left hand side inequality. That's why I post this question.
Comment: Ok! Well then this is a valid reason to use the lower inequality I think (as long as $\rho \geq 1$ of course, compare to the post of David Ullrich). But I think for research level type problems, your advisor will be the most appropriate one to tell you whether such an assumption is too restrictive or not.
Comment: Thank you. I just want to gain some broader insight before talking to my advisor.

modulus of continuity


React Functional component unmount

Question: I want to rewrite this component https://github.com/josdejong/jsoneditor/blob/master/examples/react_advanced_demo/src/JSONEditorReact.js
to a functional component.
I made this:

const Editor = ({json, mode, onChange}) => {
  const elRef = useRef(null);

  useEffect(() => {
    const options = {
      onChangeText: onChange,
      onChangeJson: onChange,
    };

    const jsonEditor = new JSONEditor(elRef.current, options);
    if (jsonEditor) {
      if (json) {
        jsonEditor.set(json);
      }

      if (mode) {
        jsonEditor.setMode(mode);
      }
    }

    return () => {
      if (jsonEditor) {
        jsonEditor.destroy();
      }
    }
  },[json,mode]);

  return (

  )
}

export default Editor;

My question is next: Is it correct to unmount the component jsonEditor.destroy(); inside that useEffect with [json, mode] dependancies or i should create another useEffect with empty dependancy array to get the same behaviour as in class component?
Answer: What you're doing is fine provided that destroying and rebuilding the JSONEditor doesn't take discernible time or cause a visual twitch that's apparent to the user. The editor will be cleaned up when the component is unmounted.
But, since it seems to allow you to change mode and JSON on an existing instance (based on the API), I think I'd do that rather than completely destroying it and rebuilding it when those change:
const Editor = ({json, mode, onChange}) => {
  const elRef = useRef(null);
  const edRef = useRef(null);

  useEffect(() => {
    // On mount
    const options = {
      onChangeText: onChange,
      onChangeJson: onChange,
    };

    const jsonEditor = edRef.current = new JSONEditor(elRef.current, options);
    if (json) {                 //
      jsonEditor.set(json);     // I don't think you actually need these here,
    }                           // I *think* `useEffect` callbacks are run in
    if (mode) {                 // order so the below will do it. But...
      jsonEditor.setMode(mode); //
    }                           //

    return () => {
      // No `if`, you *know* it exists
      jsonEditor.destroy();
      edRef.current = null;
    }
  }, []);

  useEffect(() => {
    const jsonEditor = edRef.current;
    if (!jsonEditor) { // I don't think this can happen
      return;
    }
    if (json) {
      jsonEditor.set(json);
    }
    if (mode) {
      jsonEditor.setMode(mode);
    }
  }, [json, mode]);

  return (

  );
};

export default Editor;

But that's more complicated, so if what you're doing works well and provides the user experience you want, you might want to leave it alone.

React Functional component unmount


How can I add datepicker into jQuery modal dialog box in Rails?

Question: I add a datepicker into my modal dialog box. but when I click on the date picker, it always display behind the modal dialog box. How can I load it inside the jQuery modal dialog box? Following is my code to load date picker...
<code><%= calendar_date_select_tag "event[start_at]", "", :valid_date_check => "date.getDay() != 0 && date.getDay() != 6  && date.stripTime() > (new Date()).stripTime()" %>
</code>
I am using date picker plug-in in my application..
Comment: Try making the datepicker css z-index higher than the modal's
Comment: @ Barlow can u put this as an answer? thank u.. it is working now..
Answer: Sounds like the z-index of the modal box is higher than the datepicker
make the css z-index for the datepicker higher than the modal box.
example css:
<code>.modal {
  z-index: 9990;
}

.datepicker {
  z-index: 9999;
}
</code>
Hope this helps.


Definition of the gamma function along different paths

Question: Consider the gamma function $\Gamma(z)=\int_0^{\infty}x^{z-1}e^{-x}dx$, here $\Re(z)>0$.
Let $C$ be the path from $0$ to $ti$ and then from $ti$ to $\infty+ti$, where $t>0$ is a fixed number.
If I define $\Gamma_1(z)=\int_Cs^{z-1}e^{-s}ds$, here the $\log(s)$ is the continuation of the real $\log(x)$ on $\{x>0\}$ along the counterclockwise direction.
Then would the two function equals, or do they have any relations? Especially when $0<\Re(z)<1$.
Comment: By Cauchy's theorem, $\Gamma_1=\Gamma$ since your integrand is analytic when $s \in \mathbb{C}\setminus \left( { - \infty ,0} \right]$.
Comment: @Gary But at $s=0$ a 'pole' of integral may exsits, so I'm not sure.
Comment: You can argue that they coincide for $\Re z >1$ (the integrand will be continuous at $s=0$, so the (general) Cauchy theorem applies), and that they are both analytic for $\Re z>0$.
Comment: @Gary Great, thank you.
Answer: They will coincide for ${\rm Re}\,z>0$ since the integral is convergent in this range of $z$.
Actually, we have the full course on complex analysis on edX.
https://www.edx.org/course/complex-analysis
The registration opened two days ago. It has a special chapter on analytic continuation with the help of contour deformation.
The welcome video on the course is here:
https://youtu.be/2aHEqRUYBUE


Should I rather explicitly run programs in foreground (instead as a daemon), or `expect fork` when configuring upstart daemons?

Question: Many programs allow to be run either in daemon mode (which is usually the default), or explicitly run it in foreground with a flag such as -f.
Now when configuring upstart to run programs like this, I can either do
exec foo -f # run in foreground

or
expect fork
exec foo # automatically runs as a daemon

Is there a reason to choose one over the other? It feels that it's just easier to run everything in foreground and let upstart handle the processes, but is there a downside to that?
Comment: The answer would depend on end-use, no? The foreground option is often provided as an easy way to debug what the daemon is doing.
Answer: I strongly prefer to run things in the foreground; it avoids any complications that may arise from the daemonisation process (such as upstart losing track of the long-running daemon process).  The only exception to this is a small minority of daemonising programs which have the unpleasant habit of interpreting "please run in the foreground" as "please run in some sort of poorly-performing debug mode", and do something silly like run only one thread, or don't spawn child workers, or some such.


Como salvar uma imagem com pyplot?

Question: Estou tentando salvar um gráfico com resolução de 300 dpi no pyplot
python, mas no arquivo salvo resulta numa imagem toda preta.
Aqui está meu código:
import matplotlib.pyplot as plt

xa = [0, 1, 2, 3, 4, 5, 6]
ya = [0, 2, 4, 6, 8, 10, 12]
xb = [0, 2, 4, 6, 8, 10, 12]
yb = [0, 4, 6, 10, 12, 18, 20]
xc = [5, 7, 9, 11, 13]
yc = [0, 1, 2, 3, 4]

plt.plot(xa, ya, label='A', ls='dashed', color='k', marker='o') #plot ensaio A
plt.plot (xb, yb, label='B', ls='-.', color='k', marker='s') #plot ensaio B
plt.plot (xc, yc, label='C', ls=':', color='k', marker='^') #plot ensaio C

plt.ylabel('produto')
plt.xlabel('Time (h)')
plt.title('(a)')
plt.legend()

plt.show()
plt.savefig ("produto.png", dpi=300)

Quando vou verificar o arquivo que foi salvo, está em formato png mas uma tela preta aparece, como se fosse uma foto inteira preta
não consegui identificar meu erro, o código roda normalmente sem gerar erros ou alertas.
Answer: Na documentação do método matplotlib.pyplot.show() há uma orientação a respeito do uso do método matplotlib.pyplot.show() em conjunto do método matplotlib.pyplot.savefig(). Segue a tradução livre da orientação:

Salvando figuras em arquivo e mostrando uma janela ao mesmo tempo
Se você quiser um arquivo de imagem e uma janela de interface do
usuário, use pyplot.savefig() antes de usar pyplot.show().    Ao
final de pyplot.show()(em modo blocante) a figura é fechada e
portanto não registrada do pyplot. Chamar pyplot.savefig após
pyplot.show() salvaria uma nova e portanto vazia figura.    Esta
limitação de ordem de comando não se aplica se o show não for
bloqueante ou se você mantiver uma referência à figura e usar
Figure.savefig.

Então segundo essa orientação basta salvar a imagem no arquivo antes de exibir o gráfico com pyplot.show() que obterá o resultado desejado.
import matplotlib.pyplot as plt

xa = [0, 1, 2, 3, 4, 5, 6]
ya = [0, 2, 4, 6, 8, 10, 12]
xb = [0, 2, 4, 6, 8, 10, 12]
yb = [0, 4, 6, 10, 12, 18, 20]
xc = [5, 7, 9, 11, 13]
yc = [0, 1, 2, 3, 4]

plt.plot(xa, ya, label='A', ls='dashed', color='k', marker='o')
plt.plot (xb, yb, label='B', ls='-.', color='k', marker='s')
plt.plot (xc, yc, label='C', ls=':', color='k', marker='^')
plt.ylabel('produto')
plt.xlabel('Time (h)')
plt.title('(a)')
plt.legend()

#Apenas salve a figura no arquivo antes de exibir o gráfico.
plt.savefig ("produto.png", dpi=300)
plt.show()

Teste o exemplo acima no Replit
Comment: +1. É como sempre insisto, antes de usar algo comecem pela documentação, muitos erros seriam evitados se as pessoas ao invés de seguir algo como se fosse uma *receita de bolo*, gastassem um tempo lendo instruções técnicas.

Como salvar uma imagem com pyplot?


pegar valor espcefico de um texto do tipo string [PYTHON]

Question: Eu estou tentando pegar o valor especifico de um retorno que fiz usando requests
O python retornou todo o HTML do site no print(return.text), mas eu quero pegar somente esse input:
<input class="give-input required" type="text" name="descricao" autocomplete="given-name" placeholder="First Name" id="descricao" value="Roberta Bellamy" required="" aria-required="true">

Sou novo no python!
Comment: Aqui está o input que quero atribuir uma variavel a ele:
Comment: Seja Bem Vindo ao SOpt, recomendo dar uma passada pelo nosso [tour](https://pt.stackoverflow.com/tour), e ler um pouco sobre o [Mínimo, Completo e Verificável para criar perguntas](https://pt.stackoverflow.com/help/mcve). Da maneira que está, o código não pode ser reproduzido e testado. O que você já conseguiu fazer?
Comment: Mas independentemente do que seja o HMTL completo e o seu código, acredito que você possa usar [regex](https://docs.python.org/3/library/re.html), [manipulação de strings](https://docs.python.org/3/library/stdtypes.html#string-methods) ou até a biblioteca [BeautifulSoup](https://www.crummy.com/software/BeautifulSoup/bs4/doc/).
Answer: Mesmo que não tenha posto informação suficiente, vou demonstrar como é fácil fazer isso com o BeautifulSoup.
O BeautifulSoup é uma biblioteca focada em webscrapping, na busca de dados em HTML e XML. A utilização é simples. No caso, depois de instalar (pip install bs4), você importa no bs4 a classe principal BeautifulSoup e a instancie com um html e um parser de preferência (como html.parser ou o lxml).
Para encontrar uma tag específica, indique o número mínimo de informações para achar aquela única tag ao invés de várias do mesmo tipo.
Traduzindo para um código pronto seria:
from bs4 import BeautifulSoup

textoHTML = '<input aria-required="true" autocomplete="given-name" class="give-input required" id="descricao" name="descricao" placeholder="First Name" required="" type="text" value="Roberta Bellamy"/>' #SEU HTML ARQUI

soup = BeautifulSoup(textoHTML, 'html.parser')

print(soup.find("input", class_=['given-input', 'required'], id='descricao'))
# IMPRIME: <input aria-required="true" autocomplete="given-name" class="give-input required" id="descricao" name="descricao" placeholder="First Name" required="" type="text" value="Roberta Bellamy"/>

Answer: Você pode usar o replace para remover as tags desta forma:
linha1 = "
Conceito e Significado de Texto.
"
linha2 = "
Geralmente, entendemos o texto como um conjunto de frases
"

linha1 = linha1.replace('','').replace('','')
linha2 = linha2.replace('','').replace('','')

print(linha1)
print(linha2)

Saída:

Conceito e Significado de Texto.

Geralmente, entendemos o texto como um conjunto de frases

Comment: Se quiser remover também as `tags` de parágrafo poderia fazer desta forma: `linha1.replace('','').replace('','').replace('','').replace('','')`


Lattice of interval

Question: I would like to create a lattice of intervals of integers, but I don't know how to 'draw'(Hasse diagram) it.
An interval looks like: [1,4] or ]-Inf,3] for example.
I'm having difficulties deciding what should be bottom and top, and what should be in between.
Some join/meet rules that should hold:
join
[0,10]⊔[15,20]=[0,20]
[0,10]⊔[5,7]=[0,10]
meet
]−∞, 10] ⊔ [5, 15] = ]−∞, 15]
[0,10]⊓[15,20]= Bottom
[0,10]⊓[5,7]=[5,7]
]−∞,10]⊓[5,15]=[5,10]
any pointers would be greatly appreciated.
Comment: What about the lattice $\{[1,1]\}$?
Comment: @GitGud Sorry if I sound dumb, but I don't understand what you mean. Isn't a lattice something with a bottom and a top?
I'm pretty new to this topic, so I might be mistaking.
Comment: Inclusion wise, the set I provided has both a top and a bottom, it is $\{1\}$.
Answer: The part of the lattice consisting of finite sets has a Hasse diagram as follows:

where the bottom node is the empty interval and is covered by all singleton intervals. Every other interval has that $[a,b]$ is covered by $[a-1,b]$ and $[a,b+1]$, creating the visible grid that we see. Notice that through each element, we can draw two lines following the grid - that is, through $[a,b]$, we can draw a line consisting of $\{\ldots,[a-2,b],[a-1,b],[a,b],[a+1,b],[a+2,b],\ldots,[b,b],\emptyset\}$ and a similar one where we modify the second endpoint. If we take two elements, and draw these lines, then the meet and the join lie at the two intersections of these lines (and it should be obvious which is which).
For the infinite elements, we end up with two infinite "chains" (i.e. posets isomorphic to $\mathbb Z$) which we have to imagine as lying diagonally above, in either direction, the poset. That is, we consider that if we start at a point $[a,b]$ and travel $[a-1,b],[a-2,b],\ldots$ we eventually get up to this diagonal limit to $(-\infty,b]$, placing us between $(-\infty,b-1]$ and $(-\infty,b+1]$ - these sort of acts like "points at infinity" on the grid. Moreover, these two chains have their meet $\mathbb Z$, thrust way in the middle of nowhere, above everything else - and it covers no elements, but acts as the result of traveling upwards forever through the grid.

Lattice of interval


Understanding a proof in Rudin

Question:
Closed subsets of compact sets are compact
Proof: Suppose $F \subset K \subset X$, $F$ is closed (relative to $X$), and $K$ is compact. Let $\{V_{\alpha}\}$ be an open cover of $F$. If $F^c$ is adjoined to $\{V_{\alpha}\}$, we obtain an open cover $\Omega$ of $K$. Since $K$ is compact, there is a finite subcollection $\Phi$ of $\Omega$ which covers $K$, and hence $F$. IF $F^c$ is a member of $\Phi$. we may remove it from $\Phi$ and still retain an open cover of $F$. We have thus shown that a finite sub collection of  $\{V_{\alpha}\}$ covers $F$

So the second step confuses me. Basically they are saying the union of the complment of $F$ and the open cover of $F$ covers $K$. I don't see why this is true. Why can't $F^c \subset K$? If that were true, doesn't it mean it wouldn't necessary cover $K$?
Answer: $\forall x\in K, (\text{and}\;\;\forall x \in X)$: $x\in F\cup F^c$. $\;x\in F$ or $x\in F^c \implies (x \in F$ or $x \notin F$). That is $x$ is in $F$, or it's not in $F$ (Law of excluded middle).   If it's in $F$, it's covered by the open cover of $F$: $\{V_\alpha\}$.  If it's in $F^c$ (i.e., if it's not in $F$), it's covered by $F^c$.
Whatever the case, it's covered: all of $X$ so all of $K$ is covered, and since K is compact, it can be covered by a finite subcover, and following the proof, $F$ can then be covered by a finite collection of $\{V_\alpha\}$, so it too is compact.

Edit: Since the problem seems to be in understanding $F^c$, the complement of $F$ relative to $X$:
Complement clarification: See image.
Let $X = U = \{0, 1, 2, 3, 4, 5, 6, 7, 8, 9\}$.
Let $F = B = \{0, 1, 4, 5, 6, 7, 8\}.$
Then $F^c = B'= X \setminus F = U \setminus B = \{2, 3, 9\}$
Comment: The **complement** of a set $F \subset K \subset X$ is made up of ALL elements in set X which are NOT in $F$. We are interested only in $F \subset K \subset X$. If $Y\cap(F\cup F^c) = \varnothing$, then $Y\not\subset X$, so it is of NO relevance in the given proof.
Comment: Sizz, if it's still not making sense, try building an example. Let $X=\mathbb{R}$, $F=\{x|0\leq x\leq 1\}$, and $K=\{y|-1\leq y\leq 2\}$. Ignore the fact that $F$ and $K$ are clearly compact and instead build $F^c$. What is $F^C$ in this case? Does $F\cup F^c$ cover $K$ in this case?
Comment: Is this making sense now? I do agree that Rudin can be rather brief and dry in his proofs.
Comment: Ooooooo.... $x,y,z$ confused you? Ohhh... Hm. Yeah, I didn't mean the typical usage of $x$, $y$, and $z$ to be the normal coordinates in $\mathbb{R}^3$. My bad. No, just three arbitrary variables in regular old one-dimensional $\mathbb{R}$. Thanks for realizing that, amWhy.
Comment: Okay but what if there is another party member in $X$ that is disjoint from all the Fs?
Comment: Then it's in $F^c$.
Comment: Again: any element of $X$, and of $K$ is either in F, or not in F. By the definition of the complement of F in X, an element in the complement of F is not in F: $X\setminus F = F^c;\;F\cup F^c = X$.
Comment: Sorry I meant like why can't $K = F \cup F^c \cup Y$ for $Y$ is some new set such that $Y \cap (F \cup F^c) =\empty$
Comment: Sorry I drew a venn diagram of what's happening. Basically I have big $X$ as the universe and I have three circles (sets) all disjoint from each other and all of them are subsets of $X$. I labelled the three sets, $Y$, $F$ and $F^c$.
Comment: You're not understanding: if $Y \cap F = \varnothing$, since $F^c = X \setminus F = X - F$, then $Y\subseteq F^c$. $F^c$ is ALL of X except for F.
Comment: @sizz: In your Venn diagram with the three circles, presumably you have one of the circles labeled as $F$. That means the other two circles are not part of $F$, i.e., they are part of $F^c$. Not just one circle is $F^c$. Remember, every elements either IS in $F$ or IS NOT in $F$. There are no exceptions to this rule inside the universe of $X$. Thus, $X=F\cup F^c$, which is a disjoint union.
Comment: So basically $Y$ gets sucked into $F^c$?
Comment: But how do I know that $F^c \not\subset K$? There is still a possibly that $F^c \subset K$ and $F^c \cap F = \phi$
Comment: We know $F\subseteq K$. Assuming $F\neq\varnothing$, then there is some element in $K$ that is not in $F^c$. Note that $F^c\cap K$ may not be empty, though, since we aren't saying $F=K$.
Comment: Sorry but since $F \subset K$, can $F^c \cap K $ even be empty?
Comment: If $F\subset K$ and $\subset$ indicates a proper subset, ($\exists x\in K$ with $x\notin F$) then no, $F^c\cap K$ cannot be empty.
Comment: @ToddWilcox, in your example. $F^c$ is pretty much $\mathbb{R^2} \backslash F$, so I guess I see what you mean.
Comment: Is this helping, sizz?
Comment: @ToddWilcox, oh okay I didn't notice that subtlety. Thank you. I think I am beginning to see my flaw. Interesting confusion eh?
Comment: Actually, $F^c$ would not be $\mathbb{R}^2$ at all. In my example, $F^c=\{z\in\mathbb{R}|-\infty <z<0,$ or $1<z<\infty\}$.
Comment: No I meant $\mathbb{R}^2$ without the infinite rectangle contained by $F$. I was sturggling to figure out how to type out \ in latex.
Comment: And since we're trying to prove that F is compact (the proof you posted), and already know K is compact, it would be trivially true if F = K, so we can safely assume F is a proper subset of K, which works fine.
Comment: I was taking $X=\mathbb{R}$, not $X=\mathbb{R}^2$. Aside from that, it looks like you're getting it, or at least getting very close. And $F^c$ is exactly $\mathbb{R}\backslash F$. It's just two ways of writing the same thing.
Comment: sizz: I think Todd was using x, y, z just to distinguish elements of the respective sets.
Comment: Maybe I got the idea but just from a wrong example? I thought you made a typo on $X = \mathbb{R}$ in the first place
Comment: No I redid the whole thing and I think our "examples" were saying the same thing.  $F^c$ alone doesn't cover all of $K$, but the union of $F^c$ and $F$ here does
Comment: @Todd no worries: I appreciate you helping out.
Comment: Correct!! Actually, the union of $F$ and $F^c$ covers $X$ also.
Comment: Btw, if you try my example (where we took $X = \mathbb{R}^2$, we are saying more or less the same thing I think
Comment: yes, I think you're right...sizz
Comment: @ToddWilcox, are we back in square one again? Ah sigh, I thought the union of $F^c$ and $F$ *IS* $X$. A set can't cover itself right? Or is this also consistent with the fact that there is no darn way I can find a finite subcover of $X$ anyways (since $\mathbb{R^n}$ isn't compact)
Comment: Oh, you are probably right. I'm trying not to panic about the fact that I just looked for my baby Rudin and don't know where it is. $F^c\cup F$ IS $X$, yes. If a set can't cover itself then you are totally right. I think I was playing too fast and loose with "cover" just there and I apologize.
Comment: $F^c \cup F = X$, yes. The cover of K, is finite (since K is given as compact), but also covers F. If we remove the cover of the part of $F^c$ from the cover of K, the finite cover of K then reduces just enough to show that there exists a finite cover of F, hence F is compact. Which was to be shown.
Comment: I have a definition of "cover" by Richardson that allows a set to cover itself, but the cover must be open, so my possibly erroneous statement would work if we use Richardson's definition and $X$ is considered open. But this is all besides the point.
Comment: I am probably pushing this discussion a little too much. But while we are on the topic of whether a set itself can cover, itself, then shouldn't we necessary add to the proof that the complement must cover more than $K$ and not just $K$? But I suppose that's obvious and doesn't need to be stated
Comment: @Todd, aren't all covers, by definition *open*? At least that's how Rudin suggests it. In fact, it's the first definition in the topic of compact sets. It stresses *open cover* and doesn't seem to acknowledge the existence (if it does) of other type of covers.
Comment: Yes, covers are open, but the proof shows that for closed F, we can have a finite open cover of F. I wouldn't worry too much abuot it now, but you'll probably encounter an exercise to find an open cover for the interval [0, 1] in $\mathbb{R}$ sometime soon.
Comment: We shouldn't add anything to a proof that is not necessary for the proof. In this case, I only mentioned the expanse of $F\cup F^c$ to try to clarify what it contains. I don't think we should get too bogged down on whether a set can cover itself, unless you are fully clear on the proof in question and then maybe asking a new question would be a better way to discuss that. I'm pretty sure if a set is open, it can cover itself by most, if not all, definitions.
Comment: But the book Todd uses suggests, according to him that, *but the cover MUST be open* covers don't necessary have to be open?
Comment: For your purposes, since you are using Rudin, all of your covers must be open. Even in my book by Richardson (all I have handy right now), all covers are open. I think we can safely assume that all covers are open. Again, that's not really related to the question and answer we are commenting on so it would be best for Math.SE if we leave it at that or open a new question about whether a set can cover itself.
Comment: Yes, closed sets can/must have open covers, but you'll get to that soon enough. It's not crucial here in this proof.
Comment: Basically the open set serves an open cover, for itself. I think that's what you were getting at? In that case I can tolerate the idea, though I yearn for a stricter condition. I'll accept it for now. Thank you all, I think we 've broken the record for longest comments chain haha, and thank you for participating too! (37 comments wow)
Comment: Already ahead of you (acceptance), I am not sure how much content I can add to follow up on my question. It would be somewhat empty to barge out and ask "okay guys, can open sets serve as an open cover, for itself?"
Comment: Actually I think I can add some content, Rudin's seem to have added a condition which doesn't allow this. I will ask
Comment: The more comments here the more pluses needs here.
Answer: Every member of $K$ is either in $F$ or in $F^c$.  If it's in $F$, it's covered by the open cover of $F$.  If it's in $F^c$, it's covered by $F^c$.  So in either case, it's covered.
Comment: @sizz $F^C$ means the complement of set $F$.  Everything in $X$ that isn't in $F$ is in $F^C$, by definition.  So there is no third case.
Comment: What if there is a third set $Y$ that's disjoint from all the $F$s?
Answer: $$X\subseteq F\cup F^c$$
Since $F\subseteq\cup\Omega$ (Here $\cup\Omega$ is the union of all elements of $\Omega$), therefore:
$$X\subseteq\cup\Omega\cup F^c$$
Thus:
$$K\subseteq\cup\Omega\cup F^c$$
Answer: The open cover you're dealing with is $\{F^c\} \cup \{V_\alpha\}$.  This covers the entire space $X$, not just $K$. To see this, let $x \in X$.  Either $x \in F$ or $x \notin F$.  If $ x \in F$, then
$$x \in F \subseteq \bigcup V_{\alpha}$$
Otherwise, $x \in F^c$, so $X \subseteq F^c \cup \bigcup V_{\alpha}$.

Understanding a proof in Rudin


Get list of all sql servers installed in the system

Question: I am trying to get list of all SQL Servers installed in the machine and populate them in a drop downlist.  I have searched in google and tried the following:
<code>using System;
using System.Data;
using Microsoft.SqlServer.Management.Smo;

namespace SMOTest
{
    class Program
    {
        static void Main()
        {
           DataTable dt = SmoApplication.EnumAvailableSqlServers(false);
           if (dt.Rows.Count > 0)
           {
              foreach (DataRow dr in dt.Rows)
              {
                 Console.WriteLine(dr["Name"]);
              }
           }
        }
    }
}
</code>
However I didn't find a reference for Microsoft.SqlServer.Management.Smo;
What is the best way to get all the sqlserver names and populate it in a drop down list?
Comment: @ShaliniPavan If you don't want SQL Server instances then you should  update your question to make it clear what you do what - at the moment the question seems very much like you are asking for a list of SQL Server instances.
Comment: Maybe it helps: http://stackoverflow.com/questions/141154/how-can-i-determine-installed-sql-server-instances-and-their-versions
Comment: @Samich I dont want instances and their references
Answer: If you dont find it than you can google it and than you can pass the reference of it the simplest way to achive it.
Check this answer : http://social.msdn.microsoft.com/forums/en-US/sqlsmoanddmo/thread/883d89df-fb19-4b04-ab83-1006a3559476/
Do Install : Microsoft SQL Server 2008 Feature Pack, October 2008


Android appstore

Question: Just a quick question, On Android there are various appstore's. For instance Google's own, Amazon's etc.
Is it possible for other 3rd parties to easily create there own app store?
Answer: If a device supports side-loading of apps, yes. In fact, you can download and prompt the user to install applications from any other application. Just trigger the phone to download the corresponding APK. The difficult part is getting developers to pay and submit their apps to you.
Comment: Nope. The phone just needs to have the option to "Allow installation of non-Market applications" in the Applications screen of the device's settings. That's what allows you to install external apps. Some phones don't ship with the ability to turn this on, and in those cases, yes, the phone needs to be rooted to allow this to be turned on.
Comment: So would the phone need to be rooted?

Android appstore


tag requires a 'drawable' attribute or child tag defining a drawable

Question: I'm new to Android development. I'm trying to create a splash screen for my first app using an XML file. However, it's giving me the following error message:
Rendering Problems Couldn't resolve resource @color/blue  Failed to convert @color/blue into a drawable (Details)  <item> tag requires a 'drawable' attribute or child tag defining a drawable

I've looked all over the place to try to find out how to get drawables to work, but can't find much.
Here's my code:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:drawable="@color/blue"/>

    <item>
        <bitmap
            android:gravity="center"
            android:src="@mipmap/ic_launcher"/>
    </item>

</layer-list>

Answer: First create a custom drawable file, and add  tag and apply your color to  tag. then this give the this newly created drawable path to android:drawable.
drawable/bg_bule.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<solid android:color="@color/blue"/>
</shape>

then put in your code:
<?xml version="1.0" encoding="utf-8"?>

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

<item
    android:drawable="@drawable/bg_bule"/>

<item>
    <bitmap
        android:gravity="center"
        android:src="@mipmap/ic_launcher"/>
</item>

</layer-list>


Programmatically getting variation type fields in order

Question: I am trying to get variation type field values from the order entity but I can't find any documentation on this. I am using an event subscriber to run the following code when an order is paid. The code works, but I can't see any reference to the fields in kint and I can't find any references to any kind of "getVariation" or equivalent function online.
/**
 * This method is called when the commerce_order.order.paid is dispatched.
 *
 * @param \Symfony\Component\EventDispatcher\Event $event
 *   The dispatched event.
 */
public function commerceOrderOrderPaid(Event $event) {
  /** @var \Drupal\commerce_order\Entity\OrderInterface $order */
  $order = $event->getOrder();
  $items = $order->getItems();
  foreach ($items as $item) {
    kint($item);
    if ($item->get('type')->target_id == 'purchase_things') {
      // 'number_of_things' is a variation type field.
      $thingQuant = $item->get('number_of_things');
      // The line does not work, obviously.
      // I cannot see 'number_of_things' anywhere in kint($item).
    }
  }
}

Answer: Using Devel and Kint I was able to find the "getVariation" function I was looking for. This code lets you get the variation type fields.
$item->getPurchasedEntity()->get('field_number_of_things')->value


Max Clique - NP Problem

Question: The question is to show that the recognition version of Clique is in NP.
I have started with a graph G=(V,E) and integer k such that G does have a clique C of cardinality k. How to proceed further from here?
Thanks in advance for any help.
Comment: Because of the capital letters, it took me some time to understand that this is not about the recognition by the mathematical community of a guy called Max Clique who claimed to have solved the P=NP problem...
Answer: The idea is that given a set $C$ of vertices, you can check in polynomial
time whether $C$ is a clique of cardinality $k$.
Comment: @hardmath NP means that a "yes" answer can be checked in polynomial time.  If a "no" answer can be checked in polynomial time, the problem is in co-NP.
Comment: Isn't this only half of the problem though?  How would I give an evidence of the nonexistence of a $k$-clique that can be checked in polynomial time?
Answer: Why don't you even try to find the solution in wikipedia?
http://en.wikipedia.org/wiki/Clique_problem#NP-completeness

Max Clique - NP Problem


How to open google chrome from windows start menu using pywinauto

Question: I am new to pywinauto and I want to open my own application from the windows start menu.
For this, if I come to know how to open Google chrome from the windows start menu, then I can able to handle my application.
I have gone through code mentioned in below URL but did not understand.
automation using pywinauto to chick on start button
Here's the Code I tried :
import pywinauto.application
app = pywinauto.application.Application().connect(path="explorer")
app.TaskBar.print_control_identifiers()

Comment: What is the reason to use "Start" menu? The executable name or command line can be found in the Start menu shortcut when you right click at your app icon and call "Properties" dialog. Also you may need to choose more proper `Application(backend="uia")` (it depends on the app). Please read the [Getting Started Guide](https://pywinauto.readthedocs.io/en/latest/getting_started.html) for further guidance.
Comment: If you need to check presense of the app in Start menu, it can be checked by walking corresponding folder on file system. Why overcomplicating it through GUI?
Comment: I am able to open my application by giving the full installation path.
Comment: Why Pywinauto APIS are unstable. some of the options like example "Edit" is not working all the time. Some time its fails and some times its pass. When it fails it throws "COMError : (-2147220991, 'as an event was unable to invoke any of the subscribers')
Comment: Can you provide the full traceback by editing the question? Usually such message appears when the GUI element is not in the fully initialized state. So please provide the whole error context. Every GUI may have timing issues if you're not dealing with them properly. Emotions won't help, just detailed report is always useful.
Answer: I know this isn't pywinauto, but I am more experienced with pyautogui.
Type into command prompt:
pip install pyautogui

Code:
import pyautogui
from time import sleep

x, y = pyautogui.position()  # gives the x and y of the bottom right corner
pyautogui.click(x, y-1)
sleep(1)  # ensure that we clicked may need to be extended for older systems
# or just pyautogui.write('win')

pyautogui.write("Google Chrome")
sleep(1) #ensure we typed it may need to be extended for older systems
pyautogui.press("enter") #press enter

There you go! it opens chrome in two seconds.
If you want to go to an website add this:
sleep(3) #google chrome takes forever to load. Just checking. Also may
need to be extended for older systems.
pyautogui.moveTo(10, y-10)
sleep(3)
pyautogui.typewrite("URL/domain to go to", 0.25) #the 0.25 is a delay of 1/4 of a second, to bypass new chrome anti-bot protection.
sleep(12) #ensure we typed it. make sure to extend by the rule of 4 characters=add 1 also add 1 to that to make sure. this supports 40 character long URLs
pyautogui.press("enter") #press enter

Ok, so there you go. Just made a script to open chrome and to (optionally) go to a URL.
Comment: Could someone help me with the adding line breaks?


SQLite query that contains special characters

Question: I have to build SQLite database where I store some strings which has some special character, for most of the cases it is working find except this one
SELECT * FROM table1 WHERE use_id = 3B:02

It throws this errors
android.database.sqlite.SQLiteException: near ":02": syntax error (code 1):

How can I handle this when this "3B:02" is variable
Here is my query
selectQuery = "SELECT * FROM " + DataBaseHelper.TABLE_COM + " WHERE "
                + DataBaseHelper.COLUMN_USER_ID + " = " + value;

Answer: String literal values in SQL need to be in 'single quotes'.
However, it's better to use ? placeholders for literals and bind the values, e.g.
Cursor c = db.rawQuery("SELECT * FROM " + DataBaseHelper.TABLE_COM + " WHERE "
            + DataBaseHelper.COLUMN_USER_ID + " = ?", new String[] { value });

Comment: but is not it requies to have minimum API level 16 ?
Comment: `rawQuery(String,String[])` has been there since API level 1. There's another overload of it that was added in 16.


HP Proliant DL120 G6 Memory issue

Question: I bought new RAM for my DL120 G6, but with it installed it does not boot. I thought it might be incompatible so I bought another batch of memory but same result.
I get no display output and no keyboard input, the fans are spinning at pre-boot rpm, no audible error codes and iLO says everything's ok.
CPU: Intel Xeon x3470
Previous RAM (if I put it in it works fine) : 4x 2GB-2Rx8-10600E DDR3
New RAM 1: 4x 4GB-2Rx4-10600R DDR3 (Lenovo)
New RAM 2: 4x 4GB-2Rx4-8500R DDR3 (Hynix)
P.S.: It will not boot with only 2 sticks installed either.
Answer: According to this spec it's an entry level model and doesn't supports 4Gb modules. It also supports only unbuffered memory which you've had before. But now you are trying to install registered memory. Bus width also differs (x8 vs x4).
My best guess is to try 4GB-2Rx8-10600E (unbuffered, ECC) RAM module to see if it works, but that will most likely fail so I won't suggest spending money on this unless you can "try before buy".
Comment: why is it a entry model? with the x3470 cpu i got the highest one supported by this server
Comment: @TwoFish entry model platform, not the CPU.
Comment: but it says 4gb r-dimms are supported here
Comment: https://support.hpe.com/hpesc/public/docDisplay?docId=c02037017

HP Proliant DL120 G6 Memory issue


Does the Exchange Management Console throw an error if duplicate mailbox permissions are added?

Question: Assume the following - this assumes that the Exchange Management Console is being used to modify permissions:

You have a mailbox with an email address of "email@example.com"; User B asks if they can be given access to this mailbox. Access is granted
User C then requests access to the "UserA" mailbox, as well as User B; despite previously adding User B's permissions, this is done at the same time as User C

In the above example, is an error thrown when choosing to give Full Access Permission from within the EAC? I know that for Active Directory security groups, if using the ADUC snap-in, an error is displayed stating that a user already has access to a group if you attempt to add duplicate permissions but I wasn't sure if this was also true for Exchange.
Answer: What the version of your exchange server?
I tested in my exchange 2016 lab, detail information in below screenshots for your reference.

There is no error message when you click ok.


Under which circumstances does LDA achieve a higher classification accuracy than QDA?

Question: Since some weeks, I pursue the question "Under which circumstances will LDA achieve a higher classification accuracy than QDA using the same training and test set as well as the same prior probabilities?".
I have found these links to this issue:
link1
link2
link3
link4
link5
Unfortunately, the answers do not satisfy me completely.
Therefore, I would like to ask this question again in the hope of comprehensive responses consisting of descriptive examples.
Comment: Have you considered a case where the data generating process corresponds to LDA? The true model should beat any competitors in large samples and it should beat more complex competitors (such as QDA) in small samples, too.
Comment: I have, and the QDA accuracy was always higher than the LDA accuracy.
Comment: That is weird...
Comment: @RichardHardy do you maybe have any other idea?
Comment: Thank you for your answer!
I will check your answer and notify as soon as I have finished writing my paper.
Answer: Consider a case where the data generating process (DGP) corresponds to LDA or can be closely approximated by it. LDA should beat any competitors in large samples and it should beat more complex competitors (such as QDA) in small samples, too. The added flexibility of QDA would result in higher estimation variance due to the need for estimating some additional parameters. In relatively small samples, this cost will outweigh the lower model bias due to QDA offering a better approximation to the DGP than LDA. James et al. "An Introduction to Statistical Learning" (2013) p. 152-153 offer three examples where LDA beats QDA:

Scenario 1: There were 20 training observations in each of two classes. The observations within each class were uncorrelated random normal variables with a different mean in each class. The left-hand panel of Figure 4.10 shows that LDA performed well in this setting, as one would expect since this is the model assumed by LDA. KNN performed poorly because it paid a price in terms of variance that was not offset by a reduction in bias. QDA also performed worse than LDA, since it fit a more flexible classifier than necessary. Since logistic regression assumes a linear decision boundary, its results were only slightly inferior to those of LDA.
Scenario 2: Details are as in Scenario 1, except that within each class, the two predictors had a correlation of $−0.5$. The center panel of Figure 4.10 indicates little change in the relative performances of the methods as compared to the previous scenario.
Scenario 3: We generated $X_1$ and $X_2$ from the $t$-distribution, with 50 observations per class. The $t$-distribution has a similar shape to the normal distribution, but it has a tendency to yield more extreme points — that is, more points that are far from the mean. In this setting, the decision boundary was still linear, and so fit into the logistic regression framework. The set-up violated the assumptions of LDA, since the observations were not drawn from a normal distribution. The right-hand panel of Figure 4.10 shows that logistic regression outperformed LDA, though both methods were superior to the other approaches. In particular, the QDA results deteriorated considerably as a consequence of non-normality.

(Emphasis is mine.)


A Proof for Generalized Rolle's Theorem

Question: Can anyone please critique my proof?
Problem
Generalized Rolle's Theorem Let $f(x)$ be differentiable over $(-\infty,+\infty)$, and $\lim\limits_{x \to -\infty}f(x)=\lim\limits_{x \to +\infty}f(x)=l$. Prove there exists $\xi \in (-\infty,+\infty)$ such that $f'(\xi)=0.$
Proof
Consider proving by contradiction. If the conclusion is not true, then $\forall x \in \mathbb{R}:f'(x)\neq 0$. Thus, by Darboux's Theorem, $f'(x)$ can not change its sign, in another word, $f'(x)$ is either always positive or always negative.
Without loss of generality, we assume $f'(x)>0$, then $f(x)$ is strictly increasing. It's obvious that
$$\inf_{x \in \mathbb{R}} f(x)=\lim_{x \to -\infty}f(x),~~~\sup_{x \in \mathbb{R}} f(x)=\lim_{x \to +\infty}f(x).$$
Therefore
$$l=\inf_{x \in \mathbb{R}} f(x)<f(x)<\sup_{x \in \mathbb{R}} f(x)=l,$$
which is absurd. The proof is completed.
Comment: The proof is OK.
Comment: You could use Rolle's theorem directly. Define $h(x)=f\left(\frac{1}{a-x}+\frac{1}{b-x}\right)$ and also assert that $h(a)=h(b)=l$. Then all the conditions of Rolle's theorem are met, so there exists $x^*$ such that $h'(x^*)=0$. Using the chain rule this implies that $f'\left(x^{**}\right)=0$, where $x^{**}=\frac{1}{a-x^*}+\frac{1}{b-x^*}$ completing the proof.
Comment: Its fine but the usual proof for Rolle is simpler.
Answer: The proof is solid. However, I do have some comments (as I frequently do):

You say, "It is obvious that...". While I do agree that the next conclusion is fairly obvious, at the level of an introductory real analysis course, there are some steps that many students would not be able to fill in. I understand omitting steps for brevity, but I would recommend being clear in your own head about how you would go about expanding the proof here, and if this proof is being submitted for an assessment, how you would go about convincing the marker that you do know what you're talking about.
The line
$$l=\inf_{x \in \mathbb{R}} f(x)<f(x)<\sup_{x \in \mathbb{R}} f(x)=l$$
could be improved to say
$$l=\inf_{x \in \mathbb{R}} f(x)\le f(-1) < f(0)< f(1) \le \sup_{x \in \mathbb{R}} f(x)=l.$$
In order to make the original line make sense, you would have to follow it with a "for all $x \in \mathbb{R}$", which would make the $\sup$ and $\inf$ poorly-formed. You could consider replacing the $x$ with a different pronumeral $y$, or (as I did) a specific number like $0$. I also included specific numbers to either side of $0$ to help neatly demonstrate why the inequality is strict.
Comment: thanks.please read my reply.
Answer: Thanks for @Theo Bendit's critique. I'm willing to give a reply, but it seems to be a bit long, so please allow me to initiate a new post.
Part 1
For the first point, I admit I omitted some details in the former post indeed. However, it's easy to add a proof for complement.
For any fixed $x_0 \in \mathbb{R}$, according to the monotonity of $f(x)$, we have
$$\forall t>0 :f(x_0)<f(x_0+t).$$
Let $t \to +\infty$ and take the limits of both sides. We have
$$f(x_0)\leq \lim_{t \to +\infty}f(x_0+t)=l,$$
which shows that $\forall x_0 \in \mathbb{R}:f(x_0)\leq l$. Therefore $l$ is an upper bound of $f(x).$ Moreover, since $\lim\limits_{x \to +\infty}f(x)=l$, then
$$\forall \varepsilon>0,\exists X>0, \forall x>X:|f(x)-l|<\varepsilon.$$
Thus, $$\exists x' \in (X,+\infty):f(x')>l-\varepsilon.$$
Now, we can claim that, $l$ is surely the supremum of $f(x)$. Likewise, we may prove $l$ is also the infimum of $f(x)$.
Part 2
As for the second point, I can agree that
$$\inf_{x \in \mathbb{R}} f(x)\leq f(x) \leq \sup_{x \in \mathbb{R}} f(x),\tag1$$
if we merely notice the property of the bound. But, taking the monotonicity into account, we can improve the conclusion, namely, cancel the equal mark.
Actually, the equality within $(1)$ can never hold at all. That's because, if
$\exists x''\in \mathbb{R}:f(x'')=\sup\limits_{x \in \mathbb{R}}f(x),$ then $\forall \xi>0: f(x''+\xi)>f(x'')=\sup\limits_{x \in \mathbb{R}}f(x)$, which contradicts.

A Proof for Generalized Rolle's Theorem


Definition of a group written in formal logic

Question: Is the formal logic in these axioms correct?
A group is a nonempty set $G$ with a binary operation $*$ that satisfies the following axioms:

$(a * b) \in G \; \forall \;a,b \in G$
$a * (b * c) = (a * b) * c \; \forall \; a,b,c \in G$
$\exists \; e \in G : a * e = e * a = a \; \forall \; a \in G$
$\forall \; a \in G \; \exists \; a^{-1} \in G: a * a^{-1} = a^{-1} * a = e$

In particular, in the last two axioms notice the difference of where the "for all" is placed.
The third axiom is meant to state that there exists an $e$ in $G$ that is a identity for all $a$ in $G$ under $*$.
While the last axiom is meant to state that for every $a$ in $G$ there exists an inverse $a^{-1}$ in $G$ under $*$.
Comment: If you are concerned about the formal logic I think you should be very careful with the placement of quantifiers.  I would recommend rewriting the third statement as$$\exists \; e \in G : \; \forall \; a \in G : a * e = e * a = a$$and similarly for the first two.
Comment: The axioms as given are not sentences of first-order predicate calculus. In particular, the placement of the universal quantifiers is not right.  There is also nothing connecting the $e$ of the fourth axiom with the $e$ of the fifth. As a very informal description, it is sort of OK. From the formal point of view, quite far from right.
Comment: One can avoid the constant symbol by combining the last two sentences suitably into a single sentence. And a single binary function symbol is enough, if that's what we want. A more serious issue for formalization is the $\in$ symbol. In first-order group theory, one would omit all the $\in G$ stuff.
Comment: By definition, a binary operation on a set $S$ is a function $S \times S \to S$, so the first axiom is unnecessary.
Comment: correct it is....
Comment: Total pedantry would identify the operation as an "infix binary operation" since that is how you have used it.  Most people aren't total pedants, so this is excessive.
Comment: To address André Nicolas's objection about $e$, you could state that a group is a tuple $(G,*,e,{}^{-1})$ comprising a nonempty set, an infix binary operation, a distinguished element of $G$, and a unary postfix operation, together satisfying the following axioms...
Comment: You either need to fully parenthesize things or switch to Polish notation or reverse Polish notation.  All axioms have to follow the formation rules.  Even if we did that though, we couldn't tell if you had correct axioms until we knew which formation rules you had at work.
Comment: @AndréNicolas I don't see why we couldn't rewrite the formation rules to allow for quantifiers to succeed (instead of preceding) a formula.  It wouldn't result in any consistency or any ambiguity so far as I can tell (unlike how if we rewrote the formation rules to say that "a $\land$ b" is a formula).  Of course though we'll have to rewrite the formation rules *first*.
Comment: Certainly. I was thinking OP's question as analogous to asking whether a particular paragraph is written in grammatical English.
Answer: You can see List of first-order theories under the heading : Groups.
In addition, you can check the details in every mathematical logic textbook, like Herbert Enderton, A Mathematical Introduction to Logic (2nd - 2001), page 93.
Note
As you can see, there are different possibilities; what make the (little) differences are the symbols used as "basic".
In order to be "formal", you have to specify a language : an alphabet and the syntactical rules for building expressions (see comments above).


Recarregar apenas uma DIV com Javascript

Question: Olá. Estou utilizando LARAVEL.
Possuo uma div que exibe se o site está ON ou OFF.
Utilizando a função curl_info, é passada a url e então a função retorna o status do site.
Gostaria que essa div ficasse sendo atualizada constantemente para verificar quando o site fica OFF. Como atualizar apenas esta div e não o site todo com Javascript?
PHP
public function curl_info($url){
        $ch = curl_init();
        curl_setopt( $ch, CURLOPT_URL, $url );
        curl_setopt( $ch, CURLOPT_HEADER, 1);
        curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT, 1);
        curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1 );

        $content = curl_exec( $ch );
        $info = curl_getinfo( $ch );

        if ($info['http_code']==200 ) {
                return "ON";
                } else {
                return "OFF";
                }

    }

curl_info('http://google.com.br') !!}" id="meupc">
            SITE

{!! app(App\Http\Controllers\monitController::class)->curl_info('http://google.com.br') !!}

Comment: *setInterval* + *AJAX*
Comment: Qual a sua dúvida? Como executar o método de tempos em tempos, como atualizar a div ou como fazer o curl?
Comment: Só para confirmar, você alterar a div assim você sabe? $('#suaDiv').text('conteudo')     OU em JS: document.getElementById("bla").innerHTML = "novo conteudo da div";
Answer: Tente incrementar isso em seu código, só que ao invés de deixar a execução da function myFunction()  em um button, deixa em no onload do body.

function myFunction() {
setInterval(function(){
  console.log("executando")
},1000)
}
<button onclick="myFunction()">Try it</button>


Como formatar tags html com javascipt

Question: Como faço, para que quando alguém digitar uma tag html, no meu editor online, o javascript defina uma cor para aquela tag ?
Um exemplo seria:

//Essa tag teria sua cor mudada por uma função

function Tag(){

//A função tag ao ser chamada iria setar uma cor

}

Comment: Dê uma olhada nesse [link](https://www.w3schools.com/howto/howto_syntax_highlight.asp)
Comment: Tem muita coisa pronta já para fazer isso. Acho que o nome disso é hightlighter
Answer: É possivel fazer isso pelo atributo contenteditable="true" em uma div, por exemplo.
Plunkr
Answer: Eu recomento a biblioteca javascript highlight.js (open-source):

176 linguagens e 79 estilos
Detecção automática de linguagem
Estilizador de códigos Multi-Linguagem
Disponível para node.js
Funciona com qualquer marcação
Compatível com qualquer biblioteca javascript

Segue um exemplo utilizando highlight.js para javascript e css com o tema atelier-forest-dark:

//Função que inicializa o highlight.js para personalização das cores do código
hljs.initHighlightingOnLoad();
<link rel="stylesheet" href="http://email@example.com/build/styles/atelier-forest-dark.min.css">

Exemplo estilo para códigos javascript:

function funcaoTeste(block, cls) {
    try {
      if (cls.search(/\bno\-highlight\b/) != -1)
        return process(block, true, 0x0F) +
               ` class="${cls}"`;
    } catch (e) {
      /* comentário: captura da exceção */
    }
  }

Exemplo estilo para códigos css:

@font-face {
  font-family: Chunkfive; src: url('Chunkfive.otf');
}

body, .textoUsuario {
  color: #F0F0F0; background: #600;
  font-family: Chunkfive, sans;
}

@import url(estilo.css);
@media print {
  a[href^=http]::after {
    content: attr(href)
  }
}

Documentação completa: http://highlightjs.readthedocs.io/en/latest/
Exemplos utilizando várias linguagens:
https://highlightjs.org/static/demo/
Código fonte do projeto highlight.js:
https://github.com/highlightjs/highlight.js
Estilos disponíveis: http://firstname.lastname@example.com/build/styles/

Como formatar tags html com javascipt


If $x\in \mathbb{R}$ such $|1-|2-|3-|4-\cdots-|2011-x|\cdots||||=x$

Question: Let $x\in \mathbb{R}$, and such
$$|1-|2-|3-|4-\cdots-|2011-x|\cdots||||=x$$
find the maximum of the $x$
I have try $f(x)=|1-|2-|3-|4-\cdots-|2011-x|\cdots||||$,I have find
$$f(0)=0,f(1)=1,f(2)=0$$
Comment: Well, using Desmos, I have an idea that the maximum is at most $0,1.$
Comment: @JasonKim How did you write the formula to get it into Desmos?
Comment: Like $\left|1-\left(\left|2-\left(\left|3-\left(4-x\right)\right|\right)\right|\right)\right|$
Comment: @JasonKim I should have realized that.  I thought you had some magic way to enter the whole thing.
Comment: If a solution $x$ is larger than $1$, it must be giant. Indeed, if $x = |1-|2-|\ldots||| > 1$, then $|2-|\ldots|| > 2$. So, $|3-|\ldots|| > 4$ and hence $|4 - |\ldots|| > 7$ and so on.
Comment: That is, $x$ must be larger than $1+\frac 1 2\cdot 2011\cdot 2012$.
Comment: For $x=2023066=1+2+\cdots+2011$, the big expression evaluates to zero; for larger $x$ the graph has slope $1$ and therefore never crosses $y=x$.
Comment: @vadim123 How do you get to the conclusion that the slope is $1$?
Comment: @vadim123 Now I see why. Great, so the answer is $x = 1$.
Comment: Yup... it took me a long time to realize what to do.
Also, we need to prove that $x=1$ works if we are to claim that $x=1...$
Comment: @JasonKim I added this in my answer.
Answer: Let us show that $x=1$ is the largest fixed point of $f(x) = |1-|2-|\ldots-|2011-x|\ldots|||$. First of all, it can be easily seen that it is indeed a fixed point (see the table below).
Now, let $N := 1+\ldots+2011$. We definitely have $f(N) = 0$ and $f(N+z) = z$ for $z\ge 0$. So, $f$ cannot have a fixed point larger than $N$.
Assume that $x > 1$ is a fixed point of $f$. Then $1 < x = |1-|2-|\ldots|||$. That means that the non-negative number $|2-|\ldots||$ has distance larger than $1$ to $1$. That is, $|2-|\ldots|| > 2$. Hence, similarly, $|3-|\ldots|| > 4 = 1 + 1 + 2$. Therefore, $|4-|\ldots|| > 7 = 1 + 1 + 2 + 3$ and so on. In the end, $|2011-x| > 1 + 1 +\ldots + 2010$. So $x > 1+N$, which is a contradiction.
Here is why $x=1$ is a fixed point of $f$:
$$
\begin{matrix}
k & |k-a|\\
2011 & \boxed{2010}\\
\boxed{2010} & 0 \\
2009 & 2009\\
2008 & 1\\
2007 & \boxed{2006}\\
\boxed{2006} & 0\\
\vdots & \vdots\\
 & \boxed{2}\\
\boxed{2} & 0\\
1 & 1
\end{matrix}
$$
The boxed values are the ones that are even but not divisible by $4$.
Comment: Why must $x$ be so large? I can't tell...
Comment: What is it you don't understand in my reasoning?
Comment: $N=1+2+3...+2011$
Comment: @JasonKim How do you think I can understand what you mean? Try to show a bit of empathy. That's also very important when writing proofs in mathematics. You don't write them to show others that you have understood the problem, but *for making others understand*. So, when you write something mathematic, think twice about whether other people can understand your stuff. What I have written above and what you stated in your last comment is the definition of a number, nothing more.
Comment: I don't understand why we need to prove for just all numbers $N$ greater than $1.$
Also, I suggest writing a few more terms to make the reader understand how it went from all $1$'s to $2011.$
Comment: @JasonKim "I don't understand why we need to prove for just all numbers N greater than 1" Prove what? That $x > 1$ cannot be a fixed point?
Answer: We claim that $1$ is the highest value for which $f_{2011}(x)=x.$
Let $f_a(x)$ represent $|1-|2-|3-|4-...-|a-x|...||||.$
We look for a pattern to calculate $f_{2011}(1).$
Take note that for $c>4,$ we have $f_{c}(1)=f_{c-1}(|c-1|)=f_{c-1}(|c-1|)=f_{c-2}(|(c-1)-(c-1)|)=f_{c-2}(0)=f_{c-3}(|c-3|)=f_{c-3}(c-3)=f_{c-4}((c-4)-(c-3))=f_{c-4}(|-1|)=f_{c-4}(1).$
Applying this repeatedly gives $f_{2011}(1)=f_{2007}(1)=f_{2003}(1)=...=f_{3}(1)=|3-|2-|1-1|||=|3-|2-0||=|3-2|=1.$ Therefore, $f_{2011}(x)=x$ is satisfied for $x=1.$
Now we will prove that that is the maximum possible value of $x$ which can work.
We will evaluate $f_{2011}(2).$ We let $d$ be a positive integer such that $g<4.$ We will start to evaluate $f_{a}(2)$. Calculating, we have $f_{a}(2)=f_{a-1}(|a-2|)=f_{a-1}(a-2)=f_{a-2}(|(a-1)-(a-2)|)=f_{a-2}(1).$ Applying this, we get $f_{2011}(2)=f_{2009}(1)=f_{1}(1)=|1-1|=0.$
We know that the slope of the absolute value is $-1$ or $1$ since there is just one variable $x,$ and the absolute value would change its coefficient, and nothing else.
Since we know that the function is continuous, we have that from $f_{2011}(1)$ to $f_{2011}(2)$ that the slope is $-1.$ We know that from there, even if it it has a slope of $1$ $f_{2011}(2)$ to infinity, it would still be an parallel line that never intersects. That means for every real number greater than $2,$ since $y=x$ can't intersect with $f_{2011}(x),$ $x=1$ is the greatest solution $\boxed{\text{Q.E.D.}}.$


OpenVPN faster with encryption than without it

Question: I would've expected OpenVPN to achieve higher speeds when encryption is disabled, but the opposite is true.
When setting the cipher to AES-128-GCM, the speed between two of my computers is 580 to 613 Mbit/seconds:
Mon Jun 15 11:46:06 2020 Data Channel: using negotiated cipher 'AES-128-GCM'
Mon Jun 15 11:46:06 2020 Outgoing Data Channel: Cipher 'AES-128-GCM' initialized with 128 bit key
Mon Jun 15 11:46:06 2020 Incoming Data Channel: Cipher 'AES-128-GCM' initialized with 128 bit key

When setting the cipher to none, the speed between two of my computers is only 460 - 490 Mbit/seconds.
Mon Jun 15 11:45:11 2020 ******* WARNING *******: '--cipher none' was specified. This means NO encryption will be performed and tunnelled data WILL be transmitted in clear text over the network! PLEASE DO RECONSIDER THIS SETTING!
Mon Jun 15 11:45:11 2020 Outgoing Control Channel Encryption: Cipher 'AES-256-CTR' initialized with 256 bit key
Mon Jun 15 11:45:11 2020 Outgoing Control Channel Encryption: Using 256 bit message hash 'SHA256' for HMAC authentication
Mon Jun 15 11:45:11 2020 Incoming Control Channel Encryption: Cipher 'AES-256-CTR' initialized with 256 bit key
Mon Jun 15 11:45:11 2020 Incoming Control Channel Encryption: Using 256 bit message hash 'SHA256' for HMAC authentication

From what I understand, the "control" channel is just used for really small data packets, while a second "data" channel is used for real information.
I'm trying to reach gigabit speeds through OpenVPN. Even when setting the server's CPU governor to performance, the maximum speed that I can achieve is 613 Mbit/seconds with the AES-128-GCM configuration. I'm still working through this guide.
When I change my protocol with the AES-128-GCM config to proto udp, the speed drops down to 414 Mbit/seconds...
After increasing tun-mtu on the client AND the server, the speed goes up to 700 Mbit/second.  This change persists when using AES-256 encryption too...
When I also disable auth, the speed goes up to 818 Mbit/second.
When I connect directly (not through open vpn), the speed is around 914-980 Mbit/second.
Comment: What CPUs are you using, then?
Comment: Both computers use  Intel(R) Xeon(R) CPU E5-2670 0 @ 2.60GHz. Originally i was using an older CPU and couldn't get above 260 Mbits/second
Answer: The answer is simple: AES-128-GCM is faster for you than SHA1. Without an AEAD cipher OpenVPN will still use the configure --auth option (default sha1) to authenticate the packets.


How to get count of data using mysql

Question: I have two table data and user. I need to get count of data->value and show only greatest count and user->name.
eg, user_id 2: count is 3
I tried some query but it's wrong.
SELECT data.value, user.name
FROM data
INNER JOIN user
ON data.value = user.id
WHERE data.field = 'user_id'

DATA
id  order_id   field     value (id of user table)
1      1      user_id     1
2      2      user_id     3
3      3      user_id     2
4      4      user_id     2
5      5      user_id     1
6      6      user_id     2

USER
id    name
 1    foo
 2    joo
 3    peter

Comment: What is your expected output? Do you want to filter data with user_id?
Comment: @Sadikhasan Expected result is user_id 2 has three entry in data table. So result would be user_id 2 has 3 count.
Answer:
Data is dependent on user's records and each user has multile associated rows in the data table, we need to use GROUP BY.
We need to find the user with the maximum count. For that, the count column is arranged in descending order using ORDER BY count DESC  and the very first row with the max. value is extracted using LIMIT 0, 1.

Try this:
SELECT data.value, user.name, data.field, COUNT(*) as count
FROM data
INNER JOIN user
ON data.value = user.id
GROUP BY user.name
HAVING data.field = 'user_id'
ORDER BY count DESC
LIMIT 0,1

Output:
value  |  name  |  field  |  count
  2    |  john  | user_id |    3

Answer: Use group by
select count(value) from tablename group by value;

this will give you count 3 according to your table
Answer: According to your example requirement, you can do something like this :-
SELECT data.value AS user_id,
data.field,
COUNT( * ) AS count
FROM data
INNER JOIN user
ON data.value = user.id
GROUP BY user.name
HAVING data.field = 'user_id'
ORDER BY count DESC
LIMIT 0 , 1

Comment: Please offer some consoling commentary like OM did to further explain your answers Manish. And format your output so we don't have to.

How to get count of data using mysql


Adjoint pair between Category of Chain Complexes

Question: I have to show that if (L,R) is an adjoint pair between two abelian category A and B, then  L and R induces
L:  Ch(A)->Ch(B)
R:  Ch(B) ->Ch(A)
(where Ch(A) is the category of chain complexes in A)
such that (L,R) is an adjoint pair.
I know I have to use the naturality of the isomorphism given by (L,R) but I'am a bit confused..Thanks for the help!!
Comment: I propose it may be easier to prove a more general theorem: let $\mathcal{C}$ be a preadditive category, and $L : \mathcal{A} \rightleftarrows \mathcal{B} : R$ be an adjunction of preadditive categories. Then the induced functors (i.e. given by composition) give an adjunction $L^\mathcal{C} : \mathcal{A}^\mathcal{C} \rightleftarrows \mathcal{B}^\mathcal{C} : R^\mathcal{C}$, where by the exponential I mean the category of additive functors.
Comment: Here $(L, R)$ is an adjoint pair of _additive_ functors between **A** and **B**?
Comment: yes, sorry I forgot to say it.
Comment: @EricCanton: if a functor between Abelian categories has adjoint, it must preserve finite biproducts (=products=coproducts), so in the end it must be additive.
Answer: Since $L$ is a functor, if $f: M \to N$ is a morphism in A then $L(f): L(M) \to L(N)$ is a morphism in B. Thus, if we have a chain complex
$$ (M_\bullet, d) =(\cdots \to M_i \to M_{i-1} \to \cdots) $$
the only reasonable candidate for $\mathbf{L}(M_\bullet, d^M)$ is
$$(L(M_\bullet), L(d)) = (\cdots \to L(M_i) \to L(M_{i-1}) \to \cdots),$$
where of course I'm applying $L$ to the all of the morphisms $d_i: M_i \to M_{i-1}$, too. We have to check is  this again a chain complex and that composition of morphisms works, but this is straightforward:
 by virtue of being a functor, $L(d)^2 = L(d^2)$, and since $L$ is additive we know $L(0) = 0$.
 composition of chain maps works fine essentially because chain maps in Ch(A) are built out of morphisms in A, and $L$ is a functor on A. It's a routine check, but do it if it's not totally clear.
As you may guess, $\mathbf{R}$ is obtained in the same way.
For the adjunction, try starting with a chain map $\phi \in \mathrm{Hom}_\mathbf{Ch(B)}(\mathbf{L}(M_\bullet, d), (N_\bullet, d'))$, use that this gives us a sequence $\phi_i \in \mathrm{Hom}_{\mathbf{B}}(L(M_i), N_i)$, use this to get $\psi_i \in \mathrm{Hom}_{\mathbf{A}}(M_i, R(N_i))$ by the original adjunction, and then prove that $\psi = (\dots, \psi_i, \dots)$ link up together to give a chain map $(M_\bullet, d) \to (R(N_\bullet), R(d'))$.


Why don't I have permissions to edit an S3 bucket policy when logged on as the person who created the AWS account

Question: I am new to AWS. I am setting up an S3 bucket that I want to use to store media files for a Django App I am developing.
I am logged in as the person who created the AWS account, but when I click on the permissions tab and then try to edit the bucket policy I am getting a message that states "You don't have permissions to edit bucket policy".
I am following a guide which describes the configuration for Django setup, but my understanding is that the purpose of doing this is to allow public read access to the files. I was able to set the CORS policy without any problems.
I created an IAM user logged in as them and it still gives errors. That IAM user has permissions to all S3 Buckets. The error states "After you or your AWS administrator have updated your permissions to allow the s3:PutBucketPolicy action, choose Save changes."
I went to the policy applied to the bucket and it has this permission. Here is the JSON.
<code>{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "s3:ListBucket"
            ],
            "Resource": "mybucketARN"
        },
        {
            "Effect": "Allow",
            "Action": [
                "s3:PutObject",
                "s3:GetObject"
            ],
            "Resource": "mybucketARN"
        }
    ]
}
</code>
Comment: S3 permissions can be tricky. Try logging in as the AWS root user.
Comment: I am logged on as the root user when trying to do this.
Comment: You can also create an admin policy/roles for yourself. AWS has a managed administrator policy. Root user is the fastest way though.
Comment: You cannot edit some policy when when you have "Block Public Access" unchecked. Enable it and try again.
https://aws.amazon.com/blogs/aws/amazon-s3-block-public-access-another-layer-of-protection-for-your-accounts-and-buckets/
Answer: It was necessary to enable public access on the bucket and then I was able to save the bucket policy.
This is the policy I was adding.
<code>{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "PublicReadGetObject",
      "Effect": "Allow",
      "Principal": "*",
      "Action": "s3:GetObject",
      "Resource": "myBucketarn"
    }
  ]
}
</code>
Comment: That doesn't sound quite right. The permission for updating a bucket policy is  s3:PutBucketPolicy.
Comment: The policy in the answer is for public access. The policy in the question is the rights for the admin users.
Answer: When you try to allocate a bucket policy and it has "*" in the Principal, then it is required that "Block public access" setting should be disabled. Otherwise, you will get the error "After you or your AWS administrator have updated your permissions to allow the s3:PutBucketPolicy action, choose Save changes."
The problem in your original question was that you have put a policy which does not look like a bucket policy as there is no Principal in it.
You can very well put a bucket policy which has a specific ARN in Principal even without disabling "Block public access" setting.
Hope it helps!


View with multiple value fields: suppress display of repeated column values

Question: My content type has two fields: field_title and field_related. The field_related is of type Entity Reference and its cardinality is set to unlimited.
The view should display the title, updated date and all related titles, in tabular form, like this:
Title          Updated      Related
=====================================
Chapter 1      2014-01-01   Note A
                            Note B
                            Note C
Chapter 2      2014-02-02   Note A
                            Note B

Currently, it is displaying this:
Title          Updated      Related
=====================================
Chapter 1      2014-01-01   Note A
Chapter 1      2014-01-01   Note B
Chapter 1      2014-01-01   Note C
Chapter 2      2014-02-02   Note A
Chapter 2      2014-01-01   Note B

I tried grouping, but it divided the whole table into separate tables.
I see no point here in using aggregation here (maybe I am wrong..)
What is the solution to this?
Answer: The answer was obvious. For the Entity Reference type of field, don't use fields from the referenced entity (like e.g. "Title") from a relationship. Instead, use the field from the main entity (without relationship). As a result, it displays a title of the referenced entity anyway and not an ID or something.
But in this case, the field gets "Multiple Field Settings" config group, which should be set to "Display all values in the same row". I saw that solution before, but in my view there wasn't this config group at all. That's because I used a field from relationship, which apparently doesn't have a setting for multiple value, because in that entity it's single value, it's a title.


Pictures are not responsive on Firefox & Internet Explorer, Using grid on views

Question: I am building a site with a lot of pictures.
On Google Chrome Everything is working fine.
On FF & IE, If I am just viewing the content & picture not through a view - everything is fine.
But, the pictures are not responsive when I am presenting the picture using views.
I read & saw many tutorials regarding breakpoints Module, Picture Module, and more.
On the picture field on views, I chose the right Formatter, picture group and Fallback image style.
I am using zen sub-theme, but the problem also occur on other themes I tried.
If there are other modules that can fix this issue, or you can help me solve the situation currently, it will be great.
Any Ideas?
Thanks!
Comment: I have tried  Adaptive Image module, Adaptive Image Styles (ais), Client-side adaptive image,Responsive images and styles.
The problem still occur. The pictures are not responsive or adaptive. Meaning, if  I am make the browser (firefox or internet explorer) smaller, the pictures stays in the same size. In crome, the pictures will re-size automatically.. Any ideas?
Comment: What versions of FF and IE are you trying? IE 8 and earlier doesn't support media queries, so it will never work on those browsers. FireFox has supported media queries since version 3.0 so I'm guessing you have recent versions and your problems may lie with your CSS. If you are styling the image (or its containing divs/spans) and using pixels (e.g., width:265px;), that may be your problem. Trying using percentage based dimensions instead. You can also force the image's dimensions at each breakpoint by explicitly styling them in each breakpoint's stylesheet.
Answer: I use the Adaptive Image module. It gives you an adaptive behavior you can select when on Admin>Configuration>Image Styles. In other words, you'll need to create an image style with the new adaptive behavior (it should appear in the pick list after you install the module), or alternately, add the adaptive behavior to existing image styles. Once you've done that, you just need to use the adaptive image style in the view, either by adjusting the image field settings, or by changing the settings on the display type fields if you're using content or rendered entities. For the most part, I found that doing the above steps gives me responsive images, but I sometimes have to tweak my CSS also.
Comment: Sounds Great.
Does it works across all browsers? DO I need to use breakpoint module?
Comment: I've checked it in all recent/current major browsers, on mac, Windows and a few mobile devices, and it works OK. IE 8 and earlier is going to ignore Zen's responsiveness, so the images won't respond either. I'm assuming you haven't disabled Zen's responsiveness. I suspect a lot of people do that at first (I did). I haven't used Zen but I understand it is a responsive theme (make sure your version of Zen is). It's the responsive parent theme that is going to deliver the breakpoints & sometimes xtra features. My experience is with Omega subtheming.
Comment: So, if I understood correctly, using Zen responsive theme, I do not need to use breakpoint module?
Comment: Right - zen will provide the media queries that create the breakpoints. You'll need to style each breakpoint. This explains how: http://banoodle.wordpress.com/2013/09/25/how-to-style-responsive-omega-subthemes/
Comment: I don't want to discourage you from using the breakpoints module, though. I wasn't familiar with it so I just researched it a little and it looks cool and the fact that the breakpoints are stored in the db, may deliver enhanced performance (not sure if zen or omega do this). I still think it would be redundant in a responsive subtheme to use this module: I think the main purpose of this module is if you were creating a theme from scratch and wanted it to be responsive. Thanks for pointing out this module to me - I may us it on an upcoming project.
Answer: I think I solve the Problem, but I am not sure if this is a good solution.
All the pictures were responsive on Google Chrome, But not on Firefox & Internet Explorer.
I found out that I was using the Grid format on the view, and I think that what caused the problem.
After I have installed the View-Fluid-Gird-Module, and chose that on the view, all the designs and the pictures in all browser became fluid.
Still, only the pictures on the Google chrome are responsive and can shrink, but I think the fluid module is enough for most of the devices.
Note: when I am NOT using the grid/fluid grid on a view, but let's say "unformatted list" -> all the pictures on all browsers are responsive (shrinks when needed)
I will be happy to get insights, and maybe someone can find a better solution..
Answer: After trying all sorts of codes and fidles, this simple edition on my CSS did the trick:
img {width: 100%;}

Where you wish your images to resize, define them without adding the width parameter (sizing to original from source); and then, if you want to fix their size,  add the width parameter on SRC you wish (on the style="", the regular width="" will not work). Also, if it's an inline image on your paragraph, simply wrap it inside a div and align that div to whatever side you'd like. Reeeeally simple!
It works both for Google, Firefox and IE. Cheers!
PS: Thanks for the editors for fixing my comment!! ;)


How to change "Secure Login Module - Secure base url" without login?

Question: I have installed Secure Login with Secure base URL setting on a live site, and clone that into a different domain for testing. The "/user" page has no login form because the Secure base URL should be different. How can I change this URL without login? Where is this data in phpMyadmin?
Answer: It's in the variables table. Variable name is securelogin_base_ssl, value like s:4:"theurl";
Comment: Update the securelogin_base_url actually work :)
Comment: I only see the securelogin_base_url not securelogin_base_ssl


TypeError: 'tuple' object does not support item assignment

Question: I'm trying to write a short program which allows the user to input a list of numbers into an input() function, and then using the add_25 function add 25 to each item in a list.
I get the following error when the program runs: TypeError: 'tuple' object does not support item assignment
I tried dividing the numbers using a comma. This is the program:
testlist = [2,6,2]

def add_25(mylist):

    for i in range(0, len(mylist)):
        mylist[i] = mylist[i] + 25

    return mylist

print add_25(testlist)

actual_list = input("Please input a series of numbers, divided by a comma:")

print add_25(actual_list)

Answer: In Python 2 input() will eval the string and in this case it will create a tuple, and as tuples are immutable you'll get that error.
>>> eval('1, 2, 3')
(1, 2, 3)

It is safer to use raw_input with a list-comprehension here:
inp = raw_input("Please input a series of numbers, divided by a comma:")
actual_list = [int(x) for x in inp.split(',')]

Or if you're not worried about user's input then simply convert the tuple to list by passing it to list().

Also note that as you're trying to update the list in-place inside of the function it makes no sense to return the list unless you want to assign another variable to the same list object. Either return a new list or don't return anything.
Comment: Thank you! On a side note, what is "eval"?
Comment: @Artyom721 eval is built-in function in Python.  https://docs.python.org/2/library/functions.html#eval
Answer: The function input reads a string and evaluates it as a Python expression.  Thus, the comma-separated list becomes a tuple of values, these are passed to add_25(), and this function tries to assign to mylist[i] something.
And tuples are immutable, they do not support item assignment (on purpose).
You could use actual_list = list(input(...)) to convert the tuple to a list (which supports item assignment).
But every time someone uses input(), one has to warn him:  input() is a security risk.  It evaluates the input of the user and thus might execute arbitrary things the user typed.  This means that your program will perform what the user asks it to, with your permissions.  This is normally not what is considered a good design.
If you always will be the only user or if you trust all users of your program completely, then so be it.
Comment: Note that as `ast.literal_eval` is the safe version of `eval`, one should really use: `ast.literal_eval(raw_input(...))` and nearly never `input(...)`.
Comment: As `ast.literal_eval("1, 2, 3")` results in `(1, 2, 3)` just as `eval` does, it actually is a drop in replacement in this case.
Comment: Yes, but in this case the programmer intended to parse a list or comma-separated values, so not a literal.  But thanks for the pointer to that function; didn't know that one yet.
Comment: OH, I see.  A tuple counts as a literal in this meaning.  That's really a good thing, thank you.
Answer: Besides all the input() aspects covered in the other answers, I'd like to add this completely different aspect:
Your function add_25() is probably not supposed to change its input.  Yours does, or tries to, and fails because tuples do not allow that.
But you actually do not have to change the input (and you should not, because this is not good style due to its ugly side-effects).  Instead you could just return a new tuple:
def add_25(mytuple):
    return tuple(x + 25 for x in mytuple)

This way, nothing is assigned to a tuple, just a new tuple is created and returned.
Answer: def test_tuples_of_one_look_peculiar(self):
    self.assertEqual( __,(1).__class__)
    self.assertEqual(__, (1,).__class__)

Comment: Please try to avoid just dumping code as an answer and try to explain what it does and why. Your code might not be obvious for people who do not have the relevant coding experience. Please edit your answer to include [clarification, context and try to mention any limitations, assumptions or simplifications in your answer.](https://stackoverflow.com/help/how-to-answer)
Comment: Kindly specify your problem in proper way.