useRef hooks doesn't work with lottie-react-native

Question: I have upgraded my class component to functional component hooks, but right now the ref does not work.
Before:
class A extends Component{

   animation = null;

   onPress = ()=> {
      this.animation.play();
   }

   render(){
     return (
        <View>
          <LottieView
            source={require('./file.json')}
            ref={animation => {this.animation = animation}}
          />
          <Button onPress={this.onPress} title='click me' />
        </View>
     );
   }
}

The above code which it is class Component works very well.
But the following code which I upgraded doesn't work.
Updated code:
const A = props => {

   const animation = useRef(null);

   const onPress = ()=> {
      animation.play();
   }

   return (
        <View>
          <LottieView
            source={require('./file.json')}
            ref={animation}
          />
          <Button onPress={onPress} title='click me' />
        </View>
   );
}

Answer: You're missing .current.
See working example at: https://snack.expo.io/@zvona/lottie-and-useref-example
const onPress = () => {
  animation.current.play();
}

Comment: Thank you for your answer, I tested `animation.current.play();` too, but doesn't work.
Comment: @Muhammad hmm hmm... are you having a mismatch between RN and Lottie versions? If you check expo example, it works fluently.
Comment: `lottie-react-native: 3.0.2` and `react-native: 0.59.9`
Comment: This worked for me but now I'm getting an annoying eslint error: animation.current: Object is possibly 'null'. Any ideas on how to prevent this?


How can I prevent overlapping of table columns?

Question: I want to make my first column in the table static. Here is my jsfiddle:
https://jsfiddle.net/q2ymc76r/12/
css code:
.table .headcol {
  position:absolute;
}
Problem is that the first column overlaps with the second column. Any suggestion to prevent the overlapping. Thanks.
Comment: Static in what way? Is the rest of the table supposed to scroll horizontally? Please edit your question to clarify what you're trying to achieve.
Comment: have you tried position: static?
Comment: static did not work.
Comment: Yes the rest of the table should scroll horizontally when we use it in mobile view.
Answer: In the following post, as you can read from the title, seems that the user had a similar problem
how-do-i-create-an-html-table-with-fixed-frozen-left-column-and-scrollable-body
It should cointain something close to the answer your are looking for
Comment: Hi, i've just edited my answer. It's good now, or I have to edit more? Thank you :-)
Answer: Just set fixed width to your fisrt column, just like this:
Date


A Formulation of The Riemann Hypothesis

Question: To preface this inquiry, I am aware of the fastidious nature of the mathematics presented on this exchange. In addition to that, I apologize for my ineptness and the contention in this particular subject; however, this is of great interest to me. I ask for pardon with the great length of this text.
The following formulation invokes the Argument Principle due to Cauchy. In this sense, consider the closed rectifiable Jordan curve $\mathcal D^{+}= \mathcal D^{+}(T)$ with vertices $(\frac{1}{2}+\epsilon)-iT, 2-iT, 2+iT, (\frac{1}{2}+\epsilon)+iT$, traversed in that order, i.e., with positive orientation. Likewise, let $D^{-}=D^{-}(T)$ denote the closed contour with vertices $-1-iT, (\frac{1}{2}+\epsilon)-iT, (\frac{1}{2}+\epsilon)+iT, -1+iT$, and positive orientation. In both cases $\epsilon$ is chosen to be arbitrarily small. Furthermore, invoking the detail that the zeros of the function $\xi(s)$, where $s=\sigma+it$, are identical to the non-trivial zeros of the function $\zeta(s)$, and the fact that $\xi(s)$ has no poles; we obtain the number of zeros of $\zeta$ in the region $\mathcal D^{+}$ and $\mathcal D^{-}$ are $$N_+(T)=\frac{1}{2\pi i}\int_{\mathcal D^+} \frac{{\xi}^\prime (s)}{\xi(s)}ds=\frac{1}{2 \pi}Im\left(\int_{\mathcal D^+} \frac{{\xi}^\prime (s)}{\xi(s)}ds\right)$$ and $$N_-(T)=\frac{1}{2\pi i}\int_{\mathcal D^-} \frac{{\xi}^\prime (s)}{\xi(s)}ds=\frac{1}{2 \pi}Im\left(\int_{\mathcal D^-} \frac{{\xi}^\prime (s)}{\xi(s)}ds\right),$$ respectively. By the symmetry of both $\xi$ and $\mathcal D^{+}, \mathcal D^{-}$, $N_-(T)=N_+(T)$. Let $\mathcal C_0^{+}$ denote the contour with vertices $\frac{1}{2}+\epsilon, 2, 2+iT, (\frac{1}{2}+\epsilon)+iT$, traversed in the positive sense. Similarly, let $\mathcal C_1^{+}$ denote the contour with vertices $(\frac{1}{2}+\epsilon)-iT, 2-iT, 2, \frac{1}{2}+\epsilon$, also traversed in the positive sense. Decomposing $\mathcal D^{+}$ into $\mathcal C_0^{+}$ and $\mathcal C_1^{+}$ yields $\mathcal D^{+}:=\mathcal C_0^{+} \cup \mathcal C_1^{+}$, whereby $\mathcal D^{+}:=\mathcal C_0^{+} \cap \mathcal C_1^{+}=[\frac{1}{2}+\epsilon,2].$ Hence, the former integral $N_+(T)$ can be expressed as
$$N_+(T)=\frac{1}{2 \pi}Im\left(\int_{\mathcal C_0^{+}} \frac{{\xi}^\prime (s)}{\xi(s)}ds\right)+\frac{1}{2 \pi}Im\left(\int_{\mathcal C_1^{+}} \frac{{\xi}^\prime (s)}{\xi(s)}ds\right).$$ Since $\xi$ is positive real on the portion of the real axis $\mathcal C_0^{+} \cap \mathcal C_1^{+}$, the argument of $\xi$ does not change there. Let $\tilde {\mathcal C_0^{+}}, \tilde {\mathcal C_1^{+}}$ denote $\mathcal C_0^{+}, \mathcal C_1^{+}$ without $\mathcal C_0^{+} \cap \mathcal C_1^{+}$. Therefore
$$\begin{align*} N_+(T)& =\frac{1}{2 \pi}Im\left(\int_\tilde {\mathcal C_0^{+}} \frac{{\xi}^\prime (s)}{\xi(s)}ds\right)+\frac{1}{2 \pi}Im\left(\int_\tilde {\mathcal C_1^{+}} \frac{{\xi}^\prime (s)}{\xi(s)}ds\right)\\ & \equiv \frac{1}{2 \pi}Im\left(\int_\tilde {\mathcal C_0^{+}} \frac{{\zeta}^\prime (s)}{\zeta(s)}ds\right)+\frac{1}{2 \pi}Im\left(\int_\tilde {\mathcal C_1^{+}} \frac{{\zeta}^\prime (s)}{\zeta(s)}ds\right)\end{align*}$$
Since the set of zeros of $\zeta$ is discrete, we may assume no zero of $\zeta$ has imaginary part $T$. This integral can be decomposed into the contribution over the vertical lines, and over the one horizontal line. In particular,
$$\begin{align*} \frac{1}{2 \pi}Im\left(\int_\tilde {\mathcal C_0^{+}} \frac{{\zeta}^\prime (s)}{\zeta(s)}ds\right) &= Im \left(i \int_0^{-T} \frac{{\zeta}^\prime ((\frac{1}{2}+\epsilon)+iy)}{\zeta(\frac{1}{2}+\epsilon)+iy)} dy+\int_{\frac{1}{2}+\epsilon}^{2} \frac{{\zeta}^\prime (\sigma-iT)}{\zeta(\sigma-iT)} d\sigma \right)\\ &=Im\left(\int_{\frac{1}{2}+\epsilon}^{2} \frac{{\zeta}^\prime (\sigma-iT)}{\zeta(\sigma-iT)} d\sigma \right)-Im \left(i \int_{-T}^{0} \frac{{\zeta}^\prime ((\frac{1}{2}+\epsilon)+iy)}{\zeta(\frac{1}{2}+\epsilon)+iy)} dy \right)\end{align*}$$
for which the integral over the vertical segment $[2-iT,2]$ vanishes, due to the boundedness of the total variation of $arg(\zeta(2+it))$ on the segment $[2-iT,2]$. It can be shown that $$\frac{\zeta^{\prime}(s)}{\zeta(s)}=-\frac{1}{s}-\frac{1}{s-1}+\frac{1}{2}log(\pi)+\sum_\rho \frac {1}{s-\rho}-\frac{1}{2}\frac{\Gamma^{\prime}(\frac{s}{2})}{\Gamma(\frac{s}{2})}=\sum_\rho \frac {1}{s-\rho}+O(log|t|),$$ for $\sigma \ge -1, |t| \ge 2.$ This, in turn, can be used to show $$\frac{\zeta^{\prime}(s)}{\zeta(s)}=\sum_{|\gamma_n-t|\le 1} \frac{1}{s-\rho_n}+O(log|t|),$$ with the same condition $\sigma \ge -1, |t| \ge 2.$ As such, it follows that
$$\begin{align*}Im\left(\int_{\frac{1}{2}+\epsilon}^{2} \frac{{\zeta}^\prime (\sigma-iT)}{\zeta(\sigma-iT)} d\sigma \right)&=Im\left(\sum_{|\gamma_n-T| \le 1}\int_{\frac{1}{2}+\epsilon}^{2} \frac{d\sigma}{\sigma-it-\rho_n} \right)+Im\left(\sum_{|\gamma_n-T| \le 1}\int_{\frac{1}{2}+\epsilon}^{2} O(log|T|)dT \right)\\ &\equiv \sum_{|\gamma_n-T| \le 1}Im\left(\int_{\frac{1}{2}+\epsilon}^{2} \frac{d\sigma}{\sigma-it-\rho_n} \right)\end{align*}$$
By the Argument Principle, each summand equals the net change of $arg(s-\rho_n)$ on $[\frac{1}{2}+\epsilon-iT,2-iT]$; thus, its absolute value is less than $\pi.$ In similar vein, by the von Mangoldt estimate of the vertical density of roots $\rho_n$: $N(T+1)-N(T) \le \sum_{T \le \gamma_n \le T+1}1 < 2logT,$ the number of summands is less than $4logT.$ The modulus of the latter integral is $$\left |\sum_{|\gamma_n-T| \le 1}Im\left(\int_{\frac{1}{2}+\epsilon}^{2} \frac{d\sigma}{\sigma-it-\rho_n} \right) \right|<4\pi logT,$$ for large $T.$ Consequently $$\sum_{|\gamma_n-T| \le 1}Im\left(\int_{\frac{1}{2}+\epsilon}^{2} \frac{d\sigma}{\sigma-it-\rho_n} \right)=O(logT).$$
Similarly
$$\begin{align*}Im \left(i \int_{-T}^{0} \frac{{\zeta}^\prime ((\frac{1}{2}+\epsilon)+iy)}{\zeta(\frac{1}{2}+\epsilon)+iy)} dy \right)&=Im\left(i \int_{-T}^{0} \sum_{|\gamma_n-T|\le 1} \frac{dy}{(\frac{1}{2}+\epsilon)+iy-\rho_n}+i\int_{-T}^{0}O(log|T|)dy \right)\\ &=Im\left(i \sum_{|\gamma_n-T|\le 1} \int_{-T}^{0} \frac{dy}{(\frac{1}{2}+\epsilon)+iy-\rho_n}\right)+TO(log|T|)\end{align*}$$
As before, each summand equals the net change of $arg(s-\rho_n)$ on $[(\frac{1}{2}+\epsilon)-iT, \frac{1}{2}+\epsilon].$ Therefore, the absolute variation in the argument is less than $\pi.$ By the above estimate of $N(T+1)-N(T),$ the number of summands is less than $4logT.$ Thus $$Im\left(\sum_{|\gamma_n-T|\le 1} \int_{-T}^{0} \frac{dy}{(\frac{1}{2}+\epsilon)+iy-\rho_n}\right)+TO(log|T|)<4\pi logT $$ for large $T.$ Finally, $$\sum_{|\gamma_n-T|\le 1}Im\left(i \int_{-T}^{0} \frac{dy}{(\frac{1}{2}+\epsilon)+iy-\rho_n}\right)+TO(log|T|)=O(logT)+O(TlogT),$$ which implies that $$\frac{1}{2 \pi}Im\left(\int_\tilde {\mathcal C_0^{+}} \frac{{\zeta}^\prime (s)}{\zeta(s)}ds\right)=O(logT)-O(TlogT),$$ keeping the negative signature for convenience. Therefore $$N_+(T)=\frac{1}{2 \pi}Im\left(\int_\tilde {\mathcal C_1^{+}} \frac{{\zeta}^\prime (s)}{\zeta(s)}ds\right)+O(logT)-O(TlogT).$$

