Finding the Derivative of |x| using the Limit Definition

Question: Please Help me derive the derivative of the absolute value of x using the following limit definition.
$$\lim_{\Delta x\rightarrow 0}\frac{f(x+\Delta x)-f(x)}{\Delta x}
$$
I have no idea as to how to get started.Please Help.
Thank You
Comment: Does $|x|$ differentiable at zero?
Answer: $\dfrac{d}{dx}|x|$
$=\lim\limits_{\Delta x\to 0}\dfrac{|x+\Delta x|-|x|}{\Delta x}$
$=\lim\limits_{\Delta x\to 0}\dfrac{(|x+\Delta x|-|x|)(|x+\Delta x|+|x|)}{\Delta x(|x+\Delta x|+|x|)}$
$=\lim\limits_{\Delta x\to 0}\dfrac{|x+\Delta x|^2-|x|^2}{\Delta x(|x+\Delta x|+|x|)}$
$=\lim\limits_{\Delta x\to 0}\dfrac{(x+\Delta x)^2-x^2}{\Delta x(|x+\Delta x|+|x|)}$
$=\lim\limits_{\Delta x\to 0}\dfrac{x^2+2x\Delta x+(\Delta x)^2-x^2}{\Delta x(|x+\Delta x|+|x|)}$
$=\lim\limits_{\Delta x\to 0}\dfrac{2x+\Delta x}{|x+\Delta x|+|x|}$
$=\dfrac{x}{|x|}$
$=\dfrac{x|x|}{|x|^2}$
$=\dfrac{x|x|}{x^2}$
$=\dfrac{|x|}{x}$
Comment: Can you show the further derivatives?
Comment: @MathLover use quotient rule. $\frac{d}{dx} \frac{|x|}{x}=\frac{\frac{|x|}{x} \cdot x - |x| \cdot 1}{x^2}$
Answer: Since the absolute value is defined by cases,
$$|x|=\left\{\begin{array}{ll}
x & \text{if }x\geq 0;\\
-x & \text{if }x\lt 0,
\end{array}\right.$$
it makes sense to deal separately with the cases of $x\gt 0$, $x\lt 0$, and $x=0$.
For $x\gt0$, for $\Delta x$ sufficiently close to $0$ we will have $x+\Delta x\gt 0$. So
$f(x)= |x| = x$, and $f(x+\Delta x) = |x+\Delta x| = x+\Delta x$; plugging that into the limit, we have:
$$\lim_{\Delta x\to 0}\frac{f(x+\Delta x) - f(x)}{\Delta x} = \lim_{\Delta x\to 0}\frac{|x+\Delta x|-|x|}{\Delta x} = \lim_{\Delta x\to 0}\frac{(x+\Delta x)-x}{\Delta x}.$$
You should be able to finish it now.
For $x\lt 0$, for $\Delta x$ sufficiently close to zero we will have $x+\Delta x\lt 0$; so $f(x) = -x$ and $f(x+\Delta x) = -(x+\Delta x)$. It should again be easy to finish it.
The tricky one is $x=0$. I suggest using one-sided limits. For the limit as $\Delta x\to 0^+$, $x+\Delta x = \Delta x\gt 0$; for $\Delta x \to 0^-$, $x+\Delta x = \Delta x\lt 0$; the (one-sided) limits should now be straightforward.
Comment: @alok: Notice that you'll get different result for $x<0, x>0$, and $x=0$.
Comment: If i plug in the given function into the derivative formula i get $$\lim_{\Delta x\rightarrow 0}\frac{f(x+\Delta x) - x}{\Delta x}$$.Upon evaluating it i get the final answer as 1
Comment: @alok: Be sure to keep track of what case you are in! You will not get $1$ *except* when $x\gt 0$, or when $x=0$ and $\Delta x\to 0^+$. If you are getting $1$ in all cases, you are doing it wrong.
Comment: The derivative does not exist at 0!
Answer: We can write $|x| = \sqrt{x^2}$. Using the chain rule we then get
$$|x|' = \frac{1}{2\sqrt{x^2}} \cdot 2x = \frac{x}{\sqrt{x^2}} = \frac{x}{|x|}$$

EDIT Using limit:
$$\begin{align}
\frac{\sqrt{(x+\Delta x)^2}-\sqrt{x^2}}{\Delta x}
& = \frac{(\sqrt{(x+\Delta x)^2}-\sqrt{x^2})(\sqrt{(x+\Delta x)^2}+\sqrt{x^2})}{\Delta x (\sqrt{(x+\Delta x)^2}+\sqrt{x^2})} \\
& = \frac{(x+\Delta x)^2-x^2}{\Delta x (\sqrt{(x+\Delta x)^2}+\sqrt{x^2})} \\
& = \frac{2 x \Delta x + \Delta x^2}{\Delta x (\sqrt{(x+\Delta x)^2}+\sqrt{x^2})} \\
& = \frac{2x + \Delta x}{\sqrt{(x+\Delta x)^2}+\sqrt{x^2}} \\
& \to \frac{2x}{\sqrt{x^2}+\sqrt{x^2}} = \frac{2x}{2|x|} = \frac{x}{|x|}
\end{align}$$
Comment: The OP wants to obtain the result using only the definition, nothing more.
Comment: I think there is a typo in the first method, the last squality should be  $\dfrac {x}{\sqrt {x^2}} = \dfrac {x}{|x|}$?
Comment: Oh, you're correct, I've missed ${}^2$. Will now fix it.
Answer: Cheap, non-rigorous, non-mathematical, engineering-type answer: sgn(x) ("signum x", the sign of x, being -1 for x<0 and +1 for x>0). Note that sgn(0) = 0, which is a practical compromise, being the average of -1 ("coming from the negatives") and +1 ("coming from the positives").
Of course we all know that d|x|/dx is not defined at x=0. Intuitively: the "tangent" of |x| at x=0 can be any line with slope -1 < s < +1 . So it is not unique. Hence: no derivative at that point.
Once again: these are not rigorous considerations (see @doraemonpaul 's answer for proper maths), but rather intuitive hints that help you grasp the issue.
Mathematica's answer (Version 11) is even more pragmatic: D[Abs[x], x] ==> Abs'[x] . I like it a lot :-)
Answer: Well, the simple answer is if x < 0, it's obviously a linear line with a slope of -1, and when x > 0, it's a line with slope 1, and at x = 0, both formulas can be used and therefore we can't calculate the derivate.
So:
when x > 0, |x|' = 1
when x < 0, |x|' = -1
when x = 0, |x|' is undefined
As doraemonpaul said, the implicit way to say this is |x|/x, because it returns the sign of x, except when x = 0, when dividing by 0 makes it undefined.
x/|x| could also work.
Comment: What is a linear line? :)
Answer: One can cast this question about the differentiation of absolute value operator into the more general setting of (partial) differentiation of the Euclidean norm. This article gives the formula in $\mathbb{R^n}$ with coordiantes $x=(x_1,x_2,\cdots x_n)$ :
$$\dfrac{\partial}{\partial x_k}\|x\|=\dfrac{x_k}{\|x\|}$$
Considering the case $n=1$, one gets :
$$\dfrac{ \mathrm{d}}{ \mathrm{d}x}\|x\|=\dfrac{x}{|x|}$$
Answer: Using alternative limit definition of the derivative of function:
$$\lim_\limits{x\to x_0}\frac{f(x)-f(x_0)}{x-x_0}=\lim_\limits{x\to x_0}\frac{|x|-|x_0|}{x-x_0}=\lim_\limits{x\to x_0}\frac{(|x|-|x_0|)(|x|+|x_0|)}{(x-x_0)(|x|+|x_0|)}=$$
$$\lim_\limits{x\to x_0}\frac{x^2-x_0^2}{(x-x_0)(|x|+|x_0|)}=\lim_\limits{x\to x_0}\frac{(x-x_0)(x+x_0)}{(x-x_0)(|x|+|x_0|)}=\lim_\limits{x\to x_0}\frac{x+x_0}{|x|+|x_0|}=\frac{2x_0}{2|x_0|}=\frac{x_0}{|x_0|}.$$


Display two variables in a histogram

Question: I have the data set
structure(list(Latitude = c(8.983, 44.3498, 50.9332, 36.1333,
35.7833, 37.65, 35.7667, 39.1332, 5.2833, 3.65, -0.05, -25.41666667,
-44.63333333, -39.73333333, -14.9, -23.93333333, -39.83333333,
-53.038, -43.308, -48.008, -47.533, -46.448, -45.037, -43.953,
-41.02, -39.515, -45.022, -47.128, -47.988, -49.378, 24.5, -43.78,
-43.63, -55.33, -44.77, -39.38, -36.75, -46.53, -49.33, -51.08,
-47.77, -45.42, -41.37, 17.883, 45.1, 54.983, -43.03, -34.33,
-34.92, -36.48, -28.07, -49, -42.58, -25.49, -46.6, -49.92, -46.1,
59.6532, 53.867, 63.4832, 42.467, 38.917, 40.767, 31.383, 31.433,
-22.98, 14.3, -39.2, -35.88, -4.3, -2.833, -0.633, 60.033, -33.2,
-33.35, -33.35, -46.02, -45, -37.15, -29.73, -31.05, -31.63,
-32.38, -30.2, -28.883, -28.017, -31.53, 12.383, 58.367, 60.733,
-33.23, -38.98, -20.58, -38.57, 38.75, -29.52, -21.83, 2, 1.417,
-21.98), Longitude = c("51.733", "-30.267", "-41.75", "-68.9167",
"-68.9333", "-72.95", "-69.0833", "-42.65", "-17.0667", "-18.3",
"-24.1667", "70.4", "70.96666667", "67.88333333", "70.2", "73.88333333",
"75.05", "119.735", "105.548", "114.478", "114.423", "114.417",
"114.348", "114.368", "100.012", "83.723", "95.082", "95.08",
"95.037", "94.832", "-16.95", "46.2", "51.267", "65.467", "92.417",
"104.37", "120.9", "125.57", "127.12", "129.97", "123.1", "121.12",
"114.13", "58.083", "-10.57", "-15.4", "57.35", "54.217", "67.583",
"69.55", "95.967", "-4.6", "-17.8", "11.307", "7.625", "-15.57",
"-13.23", "-22.77", "-21.1328", "-0.0667", "-54.9", "-57.13",
"-64.6", "-11.62", "-64.17", "7.017", "51", "13.5", "15.917",
"64.817", "66.3", "69.45", "-50.83", "15", "16.433", "16.433",
"44.367", "45.767", "43.5", "79.567", "82.85", "83.8", "84.85",
"91.717", "92.833", "95.183", "99.25", "-18.92", "-47.73", "-57.83",
"15.983", "29.933", "63.533", "140.62", "-67.55", "9.583", "10.8",
"-5.25", "-9.083", "68.483"), Neogloboquadrina_pachyderma...35 = c("1",
"8", "94", "1", "1", "6", "1", "2", "1", "1", "2", "1", "64",
"4", "3", "1", "12", "232", "50", "93", "88", "54", "43", "23",
"21", "14", "49", "74", "76", "78", "2", "41", "163", "264",
"24", "4", "6", "35", "20", "59", "26", "20", "1", "1", "4",
"2", "27", "4", "5", "4", "4", "364", "9", "6", "118", "386",
"146", "25", "32", "138", "34", "5", "22", "2", "2", "5", "1",
"3", "5", "2", "1", "2", "310", "4", "3", "6", "109", "97", "2",
"6", "3", "5", "6", "3", "1", "1", "2", "2", "378", "374", "2",
"2", "1", "3", "3", "4", "15", "1", "3", "2")), row.names = c(NA,
-100L), class = c("tbl_df", "tbl", "data.frame"))