Using this formulation of Argument Principle, would the Riemann Hypothesis follow if it was shown that $$\frac{1}{2 \pi}Im\left(\int_\tilde {\mathcal C_1^{+}} \frac{{\zeta}^\prime (s)}{\zeta(s)}ds\right)$$ exactly cancels $O(logT)-O(TlogT)$ as $\epsilon$ tends to zero and as $T$ tends to infinity? In addition to this, is there a differential-geometric approach to the Riemann Hypothesis?

Thanks in advance.
Comment: ? the Riemann hypothesis is $\int_{\begin{array}{l}\sigma-i\epsilon \ \to \ \sigma-iT \\ \to \ 2-iT\ \to \ 2-i\epsilon \\ \to \sigma-i\epsilon\end{array}} \frac{{\zeta}^\prime (s)}{\zeta(s)}ds = 0$ for every $T, \sigma > 1/2,\epsilon > 0$. And did you read Titchmarsh's book ?
Comment: I don't get it. $F(s) = (s-1)\zeta(s)$ is entire, so integrating $\frac{1}{2i\pi}\frac{F'(s)}{F(s)}$ on the boundary of any finite region just counts  (with multiplicity) the (finite) number of zeros it has in that region, and no cancelling occurs. Of course, $\frac{F'(s)}{F(s)} = \frac{\zeta'(s)}{\zeta(s)} + \frac{1}{s-1}$, so up to a constant $1$, the same is true for $\frac{\zeta'(s)}{\zeta(s)}$. And Titchmarsh's book is [there](http://www.paris8.free.fr/Titchmarsh%20E.C.%20The%20theory%20of%20the%20Riemann%20zeta-function%20(2ed.,%20Oxford,%201986)(T)(418s)_MCsf_.pdf), see p.210
Comment: I split four of the equation chains (ones that had display problems) across multiple lines using the $\LaTeX$ `align*` environment.  Please check my edit did not introduced unintended errors or unwanted effects.
Comment: I have been introduced to the general theory of the Riemann Zeta Function via 'Rimann's Zeta Function' by Harold Edwards. However, I have yet to read Titchmarsh's book. Also, what does this particular notation mean?@user1952009
Comment: the RH is that $\frac{\zeta'(s)}{\zeta(s)}$ is analytic on the rectangle I wrote (the $\epsilon > 0$ is for avoiding the pole at $s=1$), so if your contour $\tilde{C_1^+}$ means the rectangle I wrote, then the RH is $\int_{\tilde{C_1^+}} \frac{\zeta'(s)}{\zeta(s)} ds = 0$
Comment: I know the text it is quite lengthy; however, it explains this particular decomposition above. What makes it so difficult to show this analyticity condition?@user1952009
Comment: I told you I don't understand your question. ${}{}$
Comment: I am essentially asking, if we use an asymptotic Stirling approximation, can it be shown that, by decomposing $\mathcal D^{+}$ into ${\mathcal D}^{+}:=\tilde {\mathcal C_0^{+}} \cup \tilde {\mathcal C_1^{+}}$, the contribution from these regions cancel? In addition, I am also curious if there is any approach in differential-geometry that addresses such issues. I hope this clarifies my query.@user1952009
Comment: Thank you for the reference. @user1952009
Answer: As a place-holder "answer" by the specs of this site/forum: the baseline situation is that many people have thought about RH for 150+ years. Stietljes thought he had a proof a few decades after Riemann's 1859 paper, but it evaporated...
The wonderful fallout of Riemann's paper was much of the late 19th century, and early 20th, development of the function theory of one complex variable. Indeed, the things needed to make Riemann's epiphanies "provable" were not done until after Hadamard's results (1890s) on product expressions for entire functions, and, equally significantly, the Phragmen-Lindelof results c. 1908.
Landau, Hardy, Littlewood, ... bore down quite hard on complex-variables ideas. Cf Levinson.
But, no, ... we do not have useful information. And, equally, re-inventing wheels (while eminently interesting to oneself, at least), is not ... significant.
Comment: as far as I understand it now, there are only two analytic approaches to the RH : the one trying to show $\zeta(s) = 0 \implies \zeta(1-s) \ne 0$ when $Re(s) \ne 1/2$, and the other one trying to say $\xi(1/2+it)$ changes of sign (at least asymptotically) in the neighborhood of every zero of $\zeta(s)$. the two are by nature very complicated, because there are many functions close to $\zeta(s)$ having some zeros off $Re(s) = 1/2$

A Formulation of The Riemann Hypothesis


when can I say there is a relationship between events?

Question: I am analysing a weather data for a computer science course using hadoop.I am taking away all the weather related issues out of the analysing and just looking strictly at it in the eyes of statistics.
Lets say there are 2 events, 1 occurs 250 times in the year, and the other event occurs 50 times in a year. The second event occurs every single day the first event occurred. Can I say that there is a relationship between the two events? I am not sure if it is safe to say there is a good chance there is a relationship between the data because this could just be a coincidence. For example if the event A occurred 25 times a year and event B occurred 15 times again event B occurring every time event A occurred I would be more confident to say there is a relationship between the two events because there is less of a chance it is a coincidence due the the number of times event A occurred. To rephrase, lets say event A occurred 365 times in the year and event B occurred 10 times in the year, event B would occur every single time event A occurred, but this is just because event A occurred every day so there is no relationship. Is there some sort of standard to say that when two events have a statistically high probability of having a relationship of some sort?
he dataset will check for relationships in the short term and longterm (check to see if there is a relationship recently say in the last 3 months, 1 year, but also longer 4 years, 8 years, 10 years). I know for 10+ years, I can probably rely that if events occurred always together there is probably a good chance of a relationship because of the vast time, but for shorter ranges, is there some sort of method?
Hope this makes sense.
Answer: In respect of a single day, day $i$, consider the four compound events:
1) A occurred and B occurred.
2) A occurred and B did not.
3) A didn't occur and B did.
4) Neither A nor B occurred.
For each day, one of those four situations occurs.
Knowledge of all four can be used to decide whether the occurrence of A and B are dependent (either positively related or negatively).
To clarify notation, let $X_i=1$ if $A$ occurs on day $i$ and $=0$ otherwise. Let $Y_i=1$ if $B$ occurs on day $i$ and $=0$ otherwise.
If we further assume that there's independence across days -- that $P(X_i=1|X_j=1)=P(X_i|X_j=0)$ for all $j\neq i$, and similarly for conditioning on $Y_j$ and for conditioning on combinations of $X_j$ and $Y_k$.$^\dagger$
In that case we can use a test for independence. The most commonly used one is the chi-squared test, though I mention some other possibilities later.
Let $Z_{lm}(i)=1$ if $X_i=l$ and $Y_i=m$ for $l=(0,1)$ and $m=(0,1)$.
That is, let $Z_{00}(i)=1$ if $X_i=0$ and $Y_i=0$, and so on.
Further, let $O(l,m) = \sum_i Z_{lm}(i)$, so that the $O$ values represent the counts of how often each combination of A or not-A co-occurs with B or not-B
Then construct a contingency table:
<code>               (not-B)    (B)
                 Y=0      Y=1
(not-A) X=0     O(0,0)  O(0,1)
  (A)   X=1     O(1,0)  O(1,1)
</code>
Then this data is in suitable form for a chi-square, or a G-test or a Fisher-Irwin test (of which the chi-square is the best-known). An alternative would be a two-sample proportions test (say as a Z-test).
$\dagger$ [This may be too strong an assumption, in which case some alternative analysis that deal with the time dependence needs to be used]

1 occurs 250 times in the year, and the other event occurs 50 times in a year. The second event occurs every single day the first event occurred. Can I say that there is a relationship between the two events?

Let's cast this in the above framework. Given a 365 day year, it's possible to work out every combination from that information (it takes a little thinking but you can get there):
<code>                (not-B)   (B)       Tot
                 Y=0      Y=1
(not-A) X=0      115        0       115
  (A)   X=1      200       50       250

Tot.             315       50       365
</code>
This yields a chi-square of around 25.0 or 26.7 depending on whether a continuity correction is applied, which (unless you had chosen an incredibly small significance level to start with) would lead to rejection of the null of no association between occurrence of A and occurrence of B.
In cases where your expected values in some cell or cells may be small (on the order of 1 or 2, say), Yates' continuity correction can help somewhat with improving the chi-square approximation.
[In your example where A and B only occur 15 times together and A only occurs 25 times, the expecteds might be a bit too small to apply the chi-square approximation.]


MLE for Uniform $(0,\theta)$

Question: I am a bit confused about the derivation of MLE of Uniform$(0,\theta)$.
I understand that $L(\theta)={\theta}^{-n}$ is a decreasing function and to find the MLE we want to maximize the likelihood function.
What is confusing me is that if a function is decreasing, then wouldn't the function be maximized at the smallest input rather than the largest?
Thank you in advance for your help.
Comment: @hardmath Highly upvoted but highly incorrect in my mind.
Comment: Your formula for $L(\theta)$ is incorrect.  What happens when you have data points with values larger than $\theta$?
Comment: I did.  No matter where I look at they say that the function is decreasing therefore the maximum X maximizes L(theta), as if it is self evident.  I know that there must be a misunderstanding on my part, but I cannot figure out.
Comment: Brian: I am assuming that you are referring to the fact that all X_is are between 0 and theta.
Comment: A more detailed explanation of what @BrianBorchers comments above is given in [this (highly upvoted) Answer](https://math.stackexchange.com/a/49549/3111) to a previous Question.
Comment: Thank you for providing the link but I already saw that.  I don't understand the part that says, "decreasing function maximizes at the largest X."  $1/x$ for example, maximizes as x is smaller as long as x>0
Comment: @hardmath The objection with that post is that the likelihood function is not differentiable at $\max x_i$. As such, differentiating the likelihood to find the MLE is not justified.
Comment: @StubbornAtom: Okay, maybe the maximization of likelihood function is worth my two cents, assuming this Question stays open (it is hovering on threshold to close now), but I can post on the proposed duplicate and would welcome critiques there.
Comment: See https://math.stackexchange.com/questions/649678/how-do-you-differentiate-the-likelihood-function-for-the-uniform-distribution-in?rq=1.
Answer: Welcome back to MSE.
This is one of those things that once you're explained it correctly the first time, without any gaps in explanation, that it makes sense. Unfortunately, most answers and even professors don't explain all of the details, in my experience.
Suppose $X_1, \dots, X_n$ are independent and distributed $\text{Uniform}(0, \theta)$, with $\theta > 0$.
Let $\mathbf{I}$ denote the indicator function, where
$$\mathbf{I}(\cdot) = \begin{cases}
1, & \cdot \text{ is true} \\
0, & \cdot \text{ is false.}
\end{cases}$$
The probability density function of any of the $X_i$, for $i \in \{1, \dots, n\}$, can be written like so:
$$f_{X_i}(x_i \mid \theta) = \dfrac{1}{\theta}\cdot\mathbf{I}(0<x_i<\theta)\text{.}$$
The likelihood function is thus given by
$$\begin{align}
L(\theta)&=f_{X_1, \dots, X_n}(x_1, \dots, x_n \mid \theta)\\
&=\prod_{i=1}^{n}f_{X_i}(x_i \mid \theta) \\
&= \dfrac{1}{\theta^n}\prod_{i=1}^{n}\mathbf{I}(0 < x_i < \theta)\text{.}
\end{align}$$
The following claim, although used, is often omitted from explanations:

Claim. Let $A$ and $B$ be events. Then $\mathbf{I}(A)\cdot \mathbf{I}(B)=\mathbf{I}(A \cap B)$.

I leave the proof of this to you. Note that $ 0 < x_i < \theta$ is the same as requiring both $x_i > 0$ and $x_i < \theta$. Hence, we write
$$\begin{align}
L(\theta)&=\dfrac{1}{\theta^n}\prod_{i=1}^{n}\mathbf{I}(0 < x_i < \theta) \\
&= \dfrac{1}{\theta^n}\prod_{i=1}^{n}[\mathbf{I}(x_i > 0)\mathbf{I}(x_i < \theta)] \\
&= \dfrac{1}{\theta^n}\prod_{i=1}^{n}[\mathbf{I}(x_i > 0)]\prod_{j=1}^{n}[\mathbf{I}(x_j < \theta)]\text{.}
\end{align}$$
It will be clear why I split the product as above in a bit.
The claim given above is true if we were to extend to an arbitrary number of events as well. Thus,
$$\prod_{i=1}^{n}[\mathbf{I}(x_i > 0)] = \mathbf{I}(x_1 > 0 \cap x_2 > 0 \cap \cdots \cap x_n > 0)$$
and
$$\prod_{j=1}^{n}[\mathbf{I}(x_j < \theta)] = \mathbf{I}(x_1 < \theta \cap x_2 < \theta \cap \cdots \cap x_n < \theta)\text{.}$$
The next claims are often omitted as well from explanations:

Claim 1. Given $x_1, \dots, x_n \in \mathbb{R}$, $x_1, \dots, x_n < k$ if and only if $$x_{(n)}:=\max_{1 \leq i \leq n}x_i  < k\text{.}$$
Claim 2. Given $x_1, \dots, x_n \in \mathbb{R}$, $x_1, \dots, x_n > k$ if and only if $$x_{(1)}:=\min_{1 \leq i \leq n}x_i > k\text{.}$$

Thus
$$\prod_{i=1}^{n}[\mathbf{I}(x_i > 0)] = \mathbf{I}(x_1 > 0 \cap x_2 > 0 \cap \cdots \cap x_n > 0) = \mathbf{I}(x_{(1)} > 0)$$
and
$$\prod_{j=1}^{n}[\mathbf{I}(x_j < \theta)] = \mathbf{I}(x_1 < \theta \cap x_2 < \theta \cap \cdots \cap x_n < \theta) = \mathbf{I}(x_{(n)} < \theta)\text{.}$$
The likelihood function is thus
$$L(\theta) = \dfrac{1}{\theta^n}\mathbf{I}(x_{(1)} > 0)\mathbf{I}(x_{(n)} < \theta)\text{.}\tag{*}$$
Now, consider the above as a function of $\theta$. For all intents and purposes, $\mathbf{I}(x_{(1)} > 0)$ is irrelevant when it comes to maximization of $L$ with respect to $\theta$, because it is independent of $\theta$. So, the part that really matters is
$$L(\theta) \propto \dfrac{1}{\theta^n}\mathbf{I}(x_{(n)} < \theta) = \dfrac{1}{\theta^n}\mathbf{I}(\theta > x_{(n)})\text{.}\tag{**}$$
Generally, when doing maximum-likelihood estimation, we assume that the observed $x_i$ fall within the support of the given distribution, so we'll just assume $x_{(1)} > 0$.
Remember to view (**) as a function of $\theta$. If $\theta \leq x_{(n)}$, note that $L(\theta) = 0$ because of the indicator function. This is not the maximized value of $L$; $L$ is, at its crux, a probability density function: $0$ is in fact the smallest value that a probability density function can take.
So, in attempting to maximize $L$, suppose that $\theta > x_{(n)}$. For $n$ fixed, we obtain
$$L(\theta) \propto\dfrac{1}{\theta^n}\text{.}$$
Now, note that $\dfrac{1}{\theta^n}$ is indeed a decreasing function of $\theta$ with $n$ fixed. Thus, we must make $\theta$ as small as possible, given our restriction of $\theta > x_{(n)}$.

Note. Technically, no such $\theta$ exists (because $\theta$ is strictly greater than $x_{(n)}$ per our assumptions). This is often ignored in many textbooks.

Most textbooks will then say that the maximum likelihood estimator of $\theta$ is
$$\hat{\theta}_{\text{MLE}} = X_{(n)}\text{.}$$

Note. Technically, the above result is false. The MLE does not exist, because $\theta$ cannot take on the value $x_{(n)}$ itself. For this answer to be correct, the support of the uniform PDF must include $\theta$ itself (because the maximum likelihood estimator equals one of the $X_i$). The reason for this is discussed in the Lecture 2: Maximum Likelihood Estimators from MIT OpenCourseWare 18-443 Statistics for Applications, found here. As the question currently stands, $(0, \theta)$ should be $(0, \theta]$.
Comment: +1. Perfect! I've saw so many solutions of this on MSE and google, but none was unable to explain how they "jump" from likelihood function to ML. Thanks!
Comment: you're a true beauty

MLE for Uniform $(0,\theta)$


ValueError: too many values to unpack (expected 2) when using tf.keras.preprocessing.image_dataset_from_directory

Question: I want to create a dataset-variable as well as a labels-variable using the function tf.keras.preprocessing.image_dataset_from_directory (https://www.tensorflow.org/api_docs/python/tf/keras/preprocessing/image_dataset_from_directory).
The documentation states:

Returns:
A tf.data.Dataset object.
If label_mode is None, it yields
float32 tensors of shape (batch_size, image_size[0], image_size[1],
num_channels), encoding images (see below for rules regarding
num_channels).
Otherwise, it yields a tuple (images, labels), where
images has shape (batch_size, image_size[0], image_size[1],
num_channels), and labels follows the format described below.

My code is the following:
train_ds, labels = tf.keras.preprocessing.image_dataset_from_directory(
  directory = data_dir,
  labels='inferred',
  label_mode = "int",
  validation_split=0.2,
  subset="training",
  seed=123,
  image_size=(img_height, img_width),
  batch_size=batch_size)

I expect to get a tuple as return values, but instead I get the error message:
Found 2160 files belonging to 2160 classes.
Using 1728 files for training.
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-168-ed9d42ed2ab9> in <module>
      7   seed=123,
      8   image_size=(img_height, img_width),
----> 9   batch_size=batch_size)

ValueError: too many values to unpack (expected 2)

When I save the output in one variable (just train_ds) and I inspect the variable, I get the following output:
<BatchDataset shapes: ((None, 120, 30, 3), (None,)), types: (tf.float32, tf.int32)>

How can I access the two tuples inside seperatly?
Comment: Thank you, but how can I access the both lists from train_ds?
Comment: Instead of train_ds, labels use only train_ds. You can get image_batch, labels_batch from train_ds. Thanks!
Answer: You can plot it with the code below
import matplotlib.pyplot as plt

plt.figure(figsize=(10, 10))
for images, labels in train_ds.take(1):
    for i in range(9):
        ax = plt.subplot(3, 3, i + 1)
        plt.imshow(images[i].numpy().astype("uint8"))
        plt.title(int(labels[i]))
        plt.axis("off")

What actually the code does is printing nine images from your dataset and adding title to each image.
Note that there is no need to get labels in your first line of code.


Fazer busca em profundidade usando uma pilha

Question: Estou tentando fazer uma busca em profundidade usando uma pilha, mas está dando erro em um if e não sei o motivo.
   package Grafos;
import java.io.*;
import java.util.*;
public class Grafo {
    LinkedList<Integer> Arestas [];
    int n;
    int qtd_Arestas = 0;
    public Grafo(int n){
        this.n = n;
        Arestas = new LinkedList[n];
        for (int i=0; i<n; ++i)
            Arestas[i] = new LinkedList();
    }
    public void Adiciona_aresta(int origem, int destino){
        Arestas[origem].add(destino);
        qtd_Arestas++;
    }
    public int DFS(int S, boolean visited[], int contador){
        visited[S] = true;
        ListIterator<Integer> v = Arestas[S].listIterator();
        while(v.hasNext()) {
            n = v.next();
            System.out.println(S + ">>" + n);
            if(!visited[n]){
                contador = DFS(n,visited,contador+1);
            }
        }
        return contador+1;

    }
    public void DFS_ini(int S){
        boolean Visitados[] = new boolean [n];
        int contador = 0;
        int b = DFS(S,Visitados,contador);
        System.out.println("____________________________________________________");
    }

    public void Pilha_DFS(int S) {
        boolean visitados [] = new boolean [n];
        for(int i = 0; i < n;i++){
            visitados[i] = false;
        }
        int gatilho;
        int topo;
        visitados[S] = true;
        Stack pilha = new Stack();
        pilha.push(S);
        while(!pilha.isEmpty()){
            topo = (int) pilha.firstElement();
            if(Arestas[S].isEmpty()){
                gatilho = 1;
                break;
            }
            for(int linha : Arestas[S]) {
                if(visitados[linha] == false){//Erro aqui
                    System.out.println(S + ">>" + linha);
                    visitados[linha] = true;
                    pilha.add(linha);
                    S = linha;
                }else if(visitados[topo] == true){
                    pilha.remove(topo);
                }
            }
        }

    }
}

Erro apresentado:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
    at Grafos.Grafo.Pilha_DFS(Grafo.java:55)
    at Grafos.Main.main(Main.java:12)

Comment: Qual é o erro? `ArrayIndexOutOfBoundsException`?
Comment: Qual é o tipo de `Arestas`? O código dá a entender que é algo como `List[]`, mas tenho algumas dúvidas.
Comment: `Stack` é `java.util.Stack` ou é alguma outra implementação de pilha?
Comment: eu vou por o codigo completo para um entendimento melhor.
Comment: Codigo completo agora
Comment: Respondi com base no código que havia originalmente. Vou atualizar a resposta daqui há pouco considerando o código completo.
Answer: O procedimento deveria ser mais ou menos assim:

Insere o primeiro nó na pilha e marca como visitado.
Enquanto houver nós na pilha, desempilha o nó e empilha todos os seus vizinhos que não tiverem sido visitados, marcando-os como visitados.

Note que há uma restrição aí: Apenas nós visitados podem entrar na pilha. Isso significa que o else if no final é uma violação dessa restrição. Mais do que isso, ele é uma violação do conceito de pilha, onde você está tentando remover um elemento do meio da pilha ao invés de remover do topo. Aquele remove não deveria estar lá.
A classe java.util.Stack herda o método remove(int) de java.util.Vector. Este método não faz o que você espera que faria. Ele não vai remover o elemento topo da pilha. Ao invés disso, ele vai interpretar topo como sendo a posição do elemento a ser removido. Isso vai bagunçar totalmente com a sua pilha.
Inclusive, não é recomendado utilizar-se a classe java.util.Stack devido a inúmeras falhas de projeto que ela tem (principalmente por herdar de Vector). Veja mais sobre isso aqui. O ideal é você implementar a sua própria pilha (vou dar um nome diferente para evitar confusão):
import java.util.NoSuchElementException;

public interface Pilha<T> {
    public T top() throws NoSuchElementException;
    public T pop() throws NoSuchElementException;
    public void push(T element);
    public boolean isEmpty();
}

import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;

public class PilhaArrayList<T> implements Pilha<T> {
    private final List<T> elementos;

    public PilhaArrayList() {
        this.elementos = new ArrayList<>();
    }

    @Override
    public T top() throws NoSuchElementException {
         if (isEmpty()) throw new NoSuchElementException();
         return elementos.get(elementos.size() - 1);
    }

    @Override
    public T pop() throws NoSuchElementException {
         if (isEmpty()) throw new NoSuchElementException();
         return elementos.remove(elementos.size() - 1);
    }

    @Override
    public void push(T element) {
        elementos.add(element);
    }

    @Override
    public boolean isEmpty() {
        return elementos.isEmpty();
    }
}

Seu código arrumado deve ser assim:
    public void pilhaDFS(int s) {
        boolean[] visitados = new boolean[n];
        visitados[s] = true;
        Pilha<Integer> pilha = new PilhaArrayList<>();
        pilha.push(s);
        while (!pilha.isEmpty()) {
            int topo = pilha.pop();
            for (int linha : arestas[s]) {
                if (visitados[linha]) continue;
                System.out.println(s + ">>" + linha);
                visitados[linha] = true;
                pilha.push(linha);
            }
        }
    }

Observe que o valor da variável gatilho nunca era lido em lugar nenhum, e portanto era inútil. O break que acompanhava o gatilho era nocivo, pois impedia a sua busca de voltar alguns passos e tentar prosseguir por outro caminho tão logo encontrasse o primeiro "beco sem saída". Inicializar o array visitados com tudo false é desnecessário pois todo array de boolean já é criado com false em todas as posições.
Por fim, é boa ideia seguir as convenções de código no que diz respeito a nomenclatura de variáveis.
Olhando para o resto do código, tipos genéricos e arrays não se dão bem juntos. Sugiro modelar as arestas com lista de adjacência:
private final Map<Integer, List<Integer>> arestas;

O código da sua classe fica assim:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public Grafo {
    private final Map<Integer, List<Integer>> arestas;
    private final int n;
    private int qtdArestas = 0;

    public Grafo(int n) {
        this.n = n;
        arestas = new HashMap<>();
    }

    public void adicionaAresta(int origem, int destino) {
        List<Integer> adjacencias = arestas.get(origem);
        if (adjacencias == null) {
            adjacencias = new ArrayList<>();
            arestas.put(origem, adjacencias);
        }
        adjacencias.add(destino);
        qtdArestas++;
    }

    // Resto da classe.
}

O método pilhaDFS que mostrei acima ficaria quase igual. A única mudança é que arestas[s] viraria arestas.get(s).
Seus métodos dfs ficariam assim:
    private int dfs(int s, boolean[] visited, int contador) {
        if (visited[s]) return contador;
        contador++;
        visited[s] = true;
        for (int n : arestas.get(s)) {
            System.out.println(s + ">>" + n);
            contador = dfs(n, visited, contador);
        }
        return contador;
    }

    public void dfs(int s) {
        int b = dfs(s, new boolean[n], 0);
        System.out.println(contador);
    }

Note que o dfs com vários parâmetros é privado.
Comment: Muito obrigado, ajudou bastante.
Comment: @AmandaNunes Terminei a resposta. Foi um prazer ajudá-la.
Comment: Amigo, tem uma parte q ta dando erro ainda
Comment: @AmandaNunes Qual é?
Comment: ja consertei, muito obrigado


Android NumberFormatException: Invalid Double - except the value is a valid Double

Question: So the other day, the following error popped up in the Crashes section of the Google Play Developer Console:
java.lang.NumberFormatException: Invalid double: "−0.05"

Now correct me if I'm wrong, but that is in fact a valid double - and it is recognised as a valid double on my computer, on the emulator and on my own Android device (Nexus 5)
The device that it crashed on was a Galaxy Note II running Android 4.3 - any ideas as to why it might be crashing please?
Comment: Show the code. Likely the user was running with a `Locale` with `,` as decimal separator. Parse your numbers with explicit locales.
Comment: There is a nice section called [Be wary of the default locale](http://developer.android.com/reference/java/util/Locale.html) in the `Locale` documentation
Answer: It is or isn't a valid double depending on your Locale. With a US/ENGLISH locale, -0.05 is a valid double but with a FRENCH locale for example, it is not (it should be -0,05 with a comma).
You can see it in action with:
NumberFormat fmt = NumberFormat.getNumberInstance(Locale.US);
double d = fmt.parse("-0.05").doubleValue(); //-0.05

fmt = NumberFormat.getNumberInstance(Locale.FRENCH);
d = fmt.parse("-0.05").doubleValue(); //-0.0
d = fmt.parse("-0,05").doubleValue(); //-0.05

EDIT
However your issue is maybe not that. The minus sign is not valid. You are using − instead of - (they look the same but are not the same character). Demo:
Double.parseDouble("-0.05"); //ok
Double.parseDouble("−0.05"); //exception

Comment: My only problem with this is that nearly 50% of my app users' devices use a non-English Locale - so how come this issue has only occurred once, out of thousands of devices, over a period of several months?
Comment: @BenEzard How do you parse the number? `Double.parseDouble`?
Comment: Yep, just that method - and the input String is always formatted with a '.' (guaranteed to be in this format because it's from a file downloaded from my server)
Comment: Unlikely that this is the issue, as it has worked fine on thousands of other devices with the exact same code?
Comment: @BenEzard If you copy paste the string in your question and try to parse it, you will get an error. Maybe the string was generated differently for some reason?
Comment: Indeed you're right - which is weird considering the String is retrieved from a MySQL database from a column with a datatype of Double.

Ah well, at least we got to the bottom of it - thanks :-)
Comment: You are faced with a Java language restriction ... not what "runs on thousands of devices".  Only the "hyphen" is used as the unary negative operator (and the subtraction dyadic operator), not the long dash
Answer: For double constants, the language asks you to use the form  -0.05d  (with the "d" suffix).  See this for reference
Also make sure that the symbol intended to be a minus sign is a "hyphen" and not a "long em dash".
Comment: This isn't mandatory though - any floating point number without an "f" or "d" suffixed is automatically determined to be a double - indeed, under the "Floating-Point Literals" section in your link, they write `double d1 = 123.4;`
Comment: And about the minus sign - if it works fine on all other devices, then I presume it's the correct character?


Apache csv file download not in excel

Question: I have a CSV file thats been hyperlinked. When the user clicks it, its supposed to open in a XLS file but for some reason its opening in HTML page..How can I fix it?
The python bottle application runs on apache webserver.
PRODUCT_LIST.csv

Comment: csv is probably being served up as text/plain. you'd have to serve it up with an appropriate excel mime type, e.g. http://stackoverflow.com/questions/974079/setting-mime-type-for-excel-document
Answer:
Assuming this to be a link to a static .csv file that is directly linked,  you can modify the
mime types definitions on your webserver to set the Content-Type header
for csv as  ms-xl file type.
If you are using apache webserver , edit the mime.types  file to add the following line:
application/vnd.ms-excel csv
of-course then all .csv files would be opened by default in the MS-Excel app.

2.If the file is dynamically generated , then set the response header 'Content-Type:application/vnd.ms-excel'  in your server side code.
Answer: You're confusing a Microsoft Excel spreadsheet, .xls with a comma separated value file, .csv.
csv is just a text file in which tabular data is delimited by a comma (or a tab, a dot, a semicolon, etc). Your browser can handle this file type as a text file and will display it as such.
You will have to modify the HTTP header and change the Content-Type to something more fitting.

Apache csv file download not in excel


How to implement charts in Python without libraries such as Matplotlib or PyQtChart?

Question: I'm starting a programming project as a part of my studies. My project will be a data visualization program that must be able to at least visualize or "draw" a line chart and possibly other charts such as a bar or a pie chart. However I'm not allowed to use Python libraries that make this easy (such as Matplotlib, QtDesigner, NumPy or PyQtChart). The visualization should be done with PyQt.
The project seems really hard to me as I'm quite new with programming. I was wondering if anyone has experience with similar programming projects or tips to help me approach the project. Thanks in advance!
Also, if this is not a relevant question for StackOverflow, let me know and I'll take it down.
Comment: Why you're not allowed to use those libraries? Also, QtCharts is part of Qt (and Designer has nothing to do with charts, nor python), so I don't understand the limitation.
Comment: It is a beginners' course in Python so the goal is to implement the project with more traditional Python tools. And regarding QtCharts, it would make the project too "easy" so it is prohibited.
Answer: Considering the constraints, the only remaining solutions are using custom widget painting through QPainter, or using the Graphics View Framework, which is more powerful but also much more complex.
In the following two simple examples you can see some differences between the two approaches, which will show the same data.
QWidget subclassing is normally much more simpler since you can directly draw basic shapes (including ellipses, arcs and pies). You just have to implement the paintEvent (remember, QPainter on a widget can only happen in a paint event! You cannot call paintEvent() on your own) construct a QPainter on the widget and then begin drawing.
This simplicity has the drawback that if you need higher modularity and better control it will probably result more cumbersome to modify.
The Graphics View (which is exactly what QtCharts uses) allows higher extensibility as it provides an object oriented framework (using QGraphicsItem subclasses) and, as such, allows manipulation of existing data, so you can add/remove bars/pies/etc more easily; unfortunately, it is as powerful as hard to get along with, and it requires some long studying and experimenting in order to begin to really grasp it.
from PyQt5 import QtCore, QtGui, QtWidgets
from random import random, randrange

class ChartWidget(QtWidgets.QWidget):
    def __init__(self, data):
        super().__init__()
        self.data = data
        self.setMinimumSize(480, 320)

    def paintEvent(self, event):
        if not self.data:
            return
        columnSpace = self.width() / len(self.data)
        columnWidth = columnSpace * .6
        qp = QtGui.QPainter(self)
        labelHeight = self.fontMetrics().height()
        columnHeight = self.height() - labelHeight
        for i, (value, color) in enumerate(self.data):
            height = columnHeight * value
            x = i * columnSpace
            bar = QtCore.QRect(x, columnHeight - height, columnWidth, height)
            qp.setBrush(color)
            qp.drawRect(bar)
            labelRect = QtCore.QRect(x, columnHeight, columnSpace, labelHeight)
            qp.drawText(labelRect, QtCore.Qt.AlignLeft, 'Value {}'.format(i + 1))

class ChartView(QtWidgets.QGraphicsView):
    def __init__(self, data):
        super().__init__()
        scene = QtWidgets.QGraphicsScene()
        self.setScene(scene)
        self.setRenderHint(QtGui.QPainter.Antialiasing)

        pen = QtGui.QPen(QtCore.Qt.black, 1)
        pen.setCosmetic(True)
        for i, (value, color) in enumerate(data):
            # for simplicity, I created rectangles from the *bottom*
            bar = scene.addRect(QtCore.QRectF(0, 0, 600, -value * 1000))
            bar.setX(i * 1000)
            bar.setPen(pen)
            bar.setBrush(color)
            label = scene.addSimpleText('Value {}'.format(i + 1))
            label.setFlags(QtWidgets.QGraphicsItem.ItemIgnoresTransformations)
            label.setX(i * 1000)

    def resizeEvent(self, event):
        super().resizeEvent(event)
        self.fitInView(self.sceneRect().adjusted(-10, -10, 10, 10))

import sys
app = QtWidgets.QApplication(sys.argv)

data = []
for i in range(randrange(5, 10)):
    data.append((
        random(),
        QtGui.QColor(randrange(255), randrange(255), randrange(255))))

test = QtWidgets.QWidget()
layout = QtWidgets.QHBoxLayout(test)
layout.addWidget(ChartWidget(data))
layout.addWidget(ChartView(data))

test.show()
sys.exit(app.exec_())

Some considerations:

widgets can have children; you can create a basic widget class for a single "bar", then add them to another widget with a layout;
pie graphs are a bit more trickier with the above implementation; also note that QPainter uses units of 1/16th of a degree for angles;
similarly to creating a QWidget class for bars, you can create a QGraphicsRectItem subclass for graphics view instead of using the convenience functions addRect() as above;
remember that all graphics items initially have 0x0 coordinates, this also includes creating a rectangle at (100, 100), which is a rectangle item positioned at 0x0, but that shows the rectangle at 100x100 relative to the position;
Comment: Thanks for a great answer!  This helps a lot, I appreciate it.


displaying a webform in an overlay

Question: I want the user defined webform to be popped up in an overlay when a button is clicked. I am using colorbox and colorbox-node modules. I am able to display the whole node. But I am not understanding how to display just the webform instead of the whole node. I used the following code:
 <input value="Send Enquiry" type="submit">

Comment: Do you mean Webform module? If not, please try avoid the word, as it has pretty specific meaning in Drupal. And remove the tag. Either way, please tell us exactly how have you created your form, as it defines what can be done with it.
Answer: If I need to display webform in popup, then I would use ctools modal.
You can use modal forms module which make use of the modal feature in the ctools module to open some common forms in a modal window.
Supported forms

Log in (modal_forms/nojs/login)
Request new password (modal_forms/nojs/password)
Create new account (modal_forms/nojs/register)
Contact (modal_forms/nojs/contact)
Comment (modal_forms/nojs/comment/reply/%node)
Webform (modal_forms/nojs/webform/%node)

May be this is not answer to your question as you are using colorbox, but I am adding this so that you can check other option.
Answer:
you can enable webforms as a block --> select the webform content
you created, tab "Webform" > "Form Settings" > "Enable as a block"
put the block inside a region, I've put mine in the footer region
CSS style the footer webform block as "display: none;"
for colorbox: in "configuration", "Media", "Colorbox" --> advanced
settings, activate "Enable Colorbox inline"
add this as the html code for opening the colorbox webform link:

You can also display the webform in popup using Colorbox Node module.

Gives the user the ability to display ANY page inside a colorbox modal
  without the header and footer. Those pages include:

Node Pages
User Pages
Views Pages
Webforms (requires Webform Ajax Module)
Integration with Views
Integration with Context
Integration with Panels
Comment: anjaan has used colorbox-node as a tag so he might be already using it.
Comment: i have already tried both the things but no success
Comment: the problem is that i can open the whole node but not the particular webform.
Comment: In the colorbox module page I read that "Form support in Colorbox is removed in 7.x-2.x" and we should use Modal Forms as suggested by Jayendra
Answer: Check out these link how to display webform in overlay
Allow webforms to open in Colorbox
 display a popup box containing webform using simple dialog module

displaying a webform in an overlay


C# HttpClient throws Exception on no Sucess Status Codes

Question: i got a very weird problem. When I request a Webpage that return an Status Code that isn't a 2** Statuscode than HttpClient throws an ecxeption.
Implementation:
<code>try {

    //post-anfrage an webservice starten
    var request = await httpClient.PostAsync(SettingsPage.WebServiceURL + site,
                content);

    if (!request.IsSuccessStatusCode) {
        if (request.StatusCode == System.Net.HttpStatusCode.Unauthorized) {
            await User.Instance.Logout();
        }
        var message = await request.Content.ReadAsStringAsync();
        RaiseErrorMessage(null, message);
    }

    SaveCookies(request);

    timer.Change(PING_INTERVAL, PING_INTERVAL);

    return request;
}
catch (TaskCanceledException e) {
    RaiseConnectionError(null, "Verbindung zu Webservice fehlgeschlagen!");
    return null;
}
catch (Exception ex) {
    RaiseConnectionError(null, "Es ist etwas schief gelaufen..." + System.Environment.NewLine + "Bitte Support Kontaktieren!");
    Debug.WriteLine("AppWarehouse.pro: " + ex.Message);
    Debug.WriteLine("AppWarehouse.pro: " + ex.StackTrace);
    return null;
}
}
</code>
I don't understand why it does what it does. For me there is no reason for that behaviour. I'd be happy about a fix or help to fix it.
Comment: !request.IsSuccessStatusCode  - this throws an error if the StatusCode is not in the 2** range. If you're getting 404 for example that line of code will cause an error. You are posting content and you want to know if the operation went as expected.
Comment: @DanielHollinrake not that isn't what causes the problem. It still throws the exception called HttpRequestException.
Comment: So, the code is throwing an exception before the if statement? If that is the case then could you confirm what type the httpClient is please?
Comment: @DanielHollinrake Yes before the if-statement... HttpClient is from System.Net.Http;
Comment: How do you know that there is a response status i.e 404 or 403 instead of an HResult?
Comment: @Barnstokkr Because i return in my WebAPI an explicit Statuscode
Comment: What is the HttpStatus code that is generated when the HttpClient throws an exception? Can you please add the `Debug.WriteLine("AppWarehouse.pro: " + ex.Message);` message.
Stating that your API returns a StatusCode isn't very helpful in helping you. I'm assuming that this code isn't your actual code since, there is no way you can get the StatusCode by returning a `null`. And, HttpRequestException is only thrown when an HResult exception occurs.
Comment: @Barnstokkr ex.Message is just saying that an error occurd while sending that request... I return null, because the Function wants the request result back. Therefore i return null, because i haven't got an result
Answer: I fixed it... It was a strange behaviour from Xamarin combined with an assembly.


derivative of log(y) function.

Question: I am trying to find derivative of log function.
How would I apply the chain rule on a basic example?
$$\ln(y)=m+bx$$
I think it is
$$\frac{dy}{dx}=e^{m+bx} *b.$$
Is this correct?
Comment: For clarification: by $\log(y)$ do you mean the base-$e$ logarithm, i.e. natural logarithm? And also, the derivative of $y$ with respect to $x$, or the other way around?
Comment: yes, you are correct.
Comment: You might also find your question more well-received if you include your own attempts on the problem in the body of the question, what you understand, and what you're stuck on
Comment: I updated the question with base-e logarithm and what I thought the derivative would be, sorry. @EeveeTrainer
Answer: $\ln y = m + bx; \tag 1$
differentiate with respect to $x$:
$\dfrac{y'}{y} = b; \tag 2$
$y' = by = be^{m + bx}, \tag 3$
since from (1)
$y = e^{m + bx}. \tag 4$
Our OP thesmallprint's result is thus correct.
Answer: Using the definition of a derivative, $$\frac{d}{dy}{\log y}=\lim_{\epsilon\to 0}\frac{\ln(1+\frac{\epsilon}{y})}{\epsilon}.$$ Since logarithms are monotonic, the derivative doesn't vanish at $0$, so a Taylor-series argument implies a constant $k$ exists for which $\frac{d}{dy}\log y=\frac{k}{y}$. The value of $k$ depends on the logarithm's base. One definition of $e$ is as the basis obtaining the $k=1$ natural logarithm $\ln y$.

derivative of log(y) function.


Limits at infinity involving trigonometry

Question: I was wondering as I stumbled upon a question like this:
$$
\lim_{x\to(\pi/2)^+}\frac{\tan(x)-x}{\tan(2x)+3}
$$
$\tan(x)$, when $x$ is approaching $\pi/2$ is $-∞$, and I know that from the graph, but is there any other way that this can be done without looking at the graph? Maybe using a calculator, or drawing a table?
EDIT:  I would also like to ask why is $\tan(2x) = 0$ and not $-∞$ like $\tan(x)$.
Comment: You must know the graph of standard functions to be able to solve these kind of things. Or at least know that $\tan(x) =\sin(x) / \cos(x) $. That is my opinion.
Answer: use that $$\tan(2x)=\frac{2\tan(x))}{1-\tan(x)^2}$$ and $$\tan(x)=\frac{\sin(x)}{\cos(x)}$$
Answer: Tan (2x) evaluates the tangent of 2*x, not of x. Thus, tan lim tan(2x) as x-> pi/2 evaluates tan(pi), which = 0.
Also, as Dr. Graubner said in his answer, use the trig identities to rewrite the function to find the proof analytically.


the difference between using an AR(1) term (as in GAMM) versus using PM lag variable (in GAM)

Question: I conducted an experiment to predict particulate matter (PM) level using a GAM. To do so I included the lag1 PM (PM value of day before) as well as few meteorological terms.
In my second experiment using GAMM model, I know I need to incorporate the auto-correlation into the model.
My question is what is  the difference between using an AR(1) term (as in GAMM) versus using PM lag variable (in GAM)?
I appreciate your respond.
Answer: Think of the error term $\epsilon_t$ in a GAMM model with a continuous response (i.e., $PM$) as being an umbrella term which captures the effect of all other factors NOT included in your model on the $PM$ value recorded at time $t$. Usually, we might not even know what these factors are, though there are cases where we know what some of these factors are but we decided not to include them in the model even though we measured them.
If you assume this error term to follow an AR(1) process, you are simply stating that you believe the error term at time t depends on the error term at time t - 1. In other words, you believe that knowing how these other factors affect PM at time $t-1$ will allow you to predict how they influence $PM$ at time $t$.
When you include $PM_{t-1}$ in the model, you are assuming that the level of $PM$ at time $t-1$ influences the level of PM at time $t$, which is a different thing altogether.
Comment: Thank you Isabella for explanation. One more question: If my time series of PM is not stationary do I need to make it stationary before using GAMM with AR(1)? The acf and pacf plot of the residuals show non-stationary if I don't use differenced PM.
Comment: If you look at a plot of PM versus time, as well as plots of your meteorological predictors versus time, you will likely notice that all of these plots exhibit temporal patterns (e.g., temporal cycles).  In that case, you should include a smooth term of time in your model, along with (linear or smooth) terms for the meteorological variables.  You can then plot the residuals from this model against lag-1 PM to see if there's evidence of a systematic trend in this plot. If there is, include lag-1 PM in your model and then examine the new residuals for any evidence of autocorrelation.
Comment: thank you Isabella for great help.


Translate module strings

Question: In a custom D8 theme, we have some strings in twig using |t filter and in php using $this-t() funtion.
example :

{{'More Headlines'|t}}

$this->t('replies')

These strings are not listed in /admin/config/regional/translate. What's the right way to translate it via the administration interface like it was possible with D7?
Answer: You just need to first visit the page rendering the string you want to translate while using any other language.
Drupal only adds this string to the database once it has been rendered once, and you will be able to see it in the <code>/admin/config/regional/translate</code> page.
Comment: let's say your string is displayed on page /headlines (and your default language is english). Go to http://example.org/fr/headlines and just after you will see the string appear in User Interface Translate (`/admin/config/regional/translate`)

Translate module strings


How to instruct linux not to swap out hot pages of mmaped files?

Question: I have a server where I run worker processes that mmap serveral rather big read-only "dictionary" files (~8GB total). Tests showed that they actively access only around ~1GB worth of the pages in these files. On the same server I run another process that sequentially reads a huge file, merges some updates to it and writes the result in a new version of this huge file. There in no other major activity on the server besides this "merger" process and "worker" processes. So normally the workers should be CPU-bound and the merger should be disk-bound. But what I see is that the workers are constantly choking on major page faults. The merger uses around 20GB of RSS and the machine has 48GB. There are 4 workers. They have 2GB RSS each and only 600MB shared (instead of expected 1GB of hot pages). Somehow rest of the memory is mostly used by fs cache. Is there a way to "prioritize" the hot pages of my mmaped files into memory?
I tried madvise(MADV_WILLNEED) but it doesn't seem to help. Maybe there is a solution with cgroups or sysctls?

$ free
             total       used       free     shared    buffers     cached
Mem:      49324064   48863392     460672          0      22520   25409896
-/+ buffers/cache:   23430976   25893088
Swap:            0          0          0

$ uname -a
Linux dev-kiwi02 3.2.0-25-server #40-Ubuntu SMP Fri May 25 13:12:35 UTC 2012 x86_64 GNU/Linux

P.S. Asked this on StackOverflow already but looks like ServerFault is more appropriate.
Answer: What you probably need is mlock(), not madvise(). Madvise is too 'weak'; mlock locks the memory in the kernel. Assuming you have enough RAM and only lock the 'hot' pages (not the whole 8GB) that shouldn't be a problem for your setup.
Another solution that may seem counterintuitive: disable swap. Your machine has 48GB; subtract 4 workers, shared data and your OS and you have still > 35 GB left. You write that your merger reads a file sequentially and inserts a few entries; therefor I assume you don't need to keep the big file in memory but can write it out sequentially as well; you only need to load all your updates in memory which shouldn't be a problem.


8086Assembly - Unable to Reverse String

Question: JMP START
MSG1 DB "ISSK$"
MSG2 DB 80 DUP("$")
START:

MOV SI,00H
MOV DI,00H

LOOPER:
CMP MSG1[DI],"$"
JE COMPARE
INC DI
JMP LOOPER  ;AFTER THIS POINT DI=STRINGLENGTH-1

COMPARE:
MOV AL,MSG1[DI]
MOV MSG2[SI],AL
INC SI
DEC DI
CMP MSG1[DI],00H
JE OUTER
JMP COMPARE

OUTER:
MOV DX,OFFSET MSG2
MOV AH,09H
INT 21H
HLT

The console of my EMULATOR(emu8086) finally prints a Blank Screen instead of the Reversed string. Where did I go wrong?
Answer: When you exit LOOPER and go to COMPARE, DI contains the index of the '$' terminator character, which you then place at the start of MSG2. You should decrement DI before entering the COMPARE loop so that it contains the index of 'K'.
Then you've got CMP MSG1[DI],00H which doesn't make any sense. I suspect that you wanted to check if DI == 0. If so, this entire part:
DEC DI
CMP MSG1[DI],00H
JE OUTER
JMP COMPARE

could be replaced by:
DEC DI
JNZ COMPARE  ; continue the COMPARE loop as long as DI != 0

8086Assembly - Unable to Reverse String


Variance of linear combinations of Normal RVs in linear regression

Question: I am working with a standard multivariate linear regression model ($Y = X \lambda + \epsilon$, $Y$ and $\epsilon$ of length $n$, $X$ is $n$ x $m$, $\lambda$ of length $m$). $X$ is said to be "column-standardized", which I take to mean each column has mean $0$ and variance $1$, and each $\epsilon_i \sim N(0, \sigma^2)$. I am looking for the distribution of $X^T \epsilon$. Specifically, I have two questions.

If $X$ is column-standardized, does that mean each $X_{ij} \sim N(0, 1)$? It seems like it should, since this is just a z-transformation, but then I'm curious as to why the procedure needs to be done on columns separately. Is it because we assume that each column comes from a unique distribution with different original variances?
If every column in standardized, then each entry $(X^T\epsilon)_j = \sum_{i=1}^{n} X_{ij} \epsilon_i$, which I think is a linear combination of standard normal distributions where the coefficients are also normal. Sums of normals are normal, and so I think that $(X^T\epsilon)_j \sim N(0, \_)$, but I'm having a hard time figuring out the variance. I don't think it's $n\sigma^2$, but I can't figure out what else it would be.

Any help would be greatly appreciated!
Comment: Standardizing a variable does not make it normally distributed.
Comment: You have a _product_ of two independent normal random variables in $X_ij\epsilon_i$, See e.g. _[here](https://stats.stackexchange.com/a/15986/6633)_ for the formula for the variance of the product. Then, use standard formulas for the variance of a sum of independent random variables.
Answer: If the $X$'s are assumed independent from the $\epsilon$'s, then simple algebra produces a nice looking formula, irrespective of distributional assumptions. In general notation,
$$\text{Var}(XY) = E(X^2Y^2) - [E(XY)]^2 = E(X^2)E(Y^2) - [E(X)E(Y)]^2$$
Using the symbols $\sigma^2$ and $\mu$  we have
$$\text{Var}(XY) = (\sigma^2_x +\mu_x^2)(\sigma^2_y+\mu_y^2) - \mu_x^2\mu_y^2$$
and simplifying and rearranging,
$$\text{Var}(XY) = \sigma^2_x\sigma^2_y + \mu_x^2\sigma^2_y+\mu_y^2\sigma^2_x$$
In case of zero means, this reduces to
$$\text{Var}(XY) = \sigma^2_x\sigma^2_y $$
Let's not forget that the fact that we obtained $\text{Var}(XY) = \text{Var}(X)\text{Var}(Y) $ depends not only on the independence assumption, but also on the zero-mean assumption.
Comment: This is essentially what Macro wrote in the link provided in my comment on the OP's question.
Comment: Thanks very much Alecos and Dilip. Following up -- so $E(X_{ij}\epsilon_i)=0$ and $Var(X_{ij}\epsilon_i)=\sigma^2$, but $X_{ij}\epsilon_i$ isn't necessarily the product of two normals. Do you have a sense of what kind of distribution it might follow?


OctoberCMS: How to change the view of uploaded files for "attachMany" relation type?

Question: The default view of the attachMany relations, tries to show the preview of the file even for non-image files. For example in the following snapshot, october tries to show preview of the pdf files:

As you can see, the preview fails for pdf files. I need to fix this behavior. How can I override the HTML shown for the uploaded files?
Answer: Can you post the fields.yaml config for the form?
I guess it includes
type: fileupload
mode: image

Mode image is what tells october to create thumbnails
Comment: You really should clarify your question!
Comment: Thank you. Changing mode to `file` fixed the problem :)


Theme the User Edit Profile page

Question: I am using the Edit Profile module.
This module takes all the fields attached to a user profile and displays them on a separate tab located at yoursite.com/user/[USERID]/edit-profile.
I would like to theme the fields on this edit profile page. How can I do it?
I have tried two approaches but none seem to work:
Approach 1: Tpl.php suggestion from theme developer
Theme Developer suggests to use the following template: page--user--edit-profile.tpl.php
This however has two problems:
1) It affects the whole page and not just the user profile form.
2) It doesn't seem possible to access the fields on the user profile from this template.
Approach 2: template.php
The form ID of the user profile edit form is edit-profile-user-profile-form so I used the following code in my template.php file to override it:
function THENAME_theme(&$existing, $type, $theme, $path) {

    return array(
        'edit-profile-user-profile-form' => array(
            'arguments' => array('form' => NULL),
            'template' => 'templates/edit/user-profile',
            'render element' => 'form',
            ),
    );

}