and then I want to plot the latitude on the x-axis against the number of Neoglobya Pachyderma on the y-axis for which I have the code
library(ggplot2)

hist <-ggplot(data=daten_neu, aes(x = Latitude, y = Neogloboquadrina_pachyderma...35 )) +
  geom_histogram(binwidth = 5, fill = "lightblue", color = "black", alpha = 0.7) +
  labs(title = "Abundance of Neglobina Pachyderma vs Latitude",
       x = "Latitude",
       y = "Abundance") +
  theme_minimal()

print(hist)

However, I get an error message to which I cannot find an answer here:
Error in `geom_histogram()`:
! Problem while computing stat.
ℹ Error occurred in the 1st layer.
Caused by error in `setup_params()`:
! `stat_bin()` must only have an x or y aesthetic.

Question Update:
The Dataset which I use is much bigger (I don´t know how to disply it)
However if I Use the Answer given my Histogram Looks like that:

My quess is that there are more Points per Latitude as thought is there a way to combine them first?
Answer: **Update after clarification: This should work:
library(ggplot2)

daten_neu %>%
  mutate(across(everything(), ~as.numeric(.))) %>%
  ggplot(aes(x = Latitude)) +
  geom_histogram(binwidth = 5,
                 fill = "lightblue",
                 color = "black") +
  labs(title = "Abundance of Neglobina Pachyderma vs Latitude",
       x = "Latitude",
       y = "Count") +
  theme_minimal()

First answer:
Maybe you want a bar plot:
library(ggplot2)

ggplot(data = daten_neu, aes(x = factor(Latitude), y = Neogloboquadrina_pachyderma...35))+
  geom_col( fill = "lightblue", color = "black", alpha = 0.7)+
  labs(title = "Abundance of Neogloboquadrina Pachyderma vs Latitude",
       x = "Latitude",
       y = "Abundance") +
  theme_minimal()

Comment: Just add this : `scale_x_continuous(limits = c( -90,90 ),  breaks = c(-90, 0, 90))`
Comment: maybe better a new question with minimal reproducible example.
Comment: oki I posted the Question:) https://stackoverflow.com/questions/77854159/plot-many-plots-in-a-non-symmetrical-way-in-r-in-a-multiplot

Display two variables in a histogram


Concatenate PHP variable DATETIME inside MYSQL statment

Question: I get the DATE variable from the Datepicker Jquery UI and include it as variable in the MYSQL statement. But select does not work with the variable. What reason ?
Below the code
<code>$fromDate = new DateTime($from);
$toDate = new DateTime($to);

$fromDate2 = mysqli_real_escape_string($fromDate);
$toDate2 = mysqli_real_escape_string($toDate);

$sql = mysqli_query($mySqlConnect,"SELECT * FROM 1398_log WHERE date BETWEEN $fromDate2 AND $toDate2 ORDER by id DESC");
</code>
This select OK:
<code>$sql = mysqli_query($mySqlConnect,"SELECT * FROM 1398_log WHERE date BETWEEN '2016-03-01 00:00:00' AND  '2016-06-30 23:59:59'ORDER by id DESC");
</code>
Answer: You need to provide the date as a string in sql:
<code>$sql = mysqli_query($mySqlConnect,"SELECT *
FROM 1398_log
WHERE date BETWEEN '$fromDate2' AND '$toDate2'
ORDER by id DESC");
</code>
Watch the '


Question regarding portion of solution manual's argument to Chapter 19 Problem 36c of Spivak's Calculus

Question: In Chapter 19 of Spivak's Calculus, Problem 36c)'s author-provided solution makes the following claim:

Supposing that $f$ is integrable on $[a,b]$, then, for any partition $\{t_0=a,t_1,\cdots,t_{n-1},t_n=b\}$ of $[a,b]$, there exists a smallest and largest sum of the form $\displaystyle \sum_{i=1}^kf(x_i)(t_i-t_{i-1})$ where $k \in [1,n]$.

I interpreted this as saying that, for a given $k$, I can find vectors $\vec{x}=\{x_1,x_2,\cdots,x_k\}$ and $\vec{z}=\{z_1,z_2,\cdots,z_k\}$ where $x_i,z_i \in [a,b]$ such that across all vectors $\vec{y}=\{y_1,y_2,\cdots,y_k\}$ where $y_i \in [a,b]$ we have:
$$\sum_{i=1}^k f(x_i)(t_i-t_{i-1}) \leq \sum_{i=1}^k f(y_i)(t_i-t_{i-1})\leq \sum_{i=1}^k f(z_i)(t_i-t_{i-1})$$
My book has not really committed that much time on series (those appear in the future chapters), so I am not certain how to proceed. It is clear that there is a lower bound and an upper bound to the collection of all possible sums $\sum_{i=1}^k f(y_i)(t_i-t_{i-1})$...however, I am not certain how to show that the lower and upper bound are actually in the image of the "sum function" $\sum_{i=1}^k f(y_i)(t_i-t_{i-1})$. In fact, this strikes me as intuitively false...but the book says otherwise.
Edit: I have assumed here that the members of $\vec x$ and $\vec z$ must all be distinct...but if this restriction is relaxed, then I suppose the claim is fine. I suspect, though, that we need to have distinct members.
Comment: 1) Is $f$ assumed continuous? 2) Is $x_i,y_i,z_i\in[t_{i-1},t_i]$ assumed? 3) What makes you "suspect, though we need to have distinct members"?
Comment: @AnneBauval $f$ is not assumed to be continuous (the context of this overarching problem is specifically to investigate non-continuous functions). There are no assumptions provided regarding $x_i,y_i,z_i$...however, there is reference to Riemann sums in the introduction to the problem (which could, possibly, hint that your 2) is implicitly being applied). Regarding 3), I guess I just assumed that the author expected distinct values, given that the members $t_0,t_1,...$ of the partition are distinct...I suppose if your 2) is correct, though, then the $x_i, y_i,z_i$'s are all clearly distinct.
Comment: Not necessarily: you can have for instance $x_1=t_1=x_2.$
Comment: If $f$ is not continuous, the Riemann sums tied to $(t_0,\dots,t_k)$ may have no smallest and largest value.
Answer: It seems you misread your book(s). $x_1,\dots,x_n$ are fixed. The minimum and maximum values of $\sum_{i=1}^kf(x_i)(t_i-t_{i-1})$ are with respect to $k\in[1,n].$
Comment: I am quite confident (I had a look at the solution manual).
Comment: I'll see if I can make sense of the proof using your interpretation. Thank you for the suggestion.


Running php code using terminal that needs interaction

Question: I have a monitoring application (nagiosxi) that is deployed on a Linux box and some final settings are carried out via the web browser. For example, if the application is deployed on say, 192.168.2.10 and if I point the browser to http://192.168.2.10, it automatically redirects to http://192.168.2.10/nagiosxi/install.php. There are some basic settings like verifying the URL and click next, followed by setting up a password and finally hitting finished set-up.
Now, I trying to see if I can do the same using the php CLI
So, in a terminal I tried,
php -f /usr/local/nagiosxi/html/install.php

but this gives a big stdout and I cannot interactively set anything.
Is there a way to do this? Please note I have zero background in PHP.
Comment: Why are you trying to install via cli if it's supposed to be done in browser? The script is likely only intended to be installed via browser.
Comment: @Spudly The idea is to automate the entire deployment.
Answer: The PHP manual may help you solve your problem.
I hope the reference code and source link below will help you.
source : https://www.php.net/manual/en/function.fopen.php
I was working on a console script for win32 and noticed a few things about it.  On win32 it appears that you can't re-open the input stream for reading, but rather you have to open it once, and read from there on.  Also, i don't know if this is a bug or what but it appears that fgets() reads until the new line anyway.  The number of characters returned is ok, but it will not halt reading and return to the script.  I don't know of a work around for this right now, but i'll keep working on it.
This is some code to work around the close and re-open of stdin.
<?php
function read($length='255'){
    if (!isset($GLOBALS['StdinPointer'])){
        $GLOBALS['StdinPointer']=fopen("php://stdin","r");
    }
    $line=fgets($GLOBALS['StdinPointer'],$length);
    return trim($line);
}
echo "Enter your name: ";
$name=read();
echo "Enter your age: ";
$age=read();
echo "Hi $name, Isn't it Great to be $age years old?";
@fclose($StdinPointer);


Partial Fraction Decomposition with Exponents

Question: I want to break this fraction into two parts:
$$\frac{5^n3^n}{(5^n-3^n)(5^{n+1}-3^{n+1})}$$
when I try to equate this to:
$$\frac{A}{(5^n-3^n)} - \frac{B}{(5^{n+1}-3^{n+1})} $$
I get the value of A by substituting the value of n by 0:
$$A(5^{0+1}-3^{0+1}) = 5^03^0 $$
$$ A= \frac{1}{2} $$
Similarly the value of B is -0.5
By another method when I try to find the value of A and B
$$5^n(5A + B) - 3^n(3A+B) = 5^n3^n$$
and then solving for 5A+B = 3^n and 3A + B = 0
I get the value of:
$$A = \frac{3^n}{2}$$
$$B = -\frac{3^{n+1}}{2}$$
I can't understand why both methods give different values and why the first one is wrong?
Answer: $n=0$ is not the case you want to work with.  $5^0=3^0=1$.  Therefore
$\displaystyle \frac{A}{(5^0 - 3^0)} = $???
Note that if you solve for any particular $n$ (other than zero) you will get results that are correct for that particular $n$, but not correct for the general problem.
Answer: Partial fractions is for rational functions of a variable $x$, and what you have is not a rational function of $n$.
The methods that work for rational functions should not be expected to work here.
If you want to write
$$ \frac{5^n 3^n}{(5^n- 3^n)(5^{n+1}-3^{n+1})} = \frac{A}{5^n - 3^n} - \frac{B}{5^{n+1}-3^{n+1}}$$
(presumably when the none of the denominators are $0$),
that is equivalent to
$$ 5^n 3^n = (5^{n+1}-3^{n+1}) A - (5^n-3^n) B $$
Now there are certainly no solutions where $A$ and $B$ are constants.   A solution where $A$ and $B$ are multiples of $3^n$ is $A= 3^n/2$, $B = 3^{n+1}/2$.  A solution where
$A$ and $B$ are multiples of $5^n$ is $A = 5^n/2$, $B = 5^{n+1}/2$.
Or you could take a combination of these solutions:
$$ A = \frac{5^n}{2} t + \frac{3^n}{2} (1-t),\ B = \frac{5^{n+1}}{2} t + \frac{3^{n+1}}{2} (1-t) $$
where $t$ is arbitrary.


How to put the widget to rate nodes in a view next to title?

Question: I have a view with the list of nodes, how can I put the widget to rate the nodes next to title?
Note: I'm already using the Rate module. But it returns me only the results.
Comment: Use rate(https://www.drupal.org/project/rate) module
Comment: I'm already using this module. But it returns me only the results.
Answer: Since you're using the Rate module, you should configure Views as shown in this image:

So what you need to do, is to configure the field "Votes:Value". As you can see in my image above, within the Appearance Dropdown I selected Rate Widget (compact). if you only have "Rate Widget option or Default" (as in your comment, it's probably because you have not yet added the required Relationships to your view.
Relationships is a way to join tables from another module. To get you going with this also, have a look at the next image:

Some more details about the 3 (numbered) annotations I added in this image:

That's where you add the Relationship, in this case you need to select Content:Votes.
After you added that relationship, within Fields you can now add a new field Votes:Value (that is: because of the relationship that was added, you'll be able to select this specific field from the list of available fields when you try to add an extra field).
After you completed the previous step, automagically in the preview area you'll see a preview of the views results you'll get (don't bother too much about the theming of that preview at this time, what counts is that the result is correct).
Comment: Change that in Appearance Dropdown
Comment: You have to add relationship in views
Comment: How can I have the rate in a dropdown list?
Comment: what does dropdown list means?
Comment: Something like select list html or input list style
Comment: In Appearence (views form) I have only Rate Widget option or Default
Comment: Sorry... relationship with what?
Comment: @Nagarjuna : I "*think*" I understand what you mean (by combining your answer with its comments below it). However, I recommend you somehow integrate (move) the relevant (upvoted) comments into your question. In such a way that you add a few phrases in your answer to tell the reader what you want them to see/notice/do when looking at the screenprint. Just a suggestion ...
Comment: @pierre, thanks for prompting me. Sure no problem as always. And I updated my answer. Cheers :)
Comment: ok, much (let's say 75%) better. But apart from fixing "Relation Ships" (whatever those ships are ... funny!) to "Relationships", do you mind if I expand your answer with a few more lines to add a few more phrases to "document" what is now shown on your images? If you don't like it after I do so, you simply rollback or further refine/adapt it.
Comment: If you can make it better, i am more than happy. It may help somebody
Comment: I'm done, please QA-review, and adapt / rework as you want (worst case: perform a rollback if you don't like my edited version). Ps: I'd be interested to hear from @Daniele if this helps somehow (makes it easier to understand).
Comment: Finaly I find my problem. I have a multi entityes. Votes Relationship doesn't have the option to set  a releationship for him.
How can i do?


How to compute the correlation between two distance matrices

Question: I have $N$ samples, each described by a vector of $M$ features. I can compute the symmetric distance matrix $D_1(i, j)$ representing the pairwise distances between the samples, using a distance measure. Now let's say that I change the conditions under whch the features are extracted, producing new feature vectors and thus a different matrix $D_2(i, j)$. I am interested in understanding if the differences between samples remained more or less the same (i.e. samples that were similar before are still similar to each other).

How can I compare $D_1$ and $D_2$? Would the canonical correlation a suitable measure?
Is there a statistical test to assess if the difference between $D_1$ and $D_2$ is significant?
Answer: Since your data matrices are symmetric, canonical correlation analysis(CCA) is not the right approach I think. CCA would look for linear combinations of distances that maximize correlations between the two sets. I would drop the correlation option.
The Procrustes distance may be a better option, since it measures the difference in shape of multidimensional ensembles. You could consider a resampling technique (such as the bootstrap) to test for significance, since I am not aware of any theoretical null distributions for the Procrustes distance.
Comment: isn't the shape comparison in Procrustes analysis a simple Euclidean distance?
Comment: Yes, but after optimal translation, rotation and scaling. If you want to visually inspect differences in distance, consider a dimension reduction as in PCoA.
Comment: Ok. Also, can you help me understanding your last lines? How can I setup a test using the bootstrap method? I am not very fmailiar with this topic
Comment: Your resampling procedure would have to occur under the scenario where there is no relationship between the distances between the same two samples in the different datasets. So either resample distances within the column (or row) from one distance matrix and keep the other constant, or resample in both. Calculate Procrustes distances for every  instance. Then look at how extraordinary your observed result is compared to the resampling results.


How to convert GeoCoordinate to Pushpin Location in C#?

Question: I'm trying to make a pushpin for my current location, the examples I could find online all give me the same error of "Cannot implicitly convert type 'System.Device.Location.GeoCoordinate' to 'Microsoft.Maps.MapControl.WPF.Location'.
Here is the code segment;
<code>            GeoCoordinateWatcher watcher = new GeoCoordinateWatcher();
            GeoCoordinate looc = watcher.Position.Location;
            Pushpin piin = new Pushpin();
            piin.Location = looc; //error here
</code>
I'm using XAML and Bing maps if that makes a difference.
Answer: You will need to create a new Location object for the pushpin, populating it with the latitude/longitude of the GeoCoordinate object.
Note that the WPF control is old and no longer updated. If you're developing a new application it's recommended to use the UWP map control which can handle GeoCoordinate directly.


Unique solution of IVP on I

Question: I have been given the differential equation $dy/dx = f(x,y)$ with initial condition $y(x_0)=y_0$. Also $f$ is continuous in both $x$ and $y$ and Lipschitz continuous in $y$ with L-constant L.
Let F be a mapping on the space $C^0(I)$ of continuous functions $u:I\rightarrow \mathbb{R}$. $I = [x_0,M]$.
$$Fu(x) = y_0 + \int_{x_0}^x f(s,u(s))ds.$$
Let for $\alpha\geq 0$ the norm $||\cdot||_\alpha$ be given on $C^0(I)$ by
$$||u||_\alpha = \max_{x\in I} |u(x)e^{-\alpha x}|,\quad u \in C^0(I).$$
I have found an $\alpha$ for which F is a Lipschitz contraction with respect to $||\cdot||_\alpha$. The next question is to show that the IVP has exactly 1 solution on I. But isn't this just the contraction theorem applied to $y = F(y)$ (which gives me a unique fixed point, hence a unique solution to this IVP).
Thanks in advance
Answer: If you have found $\alpha > 0$ for which the mapping $F$ is a contraction in the metric induced by the norm $\lVert \cdot \rVert_{\alpha}$ then yes, the contraction mapping theorem just gives you the existence and uniqueness of the fixed point of $F$.
Moreover, as there exist constants $0 < c_1 < c_2$ such that
$$
c_1 \lVert u \rVert_{\alpha} \le \lVert u \rVert \le c_2 \lVert u \rVert_{\alpha}, \quad \forall \,u \in C^0(I),
$$
where $\lVert \cdot \rVert$ denotes the usual supremum norm, it follows that the sequence of successive approximations converges uniformly on $I$ to the (unique) solution of the IVP.

Unique solution of IVP on I


Using Filter by an entity reference view with Rewrite Results gives "there are no entities matching" error

Question: I'm using Drupal 9.2.
I have created entity reference views and use them as filter for entity reference fields (autocomplete widget). When I'm using only "Content: Title" field everything works as expected. When using more fields either hidden (rewriting Title) or visible, I get "There are no entities matching [my selection]" error on save.
*** Edit n.1 for more details:
I have a content type that has an entity reference field (autocomplete widget). When the user selects the referenced node I want the options to display something different than the node's title.
So I use "Views: Filter by an entity reference view" as Reference method of the field and I have created a view with an "Entity Reference Display" to use with the field.
If the only Field used in view is "Content: title" everything works as expected and the entity reference field is saved. If I use let's say "Content: Short name" then autocomplete field is indeed searching and showing Short name, but when I save the form I get "There are no entities matching [Short name]".
I have tried using only "Content: Title" and rewriting output and I still get the same problem.
The same happens if I use a view with users and I show firstname and lastname instead of username. Autocomplete widget searches and shows options with the selected fields correctly but saving the form result in error with no entities matching.
I really don't know how this feature works to start debugging. Is the actual referenced node id saved in a hidden field or element data attributes?
Does anybody have any idea why this is happening or how to debug?
Thanks
*** Edit n.2
After some debugging I can see that method matchEntityByTitle of EntityAutocomplete is called which in turn calls getReferenceableEntities of ViewsSelection. To validate selechion this plugin searched for a match of the "value" (fields combination) in any of the fields marked for search. This normally returns no results and the field is not validated.
So is this normal behaviour and this feature can only work with title (or single field) values or do I miss something else?
Comment: What are your Entity Reference Format settings in Views?
Comment: format: entity reference list, settings: all fields selected for search
Comment: Can you update the question with all information, what fields are you using, when showing the fields is the search working, is only rewriting causing problems?
Comment: I have updated with more info. The problem is the same no matter if I use rewrite on Title or just show more fields either inline or with field wrapper elements
Comment: AFAIK basically everything in views always searches for unmodified values of database fields, and completely ignores whatever you set on UI (rewriting fields, different language rendering,... etc all is done AFTER the SQL query, you can not search for any result/modification done by the render pipeline)
Comment: When I'm searching for words from other fields (other than title/name) I don't see that second field in the autocomplete suggestion list, I see the title/name, it narrows it down correctly, when I select it I see the title/name with its ID in brackets, and then I save and it saves correctly. How did you get some other field to show in the suggestion list? When I Exclude other fields from display and put their values in Rewrite of the title/name field then the autocomplete doesn't find any results if I use keywords from fields other than title/name. This all on D8, not sure if it matters.
Comment: @prkos if you don't exclude the other fields from display they are shown alongside the title in the order they are arranged in the view.  That's if you use Format > Show > Entity Reference Inline Fields. From Format > Show > Settings you can also change the markup used.
Comment: I remember that it worked that way before, showing all the fields in the suggestion list, but it's not showing up for me in this instance. Maybe it's something specific to my setup.
Comment: So if I understand correctly this is practically useless, as a multi field combination will never validate against each field separately. There should be a hidden id and validate with that and not matchEntityByTitle
Answer: Solved:
the problem was that I used method proposed here
https://drupal.stackexchange.com/a/295790/101436
to remove id in parenthesis. This would result in validation being done by matchEntityByTitle and failing.
So the real problem would be how to hide id in parenthesis and still be able to use different fields from entity reference view.


DataGrid that also supports a tree view

Question: Do you know of any datagrid-like control that also supports a treeview. Like this (but still fully WPF-stylable/templatable):
Update: UI-virtualization would be another important feature.
Comment: possible dupe http://stackoverflow.com/questions/1020213/c-can-i-show-an-expandable-tree-like-view-in-a-datagrid
Comment: @roviuser The question poster was probably satisfied with how the infragistics control can collapse groups, but AFAIK the infragistics control does not support the above behavior.
Comment: another possible dup - http://stackoverflow.com/questions/3457107/wpf-handle-editable-hierarchical-data-treeviewdatagrid-hybrid
Comment: @bitbonk were you able to implement the treeview in datagrid with any of the solutions below or by another way?
Answer: Telerik has a TreeListView control - http://www.telerik.com/products/wpf/treelistview.aspx.  It's not free, but I think it'll do what you want.
Answer: It probably wouldn't be that hard to create your own from styling a regular DataGrid w/ Groups to look like that. The extra advantage is things like sorting and resizing columns are already taken care of.
Just style the Group Templates to contain the +/- button, folder, and group name, and change your regular DataGrid style to contain a white background with no grid lines. Even the Lines wouldn't be that hard to do if you wanted them
I always find this site useful for figuring out the different DataGrid components
Comment: IMHO, when I use grouping UI-virtualization will be turned off.
Answer: You may look over this Hierarchical Data Library or this PropertyGrid control or this DataGrig control or this xamDataGrid control.
Or Look over this TreeGridControl you may set property of colomn IsReadOnly to False and edit it to WPF(its simple).
Or you can make your own control, for example whith help of this "TreeView+DataGrid in XAML" article, in which you should change TextBlock to TextBox, and make some other changes. Or whith help of this "WPF TreeListView Control" article and comments to it.
Answer: This control is somewhat similar to your request: http://www.obout.com/grid/aspnet_master_detail_self_reference.aspx
They also have this linked tree/grid example: http://www.obout.com/grid/tree_grid.aspx

DataGrid that also supports a tree view


Multiple field, but each one as individule

Question: I need an image field with only 2 field limit.
I need to call first one front and second one back and be separated.(no problem I can do that with hook_form_alter)
My problem is that in drupal 7, in adding the content, it doesn't show the second field upload button until you upload the first one.
You have to add the first file, than click on "add another" to be able to upload second file and after uploading both if you delete the first one, the second one goes to first one place, which I don't want that to happen!
I know I can make two separate fields call one front image and one back, but I want to know if there is an approach to do this with only one field. (save a database table)
Thank You
Comment: Could you please specify your use case for "after uploading both if you delete the first one, the second one goes to first one place, which I don't want that to happen!". May be someone could find a work-around for that problem such that drupal's default file upload behaviour might not cause a problem for you.
Comment: My use case: I will use this field for business card printing, the client will upload the front image and back image, If after uploading his pictures he decided to delete the front image and update it with new one, the back image will take place of front image, which will confuse the person, and may make possible problems. Thank you for your interest in my question, appreciate it.
Comment: In drupal 6, multi-value field weren't like this, so I think there should be an easy solution to bring the same functionality back, but want to make sure to don't make a wrong approach.
Comment: Could you have 2 different fields for the 2 different purposes, each being single valued?
Comment: As I mentioned I need to know if it is possible to achieve this with only one field, It seems to me that there should be an easy approach to this, because drupal 6 was like that. Thanks for suggestion.
Answer: Just use the single image field, add field description text for the user in regards to clicking to "add another" item when uploading the two images.
On updating, the user can adjust the weight of the images and drag/drop the front/back images into order.
Alternatively, you could look at using two fields, or a module like field_collection
Comment: For some reasons I don't want to use field_collection and two separate field. One of the reason is that it will add extra and unnecessary table, second because I need visitors to be able to edit the field inside a view, so if I put two different field there will be two save button, and currently there are some problems with saving the whole node with ajax using edit-field option in view, so I think more easier option would be to just accomplish this using one field.
Comment: The drag and drop option will increase the chance of mistake, and we don't want that to happen. Any way thanks for your suggestion @DavidThomas


Getting node in theme_preprocess_node

Question: I have this code:
function material_base_preprocess_node(&$variables){
    $node = $variables['node'];
    $language = \Drupal::languageManager()->getCurrentLanguage()->getId();
    $variables['username'] = $node->getOwner()->getTranslation($language)->field_name->value;
    $variables['mediums1'] = $node->getTranslation($language)->field_mediums->value;
}

this line works fine:
 $variables['username'] = $node->getOwner()->getTranslation($language)->field_name->value;

but this
 $variables['mediums1'] = $node->getTranslation($language)->field_mediums->value;

gets error:
The website encountered an unexpected error. Please try again later.

InvalidArgumentException: Invalid translation language (en) specified. in Drupal\Core\Entity\ContentEntityBase->getTranslation() (line 789 of core/lib/Drupal/Core/Entity/ContentEntityBase.php).

Why this code works for user, but not for node and how to fix that?
this one works
$node->get('field_mediums')->entity->getTranslation($language)->name->value;

Answer: As the exception message says, there is no english translation for that node.
The node is already in the translation that Drupal determined is the best available translation for this page.
If you do want to get a specific translation, you need to check with hasTranslation() first or use \Drupal::service('entity.repository')->getTranslationFromContext($entity, $langcode);
Comment: Ok, but I have translated taxonomy in non-translated node. Can I get this even if node isn't translated?
Comment: Sure, but you tried to get the node, not the taxonomy term. That call above works on any entity type, just get the entity with $node->get('your_taxonomy_field')->entity and then pass that to getTranslationFromContext()
Comment: Try this one:  `$variables['mediums1'] =$node->get('field_mediums')->entity->getTranslation($language)->value;` but nothing is printed.
Comment: That is not what I said how you should use getTranslationFromContext(). *not* getTranslation(). When you have the term you need to access its fields, there is no value field. So label() or ->name->value for example

Getting node in theme_preprocess_node


How to remove value from array json php?

Question: I have a sample code:
$json_encode = '{"OS":"Android","Title":"Galaxy"}';
$json_decode = json_decode($json_encode);
foreach($json_decode as $key => $value) {
   if($key == 'Title') {
       unset($key);
   }
}
print_r(json_encode($json_decode));

But result can't remove key='Title' from that json string, how to fix it?
Answer: You don't need those extra lines of code, if the Title index comes always, then you can unset the Title index directly :
$json_encode = '{"OS":"Android","Title":"Galaxy"}';
$json_decode = json_decode($json_encode);
unset($json_decode['Title']);

See the link below for more information on PHP Array Unset function, you are making mistake on simple syntax.
PHP Array Unset
Answer: You forgot to include the array in the unset statement. It should be:
unset($json_decode[$key]);

Actually, for your particular example, you don't even need a loop, you can unset the value directly.
Also to get an associative array from the json_encode function, you need to add another parameter:
$json_decode = json_decode($json_encode, true);

Answer: $json_decode = json_decode($json_encode,TRUE);

If "TRUE" is not passed, json_decode returns an object.
Also replace unset($key) with unset($json_decode[$key]);
Answer: $json_encode = '{"OS":"Android","Title":"Galaxy"}';
$json_decode = json_decode($json_encode, true);
foreach ($json_decode as $key => $value) {
    if (in_array('Title', $value)) {
        unset($json_decode[$key]);
    }
}
$json_encode = json_encode($json_decode);


Find the formula of the linear transformation

Question: Consider the linear transformation $f:R^3\rightarrow R^3$ with    $f(0,1,2)=(2,1,1)$     and     $\ker f=\{(0,2,1),(1,0,1)\}.$ Find:
(i) $f(0,1,0)$ (ii) the general formula of $f$.
Any help, please.
Answer: Now,
$$
(0,1,0)=\frac{1}{3}\big[2(0,2,1)-(0,1,2)\big],
$$
hence
$$f(0,1,0)
=\frac{1}{3}\big[2 \cdot f(0,2,1)-f(0,1,2)\big]
=\frac{1}{3}\big[2 \cdot 0 -(2,1,1)\big]
=\left(-\frac{2}{3},-\frac{1}{3},-\frac{1}{3}\right).
$$
Now,
$$
(0,0,1)
=\frac{1}{2}\big[(0,1,2)-(0,1,0)\big],
$$
hence
$$
f(0,0,1)
=\frac{1}{2}\left[(2,1,1)-(-\frac{2}{3},-\frac{1}{3},-\frac{1}{3})\right]
=\left(\frac{4}{3},\frac{2}{3},\frac{2}{3}\right)
$$
Furthermore,
$$
(1,0,0)
=(1,0,1)-(0,0,1),
$$
hence
$$f(1,0,0)
=f(1,0,1)-f(0,0,1)
=-f(0,0,1)
=\left(-\frac{4}{3},-\frac{2}{3},-\frac{2}{3}\right).
$$
We can get the formula of $f$:
$$
f(x,y,z)
= \left(-\frac{4}{3}x-\frac{2}{3}y+\frac{4}{3}z,-\frac{2}{3}x-\frac{1}{3}y+\frac{2}{3}z,-\frac{2}{3}x-\frac{1}{3}y+\frac{2}{3}z\right).
$$
Comment: If $x,y \in \mathbb{R}^3$, then $f(x+y)=f(x)+f(y)$, and if $\alpha \in \mathbb{R}$ we have $f(\alpha x)=\alpha f(x)$. If $x \in \mathrm{ker} f$ then $f(x)=0$. I applied all this properties writing the elements of the standard basis of $\mathbb{R}^3$ as linear combinations of elements that we know how $f$ acts on them. Then, once you know the function behaves on the basis element, you know how it acts on any vector.


How can I push the current execution state into a stack so that I can continue from it later?

Question: Imagine a simple grammar:
(a|ab)c

Which reads (a or ab) followed by c. The parse tree would look like this:
   and
   / \
  or  c
 /  \
a   ab

Now given it this input:
abc

We would traverse first down the left side of the tree, and match "a", then go back up a level. Since "a" matched, the "or" is also true, so move on to the "c". "c" does not match, and we hit the end of the road.
But there was an alternate path it could have taken; had we traversed down to "ab", we would have found a match.
So what I want to do for "or" nodes is essentially this:

Evaluate left branch
If left branch doesn't match, try right branch
If left match does match, push current state on to stack so that we can continue from this point later if necessary

Then whenever the parser hits a dead end, I want to pop an item off the stack and continue from there again.
That's the part I can't figure out...how do I essentially save the current call stack? I can save the "ab" node in a stack so that I know I have to execute that one next, but then it still needs to know it needs to fall back up to the "or" afterwards.

I think Chris was on to something. We have to find a way to translate the tree such that it isn't necessary to jump across branches like that. For example, this equivalent parse tree doesn't have that problem:
     or
    /  \
 and   and
 / \    / \
a   c  ab  c

This time we parse down the left, hit "a", it passes, so we try the "c" node beside it, that fails, "and" fails, "or" has to try the right branch, ... "ab" passes, the other "c" passes, and then the whole expression passes.
Comment: As a side note, the terminology here is kind of funny. "Stacks" are usually thought of stacking upwards, so when you pop an item off the stack, you fall down a level, but since I drew my tree the way I did, you're falling upwards. Perhaps I should flip the tree? `(ノಠ益ಠ)ノ彡┻━┻`
Answer: You have the answer to your question in the way you posed it.
You need to save the state.   The tricky part is identifying the state. Saving it is easy.
Your problem is that the parser "has a state" when it starts parsing some grammar rule.  (This gets messier if you use an LALR parser, which merges the parsing of many rules into a single state).  That state consists of:

the state of the input (e.g., where is the input stream?).
the state of the parse stack (what is the left context seen so far?)
where the parser should continue for success, and where to continue for failure

When you are parsing and face a choice alternative as you have described, you need to "save the state", run a trial parse on the first term. If successful, you can throw away the saved state and continue.  If failure, restore the state, and try the 2nd (and nth alternatives).  (Its easier to be brainless and just the save state regardless of whether you face an alternative, but that's up to you).
How can you save the state?  Push it into a stack. (You typically have a parse stack, that's a pretty convenient place!  If you don't like that, add another stack but you'll discover it and the parse stack in general move synchronously; I just make the parse stack contain a record with all the stuff I need, including space for the input.  And you'll find the "call stack" convenient for parts of the state; see below).
The first thing is to save the input location; that is likely a file source position and for optimizing reasons likely a buffer index.  That's just a scalar so it is pretty easy to save.   Restoring the input stream may be harder; there's no gaurantee that the parser input scanner is anywhere near where it was.  So you need to reposition the file, re-read any buffer, and reposition any input buffer pointer.   Some simple checks can make this statistically cheap: store the file position of the first character of any buffer; then deteimining if you have to re-read the buffer is a matter of comparing the saved file position with the buffer start file position.  The rest should be obvious.
You'll backtrack through fewer buffers (e.g, your parser runs faster) if you rearrange your grammar to minimize that. In your specific grammar, you have "(a | ab ) c", which could be re-written by hand to "a b? c".  The latter will at least not backtrack across whatever a represents.
The odd part is saving the parse stack.  Well, you don't have to, because your trial parse is only going to extend the parse stack you have, and restore it to the parse state you have whether your subparse succeeds or fails.
"where the parser goes on fail" and "where it goes on success" are just two more scalars. You can represent them as indexes of your parsing code blocks, and program counters (e.g., continuations) or as a return address on your call stack (see? another parallel stack!) followed by a conditional test to success/failure.
If you want some details on the latter, check out my SO answer on hand-coded recursive descent parsers.
If you start building trees, or doing something else as a side effect of the parse, you'll have to figure how to capture/save the state of the side-effected entity, and restore it.  But whatever it is, you'll end up pushing it on a stack.
Comment: "You can represent them as indexes of your parsing code blocks, and program counters (e.g., continuations) or as a return address on your call stack" -- I'm writing this specifically in C#; I don't think I have access to any program counter. But regardless if I could jump back to any line of code, I don't know how I can possibly restore the call stack. In my example, once "a" succeeds I can push the "ab node onto a stack so that I know I have to execute that node next if there's a failure down the road, and I can save the position of where I was at too...the part I'm specifically confused...
Comment: ...about is after I execute the "ab" node, where does the code flow to next? It would return to where-ever I called it from, which would be above the root node, because that's where I'd pop it off the stack. Perhaps I should have put some more emphasis on the C# part, or perhaps my current approach is unsalvagable.
Comment: OK,you're in C# and don't have access to the PC.  SO use the third idea, e.g, a call with a boolean return (think of this as "the subparse succeeded/failed") and a conditional branch. Look at the hand-coded recursive descent answer, which does exactly this.
Comment: I think I figured out where I'm getting confused. You're suggesting I create a parser that's specific to my grammar; I was trying to create a parser that would essentially handle any grammar. What I really need to do is build a parser out of my grammar, and then use that parser to parse the input, not go straight from grammar to parsing (which I now suspect isn't possible for any sufficiently complex grammar).
Comment: @Mark: Yes, I am suggesting to build a parser that matches the grammar, because its pretty easy to do by hand, and can be automated pretty well.   You can build an interpreter of a grammar that parses; it has the same problems with storing the state, and the solution is still the same.   You can also build a parser that doesn't backtrack, so it doesn't have to do this state saving; see GLR parsers (these essentially compiler grammars for a parsing engine to process) or Early parsers (which will parse any context-free grammar without an interpreter.) http://en.wikipedia.org/wiki/Earley_parser
Comment: I think what I had was a context-free grammar. Worked for a little while until I realized my intended grammar isn't context-free :)
Comment: Don't confuse "context-free language" (most of them aren't) with "context-free grammar" (most of them are).  There's always a context free grammar for a language, and what parser generators do is help you recognize the context-free part.  Its up to you the rest of the front end/compiler to detect violations of the non-context free part.  (That's why most compilers have symbol tables).
Answer: What you should do is is call a method for each possibility. If you hit a dead end, you can return, and you will be right back where you were, and ready to try the next option.
You can indicate whether you successfully parsed the branch by returning a value from the parsing method. For example, you could return true for success and false for failure. In this case, if the parse returns false, you try the next option.
Comment: This is the problem Kendall. In my example, I go down the left side of the tree, and I hit "a". "a" *succeeds* so I *don't* try the next option, and thus I've lost my place by the time I hit "c". I don't know how to get back to where I was.
Comment: You return from the method that parsed the left side, returning `true`, or maybe the parse tree for that branch.
Comment: Huh? When I parse "a" it returns true, returning to "or". "or" sees that "a" is true and thus also returns true, returning back to "and". "and" then evaluates the other branch, "c". "c" fails (returns false). Returning from "c" goes back to "and" (which then also fails). Can you elaborate on how I can return from "c" to "or"?
Comment: You should rewrite your grammar to eliminate that problem. You can use `ab?c` where ? indicates an optional component.
Comment: No. This was a primitive example. Unless you can prove how all "or" statements can be replaced with something followed by an optional term... this isn't possible.
Comment: Not all 'or' statements need to be. For example, `(a|b)c` is fine the way it is.
Comment: Hrm... even if that could work, I'd need an algorithm for finding the longest prefix between 2 "or" options, to keep my grammars simple. Which would be doable if all the elements were strings, but that isn't necessarily so. They could be regexes, or other complex nodes for which you can't easily break up like that.
Comment: You don't have to do this for all cases; its an optimization (a pretty good one).
Answer: Just return your state in addition to your result. Lets take a simple example where you can have an index for each element:
Grammer: (a|ab)c
Translated: AND(OR(a,ab),c)
Input: abc

Call AND
Call OR
a matches, return true,1
c does not match, start over
Call OR giving 1
ab matches, return true,2
c matches, return true

You will need a more complex structure to handle harder cases (whether it be a queue or stack is up to how you build and destruct in recreating your state)
Comment: You're saying I should restart from the very beginning each time I hit a dead end, but take a different path through? Sounds plausible, but clunky and inefficient. What if I have a really deeply nested tree? The first half or 90% of the path might be exactly the same. Plus...it would be very tricky to encode which path to take. I might travel through the same node 5 times, but only on the 5th pass do I want to fork in a different direction...
Comment: Your second pass will be pretty cheap, if the exact same child doesn't fail, then your own answer doesn't change either. If it fails (leafs would fail on the second pass every time for instance) then try your next child (if that is what your logic allows). My logic is really trying to duplicate your "save stack" idea, just a little more concrete on what you would do (saving the actual stack is both complicated and incredibly expensive, who knows how deep it goes). Obviously there are other algorithms that could be used, you could look into how regex parsers work for instance.
Comment: In that case, I'd have to cache the results. *Most* of the operations are pretty cheap though (checking if about 5 characters match), so... I don't think that would yield much benefit. I think the biggest cost would be the iteration, especially if there's a lot of backtracking. Saving the stack, expensive? In terms of memory? Rather save CPU time than memory. But anyway, I'm mostly interested in a clean and easy to implement solution right now.
Answer: you need to use recursion.
Something like:
in or statement
for each statement
 bool ret = eval(statement)
 if (ret)
    bool recVal = call the recursion
    if (recVal)
       than you find a path stop the recursion.
 else
   we continue in another loop and try next statement.
Comment: You don't need recursion.  You need a stack.  You can get one implicitly by recursing.
Comment: I am using recursion, but it's only useful for moving back *up* the tree. What I need to do is go from "c" back to "ab".
Comment: you are correct, but after you fail in "c" you go back the tree to whos call it its "a" and you try the next one in the or statement "ab"
Comment: @Horonchik: "a" doesn't call "c". "and" calls "c". That's how trees work.


I want to display a list of words based off different key words

Question: I want to make a list. Column A are the models. So model1, model2 and model3.
Next to each model is what goes into it. So going along with the picture A3="model" (B3:D3=dog, cat, horse)
When I type the word "Model1" into cell G3 I want it to display the list of items from b3:d3 under neither it. But if I type model2 I want it to display those items instead and so on.
Example these will be on sheet1

A3"model1" b3(dog) c3(cat) d3(horse)

A5"model2" b5(wine) c5(beer) d5(pop)

Etc.

This will be on sheet2
G3"model1"
g4-dog
G5-cat
G6-horse
or
G3"model2"
G4-wine
G5-beer
G6-pop
So if I type model2 into G3 I want it to display those items instead going vertical
I was trying a vlookup but could only get it to display 1 cell instead of all 3 items.
This is for Google sheets
Answer: try:
<code>=ARRAYFORMULA(TRANSPOSE(IFNA(VLOOKUP(F2, Sheet1!A:D, COLUMN(B:D), 0))))
</code>


Why does Chinese Restaurant Table Distribution look like a Gaussian Distribution?

Question: The Chinese Restaurant Table Distribution describes the probability distribution for the number of non-empty tables in the Chinese Restaurant Process after $T$ customers have been seated. Specifically, if $K_T$ is the (random) number of non-empty tables after seating $T$ customers in a $CRP(\alpha)$, its PMF is defined as
$$P(K_T = k) = \frac{\Gamma(\alpha)}{\Gamma(\alpha + T)} |S(T, k)| \alpha^k$$
where $k \in \{1, ..., T\}$ and $|S(\cdot, \cdot)|$ are unsigned Stirling numbers of the first kind. I discovered that when I fix $\alpha$ and plot the distribution for increasing values of $T$, the distribution looks more and more like a Gaussian. For alpha=10.01, I plot the distribution from T=1 (red) to T=50 (blue):

My question is: why does the Chinese Restaurant Table distribution look like a Gaussian distribution for medium-to-large $T$?
Comment: The number of tables is approximately Poisson, which is approximately Gaussian for large rates. You can get a finite sample bound from Le Cam's Theorem on how close it is to the approximating Poisson.
Comment: Well, the number of tables is $K_T = \sum_{i = 1}^T I(\text{new table at observation $i$})$, and the terms of the sum are independent. You have a lot of options here for showing that it is close to a Gaussian, as it is a sum of independent random variables. For example, if $p_i = \alpha / (\alpha + i)$ is the probability of a new table at observation $i$, then it is easy enough to check that $\sum_i p_i (1 - p_i) = \infty$, after which you can apply [this exercise](https://math.stackexchange.com/questions/2054592/do-bernoulli-random-variables-always-satisfy-the-lyapunov-condition).
Comment: Also, technically it should be $1 + $ a Poisson, if you go that route, since obviously $K_T \ge 1$. A precise result is given in [this paper](http://www2.stat.duke.edu/~mw/MWextrapubs/West1992alphaDP.pdf).
Comment: There is no way to simplify the sum, and the bound itself doesn't depend on the sum. Although to apply Le Cam's lemma you might need to take $\alpha \downarrow 0$ slowly. Probably the easiest thing to do is actually just to apply the Lyapounov CLT that I linked to in my last comment, if all you care about is the Gaussian part, and skip Le Cam's theorem.
Comment: I buy that Poisson is approximately Gaussian for large rates, but I'm unfamiliar with the first and third steps. Could you walk me through the derivation?
Comment: I buy that the number of tables is $K_T = \sum_{t=1}^T I(\text{new table at observation }t)$. I'm struggling with the next step. The probability of creating a new table at observation $t$ is given by $\alpha/(\alpha + t -1)$, so the expected value of $K_T$ will be $\sum_{t=1}^T \alpha/(\alpha + t -1)$. This looks like a harmonic series, but not exactly, so I'm unclear on how to simplify the sum to get my rate $\lambda$ to apply Le Cam's Theorem. Could you suggest how to simplify the sum?
Comment: @guy thanks for all the help! Do you want to type up a comprehensive answer so I can give you credit? If not, I can write the answer myself and give you credit. Also, as an aside, I think there is a way to simplify the sum. This [note](https://www.gatsby.ucl.ac.uk/~ywteh/research/npbayes/dp.pdf) says that the sum is given exactly by $\alpha (\psi (\alpha + n) - \psi(\alpha))$, where $\psi(\cdot)$ is the Digamma function.
Comment: ok, I added a solution. Vis-a-vis the simplification, it isn't clear to me that the expression $\alpha \{\psi(\alpha + n) - \psi(\alpha)\}$ is actually any simpler; you are just hiding the sum with the special functions :) I actually deliberately did not state this as a simplification.
Comment: @guy thanks again for the help :D :D
Answer: We can apply the Lyapounov CLT to show that $K_T$ is normal for large $T$. Let
$$
  K_T = \sum_{i=1}^T I(\text{new table at $i$}) = \sum_{i=1}^T Z_i.
$$
Then it is well-known that $Z_i \stackrel{\text{ind}}{\sim} \text{Bernoulli}(p_i)$ where $p_i = \alpha / (\alpha + i - 1)$. Now, $\sum_{i=1}^\infty p_i (1 - p_i) = \sum_{i=1}^\infty \frac{\alpha i}{(\alpha + i)^2} = \infty$ by comparison to the harmonic series. Hence we can apply the Lyapnouv CLT to conclude that
$$
\frac{K_T - E(K_T)}{\sqrt{\text{Var}(K_T)}} \to N(0,1)
$$
in distribution, using the argument outlined here to verify the Lyapounov condition for Bernoulli random variables.
Comment: Nice answer. One can also use [Berry--Esseen](https://en.wikipedia.org/wiki/Berry%E2%80%93Esseen_theorem) for non-identically distributed variables to get  a quantitative, finite-sample, bound.
Comment: @Rylan yes, thanks for the correction. For being "good at this stuff," most of it is just experience. I used to work with DPs a lot.
Comment: @RylanSchaeffer, asking good questions is perhaps the first step (which you are doing fine). Experience (as guy said) helps; it becomes easier over time... practice makes perfect. Other things that come to mind: 1) Reading research papers and seeing how others do it (esp. the really good ones). 2) Doing research: Defining a specific problem and reading and thinking around that. 3) Practice, practice, practice!
Comment: guy & @passerby51, how do you get so good at this stuff? Any tips for learning faster?
Comment: @guy, small nit: I think that $p_i = \alpha/(\alpha + i -1)$, not $p_i = \alpha/(\alpha + i)$?
Comment: guy and @passerby51,you've both been so helpful, can I ask you two to please take a look at another question? https://stats.stackexchange.com/questions/512741/reason-for-poisson-distribution-in-indian-buffet-process


Clickonce - How to add an image to installer?

Question: Is it possible to change the GUI of a Clickonce installer? To add a custom image for example?
Answer: Nope. You can change the icon, but that's it.
This is intentional, because ClickOnce allows you to install stuff from the web, and allowing UI changes opens the door to people with malicious intent. Using the same UI for every clickonce install makes sure people know that something is being installed: you can't have the UI mock a standard message box for example, while actually installing software in the background (without the user knowing).


Adding images to buttons in listview

Question: How to put images on ListView buttons? I found some tutorials but don't know how to implement in my xml that I have already. I still working only with xml files and didn't touch anything in the code of the generated MainActivity.java.
public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}
}