This, however, only over rides the main user profile page and not the fields on the edit tab. Can anyone help?
Comment: look for my [answer on adding css to user pages](http://drupal.stackexchange.com/questions/37192/how-can-i-write-url-specific-css/37193#37193)...
Answer: I have figured this out.
The solution is to use approach 2 (in my opening post). However, in the template.php file, you have to remove all the dashes from the form ID (edit-profile-user-profile-form) and replace them with underscores.
So the code in template.php would be as follows:
function THENAME_theme(&$existing, $type, $theme, $path) {

    return array(
        'edit_profile_user_profile_form' => array(
            'arguments' => array('form' => NULL),
            'template' => 'templates/edit/user-profile',
            'render element' => 'form',
            ),
    );

}
Next create a file called user-profile.tpl.php and save it in templates/edit.
In the user-profile.tpl.php file, use the following code to print out the fields:
<?php print drupal_render($form['field_NAME_OF_FIELD']); ?>

Comment: is this a working version i tried using the template and placed it in my theme module file but the template isnt being detected. I am using drupal 7.
Comment: @Alexander. Yes this works. Make sure it is your theme directory (not module file) and that you have cleaned the cache.
Comment: @big_smile You mentioned in your question that you want to theme the fields in edit profile page. Right? Why not just use css?
Answer: I think, this may work. Little modification.
function THENAME_theme(&$existing, $type, $theme, $path) {
return array(
    'user_profile_form' => array(
        'arguments' => array('form' => NULL),
        'template' => 'templates/edit/user-profile-edit',
        'render element' => 'form',
        ),
);

}
Next go to your theme (sites/all/theme/yourtheme/) and create file called user-profile-edit file inside templates/edit/. Try to dpm($form). You will get whole form elements. You can render one by one whichever you needed.

Theme the User Edit Profile page


How to find the limits or boundary of integration between two points?

Question: Im trying to calculate the work done of a field between two points. The thing im struggling with is find the limits of integration. ie.
$$\int_a^b$$
Can anyone help, if the points were A(1,2) and B(3,4) what method would I use?
Comment: The limits are simply your points $A(1,2)$ and $B(3,4)$. You integrate along a curve from A to B. [Wikipedia has a nice animation to explain the concept](https://en.wikipedia.org/wiki/Line_integral#Line_integral_of_a_scalar_field)
Comment: If you already have an equation for a curve that links the two points, say $x=x(t), y=y(t)$, then you have to integrate w.r.t. $t$, and the limits are simply the $t$ values for which $(x(t_0),y(t_0))=A$ and $(x(t_1),y(t_1))=B$
Comment: Do you know line integrals? The specific problem (i.e. with acting field written explicitely) would be good to see.
Comment: @ Wouter but once ive integrated, how can substitute in the point A(1,2) like it is a point of (x,y) do x get substituted into x and y into y ??
Comment: @Tomas I do but after i integrate can i substitute the points in, would i substitute the point A(1,2) into the equation after integration?
Comment: No it isn't like that. Your first step is to find a curve which connects the points $A$ and $B$ and then do a line integral over that curve with respect to the field. It really sounds like you need to look up what a line integral is. The link to in the first comment will tell you what you need to know.
Comment: @BernardWojcik Ive done that! its easy to find an equation that links the two points and then ive done the line integral with respect to the field. Its just the limits that i dont know how to do
Answer: Let $\phi:[a,b]\rightarrow \Bbb R^2$ be some parametrisation of a curve $\Gamma$ with endpoints $\phi(a)=(1,2)=A$ and $\phi(b)=(3,4)=B$
To calculate the work done by the field $F$ as you move from $A$ to $B$ along $\Gamma$ you need to evaluate the line integral $\int_a^bF(\phi(t))\cdot \phi'(t) \,dt$
For example, you could choose your curve $\Gamma$ to be the line segment joining $A$ and $B$ and your parametrisation to be $\phi:[0,1]\rightarrow \Bbb R^2$ given by $\phi(t)= (2t+1,2t+2)$ so the line integral would be $\int_0^1F(2t+1,2t+2)\cdot(2,2) \,dt$
Note that not only some fields (the conservative ones) will give you the same result for all curves.


how do I troubleshoot an external database access?

Question: I successfully setup a Drupal 6 site to access external databases and present them in tables via Views.
Now I am trying to move to Drupal 7, and I'm not sure how to troubleshoot.  In Drupal6, I can open table wizard after editing the settings.php file; it shows the new tables and I can add them.
Is there a way to know if Drupal 7 can see the database? I edited the settings.php file and created a module that is supposed to describe the database to Drupal 7, but I don't see the tables anywhere.
Any suggestions on how to troubleshoot? I don't get any errors or feedback; it simply doesn't do what I want it to do.
This is my code.  I have a file called datamodel.module:
function datamodel_views_api() {
  return array(
    'api' => 2,
    'path' => drupal_get_path('module', 'datamodel'),
  );
}

I have also a file called datamodel.views.inc. This file is very long but I basically got everything working in drupal6 using table wizards; then I used the table wizards to Views definition for hook_views_data(), which I put in the following code.
function datamodel_views_data() {
  $data = array();
  $data['FundManager'] = array(
    'FundManager' => array(
      'title' => t('FundManager'),
      'help' => t('FundManager.FundManager'),
      'field' => array(
        'handler' => 'views_handler_field',
        'click sortable' => TRUE,
      ),
      'filter' => array(
        'handler' => 'views_handler_filter_string',
        'allow empty' => TRUE,
      ),
      'argument' => array(
        'handler' => 'views_handler_argument_string',
      ),
      'sort' => array(
         'handler' => 'views_handler_sort',
      ),
    ),
    'fundManagerCode' => array(
      'title' => t('fundManagerCode'),
      'help' => t('FundManager.fundManagerCode'),
      'field' => array(
        'handler' => 'views_handler_field_numeric',
        'click sortable' => TRUE,
      ),
      'filter' => array(
        'handler' => 'views_handler_filter_numeric',
        'allow empty' => TRUE,
      ),
      'argument' => array(
        'handler' => 'views_handler_argument_numeric',
      ),
      'sort' => array(
        'handler' => 'views_handler_sort',
      ),
    ),
    'FundManagerFirm' => array(
      'title' => t('FundManagerFirm'),
      'help' => t('FundManager.FundManagerFirm'),
      'field' => array(
        'handler' => 'views_handler_field',
        'click sortable' => TRUE,
      ),
      'filter' => array(
        'handler' => 'views_handler_filter_string',
        'allow empty' => TRUE,
      ),
      'argument' => array(
        'handler' => 'views_handler_argument_string',
      ),
      'sort' => array(
        'handler' => 'views_handler_sort',
      ),
    ),
    'FundManagerStartDate' => array(
      'title' => t('FundManagerStartDate'),
      'help' => t('FundManager.FundManagerStartDate'),
      'field' => array(
        'handler' => 'views_handler_field',
        'click sortable' => TRUE,
      ),
      'filter' => array(
        'handler' => 'views_handler_filter_string',
        'allow empty' => TRUE,
      ),
      'argument' => array(
        'handler' => 'views_handler_argument_string',
      ),
      'sort' => array(
        'handler' => 'views_handler_sort',
      ),
    ),
    'FundManagerDescription' => array(
      'title' => t('FundManagerDescription'),
      'help' => t('FundManager.FundManagerDescription'),
      'field' => array(
        'handler' => 'views_handler_field',
        'click sortable' => TRUE,
      ),
      'filter' => array(
        'handler' => 'views_handler_filter_string',
        'allow empty' => TRUE,
       ),
       'argument' => array(
         'handler' => 'views_handler_argument_string',
       ),
       'sort' => array(
         'handler' => 'views_handler_sort',
       ),
    ),
    'FundCode' => array(
      'title' => t('FundCode'),
      'help' => t('FundManager.FundCode'),
      'field' => array(
        'handler' => 'views_handler_field_numeric',
        'click sortable' => TRUE,
      ),
      'filter' => array(
        'handler' => 'views_handler_filter_numeric',
        'allow empty' => TRUE,
      ),
      'argument' => array(
        'handler' => 'views_handler_argument_numeric',
      ),
      'sort' => array(
        'handler' => 'views_handler_sort',
      ),
    ),
    'table' => array(
      'group' => t('FundManager'),
    ),
  );

  return $data;
}

I thought I followed the instructions, but nothing happens after I enable the module.
Comment: you don't see the tables where? Using views? Or are you trying to execute custom queries? Also, show your code...
Comment: Thanks, Berdir. I will.  But I was also trying to be more general to learn how to even start troubleshooting.  With Java, you get errors when something goes wrong but it seems with drupal there is no error. I'd love to get some kind of feedback from the system on what I'm doing wrong.
Comment: Well, that totally depends on what goes wrong. And debugging views and debugging custom module code is quite different, so there isn't much generic things you could do.
Comment: Thanks Berdir.  I just posted my code..hopefully that helps with someone helping me.  I did notice you were a developer of various modules, may I ask how you troubleshoot packages or your code? Do you code outside of drupal, troubleshoot and then add it as a module or are you creating modules directly?
Answer: There are a few things you can do to debug this.
First up try switching the database and doing a general query on your 'fundmanager' table
Something like
 db_set_active('myexternal');
 $result = db_query('SELECT FundCode FROM fundmanager');
 db_set_active('default');

This will test that the database connection is working and visible from drupal.
If that is ok you can put some debug code in your hook_views_data() to make sure that is being called. Clear the cache and go to the list views page.
If both of these are present then it is likely a bug in your tablewizard code. This is a little buggy with external databases. It should define base_database somewhere but there is a bug
Comment: Thanks so much Jeremy. I totally get your logic but not sure on the execution of it.  How do I create a drupal node with php in it so I can test my code? and If I put debug code in hook_views_data() where would I see it if its only used to enable me access to the views?
Comment: Yes, it looks like the base database is missing...
Comment: I remember reading about that..but wasn't sure if it applied to me.  I added the database information into the settings.php file.  I'll look into the base info and let you know.
Comment: You can (for debug code) just put the code inline in your module. Just to see if it runs. hook_views_data is a little more tricky as views aggressively caches the output. put a var_dump('test') in there clear the cache and then go to a views admin page, you should see test in plain text at the top of your page.
Comment: Thanks I'll try that.  I have been all over drupal.org and have seen quite a few posts from you relating to this matter. Looks like you got it to work using the data module..problem is its not out for drupal7 yet. Its a bit late but tomorrow I'll look at the base database issue and let you guys know the results
Comment: I have it working on D6 but haven't tried for 7 I'm afraid.
Comment: I got it working on D6 as well, but was thinking with d7 out..it might be worth it to go through some pains right now.  If I deem it totally impossible..The main issues I see right now are data not being avail for drupal7 and schema not supporting all field types
Comment: I have been working on the base database issue for a large part of the day and still nowhere.  I looked at the example on http://www.stevekarsch.com/2008/11/30/scratching-itch-myweather-views-2 and tried to use his base code and apply it to mine but still no luck.  On the bright side, If I go into schema and settings and switch the database from default to my external one, I can see it sees my table and fields, because I'm getting errors that it doesn't like the date field.
Comment: its still not working..not sure why.  but while I was experimenting, I copied my tables within my default drupal database and using the database administration module, I can see my data.  Just not in views.  when I go into schema, I keep getting erors "no Schema type for mysql type date."  I'm not sure how to fix that or if its related to my problem
Answer: Most of the time, when something goes wrong there is an error displayed or logged somewhere depending on your PHP and system setup. Most Linux distributions provide a production safe PHP distribution that disable errors display. For developement, I suggest you enable errors display for PHP and install xdebug to enable stack traces in error messages.
In some rare occasions, Drupal fails to report an error and silently ignore the error. For these cases, tracing execution using Xdebug or the Zend Debugger are the best options. But they may take time to setup.
Comment: my site isn't in production yet..so I can enable these and see what it does..drupal has a module that logs errors to a mysql database so I'll check that out also.  Thanks for the advice.


What was the view of rhyme scheme during the tin pan alley era with 32 bar songs?

Question: I've noticed some of the 32 bar songs from the tin pan alley era have rhyme scheme all over the place. Did they care about rhyme scheme? From what sources did they learn to use rhyme scheme?
Gene Autry who used many songwriters work from tin pan alley had many songs with unorganized rhyme scheme. aabbccddee  and aabbaaccdd and abba and abcbddef and many more seemingly random rhyme schemes.
Comment: It would be helpful to give some examples of what you've noticed. Right now the question suffers a bit from a blanket generalization (I'm sure not all Tin Pan Alley writers learned from the same sources). I'll also suggest that such songs often feature internal rhymes and generous half-rhymes.
Comment: Also, a clarification on the aabbccddee-style notation, which is new to me. Does each line represent one line of vocals? Can we get a quick example of a well-known song with its rhyme scheme dissected in that notation? You know, just to help us answer more easily.
Comment: @AndyBonner and more.  Unconventional rhyming was common, such as Lorenz Hart's rhyming "by" and "July" with the first syllable of "gliding," leaving "ding" as the first syllable of the following line.
Answer: These are not particularly unusual rhyme schemes in English (and Italian) poetry. The aabbccddee... is just a string of couplets (Alexander Pope); abba is called an "enclosed" rhyme and is very common. Sometimes one gets abccba similarly. ("Big Spender" does something similar.) Varying rhyme schemes has always been popular with poets and lyricists.
Roses are red, violets are blue, sugar is sweet some of the time.
Something is wrong twixt me and you, we got the juice but never the wine. (doesn't really rhyme though)
Roses are red, violets are blue,
You'll be surprised when this doesn't rhyme.
Roses are red, violets are purple.
Sugar is sweet, so's maple surple.
All these have been used over the years. If it fits, it's good.
Comment: There are a lot of types of rhyme; words like "time" and "wine" are sometimes called _slant rhymes_. Traditional poetry has made much use of these more general types of rhyme, so I don't know why Tin Pan Alley would be any different. I wonder if some of OP's discovered rhyme schemes are ignoring these types of rhyming.


Taking items from a CSV file and putting the elements in a list

Question: I have a CSV File here: http://www.filedropper.com/excel which looks like this http://pastebin.com/ammzv4FK.
What I want to do is this:
Take each year with its corresponding rows and find the numbers in months and total them and assign them to variables.
So the first year, 2000, the list would look like this:
year2000 = ['14744', '2947', '14905', '1748',  '2859',  '11778', '1453',  '5255', '14806', '1858', '10763', '6000']

Then once I have that list I can convert the elements in the list from strings to integers, and sum them using the sum() command.
I can print the rows out but I'm having trouble excluding the year number and then storing the rest into variables because my list comes out as this:
['2000, 14744, 2947, 14905, 1748,  2859,  11778, 1453,  5255, 14806, 1858, 10763, 6000']

as one big string, instead of individual elements, and my list prints all the years out at once so I can't seem to figure out how to store them into variables and total them separately.
Here is my code:
with open("file.csv","r") as f:
    for i in range(1):
        next(f)
    for x in f:
        x=x.split()
        print (x)

But when print(x) runs it prints it all, how can I store each year with its contents in a variable while excluding the actual year number?
I'm using Python 3, thanks.
Comment: The `csv` module is what you want. Also, you should show your current code in a question.
Comment: @syhpoon Yes, if I was able to get them into their own variables.
Answer: If you are getting the row like that you probably aren't using a csv reader. You should use the csv module and store each row in a dict, with the year as the key. This only works if your data consists of integers.
data = {}

with open("data.csv") as f:
    reader = csv.reader(f, delimiter="\t")
    reader.next() # Skip header
    for row in reader:
        row = list(map(int, row))
        data[row[0]] = row[1:]

To get the sum, use the built in sum function.
Comment: In python 3.x, you might consider ``key, *values = list(map(int, row))`` as a nicer way of splitting the list.
Comment: I was using the CSV module, but for your code I am getting the error 'map' object is not subscriptable.
Comment: Now I am getting this error: invalid literal for int() with base 10:'2011,3814,2343,6367,13244,3993,9770,5662,2278,12642,12347,14991,1910,'
Comment: Is your csv comma separated or tab separated? The one you linked is tab separated. Where did the commas come from?
Comment: Oh, my original file might be different, I had to post a shorter version but I thought I made it a CSV. My original is comma seperated.
Comment: @Goose - you might want to remove the commas at the end of each line of the original file (and also the last line that is just commas), because they are unnecessary and will result in the same invalid literal error.
Comment: @Goose: you will need to change the delimiter to match your file.
Comment: @Goose: you need to ignore the top 12 rows with that file. I'll leave that to you. You also need to ignore the last element in each row, due to the trailing `,`
Comment: I can skip the 12 lines, but I don't understand why there are commas at the last element in each row, aren't they just numbers? I'm a bit confused..When I do `print(row)` it shows it as `'1961','45119', etc,` if there were commas wouldn't it be `'1961,','45119,',etc`?
Comment: @Goose: the trailing `,` tells the csv reader that there is an empty element at the end of each row with the value `''`. This is not desired.


Custom Back Office Tab Doesn't Visible in Prestashop

Question: I'm new on developing module of Prestashop and I use version of 126.96.36.199. I'm trying to developing a module and I have to create a custom tab in left menu in back office. I tried this way which is in the Prestashop official documentation(https://devdocs.prestashop.com/1.7/modules/concepts/controllers/admin-controllers/tabs/). But custom tab doesn't visible in the back office. Here I add my code and my file names. Can anyone help me about where is my mistake? Thank you so much.
My Files
driveorder
-driveorder.php
-logo.png
-controllers
--admin
---AdminDriveOrder.php
And there is driveorder.php file which is I created custom tab.
<?php
if (!defined('_PS_VERSION_'))
    exit;

class driveorder extends Module
{
    public function __construct()
    {
        $this->name = 'driveorder'; /* This is the 'technic' name, this should equal to filename (mycustommodule.php) and the folder name */
        $this->tab = 'administration'; /* administration, front_office_features, etc */
        $this->version = '1.0.0'; /* Your module version */
        $this->author = 'Sertac Bazancir'; /* I guess it was clear */
        $this->need_instance = 0; /* If your module need an instance without installation */
        $this->ps_versions_compliancy = array('min' => '1.6', 'max' => _PS_VERSION_); /* Your compatibility with prestashop(s) version */
        $this->bootstrap = true; /* Since 1.6 the backoffice implements the twitter bootstrap */

        parent::__construct(); /* I need to explain that? */

        $this->displayName = $this->l('Drive Order'); /* This is the name that merchant see */
        $this->description = $this->l('Google Drive integration for virtual products.'); /* A short description of functionality of this module */

        $this->confirmUninstall = $this->l('Are you sure you want to uninstall?'); /* This is a popup message before the uninstall */

        $this->tabs = array(
            array(
                'name' => 'Drive Order', // One name for all langs
                'class_name' => 'AdminDriveOrder',
                'visible' => true,
                'parent_class_name' => 'SELL'
            )
        );

    }

    public function install(){
        if (Shop::isFeatureActive()){
            Shop::setContext(Shop::CONTEXT_ALL);
        }
        $sql = "CREATE TABLE IF NOT EXISTS `"._DB_PREFIX_."drive_product`(
        `id_product` INT(10) NOT NULL PRIMARY KEY,
        `id_drive` VARCHAR(255) NOT NULL )";
        $result = Db::getInstance()->Execute($sql);
        if (!parent::install() OR !$result OR !$this->registerHook('actionPaymentConfirmation')){
            return false;
        }
        return true;
    }

    public function uninstall(){
        $sql = "DROP TABLE `"._DB_PREFIX_."drive_product`";
        $result = Db::getInstance()->Execute($sql);
        if (!parent::uninstall() OR !$result OR !Configuration::deleteByName('driveorder')){
            return false;
        }
        return true;
    }

    public function hookActionPaymentConfirmation($params){
        global $smarty;
    }
}
?>

Comment: There is defiantly a bug in prestashop, every time I reset the module it behave different - sometime the tab is available sometime not.
Comment: Over a year later and I am facing the same issue.. did you manage to fix it?
Answer: Your mistake is here:
'parent_class_name' => 'SELL'

Try this:
'parent_class_name' => 'AdminParentOrders'

Comment: First of all thank you so much for answer. I tried it but unfortunately it still doesn't visible.
Comment: Have you reset the module?
Comment: Yes. I have reset it after changes.
Answer: You also have to name your controller file AdminDriveOrderController.php instead of AdminDriveOrder.php


Can't write number with FileWriter

Question: This is my code and I want b[i] will be write to the file name test.txt but it is not working. It's just write something like symbols. Thanks for helping.
public class btl {
public static boolean IsPrime(int n) {

    if (n < 2) {
        return false;
    }

    int squareRoot = (int) Math.sqrt(n);
    for (int i = 2; i <= squareRoot; i++) {
        if (n % i == 0) {
            return false;
        }
    }
    return true;
}

public static void main(String args[]) {
    Scanner scanIn = new Scanner(System.in);
    int first = 0;
    int second = 0;
    try {
        System.out.println("Input First Number");
     first = scanIn.nextInt();
        System.out.println("Input Second Number");
        second= scanIn.nextInt();
    }
    catch(Exception e) {
        System.out.println("Something wrong!");
    }
    int x = first;
    int y = second;
    int a;
    int[] b = new int[y];

    Thread threadA = new Thread(new Runnable() {
        @Override
        public void run() {
            int c=0;
            for(int i=x; i<y; i++) {
                if(IsPrime(i)) {
                    b[c] = i;
                    System.out.println(b[c]);
                    c++;
               }
         }

        }
    });
    threadA.start();

    try(FileWriter fw = new FileWriter("test.txt")){

            for(int i =0; i<y; i++)
            {
             fw.write(b[i]);
            }
        }
    catch(IOException exc) {
        System.out.println("EROR! " + exc);
    }

}

}

This is my display console
And this is file "test.txt"
I don't know why FileWriter writes symbols in file text.txt. I want it's number of array b[i].
Comment: It looks like you are writing the numbers to test.txt. They're in HEX, not a string. If you want text, convert it to a string, then output the string.
Answer: FileWriter.write(int) writes a single character.
You likely want FileWriter.write(String)as in:
    fw.write(Integer.toString(b[i]));

Can't write number with FileWriter


Taking over a url and getting variables from url

Question: I have a (non drupal bound) table, that I need to display within my site.
It has information about "runs":
userID (drupal) - runID - name - distance - ... etc
I want to go to site/run/runID and display the data of that particular run.
I don't know if there is an easy way of doing it without having to create a custom module for it? I basically just need to $get the variables and display them from the database. My first concern is calling my php code when the file is loaded.
And if I need to create a module for it. How would I go about it?
Or perhaps I can use panels to put  my custom code on a page and get the url variables? Or some other module I am not thinking about...
--Update
To get started I created this little module. Now just reading the url parameter runID that is behind it...
function epicrun_menu(){
 $items['epicrun'] = array(
 'page callback' => 'epicrun_my_page',
 'title' => 'Callback',
   'type' => MENU_CALLBACK,
 'access arguments' => array('access content'),
 );
 return $items;
}

* this code (noted in the callback above) creates the
 * contents of the "epicrun" page */

function epicrun_my_page(){
 return "
This is my epicrun demo page.
";
}

Answer: I would suggest looking into the Data module. I does pretty much everything (and more) what you're describing in your request.
Answer: Ok, creating a new module for that seems very easy:
function epicrun_menu(){
 $menuitems['run'] = array(
  'title' => 'Run data',
  'page callback' => 'epicrun_mymenu_page_callback',
  'page arguments' => array(0),
  'access callback' => TRUE,
  'type' => MENU_NORMAL_ITEM,
  );
 return $menuitems;
}

/**

* Implementation of hook_menu().

*/
function epicrun_mymenu_page_callback($firstparameter = '',) {

  $result = 'This page will display the run data of the run with ID '.$firstparameter;/*
   $result.='
 The first parameter passed to the url is :'.$firstparameter.'';
   $result.='
 The second parameter passed to the url is :'.$secondparameter.'';*/

  return $result;

}


Newton-Raphson Error

Question: According to Agresti(2013) pg 364-365, iterative methods such as Newton-Raphson methods, $
\begin{aligned}
\beta^\text{new} &= \beta^\text{old} + (X^{T}WX)^{-1}X^{T}(V)
\end{aligned}
$ help to estimate the MLE of log-linear models.
These are my $Y, X , n$ matrices. The first column in $X$ matrix represents the intercept
($\beta_\text{0}$)
$$
Y=
\begin{bmatrix}
1 \\
16 \\
30 \\
71 \\
102 \\
130 \\
133 \\
40 \\
4 \\
38 \\
119 \\
221 \\
259 \\
310 \\
226 \\
65 \\
\end{bmatrix} ;X=
\begin{bmatrix}
1 & 1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\
1 & 0 & 1 & 0 & 0 & 0 & 0 & 0 & 0 \\
1 & 0 & 0 & 1 & 0 & 0 & 0 & 0 & 0 \\
1 & 0 & 0 & 0 & 1 & 0 & 0 & 0 & 0 \\
1 & 0 & 0 & 0 & 0 & 1 & 0 & 0 & 0 \\
1 & 0 & 0 & 0 & 0 & 0 & 1 & 0 & 0 \\
1 & 0 & 0 & 0 & 0 & 0 & 0 & 1 & 0 \\
1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 1 \\
1 & 1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\
1 & 0 & 1 & 0 & 0 & 0 & 0 & 0 & 0 \\
1 & 0 & 0 & 1 & 0 & 0 & 0 & 0 & 0 \\
1 & 0 & 0 & 0 & 1 & 0 & 0 & 0 & 0 \\
1 & 0 & 0 & 0 & 0 & 1 & 0 & 0 & 0 \\
1 & 0 & 0 & 0 & 0 & 0 & 1 & 0 & 0 \\
1 & 0 & 0 & 0 & 0 & 0 & 0 & 1 & 0 \\
1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 1 \\
\end{bmatrix};n=
\begin{bmatrix}
172675 \\
123065 \\
96216 \\
92051 \\
72159 \\
54722 \\
32185 \\
8328 \\
181343 \\
146207 \\
121374 \\
[111353 \\
83004 \\
55932 \\
29007 \\
7583 \\
\end{bmatrix}
$$
I am trying to fit a rate poisson model, $\log \lambda_i = \log n_i + \theta^T x$, for this data where the likelihood is $$\prod_{i=1}^N \dfrac{(n_ie^{\theta^Tx})^{y_i}}{y_i!}e^{-n_i e^{\theta^Tx}}$$
When i execute the Newton-Raphson procedure based on Agresti(2013) suggestion I am getting an error saying
<code>Error in solve.default(t(X) %*% (V) %*% X) :
  system is computationally singular: reciprocal condition number = 1.10707e-17
</code>
I am not sure what I am missing here for the inverse of the Hessian $H$ to throw that error. Need help. Please let me know if you need more details regarding my work.
Comment: Your X matrix is clearly linearly dependent. Add all of the columns after the first. It's all 1's, just like the first column. Hence X'X is singular.
Comment: Isn't it simply saying that in essence the Hessian is singular ?
Comment: @aginensky, agree but what is the solution I am not sure. Does it mean I should not use the newton Raphson approach ?
Comment: I'm not really an expert.  I'm sure the answer is yes, but...  You should google 'can I use Newton Raphson if the Hessian is singular".  Unless you data set is really large or you are unlucky, you can try something else like gradient descent or stochastic gradient descent.
Comment: @aginensky, I disagree. Gradient descent or Stochastic gradient descent might be relevant if my X are correlated. Here my X is not correlated. They are design matrices.
Comment: Newton, gradient descent etc. are numerical methods to solve equations.  I certainly didnt say they weren't relevant.
Comment: @Glen_b - perhaps you should add a sentence or two to your comment and post it as an answer, since it does answer the question and the fix is easy.
Comment: @jbowman yes; I was kind of hoping someone else would jump in but you're right.
Answer: Your $X$ matrix is clearly linearly dependent. Add all of the columns after the first - it's all $1$'s, just like the first column. Hence $X^\top X$ is singular.
The usual solution is to omit a single factor level, typically either the first or the last. There are other approaches (which boil done to some form of linear constraint on the coefficients); which you would use will depend on your needs (though it's possible to translate between them, so it's not crucial which approach you use).
My suggestion is simply to omit the second column of your X-matrix; the level of that is incorporated into the constant term and the other coefficients will then represent differences (on the scale of the linear predictor) from that baseline.

Newton-Raphson Error


Set a DIV height equal with of another DIV height

Question: I have two DIVs, .prev and .SLDR-ONE and I want to set .prev to keep the same height with .SLDR-ONE.
I've tried the following:
$(".prev").css({'height':($(".SLDR-ONE").height()+'px')});

It is not working properly because .SLDR-ONE doesn't have defined height. .prev take the height of the page except if I define a height to .SLDR-ONE (ex:300px).
.SLDR-ONE has css : float:left; position:relative, so the height is defined automaticaly.
Comment: can you try this? `https://jsbin.com/roviwi`
Comment: https://developer.mozilla.org/en/docs/Web/API/Element/getBoundingClientRect
Comment: @plonkminbuzz I tried and I don't know why but my height is not really equal. there is 20-30px of difference...
Answer: Try to use innerHeight, to obtain the height of .prev.
Answer: You could do this using offsetHeight

(function(){
var one = document.querySelector('.one');
var two = document.querySelector('.two')
two.style.height = one.offsetHeight + 'px';
}())
.one{
 float: left;
 position: relative;
}
.two{
 background: #ccc;
 clear: both;
}
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing

If you prefer jQuery then you could use innerHeight. innerHeight documentation.
Answer: As from .height() method of jQuery returns width of the element excluding padding ,margin and bottom.So if you want same height for both of the div

You should be using outerHeight().
And there are possibility that you have assigned the same class to some other element and the method may be returning value of width and height of that element.