This is the current xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="1" >

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="0.5" >

    <ImageView
        android:contentDescription="@string/food"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentBottom="true"
        android:scaleType="centerCrop"
        android:src="@drawable/food" />
</RelativeLayout>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="0.5"
    android:orientation="vertical" >

    <Button
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="35dp"
        android:padding="4dp"
        android:layout_marginTop="20dp"
        android:gravity="left"
        android:background="@drawable/bg_button"
        android:text="@string/Menu1" />

    <Button
        android:id="@+id/button2"
        android:layout_width="match_parent"
        android:layout_height="35dp"
        android:padding="4dp"
        android:layout_marginTop="5dp"

        android:gravity="left"
        android:background="@drawable/bg_button"
        android:text="@string/Menu2" />

    <Button
        android:id="@+id/button3"
        android:layout_width="match_parent"
        android:layout_height="35dp"
        android:padding="4dp"
        android:layout_marginTop="5dp"

        android:gravity="left"
        android:background="@drawable/bg_button"
        android:text="@string/Menu3" />

    <Button
        android:id="@+id/button4"
        android:layout_width="match_parent"
        android:layout_height="35dp"
        android:padding="4dp"
        android:layout_marginTop="5dp"

        android:gravity="left"
        android:background="@drawable/bg_button"
        android:text="@string/Menu4" />
 </LinearLayout>

</LinearLayout>

So I want to add images on the left side of this 4 buttons.
Anyone can help with this task?
Update:
Currently I have this structure on the left. Half of the screen (upper) is image. Second half I have 4 buttons. I want to put image on each button on the left side like is in the right picture with where is red aquare.
Comment: possible duplicate of [Android add image to button](http://stackoverflow.com/questions/12492064/android-add-image-to-button)
Comment: can you draw and upload a hand draw of your list item so tha I can help you
Comment: As @ChVKishore said, is it how your each item will look like in the list ?
Comment: Updated and sorry for my drawing skills. Image on left and text next to image.
Comment: Have a look at this answer http://stackoverflow.com/questions/17258386/how-to-add-imageleft-and-text-on-button
Comment: @JibranKhan, from your link I think this can do what I need `use android:DrawableLeft="@drawable/image" in your xml`
Comment: Yes as i also mentioned in my answer below.
Answer: Here is how you can have image and Text both on same button
<Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Testing" android:drawableLeft="@drawable/logo"/>

Adding images to buttons in listview


Java HotSpot(TM) 64-Bit Server VM warning: Insufficient space for shared memory file

Question: I am working on Linux for Mitrh and when I shutdown Apache server it gives following error:

And when I check for filesystem-

I dont know how to use /dev/sdb1/ that is 99% available
Answer: This might be a little late. But, changing the tmp file location to a place with more space for JVM could solve your problem:
<code>export JAVACMD_OPTIONS="-Djava.io.tmpdir=/path/to/temp/directory/with/more/space";
</code>
Hope this helps


Basic 2 Routers configurations for noobs

Question: So, my goal is to have each one of my devices connected to a double-NAT simple solutions.
I've started my configuration with Router 1:
IP: 192.168.1.254
Mask: 255.255.252.0

DHCP
Ipv4: 192.168.1.10 - 192.168.1.250
Mask: 255.255.252.0
Server: 192.168.1.254
Gateway: 192.168.1.254

So far so good :D
Than, I've tried to configure the second router:
WAN Setup:
Connection Type: Static IP
IP: 192.168.1.11
Mask: 255.255.252.0
Gateway: 192.168.1.254

And now my problem:
Attempt 1

Connected the Router 1 LAN port to the Router 2 WAN port
Enable DHCP, its already configured by default (192.168.4.100 to 192.168.4.200).
Everything connects fine, but they act like different networks, and for example, I cannot see the printer and my shared drive at the same the (they are in different routers)

Result -> FAIL
Attempt 2

Connected the Router 1 LAN port to the Router 2 WAN port
Enable DHCP, and change the range for 192.168.2.100 to 192.168.2.200
Get the message: The IP address is not in the same LAN IP Address.

Result -> FAIL
Attempt 3

Connected the Router 1 LAN port to the Router 2 WAN port
Enable DHCP
Change LAN to 192.168.0.1
Get message: WAN IP address and LAN IP address cannot be in a same subnet. Please input another IP Address.

Result -> FAIL
Attempt 4

Connected the Router 1 LAN port to the Router 2 LAN port
Change LAN to 192.168.0.1
Change DHCP range:  192.168.0.50 to 192.168.200
No internet in Router 2

Result -> FAIL
Attempt 5

Connected the Router 1 LAN port to the Router 2 LAN port
Change LAN to 192.168.0.1
Disable DHCP on Router 2
Too many connections for my ISP Router

Result -> FAIL
Any sugestion? PLEASE... :)
Comment: "_my goal is to have each one of my devices connected to a double-NAT simple solutions._" That is not a worthy goal. A worthy goal is to eliminate NAT unless you have public/private routing or overlapping addressing. NAT is to be avoided if at all possible. Simple routing should be used betwwen networks under your control. NAT is not a substitute for routing.
Answer: It looks like you are placing your R2 into the same network as your R1, and thus not seeing the expected behavior. If you want to design this to be double NAT separate R2 into another network, something like this:
                       LAN NAT 1
     WAN+-----+LAN   192.168.1.0/24  WAN+-----+
.254 <--+     +-------------------------+     |
        | R1  |.1                     .2| R2  |
        +-----+                         +-----+
                                        LAN|.1
                             LAN NAT 2     |
                             192.168.2.0/24|
                                           |
                                           v
                           Devices not leasing from ISP router

(R1)DHCPv4
Range: 192.168.1.10 - 192.168.1.250
Mask: 255.255.255.0
Local IP: 192.168.1.1
Gateway: 192.168.1.254

(R2)DHCPv4
Range: 192.168.2.10 - 192.168.2.250
WAN Connection Type: Static IP
WAN IP: 192.168.1.2
Local IP: 192.168.2.1
Mask: 255.255.255.0
Gateway: 192.168.1.254

Not sure what your R1's WAN setup is (what is Server: 192.168.1.254, if it is also the gateway?)
Answer: The main problem is that the Router 1 subnet mask is too broad.  Set it to 255.255.255.0 (not 255.255.252.0).

In your attempt 1, the Router 2 DHCP range is consistent with the Router 1 subnet mask.  The two are on different networks because Router 2 is routing:  Its NAT is working.
In your attempt 2, you set the Router 2 DHCP range within the Router 1 subnet.  Changing the Router 1 subnet to 255.255.255.0 would allow the DHCP range you specified but you'll still have different networks.
In your attempts 3 and 4, you have two DHCP servers active on the same subnet and the conflicts can prevent connections altogether.
Your attempt 5 seems to have bridged both routers.

I may be wrong but what I think you want is a single subnet behind at least one of your two routers, with the second router available to provide additional Ethernet jacks.  If so, then do this:

Router 1:  WAN IP = DHCP (plugs into your ISP router/modem).  LAN IP = 192.168.1.1.  Subnet mask 255.255.255.0.  DHCP range 192.168.1.3-192.168.1.254.
Router 2:  Some routers can be switched to "bridge mode" (which simply turns off NAT) by ticking a box or selecting a configuration option.  If so, do that.  You may be able to plug its WAN port into a Router 1 LAN port but if that doesn't work, run the cable to a Router 2 LAN port instead.

If Router 2 doesn't have a "bridge mode" or "disable NAT" option, then plug LAN port to LAN port and:  WAN IP = DHCP or 192.168.2.1.  LAN IP = 192.168.1.2.  Subnet mask 255.255.255.0.  DHCP range:  DISABLE DHCP (to avoid conflicts with the Router 1 DHCP), so no range.  These changes should "bridge" Router 2 and allow it to function as a bridge/switch (same thing).  DHCP clients connected to Router 2 will get DHCP configuration from the Router 1 DHCP server.
Comment: In this option, there still will be communication between devices connected to Router 1 and 2 ? Thanks
Comment: The configuration I suggest will leave devices connected to either router on a single subnet, and so devices connected to one should be able to connect to devices connected on the other.  Bear in mind, too, that buying a simple unmanaged GigE switch and using it instead of the second router may be an easier (and quite inexpensive) way to get additional Ethernet jacks.  What this configuration is intended to do, after all, is to effectively convert the second router into a bridge/switch (same thing) by disabling or working around its routing capabilities.


Is it coincidental that matrices are useful for solving systems of equations or is there a deeper (geometric) connection?

Question: Let's say we have this simple system of equations:
$$-x + y = 1$$
$$ x + y = 3$$
They intersect at the point $(1,2)$ and this is the graph:

One way of going about and solving this system of equations is to convert it into matrix form:
$$\begin{bmatrix}
-1 & 1\\
1 & 1
\end{bmatrix} * \begin{bmatrix}
x\\
y
\end{bmatrix} = \begin{bmatrix}
1\\
3
\end{bmatrix}$$
When my brain sees this matrix form, it has the following geometric meaning: If we apply the linear transformation encoded by $\begin{bmatrix}
-1 & 1\\
1 & 1
\end{bmatrix}$ to vector $\begin{bmatrix}
x\\
y
\end{bmatrix}$, then the output vector is $\begin{bmatrix}
1\\
3
\end{bmatrix}$.
We can then use Gaussian Elimination to determine $\begin{bmatrix}
x\\
y
\end{bmatrix}$.
My question: Is the matrix form of the system of equations simply a useful trick to algorithmically solve these systems of equations use Elementary Row Operations, etc. Or is there a deeper geometric connection between the intersection of two lines and the linear transformation of the vector that describes said intersection.
Comment: Aren't matrices defined with the purpose of solving linear equations? They are just a rewriting of the problem. I wouldn't even call it a trick.
Comment: It is my impression that "matrices" (blocks of numbers or symbols) historically first represented "determinants", which had an existence prior to "linear algebra", or the linear algebra understanding of systems of linear equations. And it was only a bit later (later 19th centurey) that the notation and concept were seen to connect meaningfully to solution of linear equations. E.g., apparently finite-dimensional linear algebra came _after_ the discussion of compact operators on Hilbert spaces...
Comment: A few comments have said matrices were introduced in order to solve linear systems of equations.
I think Paul Garret has the correct history. Disregardingg history, in my mind matrices exist first and foremost in order to describe linear transformations.
Comment: Is that true? I thought matrices (in linear algebra) were defined as a notation for describing linear combinations of vectors.
Comment: No. Initially the matrices were invented for solving the systems of linear equations.
Comment: You should think of matrices as a linear map. If $A$ is a matrix and $v$ is a vector, there's a formula for the coordinates of $Av$. Try to see what comes out if $A$ is the 2 by 2 matrix you wrote down and $v = (x,y)^T$!
Comment: Though disregarding the formalities, it never stops *feeling* miraculous from time to time...
Comment: I think the geometry is that affine hyperplanes in a vector space naturally correspond to affine lines in its dual space. A single non-zero equation (up to scaling) describes the kernel of such an affine line in dual space, which is precisely the associated affine hyperplane. Putting multiple equations together corresponds to the intersection of these hyperplanes on one hand and to taking the product of the functionals on the other hand.
Comment: Highly recommend 3blue1brown's Essence of Linear Algebra, for some geometric intuition. https://youtube.com/playlist?list=PLZHQObOWTQDPD3MizzM2xVFitgF8hE_ab
Answer: You are right: matrices can be thought of as representing linear transformations. An $(m \times n)$-matrix takes as inputs vectors in an $n$-dimensional vector space and outputs vectors in an $m$-dimensional vector space. The crucial observation here is that in order to completely determine a linear transformation $T: V \to V'$, it suffices to know what it does on a certain chosen basis $\{e_1, \dots, e_n\}$ of $V$, since for any other $v \in V$, writing $v = \sum_{i=1}^n v_i e_i$ means that we have to get $T(v) = \sum_{i=1}^n v_i T(e_i)$. Still the $T(e_i)$ are vectors, but we would like to express these using numbers as well. So we chooose another basis $\{e_1', \dots, e_m'\}$ of $V'$, so that we can write any vector $v' \in V'$ as a linear combination of the $e_i'$. In particular, there are certain numbers $T_{ij}$ such that we have $T(e_i) = \sum_{j = 1}^m T_ij e_j'$. We conveniently put all these $n \cdot m$ numbers in a rectangular shape because it makes calculations easier, and tadá: we get our usual matrix notation.
Answer: Ok, I think I've got a potential explanation. The key is my realization that an equation can be thought of geometrically as a linear transformation of space.
Let's take our first equation: $$ -x + y = 1$$
This can be rewritten in "linear algebra" form:
$$\begin{bmatrix}
-1 & 1
\end{bmatrix} *\begin{bmatrix}
x  \\
y
\end{bmatrix} = 1$$
This form is saying that if we apply the
linear transformation encoded by $\begin{bmatrix}
-1 & 1
\end{bmatrix}$ to a 2D vector $\begin{bmatrix}
x\\
y
\end{bmatrix}$, then the 1D output "vector" is $\begin{bmatrix}
1
\end{bmatrix}$.
As it turns out, there are an infinite amount of 2D vectors that will satisfy the above expression. These vectors form the line described by our first equation.
Now when we add the second equation into our system, the question becomes: Is there a vector that satisfies BOTH linear transformations encoded by their respective equations? Indeed, the graphical intersection of these lines is that very vector.
Correct me if I'm wrong, but thinking of equations as linear transformations of space is a beautiful example of duality in mathematics.
Comment: You can also think of $Ax = b$ as expressing $b$ as a linear combination of the columns of $A$. There is a solution to $Ax = b$ if and only if $b$ is in the column space of $A$.


Using Locks and Condition to simulate print server

Question: I want to have print server that outputs the requested messages to the computer screen as follows: Client threads invoke the printRequestV1 method to submit the messages (strings) to be output. But all the printRequestV1 method should do is place the message in the print job queue, and a separate (manager) thread then dequeues messages from the job queue and outputs them to the screen
I know that I need to synchronize the shared request queue and check whether the queue is not empty before trying to remove a message. If the queue is empty, the manager thread needs to wait until client threads add some messages, and the client thread, after adding a message, will let the manager thread know by signaling.
Here what I have so far:
import java.util.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.Condition;
import static java.lang.System.out;

public class PrintServerV1 implements Runnable {

    private static final Queue<String> requests = new LinkedList<String>();
    private Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();

    public PrintServerV1() {
        try{

          while(requests.size() != 0){ condition.await();}
          new Thread(this).start();
        }
          catch (InterruptedException exception) {}
  }

    public void printRequest(String s) {
        lock.lock();
        try
        {
          out.println("Adding print request for: " +s);
          requests.add(s);
          condition.signalAll();
        }

        finally { lock.unlock(); }

    }

    public void sendRequest() throws InterruptedException
    {
      try {

        while(requests.size() != 0){ condition.await();}
        out.println("Sending Request to printer");
        for(;;) realPrint(requests.remove());

      } finally { lock.unlock(); }

    }

   private void realPrint(String s) {
      // do the real work of outputting the string to the screen
      out.println("Currently printing: " + s);
     }

   public void run(){
    try{
      sendRequest();
    } catch (InterruptedException exception) {}
  }

    public static void main(String[] args){
        PrintServerV1 server = new PrintServerV1();
    server.printRequest("homework7.txt");
    }
}

I am getting the following output:
    Adding print request for: homework7.txt
Sending Request to printer
Currently printing: homework7.txt
Exception in thread "Thread-0" java.lang.IllegalMonitorStateException
    at java.util.concurrent.locks.ReentrantLock$Sync.tryRelease(ReentrantLock.java:151)
    at java.util.concurrent.locks.AbstractQueuedSynchronizer.release(AbstractQueuedSynchronizer.java:1261)
    at java.util.concurrent.locks.ReentrantLock.unlock(ReentrantLock.java:457)
    at PrintServerV1.sendRequest(PrintServerV1.java:43)
    at PrintServerV1.run(PrintServerV1.java:54)
    at java.lang.Thread.run(Thread.java:748)

My question is wouldn't it better if make two classes, one named manager who implements runnable and whose sole purpose is to remove from the queue and one class named client who implements runnable and whose purpose is to add requests to the queue?
Comment: Your question is a bit of a non-sequitur from the exception message. Are you trying to fix the error you have in your code (on topic), or get an opinion on  your design (off topic)?
Answer:
You can only unlock after you aquire the lock by lock, otherwise IllegalMonitorStateException will be thrown. You should also call await method after you aquiring the lock.
It is a bad idea to await in the construtor, it will cause the creation of instance get blocked;
Remove the elements only when the requests is not empty.

This code works fine on my machine:
import java.util.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.Condition;

import static java.lang.System.out;

public class PrintServerV1 implements Runnable {

    private static final Queue<String> requests = new LinkedList<String>();
    private Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();

    public void printRequest(String s) {
        lock.lock();
        try {
            out.println("Adding print request for: " + s);
            requests.add(s);
            condition.signalAll();
        } finally {
            lock.unlock();
        }
    }

    public void sendRequest() throws InterruptedException {
        lock.lock();
        try {
            while (requests.size() == 0) {
                condition.await();
            }
            out.println("Sending Request to printer");
            while (!requests.isEmpty()) {
                realPrint(requests.remove());
            }
        } finally {
            lock.unlock();
        }
    }

    private void realPrint(String s) {
        // do the real work of outputting the string to the screen
        out.println("Currently printing: " + s);
    }

    public void run() {
        try {
            sendRequest();
        } catch (InterruptedException exception) {
        }
    }

    public static void main(String[] args) {
        PrintServerV1 server = new PrintServerV1();
        new Thread(server).start();
        server.printRequest("homework7.txt");
    }
}

Output:
Adding print request for: homework7.txt
Sending Request to printer
Currently printing: homework7.txt

I suggest to use two threads, one producer and one consumer, as well as a BlockingQueue to solve this kind of problem. The synchronization will be handled by the blocking queue, so you can focus on you business logic.
import java.util.concurrent.LinkedBlockingQueue;

public class Main {

    public static void main(String[] args) {
        LinkedBlockingQueue<String> queue = new LinkedBlockingQueue<>();
        new Thread(new Producer(queue)).start();
        new Thread(new Consumer(queue)).start();
    }
}

class Consumer implements Runnable {

    private LinkedBlockingQueue<String> queue;

    public Consumer(LinkedBlockingQueue<String> queue) {
        this.queue = queue;
    }

    @Override
    public void run() {
        while (true) {
            String request;
            try {
                request = queue.take();
                System.out.println(request);
            } catch (Exception e) {

            }
        }
    }
}

class Producer implements Runnable {

    private LinkedBlockingQueue<String> queue;

    public Producer(LinkedBlockingQueue<String> queue) {
        this.queue = queue;
    }

    @Override
    public void run() {
        try {
            queue.put("homework7.txt");
        } catch (Exception e) {

        }
    }
}

Comment: I just did but now it only outputs this:
Adding print request for: homework7.txt and the program never ends


show positive and negative votes

Question: i'm trying to make a 'top voted' view of nodes and I want it to appear like this:
title of node; 655 positive, 120 negative votes, total 775.
how do i do the '655 positive, 120 negative votes' part?
Answer: The Vote Up/Down module, while it supports Views 2 integration, only allows for a Voting Up/Down widget. With no support in the module for retrieving the vote count, you'll need to do one of the following:

Wait for the maintainer to add a views handler that supports up & down votes data.
Create your own patch that adds support for that data.

Given the current state of the project (seeking maintainer, 7.x version not released), you're probably going to have to go with #2.

show positive and negative votes


AutoCompleteTextView com palavras acentuadas

Question: Estou com uma certa dificuldade para usar o AutoCompleteTextView com palavras acentuadas.
Por exemplo:
Estou buscando nomes de agências bancarias, ao digitar somente ita o banco Itaú é encontrando, conforme a imagem abaixo:

Porém, se eu digitar o último u da palavra Itaú sem o acento, o autocomplete já não o encontra mais, conforme imagem abaixo:

Existe alguma forma de ignorar essas acentuações e encontrar colocando ou não o texto com acentos?
Obs: Eu já estou fazendo com custom adapter, que implementa Filterable
Segue abaixo o código do custom adapter:
public class HRArrayAdapter<T> extends BaseAdapter implements Filterable {

        private List<T> mObjects;
        private final Object mLock = new Object();
        private int mResource;
        private int mFieldId = 0;

        private boolean mNotifyOnChange = true;

        private Context mContext;

        private ArrayList<T> mOriginalValues;
        private HRArrayFilter mFilter;

        private LayoutInflater mInflater;

        public HRArrayAdapter(Context context, int textViewResourceId) {
            init(context, textViewResourceId, 0, new ArrayList<T>());
        }

        public HRArrayAdapter(Context context, int resource, int textViewResourceId) {
            init(context, resource, textViewResourceId, new ArrayList<T>());
        }

        public HRArrayAdapter(Context context, int textViewResourceId, T[] objects) {
            init(context, textViewResourceId, 0, Arrays.asList(objects));
        }

        public HRArrayAdapter(Context context, int resource, int textViewResourceId, T[] objects) {
            init(context, resource, textViewResourceId, Arrays.asList(objects));
        }

        public HRArrayAdapter(Context context, int textViewResourceId, List<T> objects) {
            init(context, textViewResourceId, 0, objects);
        }

        public HRArrayAdapter(Context context, int resource, int textViewResourceId, List<T> objects) {
            init(context, resource, textViewResourceId, objects);
        }

        public void add(T object) {
            if (mOriginalValues != null) {
                synchronized (mLock) {
                    mOriginalValues.add(object);
                    if (mNotifyOnChange) notifyDataSetChanged();
                }
            } else {
                mObjects.add(object);
                if (mNotifyOnChange) notifyDataSetChanged();
            }
        }

        public void insert(T object, int index) {
            if (mOriginalValues != null) {
                synchronized (mLock) {
                    mOriginalValues.add(index, object);
                    if (mNotifyOnChange) notifyDataSetChanged();
                }
            } else {
                mObjects.add(index, object);
                if (mNotifyOnChange) notifyDataSetChanged();
            }
        }

        public void remove(T object) {
            if (mOriginalValues != null) {
                synchronized (mLock) {
                    mOriginalValues.remove(object);
                }
            } else {
                mObjects.remove(object);
            }
            if (mNotifyOnChange) notifyDataSetChanged();
        }

        public void clear() {
            if (mOriginalValues != null) {
                synchronized (mLock) {
                    mOriginalValues.clear();
                }
            } else {
                mObjects.clear();
            }
            if (mNotifyOnChange) notifyDataSetChanged();
        }

        public void sort(Comparator<? super T> comparator) {
            Collections.sort(mObjects, comparator);
            if (mNotifyOnChange) notifyDataSetChanged();
        }

        @Override
        public void notifyDataSetChanged() {
            super.notifyDataSetChanged();
            mNotifyOnChange = true;
        }

        public void setNotifyOnChange(boolean notifyOnChange) {
            mNotifyOnChange = notifyOnChange;
        }

        private void init(Context context, int resource, int textViewResourceId, List<T> objects) {
            mContext = context;
            mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            mResource = mDropDownResource = resource;
            mObjects = objects;
            mFieldId = textViewResourceId;
        }

        public Context getContext() {
            return mContext;
        }

        public int getCount() {
            return mObjects.size();
        }

        public T getItem(int position) {
            return mObjects.get(position);
        }

        public int getPosition(T item) {
            return mObjects.indexOf(item);
        }

        public long getItemId(int position) {
            return position;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            return createViewFromResource(position, convertView, parent, mResource);
        }

        private View createViewFromResource(int position, View convertView, ViewGroup parent,
                                            int resource) {
            View view;
            TextView text;

            if (convertView == null) {
                view = mInflater.inflate(resource, parent, false);
            } else {
                view = convertView;
            }

            try {
                if (mFieldId == 0) {
                    //  If no custom field is assigned, assume the whole resource is a TextView
                    text = (TextView) view;
                } else {
                    //  Otherwise, find the TextView field within the layout
                    text = (TextView) view.findViewById(mFieldId);
                }
            } catch (ClassCastException e) {
                Log.e("ArrayAdapter", "You must supply a resource ID for a TextView");
                throw new IllegalStateException(
                        "ArrayAdapter requires the resource ID to be a TextView", e);
            }

            text.setText(getItem(position).toString());

            return view;
        }

        public void setDropDownViewResource(int resource) {
            this.mDropDownResource = resource;
        }

        @Override
        public View getDropDownView(int position, View convertView, ViewGroup parent) {
            return createViewFromResource(position, convertView, parent, mDropDownResource);
        }

        public static HRArrayAdapter<CharSequence> createFromResource(Context context,
                                                                                int textArrayResId, int textViewResId) {
            CharSequence[] strings = context.getResources().getTextArray(textArrayResId);
            return new HRArrayAdapter<CharSequence>(context, textViewResId, strings);
        }

        public HRArrayFilter getFilter() {
            if (mFilter == null) {
                mFilter = new HRArrayFilter();
            }
            return mFilter;
        }

        private class HRArrayFilter extends Filter {
            @Override
            protected FilterResults performFiltering(CharSequence prefix) {
                FilterResults results = new FilterResults();

                if (mOriginalValues == null) {
                    synchronized (mLock) {
                        mOriginalValues = new ArrayList<T>(mObjects);
                    }
                }

                if (prefix == null || prefix.length() == 0) {
                    synchronized (mLock) {
                        ArrayList<T> list = new ArrayList<T>(mOriginalValues);
                        results.values = list;
                        results.count = list.size();
                    }
                } else {
                    String prefixString = prefix.toString().toLowerCase();

                    ArrayList<T> values = mOriginalValues;
                    final int count = values.size();

                    final ArrayList<T> newValues = new ArrayList<T>(count);
                    final ArrayList<String> strippedAccents = new ArrayList<String>();

                    for (int i = 0; i < count; i++) {
                        final T value = values.get(i);
                        final String valueText = value.toString().toLowerCase();
                        String valueTextNoPalatals = stripAccents(valueText);
                        String prefixStringNoPalatals = stripAccents(prefixString);

                        // First match against the whole, non-splitted value
                        if (valueText.startsWith(prefixString) || valueTextNoPalatals.startsWith(prefixStringNoPalatals)) {
                            newValues.add(value);
                        } else {
                            final String[] words = valueText.split(" ");
                            final int wordCount = words.length;

                            for (int k = 0; k < wordCount; k++) {
                                if (words[k].startsWith(prefixString)) {
                                    newValues.add(value);
                                    break;
                                }
                            }
                        }
                    }

                    results.values = newValues;
                    results.count = newValues.size();
                }

                return results;
            }

            @Override
            protected void publishResults(CharSequence constraint, FilterResults results) {
                //noinspection unchecked
                mObjects = (List<T>) results.values;
                if (results.count > 0) {
                    notifyDataSetChanged();
                } else {
                    notifyDataSetInvalidated();
                }
            }
        }

        private static Map<Character, Character> MAP_NORM;
        private static String stripAccents(String value) {

            if (MAP_NORM == null || MAP_NORM.size() == 0)
            {
                MAP_NORM = new HashMap<Character, Character>();
                MAP_NORM.put('À', 'A');
                MAP_NORM.put('Á', 'A');
                MAP_NORM.put('Â', 'A');
                MAP_NORM.put('Ã', 'A');
                MAP_NORM.put('Ä', 'A');
                MAP_NORM.put('È', 'E');
                MAP_NORM.put('É', 'E');
                MAP_NORM.put('Ê', 'E');
                MAP_NORM.put('Ë', 'E');
                MAP_NORM.put('Í', 'I');
                MAP_NORM.put('Ì', 'I');
                MAP_NORM.put('Î', 'I');
                MAP_NORM.put('Ï', 'I');
                MAP_NORM.put('Ù', 'U');
                MAP_NORM.put('Ú', 'U');
                MAP_NORM.put('Û', 'U');
                MAP_NORM.put('Ü', 'U');
                MAP_NORM.put('Ò', 'O');
                MAP_NORM.put('Ó', 'O');
                MAP_NORM.put('Ô', 'O');
                MAP_NORM.put('Õ', 'O');
                MAP_NORM.put('Ö', 'O');
                MAP_NORM.put('Ñ', 'N');
                MAP_NORM.put('Ç', 'C');
                MAP_NORM.put('ª', 'A');
                MAP_NORM.put('º', 'O');
                MAP_NORM.put('§', 'S');
                MAP_NORM.put('³', '3');
                MAP_NORM.put('²', '2');
                MAP_NORM.put('¹', '1');
                MAP_NORM.put('à', 'a');
                MAP_NORM.put('á', 'a');
                MAP_NORM.put('â', 'a');
                MAP_NORM.put('ã', 'a');
                MAP_NORM.put('ä', 'a');
                MAP_NORM.put('è', 'e');
                MAP_NORM.put('é', 'e');
                MAP_NORM.put('ê', 'e');
                MAP_NORM.put('ë', 'e');
                MAP_NORM.put('í', 'i');
                MAP_NORM.put('ì', 'i');
                MAP_NORM.put('î', 'i');
                MAP_NORM.put('ï', 'i');
                MAP_NORM.put('ù', 'u');
                MAP_NORM.put('ú', 'u');
                MAP_NORM.put('û', 'u');
                MAP_NORM.put('ü', 'u');
                MAP_NORM.put('ò', 'o');
                MAP_NORM.put('ó', 'o');
                MAP_NORM.put('ô', 'o');
                MAP_NORM.put('õ', 'o');
                MAP_NORM.put('ö', 'o');
                MAP_NORM.put('ñ', 'n');
                MAP_NORM.put('ç', 'c');
            }

            if (value == null) {
                return "";
            }

            StringBuilder sb = new StringBuilder(value);

            for(int i = 0; i < value.length(); i++) {
                Character c = MAP_NORM.get(sb.charAt(i));
                if(c != null) {
                    sb.setCharAt(i, c.charValue());
                }
            }

            return sb.toString();

        }

    }

Comment: Veja se ajuda: [Is there a way to get rid of accents and convert a whole string to regular letters?](http://stackoverflow.com/q/3322152/1964435)
Comment: Valeu Math! Desculpa pela demora na resposta, mas me ajudou sim! Era só usar o *java.text.Normalizer*
Answer: Antes de fazer a comparação você pode retirar os acentos da String do seu AutoCompleteTextView no método performFiltering(), usando por exemplo o Normalizer:
System.out.println(Normalizer
                    .normalize("Itaú", Normalizer.Form.NFD)
                    .replaceAll("[^\\p{ASCII}]", "")
                   );

Resultado:

Itau

Veja funcionando no Ideone.
Fonte: Is there a way to get rid of accents and convert a whole string to regular letters?


What happens if the batsman hits the gloves of the keeper just prior to playing a shot which resulted in the shot being impeded?

Question: What happens if the batsman hits the gloves of the keeper just prior to playing a shot which resulted in the shot being impeded? Should it be a dead ball or should any result - either a dismissal, do ball or runs stand?
Note - the intentions of the wicket keeper (it was not deliberate) or the gloves being in front of the wicket (they were not) are not of concern.
Answer: I have taken a long hard look at the laws and can see nothing here about this specifically.
However if the gloves aren't in-front of the stumps and the wicket keeper didn't deliberately obstruct the batsman I would play on.
If there isn't a decision to be made then status quo persists and play on and the ball stands as played.