Regex for searching URLS with excluding some words

Question: I'm trying to search and replace all URLs in the text. However, I have some words that I need to exclude from the search. For example (?!word)(?:https?:\/\/)?(?:[a-zA-Z0-9.]+)\.(?:[a-zA-Z]{2,3}). This regex found all urls but not exclude urls which contain word. Please help me finish this regex.
I'm tried:
const text = `This is a sample text with links: www.example.com, https://www.hello.com, http://www.google.com, https://word.com, http://word.com
www.word.com https://www.site.frs www.word.com asasd.cds qdwdew.www asd.cdd
sdsd https://www.word.com
https://www.word.frs some text hello word https www.example.wfd asdasd wwwsds.dsad.word.com
`;

const regex = /(?!word)(?:https?:\/\/)?(?:[a-zA-Z0-9.]+)\.(?:[a-zA-Z]{2,3})/gm;

const matches = text.replace(regex, '[xxx]');;

console.log(matches);

I got this result:
This is a sample text with links: [xxx], [xxx], [xxx], [xxx], [xxx]
[xxx] [xxx] [xxx] [xxx] [xxx] [xxx]
sdsd [xxx]
[xxx] some text hello word https [xxx] asdasd [xxx]

I want to get this result:
This is a sample text with links: [xxx], https://www.hello.com, [xxx], https://word.com, http://word.com
www.word.com [xxx] www.word.com [xxx] [xxx] [xxx]
sdsd https://www.word.com
https://www.word.frs some text hello word https [xxx] asdasd wwwsds.dsad.word.com

Answer: You could pass a callback function to String#replace instead, which checks if the match contains the given word to decide whether or not to replace.

const text = `This is a sample text with links: www.example.com, https://www.hello.com, http://www.google.com, https://word.com, http://word.com
www.word.com https://www.site.frs www.word.com asasd.cds qdwdew.www asd.cdd
sdsd https://www.word.com
https://www.word.frs some text hello word https www.example.wfd asdasd wwwsds.dsad.word.com
`;

const regex = /(?:https?:\/\/)?(?:[a-zA-Z0-9.]+)\.(?:[a-zA-Z]{2,3})/gm;

const matches = text.replace(regex, m => m.includes('word') ? m : '[xxx]');
console.log(matches);
Answer: Arguably, the best way to do this is to specify a callback as replacement:
const masked = text.replace(regex, $0 => $0.includes('word') ? $0 : '[xxx]');

...or, if you want to avoid false positives like sword:
const masked = text.replace(regex, $0 => /\bword\b/.test($0) ? $0 : '[xxx]');

Try it:

console.config({ maximize: true });

const text = `This is a sample text with links: www.example.com, https://www.hello.com, http://www.google.com, https://word.com, http://word.com
www.word.com https://www.site.frs www.word.com asasd.cds qdwdew.www asd.cdd
sdsd https://www.word.com
https://www.word.frs some text hello word https www.example.wfd asdasd wwwsds.dsad.word.com
https://this.is.a.sword.com
`;

const regex = /(?:https?:\/\/)?(?:[a-zA-Z0-9.]+)\.(?:[a-zA-Z]{2,3})/g;

const masked1 = text.replace(regex, $0 => $0.includes('word') ? $0 : '[xxx]');
const masked2 = text.replace(regex, $0 => /\bword\b/.test($0) ? $0 : '[xxx]');

console.log(masked1);
console.log(masked2);

Alternatively, here's a pure regex solution:
(?!\S*\bword\b)\b(?:https?:\/\/)?(?:[a-zA-Z0-9.]+)\.(?:[a-zA-Z]{2,3})

...in which (?!\S*\bword\b) ensures that the URL we are about to (try to) match will not contains word. \b is needed so as not to match half the URL.
Try it on regex101.com.
Try it:

console.config({ maximize: true });

const text = `This is a sample text with links: www.example.com, https://www.hello.com, http://www.google.com, https://word.com, http://word.com
www.word.com https://www.site.frs www.word.com asasd.cds qdwdew.www asd.cdd
sdsd https://www.word.com
https://www.word.frs some text hello word https www.example.wfd asdasd wwwsds.dsad.word.com
https://this.is.a.sword.com
`;

const regex = /(?!\S*\bword\b)\b(?:https?:\/\/)?(?:[a-zA-Z0-9.]+)\.(?:[a-zA-Z]{2,3})/g;

const masked = text.replace(regex, '[xxx]');

console.log(masked);


Is g with $\cosh(xg(x))=x\cosh(g(x))$ decreasing?

Question: Let $g:\mathbb{R}_{>0} \to \mathbb{R}_{>0}$ be defined implicitly by $\cosh(xg(x))=x\cosh(g(x))$ and $g(1)\sinh(g(1))=\cosh(g(1))$. How to show that $g$ is differentiable? Furthermore, is it true that $g$ is monotone decreasing?
Assuming that $g$ is differentiable, I showed that $g'\mid_{]0,1[}<0$ is equivalent to $g\mid_{]1,\infty[}<g(1)$ but I wasn't able to show much more.
Answer: Here, in a complementary approach to "classical tools" of analysis as @eldering has used, I propose a geometrical view of the defining relationship of $g$, which will provide us a graphically intuitive proof of the fact that $g$ is a decreasing function.
Let us begin by the observation that for any $x,y >0$ :
$$\cosh(xy) = x \cosh(y) \ \ \Leftrightarrow \ \ \dfrac{x}{cosh(x)}=\dfrac{xy}{cosh(xy)} \ \ \ (1)$$
Thus, if we set $\varphi(t):=\dfrac{t}{cosh(t)}$, (1) can be written
$$\varphi(x)=\varphi(xy) \ \ \ (2)$$
By observation of the curve of $\varphi$ (strictly increasing from the origin to a certain maximum $M(1.1997,0.6627)$, and then decreasing asymptoticaly to $0$ when $x \rightarrow \infty$, we see that, for a given $x$, i.e., for a given level $\varphi(x)$, there exist a unique point at the same level ; property (2) forces its abscissa to be $xy$, defining value $y$ attached to $x$. Thus $g$ is well defined for all $x \in (0,+\infty)$.
Therefore, if we take  2 values of $x$ such that $0<x_1<x_2$,  the corresponding values are ranked in the order $x_1y_1>x_2y_2$ (see graphics).
Rewriting these inequalities under the form $\dfrac{x_2}{x_1} > 1 \ \ $ and  $\dfrac{x_1y_1}{x_2y_2}>1$, and multiplying their LHS, we obtain $\dfrac{y_1}{y_2}>1$.
Thus: $0<x_1<x_2 \Rightarrow  y_1>y_2>0.$
proving that $g:x \rightarrow y$ is a decreasing function.
The curve of $\varphi(t):=\dfrac{t}{cosh(t)}$ allowing to define function $g$ :
Comment: I think it should be $\frac{y}{\cosh(y)}=\frac{xy}{\cosh(xy)}$
Comment: I thank you for the wonderful answer, but I would really like to see an analytic, not only intuitive proof, so I won't accept your answer. But +1 :)
Answer: Consider the function $f(x,y) = \cosh(xy) - x \cosh(y)$. Then $g$ is the implicit function defined by $f(x,g(x)) = 0$. Now you have to show that $D_2 f(x,g(x)) \neq 0$ to apply the implicit function theorem, and you can locally conclude that $g$ is differentiable and using the formula $g'(x) = [D_2 f(x,g(x))]^{-1} D_1 f(x,g(x))$ you can check if $g'(x) < 0$.
I've not done all calculations, so this is only a rough hint.
Comment: Yes, thats what I tried, but even to show that $\lim_{x\to 1}g(x)=g(1)$ wasn't feasible for me.
Answer: Here's an answer, if we suppose continuity of $g$ in $1$. Also, I assume that you have already checked that $g$ is well-defined, i.e.: for every $x\neq 1$ there's unique $g(x)$ fulfilling the equality. If not, consider functions
$$
\cosh ay - a\cosh y, \quad y>0
$$
with parameter $a\neq 1$ and examine its derivative and limits in $0$ and $\infty$; this is pretty straightforward. You might need to include it in your solution, depending on the formulation of the original problem.
Back to the point. By the implicit function theorem, $g$ is $C^\infty$ for $x\neq 1$. The derivative is (I often write $g$ instead of $g(x)$ for brevity)
$$
g'(x) = \frac {\cosh g - g\sinh xg} {x(\sinh xg - \sinh g)}
      = \frac {\sinh xg}{x^2} \cdot \frac{\coth xg - xg} {\sinh xg - \sinh g}
$$
The first fraction is always positive. For the second:

$\sinh xg - \sinh g >0$ for $x>1$,

$"<0"$ for $x<1$,

$\coth xg - xg > 0$ for $x$ such that $xg < g(1)$,

and respectively for $"<"$, $"="$, because $g(1)$ is the solution to $\coth y = y$ and $\coth y - y$ is decreasing.

Consider $x>1$. Then $g'(x)<0$ if $xg(x)>1$ and vice versa. We prove that $g'(x)<0$ for $x>1$ in two steps.

If $g'(x_0)<0$, then $g'(x)<0$ for $x>x_0$.

Let's take the longest interval possible with $g'<0$:
$$
z:= \sup \{y: g'(x)< 0 \text{ for } x\in [x_0, y)\}
$$
If $z=\infty$, then we're done here. Suppose not: then $g'(z)=0$, because $g'$ is continuous. Therefore

$xg(x)>g(1)$, for $x\in [x_0, z)$,
$zg(z)=g(1)$,

so the function $xg(x)$ is decreasing at least just before $z$. But let's calculate the derivative:
$$
(xg(x))'\mid_{x=z} = (g(x) + xg'(x))\mid_{x=z} = g(z) + 0 = g(z)>0,
$$
and we arrive at a contradiction.
This could be reasoned more neatly using the mean value theorem: $(xg(x))'\mid_{x=z} > 0$, so $(xg(x))' >0$ on some $(z',z)$ with $z'>x_0$, which contradicts the theorem for $xg(x)$ on $(z',z)$.
Edit: It follows that $g$ on $(1, \infty)$ is either decreasing or increasing up to some point and then decreasing. This means that $g$ has right-sided limit in $1$, but possibly infinite. Similarly for $(0,1)$. If you use remark 3. below, it turns out that to show continuity, it suffices for $g$ and $g'$ to be bounded around $1$.

If $g'(x_0)>0$, then $g'(x)<0$ for some $x\in(1,x_0)$.

Then $x_0 g(x_0) <g(1)$, so $g(x_0) < g(1)/x_0 < g(1)$. By the mean value theorem, there is $x\in(1,x_0)$, for which $g'(x) = (g(x_0) - g(1))/(x_0-1) < 0$. (This is where I use continuity.)
So if there was $g'(x_0)>0$, then $g'(x)<0$ for some $x\in(1,x_0)$, but then by (1.) $g'(x_0)<0$.
Similarly, it can be shown that for $x_0\in (0,1)$:

If $g'(x_0)<0$, then $g'(x)<0$ for $x<x_0$.
If $g'(x_0)>0$, then $g'(x)<0$ for some $x\in(x_0,1)$.

The proof is finished.
As for the continuity:

For what it's worth, Wolfram|Alpha shows that it is continuous:
solution of $\cosh(xy) = x \cosh y$ in $(0,2)$, solution around $(1,g(1))$ (some artifacts arise in these pictures, but I don't think we should be worried).
Maybe start with showing that $g$ is bounded around $1$ and then that any sequence $g(x_n)$ for $x_n\to 1$ has subsequence convergent to $g(1)$; then this must be the limit.
Try to examine the function $g(1+x)$ for $x=0$, i.e. start with the equality $\cosh ((1+x)g(1+x)) = (1+x)\cosh(g(1+x))$. Using formula for $\cosh(x+y)$, I transformed it into:  $\coth(g(1+x)) = \frac {-\sinh(xg(1+x))}{\cosh(xg(1+x)) - 1 - x}$.  Then, using L'Hôpital's rule, I got that if $l = \lim_{x\to 0} g(1+x)$ exists and $g'(1+x)$ is bounded around $0$, then it satisfies $\coth(l)= l$.
What put me on the right track was approximating $\cosh y$ with $e^y$ for large $y$. This doesn't work well around $1$, but maybe some finer approximation? Here's what I got:
Since $\frac 1 2 e^y < \cosh y < e^y$, for $x>1$:
\begin{gather}
\frac 1 2 e^{xg} < xe^g\\
xg < \log 2 + \log x + g\\
g < \frac {\log 2x}{x-1}. \end{gather}
On the other hand:
\begin{gather}
e^{xg} > \frac 1 2 xe^g\\
xg > \log x - \log 2 + g\\
g > \frac {\log x/2}{x-1}.
\end{gather}
Unfortunately, for $x\to 1$ this yields $\lim g(x) \in (-\infty, +\infty)$.
Comment: I have added another remark, thanks to which it suffices now to show that $g$ and $g'$ are bounded around $1$.
Answer: This is a global problem, insofar as we also have to establish the existence of the function
$$y=g(x)\qquad(x>0)\tag{1}$$
solving the given equation
$$f(x,y):=\cosh (xy)-x\cosh y=0\qquad(x>0, \ y>0)\ .\tag{2}$$
Note that the equation $(2)$ is solved not only by some "interesting" function $(1)$, but also by all points on the half-line $y\mapsto(1,y)$ $(y>0)$. As a consequence $g(1)$ is only obtained via some exception handling.
Consider the family of (half-)catenaries
$$\gamma_x:\quad u={1\over x}\cosh (x\,y)\qquad(x>0)$$
in the first quadrant of an auxiliary $(y,u)$-plane. These $\gamma_x$ are all similar and lying similarly with respect to the origin. They are all tangent to a certain line $u=my$, which is at the same time the envelope of the family. The following figure shows three of these catenaries, whereby to a larger $x$ corresponds a narrower catenary.

Inspection of the figure shows that any  two different catenaries $\gamma_a$, $\gamma_b$ intersect transversally in exactly one point, which is obtained by solving
$${1\over a}\cosh(ay)={1\over b}\cosh(by)\tag{3}$$
for $y$. In addition the implicit function theorem, applied to $(3)$, guarantees that for $a_0\ne b_0$  the obtained $y$ is a differentiable function of $(a,b)$ in the neighborhood of $(a_0,b_0)$.
Now the given equation $(2)$ means that we should intersect the catenary $\gamma_x$ with the "reference catenary" $\gamma_1$. Solving $(3)$ with $(a,b):=(x_0,1)$ gives a unique $y_0=:g(x_0)$; furthermore the function $x\mapsto g(x)$ thus constructed is undefined at $x=1$, and is differentiable in ${\mathbb R}_{>0}\setminus\{1\}$. But there is more in the above figure! Assume that the red catenary is $\gamma_1$, and that $1<x_1<x_2$. Then the blue catenary is $\gamma_{x_1}$, and the green catenary is $\gamma_{x_2}$. From the figure it is then obvious that $g(x_2)<g(x_1)$. Similarly: If we let the green catenary be $\gamma_1$ and assume that $1>x_1>x_2$ then we can see that $g(x_1)<g(x_2)$. This shows that $g$ is monotonically decreasing both on $\>]0,1[\>$ and on $\ ]1,\infty[\>$.
It remains to consider the value $x=1$. Interpreting the figure dynamically we see that when $x\to1$  the point $\gamma_x\wedge\gamma_1$ converges to the point where $\gamma_1$ touches the envelope $u=my$. Doing the calculations one should find the value $g(1)$ defined in the question.


Replaced outlet, no power to that circuit

Question: I am not electrician. I am a DIYer and have some experience with replacing breakers, doing basic electrical work, but nothing really "advanced".
An outlet was recently cracked, and my roommate went to replace it while I wasn't home. I am told he didn't turn off the breaker, but when I came home nothing on that circuit was working. I had assumed the breaker was broken from not turning it off, so I replaced it with a new one. Still not working. I checked to make sure the new outlet was wired correctly, and it was.
It's the second outlet in the circuit, I think. It is second closest to the breaker box, so I assume it is second in the circuit.
Anyway, does anyone think I should get an electrician, or can I at least rule out some other causes, or fix this myself?
Comment: Did you check for power at the breaker before replacing it? If not, Why not? Thats an odd thing to go for first without some verification that it's bad. Did you check for power at the breaker after replacing it? If not, go do that.
Answer: If you are correct that nothing on that circuit is working (including an outlet closer to the circuit breaker panel) then something would appear to be wrong at the panel.
I wonder if perhaps you got the wrong breaker and the actual breaker for this circuit is sitting in the tripped position? Sometimes it can be useful to flip each breaker on and off one at a time (of course that can play havoc with whatever else is on those circuits, such as computers wot don't have a UPS).
If it was only that outlet and ones further down I would suspect that the incoming wires are not correctly connected or the outlets have been separated by breaking off the tabs between the two receptacles.
Comment: Computers are connected to the first outlet, and neither work. Neither does anything else plugged into that outlet, or any other that runs off of that breaker.

The breaker I purchased and replaced the old one with is an OEM replacement. I am sure I replaced it correctly. I am no novice at replacing breakers.

Is it possible that a break was caused in the first outlet (and subsequently making the others not work) when replacing the second one?
Comment: Yes, it's possible. You can look there and anywhere the circuit goes before the outlet box. The wire should be anchored so that isn't possible. I once diagnosed a break in a junction box that was caused by a nicked wire that finally broke. If you don't find anything at known junctions then it may be time to call a pro- a break in a straight length of wire is extremely unlikely unless the wire inside the wall was damaged. I guess I'm also a bit surprised you would replace a breaker without testing that it was necessary. You can also test to see if the hot is present at the outlet.


Binding a Function to jPlayer's "next" Control

Question: jPlayer's jPlayerPlaylist addon documentation is not very complete so I'm hoping someone on here has a solution for this problem. I need a function to fire whenever the next command is triggered.
For example, this code should cause a binded function to fire:
playlist.next();

Where "playlist" is an object containing jPlayer.
Here is what I have so far:
playlist.bind($.jPlayer.event.next, function() { alert("next"); });

Answer: You could just bind a listener on the button using a jQuery selector. You won't be able to stop the next track from starting though.
One more tip: the start event is fired when using the next button. You just need to detect the difference with the first start and a stop/start.
Comment: Thanks, but the next command is triggered in many more situations than just when you click the next button, such as when a song ends and the next is loaded.


failing to autofill fields with backing bean setter after failed submit/validation

Question: I want to automatically fill a form when a checkbox within it is activated using ajax (e.g. "Use billing address as delivery address?") and the backing bean's setter.
Therefore, the backing bean's setter for that checkbox' value sets the other fields and ajax has the whole form rerenderd. This works as long as no validators come into play. Now, I've had to to add a validator to some of the fields. When submitting the form in an invalid (empty in this case) state, the corresponding validation fails. If after that, the checkbox to autofill the form is checked and ajax submits the form again, only the validated form fields will be filled in when the form is rerenderd. All other fields remain empty, although the backing bean should have them set.
Why does JSF only render the backing bean values of the validated fields, after the validation failed once, but not the values of the other fields? Which logic in the JSF lifecycle is responsible for this behaviour?
Here's a small example:
@ManagedBean
public class TestBean
{
    private boolean toggle;
    private String stringValue1;
    private String stringValue2;

    public boolean isToggle() {
        return toggle;
    }
    public void setToggle(boolean toggle) {
        this.toggle = toggle;
        if(this.toggle) {
            this.stringValue1 = "Value1";
            this.stringValue2 = "Value2";
        }
    }

    // ... the usual getters and setters
}

And the corresponding jsf form:
<h:form id="testForm">
    <h:messages />

        <h:inputText value="#{testBean.stringValue1}">
            <f:validateRequired />
        </h:inputText>

        <h:inputText value="#{testBean.stringValue2}" />

        <h:selectBooleanCheckbox id="toggleBox" value="#{testBean.toggle}">
            <f:ajax render="testForm" />
        </h:selectBooleanCheckbox>

    <h:commandButton type="submit" value="Submit">
        <f:ajax execute="@form" render="testForm" />
    </h:commandButton>
</h:form>

first, the form is submitted without values
then the checkbox is checked
Thanks in advance for any help!
Comment: Leave getters and setters alone, use listeners.
Comment: Sorry for being obtuse here... -_-

But I suspect you mean the action- and/or valueChangeListener described [here](http://docs.oracle.com/javaee/6/tutorial/doc/bnatn.html#bnats)?

I've added a valueChangeListener attribute to the checkbox and a method in the backing bean, which sets both of the other fields. The effect is still the same.
Comment: Check one of these for being a duplicate: https://www.google.com/search?q=fields+not+reset+after+validation+failed
Answer: I don't know why this behavior occurs but adding components that are not refreshed properly (without validation) to execute looks like workaround.
<h:form id="testForm">
<h:messages />

    <h:inputText value="#{testBean.stringValue1}">
        <f:validateRequired />
    </h:inputText>

    <h:inputText id="stringValue2" value="#{testBean.stringValue2}" />

    <h:selectBooleanCheckbox id="toggleBox" value="#{testBean.toggle}">
        <f:ajax render="testForm" execute="@this stringValue2" />
    </h:selectBooleanCheckbox>

    <h:commandButton type="submit" value="Submit">
        <f:ajax execute="@form" render="testForm" />
    </h:commandButton>
</h:form>

Also I suggest doing normal setter for toggle, listener for event and action in h:commandButton like this
<h:form id="testForm">
<h:messages />

    <h:inputText value="#{testBean.stringValue1}">
        <f:validateRequired />
    </h:inputText>

    <h:inputText id="stringValue2" value="#{testBean.stringValue2}" />

    <h:selectBooleanCheckbox id="toggleBox" value="#{testBean.toggle}">
        <f:ajax render="testForm" execute="@this stringValue2" listener="#{testBean.setValues}" />
    </h:selectBooleanCheckbox>

    <h:commandButton action="#{testBean.formLogic}" value="Submit">
        <f:ajax render="testForm" />
    </h:commandButton>
</h:form>

Comment: Lots of similar questions with explanation about possible causes: https://www.google.com/search?q=fields+not+reset+after+validation+failed
Answer: Sorry for breaking the etiquette here and essentially posting a question as answer, but the comments allow for too few characters for formulating the situation and my question after having a look at the google results you pointed me to.
BalusC wrote an article which is closest to explaining the jsf logic causing this effect: http://balusc.omnifaces.org/2012/03/reset-non-processed-input-components-on.html
But there is still a detail, that I don't understand in the context of my example, when I consider the following points:

The input components keep a submitted and a local value.
As described in the link above - values in validated fields either stay as "submitted value" if invalid, or are set as "local value" of their component with the submitted value being set to "null".
When rendering, jsf checks first the submitted value and then the local value for "null" and displays the first which is not null. Only if both are null the model value is rendered.

In my example, when I "execute" the whole empty form with the commandButton, the validation for the required field fails. Its value stays as "submitted value", in this case apparently null. There is no validation for the other empty field. Does it still distinguish between a local value and a submitted value? Does it set its local value to "empty" or "null"? Due to the validation failure the model is not updated and the form is being rendered with an error for the required but empty field.
Then another input is set, committed via ajax, misuses its setter method for setting the model values of the other inputs and renders the whole form again. During that rendering, the the previously invalid empty field seems to have both the submitted and local value set to "null", as the model's new value is being rendered instead of an empty field. The previously empty but not required field however, is being rendered as empty, although its value was just as empty or "null" as the validated field's one. If it had the submitted and local value set to "null", I would expect it to also display the model's value after the rendering.
Does the local value of the empty field actually distinguish between a previously submitted "empty" input and "null" when validation allows for an empty field or is absent? So during rendering, the empty local value is displayed again rather than the model value?


How to use Struts 2 with Velocity and Tiles

Question: Has anyone been able to get velocity and tiles working with struts 2?
I am having some problem finding examples or tutorials online and from what I have gathered from mailing lists it seems it might not even be possible at all (but the mails were quite old).
Answer: https://struts.apache.org/docs/tiles-plugin.html
You can start with the documentation from apache struts. I am using tiles and velocity both and they are working fine. I am using velocity for the emailing templates and tiles for the front-end templates.
You can also refer to various examples on Dzone, TutorialsPoint as well as Mykong. They have provided good examples.


Conditional expected value meaning problem

Question: I have two random variables X,Y with the same following distributions :
$$P(X=0)=P(Y=0)=1-p, P(X=1)=P(Y=1)=p$$
I want to calculate $E(X|1_{\{X+Y=0\}})$.
So Let's define random variable $Z=1_{\{X+Y=0\}}$. Then
$P(Z=1)=(1-p)^2$ and $P(Z=0)=1-(1-p)^2$
$E(X|1_{\{X+Y=0\}})=E(X|Z)=\frac{1}{P(Z)} \cdot \int_{Z}X \;dP$.
So now i have a little trouble. What exactly is $P(Z)$ ? I think that i cant even calculate that. This problem is like : Let $X \sim U[0,1]$ find $P(X)$ which is making no sense.
Answer: You have not stated enough information to solve the problem. In particular, you have only specified the marginal distributions of $X$ and $Y$, but not their joint distribution.   Two cases satisfying your description are when $X$ and $Y$ are independent, and when $X=Y$ with probability $1$.  They give rise to different answers.


How can i read and write values from a map in firestore from react?

Question: I have a database field which has a map like this in firestore:
cordinates:{_01:"copper",_02:"gold",_03:"iron"}
i see this database in firestore admin panel like this:
pic
when i try to list items with the code below
data.cordinates.map((item, i)=>
                  console.log(i+" - "+item)
                );

i receive:
Unhandled Rejection (TypeError): data.cordinates.map is not a function

what is the correct way to read/write this kind of map?
btw console.log(data.cordinates) give me output like this:
{_01: "copper", _02: "gold", _03: "iron", _04: "", _05: "", …}
_01: "copper"
_02: "gold"
_03: "iron"
_04: ""
_05: ""
_06: ""
_07: ""
_08: ""
_10: ""
_11: ""
_12: ""
_13: ""
_14: ""
_15: ""
_16: ""
_17: ""
_18: ""
_20: ""
_21: ""
_22: ""
_23: ""
_24: ""
_25: ""
_26: ""
_27: ""
_28: ""
_30: ""
_31: ""
_32: ""
_33: ""
_34: ""
_35: ""
_36: ""
_37: ""
_38: ""
_40: ""
_41: ""
_42: ""
_43: ""
_44: ""
_45: ""
_46: ""
_47: ""
_48: ""

yes there are 48 elements in total
Any help is aprreciated, thanks in advance.
Comment: I'm unclear.  What exactly is `data.cordinates` at that point in your code?  What are you expecting that code to do?  It looks like you're actually trying to just iterate the fields of that object (it's not an array).  You wouldn't normally do this with a traditional map operation.
Comment: Please paste the structure of data. i.e console.log(data);
Comment: `cordinates` is an `Object` not an `array`. `map` works on array.
Comment: @SonuBamniya so how can i retrieve an object like this?
Comment: @GangadharGandi added console.log
Comment: use `for(let i in obj){}` loop instead.
Comment: It sounds like you want to [iterate through object properties](https://stackoverflow.com/questions/8312459/iterate-through-object-properties).
Comment: @DougStevenson i am trying to read some of the field properties at once as firestore billing is counted per "read" so i didnt make seperate 40 fields alone but also i need to be able to edit these fields easily so didnt make it array. (for example as far as i know i cant edit the third field alone seperately) Each user will read these fields at least once when page loaded, so i want to make the database fields as less as possible or should i switch to firebase as it doesnt count "reads"
Comment: All that data is in just one document, which only requires one read to get it all into memory.
Answer: Change map to forin
Here is example code:
const cord = data.cordinates || {} // to handle undefined `data.cordinates` case
for(let i in cord){
   if(cord.hasOwnProperty(i)){
     const item = cord[i];
     console.log(i+" - "+item);
     // do your other stuff here
   }
}

Comment: i get Unhandled Rejection (TypeError): cord.hasOwnPorperty is not a function error
Comment: Ah! there is typo it should be `cord.hasOwnProperty(i)`. Updated my answer as well.
Comment: thank you, can you show me how to update one the object field propery also. let say i want to update _03:gold to _03:iron var mineupgrade =  db.collection("kullanici").doc(user);
        mineupgrade.update({
          cordinates:[...,_03:"iron"]
        }); can work?


Ubuntu 12.04 lts crashed. how to access the files in home folder?

Question: I am new with Ubuntu. I had installed 12.04 LTS 64 bit version. I had installed all the important updates it showed. Later on I selected some files manually in the recommended updates section. it was about 13-14mb. by default it showed some 140mb files. So I downloaded and installed it and then restarted my laptop and then the grub came. I selected Ubuntu and then it shows a blank screen. I went to the terminal using F1 key and tried commands like startx, then root startxand then sudo startx but nothing works. I don't know what all I installed exactly. another difference I observed is previously it used to show Ubuntu with Linux 3.0.0-23 now its showing Ubuntu 3.0.0-40 at the grub. Also i have my ubuntu password protected.
What should I do? I have got files inside Ubuntu and do not have its backup. how to recover them?
Answer: Try to check in the grub menu if it shows previous versions of your kernel 3.xx, and run it with the old one, Maybe the new kernel is incompatible with something in your laptop.


clearing an setInterval in react by using a loading state

Question: I am struggling with a simple timer here...I wam trying to count up when a query is running, then have it stop once the query is complete.
This is how I have currently set it up, but once the query has finished running the counter just continues to run even though !loading
  const [loading, setLoading] = useState(null)
  const [error, setError] = useState('')

  // Counter
  const [count, setCounter] = useState(0)

  const getPrestoData = async () => {
    setLoading(true)

    let count = 0

    const timer = setInterval(() => {
      count++
      setCounter(count)

      if (!loading) {
        clearInterval(timer)
      }
    }, 1000)

    await fetch(`http://127.0.0.1:8000/get-dspdaily/${dealId}`)
      .then(response => response.json())
      .then(data => {
        setData(data)
        setLoading(false)

        setDealId('')
      })
      .catch(error => {
        console.log(error)
        setError(error)
      })
  }

I have thought about putting the fetch statement inside setInterval but then it would be running every second which wouldn't be right.
I am sure this is pretty easy, but I can't figure out how to stop / pause the dam thing.
Answer: This happens because the interval callback is using the scoped loading variable at the time the callback function was created. So it will be a constant value.
You could clear the interval in the .then or .finally block of the fetch.
But even simpler would be to remove the interval completely and just use the Performance API and get the time before and after the await.
const start = performance.now();
await fetch(`http://127.......`).then(...);
const end = performance.now();
setCounter(end - start); // in milliseconds;

Comment: Thanks for this, it was only a simple tweak for what i needed. I tried the performance API, that worked fine but It was a count after the completion. Where as i needed a count up...but setting the `clearInterval` in the `.then` worked...thanks


Parsing Command Line and alter it into Char or Boolean

Question: Im in need of an option to parse the command line for a TicTacToe Game.
Player 1 & 2 Name .... Player 1 & 2 sign as (char) and isP1(P2)Ai as (boolean).
 TicTacToe ttt = new TicTacToe();

    Options options = new Options();

    Option p1Name = new Option("-p1name", "--player1Name", false, "The name for Player 1");
    p1Name.setRequired(false);
    options.addOption(p1Name);

    Option p1Sign = new Option("-p1sign", "--player1Sign", false, "The sign for Player 1");
    p1Sign.setRequired(false);
    options.addOption(p1Sign);

    Option p2Name = new Option("-p2name", "--player2Name", false, "The name for Player 2");
    p2Name.setRequired(false);
    options.addOption(p2Name);

    Option p2Sign = new Option("-p2sign", "--player2Sign", false, "The sign for Player 2");
    p2Sign.setRequired(false);
    options.addOption(p2Sign);

    Option p1IsAi = new Option("-isP1Ai", "--isPlayer1Ai", false, "Determine if Player 1 should be an AI");
    p1IsAi.setRequired(false);
    options.addOption(p1IsAi);

    Option p2IsAi = new Option("-isP2Ai", "--isPlayer2Ai", false, "Determine if Player 2 should be an AI");
    p2IsAi.setRequired(false);
    options.addOption(p2IsAi);

    CommandLineParser parser = new BasicParser();
    HelpFormatter formatter = new HelpFormatter();
    CommandLine cmd = null;

    try
    {
        cmd = parser.parse(options, args);
    }
    catch (ParseException e)
    {
        System.out.println(e.getMessage());
        formatter.printHelp("utility-name", options);

        System.exit(1);
    }

    String player1Name = cmd.getOptionValue("p1Name");
    String player2Name = cmd.getOptionValue("p2Name");
    char player1Sign = cmd.getOptionValue("p1sign");
    char player2Sign = cmd.getOptionValue("p2sign");
    String boolP1 = cmd.getOptionValue("p1IsAi");
    String boolP2 = cmd.getOptionValue("p2IsAi");
    boolean isPlayer1Ai = Boolean.valueOf(boolP1);
    boolean isPlayer2Ai = Boolean.valueOf(boolP2);

    if (args.length == 4)
    {
        Player player1 = new Player(player1Name, player1Sign, isPlayer1Ai);
        Player player2 = new Player(player2Name, player2Sign, isPlayer2Ai);
        ttt = new TicTacToe(player1, player2);
    }
    ttt.run();
}

So the Problem is :
When i try to get the argument for isPlayer1(2)Ai
boolean isPlayer1Ai = Boolean.valueOf(boolP1);
boolean isPlayer2Ai = Boolean.valueOf(boolP2);
It facts that it is auto unboxed into boolean ... is that somehow a Problem ?
And how can i parse the sign of an player, like i tried but failed, out of the command line and cast it to char?
The Constructor for my Players :
 public Player(String name, char sign, boolean isPlayerAi)
{
    this.name = name;
    this.sign = sign;
    this.isPlayerAi = isPlayerAi;
}

Answer: Based on your code, cmd.getOptionValue will always return a String, even if it's just a single character. To convert a single-char String to a character, you could use .charAt(0): get the first (0-indexed) character of a String. So, assuming the player-sign values cannot be null nor empty, change these two lines:
char player1Sign = cmd.getOptionValue("p1sign");
char player2Sign = cmd.getOptionValue("p2sign");

to:
char player1Sign = cmd.getOptionValue("p1sign").charAt(0);
char player2Sign = cmd.getOptionValue("p2sign").charAt(0);

As for your other question about the autoboxing of Boolean to boolean, that again depends on whether the Strings can be null and/or empty and/or invalid. If they are always either true or false, autoboxing to a boolean-primitive should be fine. If not, an if-check is again required, and perhaps Boolean objects holding true/false/null should be used instead.

Since I don't know what your code should do, I don't know if they can be null, and/or empty Strings, and/or invalid Strings. Nor do I know what they should be instead after converting them to boolean/char (or Boolean/Character). So I left that in the open for now..
Comment: I´ve got that thanks.  My Code should create Players for the TicTacToe, and it should be with the option isAi that it is an ComputerAi Enemy ... with logic coded by me. So i´ve altered my code for Ai´s to:       boolean isPlayer1Ai = cmd.hasOption("isP1Ai");
        boolean isPlayer2Ai = cmd.hasOption("isP2Ai");
So when either Option isP1Ai has been given in the Command Line this player is an ai so it returns a true.
Comment: New Problem : I cant initialize -> "CommandLine cmd;" .  It facts that  the variable may not have been initialized. Quick Tip is to "CommandLine cmd = null;"   the result is that "String player1Name = cmd.getOptionValue("p1Name");"  the value is null and finally on : "char player1Sign = cmd.getOptionValue("p1Sign").charAt(0);"  it throws an null pointer.


How to make a Ø25cm notch/groove/slot, 20mm thick, 10cm deep, in the ground?

Question: Strange need isn't it? It is to seal no bottom pots in the soil, like in the following photo but without the bottoms:

It is a circular notch or a groove or a slot, not a hole.
I have imagined this solution, with no soldering:
Main parts:

1x 1m steel rod with rectangular section 100mm x 40mm 3mm thick (6kg)
2x steel rod with circular section Ø25mm, 250mm long (2x 1kg)
1x drill Ø30mm, 500mm long (3kg)
2x cables 1m long, resistance 100kg
2x handles
M5 headless screws with conic ends, 4mm long (rod thickness + 1mm)

Mounting:

Grind the 2x Ø25mm rods in the bottom 100mm in V-shape to help cut the soil (20mm at thickest)
Drill the main road in the 100mm axis at its center Ø30mm, then at 12.5mm from its center in the same axis Ø25mm. They will receive respectively the drill and the circular roads
Drill laterally and tap for small screws in order to maintain solidly the roads and the drill
Drill the main rod at its extremity to mount the cables and set the handles at their end

Usage:

Drive in the drill in the soil until the lateral roads come into contact. One can turn on itself to help since it is a drill
Two people turn around the hole pulling on the handles with one hand. The central drill makes the lateral rods sink into the soil

Specs:

The tool shall not exceed say 15kg to be easily handled by two people
The tool shall enable to make a Ø25cm notch, 20mm thick, 10cm deep in less than 1 minute, so not too light
The tool shall be robust to perform thousands of operations
Easy and efficient operation
Preferably with no soldering
Not motorized tool
Clay soil not easy to dig with a shovel
No stones in the ground

Questions:

Do you have a better solution?
For this solution, what would be the best dimensioning (sections, lever arms, length) taking into account materials resistance, to best fulfil the specs?
Comment: Dirt in them and one or two stakes driven into the ground and tie with cord or wire, will prevent any wind tip overs/blowing away, except maybe an  tornado.  If no bottom in the pot, can put stakes inside the pot so they don't show.
Comment: Seems like you want an anti-thief solution?  If so the material of the pot needs to be as strong or stronger than what you use to hold it.  If you explain the why better, might get better ideas.  I would just dig a hole and put the pot/s in the hole, should keep them in place.  Even with the pots on top, the dirt in them should be enough, if not a simple stake driven down into the dirt and tie the pot to it.
Comment: Dig hole, insert pot, put dirt back in pot. Nobody gets injured by whirling unguarded steel bits. "But I want it **fast**" - great, they make posthole diggers that mount on tractors. But for 10 cm deep, a shovel will do in "less than a minute" unless the soil is absurdly hard. And two people can dig two holes at once. You are re-creating one of the most dangerous tools you can put in a drill press (a fly cutter) on a large scale and proposing that it should be operated by a hand-held drill. Someone *will* get hurt.
Comment: If I'm reading this correctly, this is not an electrical tool but a small ["donkey mill"](https://i.stack.imgur.com/MkWNp.jpg) but for core-drilling rather than grinding. How is it going to be persuaded to stay upright whist two people walk round in circles? How are you going to apply sufficient vertical force to make it actually drill? What provision is there to push out the drill core? What if you hit a rock? I'd just get a [drain spade](https://www.toolstation.com/roughneck-fibreglass-handle-drain-spade/p51294) or [rabbiting spade](https://www.toolstation.com/bulldog-rabbiting-spade/p68551)
Comment: @crip659 it is not anti-thief, but anti-wind, so I need to anchor them a little in the ground
Comment: @Ecnerwal it is not motorized and soil is a clay one, not easy to dig. No tractor.
Comment: @Tetsujin 1) "upright": that's the role of the central drill. 2) "sufficient vertical force" : central drill that screws in the soil plus weight of the tool. 3) "push out" : turn opposite until lift is possible. 4) No rocks.
Comment: @crip659 3 stakes per pot is a lot of stakes to prepare (600). At the end of the season, they have to be unset, cleaned and stored. I am afraid the overall workload is bigger.
Comment: manual post hole digger, it's kind of like  dirt pliers.
Comment: 100kg cables are going to snap if someone tugs on them, you should really use something stronger than parachute cord.
Comment: This is looking like an [XY Problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) to me, what is it that you're actually trying to accomplish?  You're looking to create a hole in the ground, but you want it to be reasonably precise? What do you mean by "make a _notch_ in the ground"? Usually a "notch" is a piece cut out of a corner or edge, so your choice of words is confusing. You're looking for a hole 25cm across and 10cm deep, what does 20mm "thick" mean? Are you looking to insert the things in the 1st picture into the ground?
Comment: @Freeman: a circular groove of 20mm thickness, Ø25cm, not a hole. I have edited the question.
Answer: I don't see how having the central auger actually helps usage, just drive a metal post into the ground, then have a  sleeve on the tool that so that it rotates on post.  with the central post there is no need for a symmetrical design, just have one lever arm and a single plough blade.
your kit will now need to include a post driver and a post extractor
Comment: symmetricity makes it more stable
Comment: it only needs to be sufficiently stable. the post will do that.


Is there any difference between Observable and Future.get

Question: Any difference between the two?
String r1 = new GoogleCommand().queue().get();

and
Observable<String> gResp = new GoogleCommand().observe();
String r1 = gResp.toBlockingObservable().single();

Answer: Got the response from Twitter:
observe() eagerly executes and caches whereas toObservable() is lazy until subscribe and doesn't add caching.
Comment: Maybe I'm missing what you meant by your question but I understood that you were asking about "future vs observable" while your answer was "observe() vs toObservable".. I was looking for "future vs observable" (in the case where the response will be one object rather than a stream).. any answer to that?


Do exterior pocket doors exist?

Question: Is there such a thing as a pocket door (with seal) for 4" exterior walls? We want to replace our sliding glass doors.
Comment: I haven't yet seen pocket doors that have anything like a real seal. I'd suggest going to a normal swinging door or double door unless you have space constraints on both sides which would prevent that.
Comment: A swinging door would be awkward in our situation, and sliding glass doors have more glass than we prefer.  The concept of a pocket door seemed ideal, but for the seal issue.
Comment: Have a look at garage door seals, available at your local home center. You can generally buy a piece of "trim" that is integrated with a seal of some kind. If your pocket door is shaped right, with a seal-friendly edge, there's no reason you shouldn't be able to get garage-door level (read: not very good, actually) performance. If you have a storm door or some other 2nd layer of protection, it might be okay depending on where you live (Florida yes, Canada no).
Comment: If the problem is just too much glass, then covering the glass might be easier and add a bit more insulation value.  4 inch walls will not have any space for insulation, so be about the same/a bit worst than well sealed glass.
Comment: Why the pocket door constraint? Are solid sliding doors sufficient? I guess the fixed panel would look pretty goofy. Is it easy for you to source and install siding over the pocket's area, though?
Comment: Just replacing -- or putting a facing on -- the glass panel is an interesting thought... Is the concern insulating or privacy? Privacy can be addressed with cling films, either frosted or mock-stained-glass; I've done that with other windows. Or with curtains, which can also help insulate somewhat
Comment: Location/weather conditions are important to know.  4 inch walls do not leave space for the good stuff like insulation.
Comment: The reason for not wanting to use sliding doors has to do with personal preference.  We do want some glass in the door, but since the space can't accommodate a swing door we may need to go back to the sliding door option.  Was hoping there might be a ready-made product available that includes good air-seal features.  We definitely don't want to spend time rigging up an unconventional pocket door scenario.
Comment: If you can't accommodate *a* swing door, have you considered French doors?  Perhaps you can accommodate two narrow swinging doors easier than a single large swinging door?
Answer: Not for residential applications. The implications for air, water, and pest intrusion, as well as security and energy efficiency, make them impractical.
I suggest a new sliding patio door with either translucent film or a solid paper to close off the glass. You may also be able to find doors with little or no glass from the factory.
Answer: This may be regional, so it may not be possible in your area.
In Florida there are some builders that will install a "stackable" slider where all the panels slide against an outside wall.  That wall can be built with a "Cover" over the stack of door panels giving the appearance of the doors going into a "pocket".
There is not a particular kit or manufacturer for this. It is something done by a custom builder. (The doors and track and frame is from a supplier. The "Pocket" is custom construction.)
This type of exterior door was only advised to be built when the doors would be totally under cover of a hard roof.  It was not good for rain and other outdoor debris, (leaves, grass clippings etc.) to be allowed to get in the pocket. Therefore a screened area was necessary as well.
As you can surmise, these were only installed on new construction.

Do exterior pocket doors exist?


Google Earth Closing Suddenly in Ubuntu 13.04

Question: Google Earth closing Suddenly in Ubuntu. I can't figure out why it is happening..but the Err log is...
<code>[0518/102428:ERROR:net_util.cc(2195)] Not implemented reached in bool net::HaveOnlyLoopbackAddresses()
[0518/102428:WARNING:backend_impl.cc(1875)] Destroying invalid entry.
[0518/102433:ERROR:nss_ocsp.cc(581)] No URLRequestContext for OCSP handler.
[0518/102433:ERROR:nss_ocsp.cc(581)] No URLRequestContext for OCSP handler.
[0518/102438:ERROR:nss_ocsp.cc(581)] No URLRequestContext for OCSP handler.
[0518/102439:ERROR:nss_ocsp.cc(581)] No URLRequestContext for OCSP handler.
[0518/102440:WARNING:backend_impl.cc(1875)] Destroying invalid entry.
[0518/102442:WARNING:backend_impl.cc(1875)] Destroying invalid entry.
[0518/102442:WARNING:backend_impl.cc(1875)] Destroying invalid entry.
[0518/102442:WARNING:backend_impl.cc(1875)] Destroying invalid entry.
[0518/102442:WARNING:backend_impl.cc(1875)] Destroying invalid entry.
[0518/102442:WARNING:backend_impl.cc(1875)] Destroying invalid entry.
[0518/102442:WARNING:backend_impl.cc(1875)] Destroying invalid entry.
[0518/102442:WARNING:backend_impl.cc(1875)] Destroying invalid entry.
[0518/102442:WARNING:backend_impl.cc(1594)] Messed up entry found.
[0518/102442:WARNING:backend_impl.cc(1875)] Destroying invalid entry.
[0518/102442:WARNING:backend_impl.cc(1875)] Destroying invalid entry.
[0518/102442:WARNING:backend_impl.cc(1875)] Destroying invalid entry.
[0518/102442:WARNING:backend_impl.cc(1875)] Destroying invalid entry.
[0518/102442:WARNING:backend_impl.cc(1875)] Destroying invalid entry.
[0518/102442:WARNING:backend_impl.cc(1875)] Destroying invalid entry.
[0518/102442:WARNING:backend_impl.cc(1875)] Destroying invalid entry.
[0518/102442:WARNING:backend_impl.cc(1875)] Destroying invalid entry.
[0518/102444:WARNING:backend_impl.cc(1875)] Destroying invalid entry.
[0518/102456:WARNING:backend_impl.cc(1875)] Destroying invalid entry.
[0518/102456:WARNING:backend_impl.cc(1875)] Destroying invalid entry.
[0518/102456:WARNING:backend_impl.cc(1875)] Destroying invalid entry.
[0518/102456:WARNING:backend_impl.cc(1875)] Destroying invalid entry.
[0518/102456:WARNING:backend_impl.cc(1875)] Destroying invalid entry.
[0518/102456:WARNING:backend_impl.cc(1875)] Destroying invalid entry.
[0518/102456:WARNING:backend_impl.cc(1875)] Destroying invalid entry.
[0518/102456:WARNING:backend_impl.cc(1875)] Destroying invalid entry.
[0518/102456:WARNING:backend_impl.cc(1875)] Destroying invalid entry.
[0518/102456:WARNING:backend_impl.cc(1875)] Destroying invalid entry.
[0518/102456:WARNING:backend_impl.cc(1875)] Destroying invalid entry.
[0518/102456:WARNING:backend_impl.cc(1875)] Destroying invalid entry.
[0518/102456:WARNING:backend_impl.cc(1875)] Destroying invalid entry.
[0518/102456:WARNING:backend_impl.cc(1875)] Destroying invalid entry.
[0518/102456:WARNING:backend_impl.cc(1875)] Destroying invalid entry.
[0518/102457:WARNING:backend_impl.cc(1875)] Destroying invalid entry.
Another crash happened while handling crash!
</code>
Help...Thanks...
Answer: I had similar issues, ie Google Earth started normally and after a few seconds crashing.
I ran:
<code>sudo dpkg-reconfigure google-earth
</code>
and this helped me to solve it.
It will reset the installation and probably allow a previously working installation to restart normally.
Comment: `sudo dpkg-reconfigure google-earth-stable` here. `google-earth` just doesn't work.
Answer: I reinstalled the Google Earth 32bit software and it fixed it for me.
Comment: oh I see, thanks. Could you edit again and add the exact command needed?
Comment: Sorry I wasn't clear, I was talking about Google Earth 32 bits software


unsupported operand type(s) for -: 'list' and 'list'

Question: import numpy as np
def answer_seven():
    counties = census_df[['POPESTIMATE2010','POPESTIMATE2011','POPESTIMATE2012','POPESTIMATE2013','POPESTIMATE2014','POPESTIMATE2015']]
return counties[[counties.max(axis=1)]-[counties.min(axis=1)]].abs().idxmax()

TypeError: unsupported operand type(s) for -: 'list' and 'list'

Above is my code which does not work and I got this error message.
But the code below does work.
import numpy as np
def answer_seven():
    counties_df = census_df[census_df['SUMLEV'] == 50][['CTYNAME','POPESTIMATE2010','POPESTIMATE2011','POPESTIMATE2012','POPESTIMATE2013',
                                                       'POPESTIMATE2014','POPESTIMATE2015']]
    counties_df["MaxDiff"] = abs(counties_df.max(axis=1) - counties_df.min(axis=1))
    most_change = counties_df.sort_values(by=["MaxDiff"], ascending = False)
    return most_change.iloc[0][0]

It uses max and min function to get the max difference as well which uses a list to subtract another list. Could someone explain to me why my code is not working but this one does? Thanks!
Comment: Welcome to SO, You can format your code as code by indenting it with 4 spaces. That would help in readability
Answer: The problem is here -
return counties[[counties.max(axis=1)]-[counties.min(axis=1)]]

You are subtracting two lists, I think the below edit should make it work
return counties[counties.max(axis=1)-counties.min(axis=1)]


Jquery Class Selector Fails to Select new Class Instances Added with .append()

Question: I'm semi-new to Javascript/jQuery so apologies in advanced if I'm missing something basic. I have a function that is triggered whenever a user types in an element with a specific class.
     $('.relevantClass').keyup(function(){
     //code...
     });

Now this function may end up, depending on the situation, creating a good deal of new HTML including new instances of relevantClass through the .append() method.
     var newHTML =
Content...
;
     $('#wrapper').append(newHtml);

However, the jQuery selector does not seem to detect and execute the function when a user types in the newly created relevantClasses. I've checked the newly created Html and it has the correct class tags and old instances of the relevant class due work.
I'm guessing this has something to do with .append(); messing with the DOM and I need someway to "refresh" the selector and let it do its jQuery thing researching the DOM to find the new classes. Any thoughts on how to do this? Is there some jQuery method I can't find?
Answer: You have to use on() to attach events that work on dynamic content:
var $parent = $("selector"); //the element you're appending .relevantClass to
$parent.on("keyup",".relevantClass",function(){
    //code...
});

Keep in mind that to work with dynamic content, you have to attach the event to relevantClass's closest parent that exists on page load.
Some people use body, but you should get used to using parent elements as close as you can get to the dynamic content. This is so that event delegation occurs on a smaller scale.
More info on on() here.
Also, I hope that newhtml variable is wrapped in quotes.
Comment: Great, thanks! Looks like this is exactly what I need. I'll let everyone know tomorrow when I can get back to this if it works.

newHtml is actually some godawful 200 char string of about three nested divs with lots of variables that I have to use .replace and regex to format dynamically. Then it gets passed to .append. Just wanted to spare you all the awfulness of it.
Comment: @purmou While I agree it's a good habit to use the closest parent for the delegated event handler, you should probably make that clearer in your code as well; if `.relevantClass` doesn't exist yet, `.parent()` doesn't find anything and the handler never gets bound. It works in this case because there are existing `.relevantClass` elements and the code just appends more, but in general you should hard-code a direct selector for the parent based on the html. (+1 anyway)
Comment: @nbrooks: Excellent catch, I didn't even realize that issue. I'll make that clear.
Answer: $('.relevantClass').on('keyup', function(){
    //code...
});

Answer: Try something like
$('body').on('keyup', '.relevantClass', function() { ... }

The idea is that you use an existing root element and use your class selector as a filter. See the examples here.


Navigation Back Button Update

Question: I have 3 views: A, B, and C.  They are connected by segues this way:
<code>A->B
A->C
B->C
</code>
When I transition from B to C, I want the view to be removed from the navigation stack.  I use this code: https://stackoverflow.com/a/14753659/2260928 to remove B.  It works fine except for the back button that still has B as the label. When I press back, it transitions to A with a back button label of A and if I press back button again the button disappears.
How can I fix this weird back button behavior?
Answer: This is not a direct answer to the question but an alternate way of achieving the behavior I wanted: Removing viewcontrollers from navigation stack

Navigation Back Button Update


About minimum 2 and maximum 9 probability

Question: There are 33 students in a class. What is the probability that at least two of the 9 randomly selected people were born in the same month?
I know classical birthday problem ( 1-(365/365.)(364/365)...) but I couldn't apply this to this problem. Minimum 2 person and maximum 9 person and month. These are the differences.
Comment: Does the issue that months consist of different numbers of days need to be considered?
Comment: This is obviously an exercise. So, you should show what you have done before. Moreover, some assumptions are missing such as the distribution of the birth month across the population. I guess it is uniform here.
Comment: Suppose that you gathered $4$ people, and asked each of the $4$ people to think of a number at random, from the set $\{1,2,3,4,5,6\}$.  Then, suppose that you were asked for the probability that the $4$ people randomly selected $4$ distinct numbers from the set $\{1,2,3,4,5,6\}$.  The probability would be $$\left[\frac{6!}{(6-4)!}\right] \times \frac{1}{6^4}.$$  Do you understand how I arrived at this computation for this alternate problem?
Answer: The first thing to realise is that the 33 is irrelevant, ask yourself, how would the outcome change if I chose 9 people from 100? Or from 1000? The answer is, it wouldn't (with some assumptioms about the distribution)
So our new problem is simply: what is the probability that 9 people don't share more than one birthday month among them?
hopefully you can see how to apply the method for finding the solution to the birthday problem now? (Hint, think of your year as being 12 days, and obviously your group is 9 people, how many ways can you distribute them with certain requirements?)


How can I read a variable from c sharp into python?

Question: I want to read variable from c sharp into python.
.cs file
class MyClass
{
    string str = "Hello world";
}

.py file
fp = open(path, 'r').read()
#str = ???
print 'str: ' + str

When I run my python code, I want to get result:
str: Hello world

Comment: Use readlines. + regex to find the string you want.
Answer: You can use a regex, and I strongly suggest using with to open your file since you could save some lines of code when closing your file.
import re
path = 'my_file.cs'
var_name = 'str'
with open(path) as f:
    for line in f:
        match = re.search(r'{} = "(.*?)"'.format(var_name), line)
        if match:
            print('{}: {}'.format(var_name, match.group(1)))

Output:
str: Hello world

In this case, I am assuming your file is in the same directory as your python file, but you can change the path variable if not.
Comment: Thx. But I want to use another directory
Answer: Well, ideally you'd want to use a parser that's smart enough to know C#. But you can kind of cheat with regex and make it work for this example.
import re

fp = open(path, 'r').read()
match = re.search(r'str = "(.*?)"', fp)

print("Str: %s" % match.group(1))

Comment: this code return error: AttributeError: 'NoneType' object has no attribute 'group'


Phased migration - running ASP.NET 4 alongside ASP.NET 5

Question: We have MVC ASP.NET Web Applications written within the ASP.NET 4.* scope that we would like to phase across to ASP.NET 5.  While we transition (as well as client-side JavaScript scripts/libraries, CSS, etc) we'd like the old app (which obviously contains Views, Controllers, Helpers, Utilities, Attributes, etc) to co-exist in an MVC/Web-Application ASP.NET 5 project, with the new (ASP.NET 5) codebase.
Firstly is this possible with minimal changes ?  I have been doing some testing and a lot of reading - for the client-side libraries I should be able to handle the co-existence by copying the existing content into the wwwroot area via Gulp.  My question is mostly around the server-side artifacts - for example I am using a framework (as specified in project.json) of "dnx46" (which seems to be the most appropriate for this purpose), but I am getting a number of conflicts (around missing assemblies) around simple things like Project references, ActionFilterAttribute & AuthorizeAttribute [eg. The type or namespace name 'AuthorizeAttribute' does not exist in the namespace 'System.Web.Mvc' (are you missing an assembly reference?)] (because they no longer exist in the System.Web.Mvc namespace), HttpContextBase, security (OWIN, etc) etc - note that I'm aware of including References which are reflected within the project.json file (and some that finish up inside the appropriate 'wrap' folder location)
If there is a preferred approach - some possibilities are

create a new WebApplication ASP.NET 5 project which among other things contains out of the box Bower, npm, Gulp, CodeFirst Migrations, Controller/Views, etc ready to go then copy your legacy project artefacts in
create a blank ASP.NET 5 project and start everything from the ground up (as per http://aspnetmvc.readthedocs.org/projects/mvc/en/latest/migration/migratingfrommvc5.html) then again copy your legacy project artefacts in
create a new WebApplication ASP.NET 5 project, then with a post-build event copy your new and legacy artifacts into a third vanilla project.  In this way the old and new projects live in isolation and only get merged in at deployment time
separate concerns like Helpers, Utilities, Attributes, etc that are used within the UI project into a traditional Class Library project and only keep the bare minimum (Views, Controller, scripts, css, etc) within the UI (ASP.NET 5) project

Any ideas would be greatly appreciated.
Answer: I don't know that how your MVC 4 project is structured, I would prefer to create it from scratch using Blank ASP.NET 5 Template targeting dnx451. The thing I don't understand is previous .NET stuff like Authorize attribute are not found as they are available and I'm using it. Here are some stuff that might be help to you while migrating:-

Your EF Context and security classes should be considered as middlewares in ASP.NET 5 and should be configured in Startup.cs class which is not found in MVC 4.
Put all your CSS\JS files in wwwroot and make a reference _Layout.cshtml as root as normally (use gulp task runner for better performance.)
Must target dnx451, because dnx50 does not contain all of the libraries and it is about immensely in ASP.NET Core RC2 and RTM. (If you can't wait for RC 2).
If you're using Identity for Authorization, note that there is now a big change in Authorization Policy as can be found Here

It is a little bit difficult but it will optimize your team working and will make your project flow faster than before.


Include an React-Nativ View into an existing Android App

Question: I have a very simple Android-App, with one view that has a button to an other view.
In that other view i have to show an React-Native component. I followed the instructions on https://facebook.github.io/react-native/docs/integration-with-existing-apps.html#integration-with-existing-apps my Activity is this my tiny code:
public class MyReactActivity extends Activity {

private ReactRootView mReactRootView;
private ReactInstanceManager mReactInstanceManager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    mReactRootView = new ReactRootView(this);

    mReactInstanceManager = ReactInstanceManager.builder()
            .setApplication(getApplication())
            .setBundleAssetName("main.jsbundle")
            .setJSMainModuleName("index.android.js")
            .addPackage(new MainReactPackage())
            .setUseDeveloperSupport(BuildConfig.DEBUG)
            .setInitialLifecycleState(LifecycleState.RESUMED)
            .build();
    mReactRootView.startReactApplication(mReactInstanceManager, "MyReactApp", null);

    setContentView(mReactRootView);
}

This app starts ok ,but when i touched the button to change the view, the app crashes with:
E/AndroidRuntime: FATAL EXCEPTION: main
              Process: com.example.kris.testa, PID: 2612
              android.view.WindowManager$BadTokenException: Unable to add window android.view.ViewRootImpl$W@65e68b3 -- permission denied for window type 2003
                  at android.view.ViewRootImpl.setView(ViewRootImpl.java:703)
                  at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:342)
                  at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:93)
                  at android.app.Dialog.show(Dialog.java:322)
                  at com.facebook.react.devsupport.DevSupportManagerImpl.handleReloadJS(DevSupportManagerImpl.java:538)
                  at com.facebook.react.ReactInstanceManagerImpl$3$1.run(ReactInstanceManagerImpl.java:386)
                  at android.os.Handler.handleCallback(Handler.java:751)
                  at android.os.Handler.dispatchMessage(Handler.java:95)
                  at android.os.Looper.loop(Looper.java:154)
                  at android.app.ActivityThread.main(ActivityThread.java:6119)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

What I am doing wrong? Can anyone help?
UPDATE:
My AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.kris.testa">

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">

    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".MyReactActivity" android:label="@string/app_name"
        android:theme="@style/Theme.AppCompat.Light.NoActionBar"
        android:configChanges="keyboard|keyboardHidden|orientation|screenSize">

    </activity>
    <activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />

</application>
</manifest>

Answer:
Try using this permission in AndroidManifest.
android.permission.SYSTEM_ALERT_WINDOW
on API >= 23 see

Link: https://stackoverflow.com/a/7570071/1796309
If you're using Android version >= 6.0, then you have to follow Android Permission model, i.e. you have to request this permission in runtime.
If you don't want to request permission in runtime, just set your targetSdkVersion to 22 in build.gradle:
android {
    compileSdkVersion 23
    buildToolsVersion "23.0.3"

    defaultConfig {
        applicationId "ru.goenglish.goenglish"
        minSdkVersion 14
        targetSdkVersion 22          <<<<<<<<<<<<<<<<<<<<<<<<<
        versionCode 1
        versionName "1.0"
    }
...
}

Comment: hm, I already have:
, I'll add this into the post.
Comment: Ah, Thanks a lot. i'll give it a try.


Will old cast iron Baseray baseboards work with a steam boiler?

Question: forgive me if this question is amateurish. We recently removed some old cast iron Baseray baseboards from a house which were being heated with hot water. I'm wondering, can these baseboards be used with a steam boiler?
The baseboards look exactly like this https://www.ebay.com/itm/323735785091
Thank you!
Comment: Do you know if your steam boiler/system is one-pipe or two-pipe?
Answer: That baseboard radiation will work great on a 2 pipe steam system or a forced hot water heating system but is not recommended for use on a 1 pipe steam system.
Comment: Thank you so much for this!


FileReader onload not getting fired when selecting same file in Chrome

Question: FileReader onload not getting fired on second time when the same file selected with Chrome, it's getting fired all the time for FireFox.
function uploadCover(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();
        reader.onload = function(e) {

            var image = new Image();
            image.src = e.target.result;

            image.onload = function () {
               // code
            };
        };
        reader.readAsDataURL(input.files[0]);
    }
}

Here I want to validate image width and height on upload. So there is two scenarios which is ending up with issue:

User selects same image without any change.
This time user should get validation message again.
User edited the image and changed size, uploaded again.
Again file value not changed, so the upload or validation not getting called.
Answer: Check this questions that are similar to your problem:
Chrome file upload bug: on change event won't be executed twice with the same file
input file onchange event not being fired in chrome
Comment: Updated question.Please suggest some alternative solution if you have.


sudo apt-get install libstdc++

Question: When i try to install libstdc++ using:
sudo apt-get install libstdc++

I am getting the below error in ubuntu. Do you have any idea about it?
The following packages have unmet dependencies:
 libstdc++-4.8-doc : Conflicts: libstdc++6-4.4-doc but 4.4.7-8ubuntu1 is to be installed
                     Conflicts: libstdc++6-4.6-doc but 4.6.4-6ubuntu2 is to be installed
                     Conflicts: libstdc++6-4.7-doc but 4.7.3-12ubuntu1 is to be installed
 libstdc++-4.9-doc : Conflicts: libstdc++-4.8-doc but 4.8.5-2ubuntu1~14.04.1 is to be installed
                     Conflicts: libstdc++6-4.4-doc but 4.4.7-8ubuntu1 is to be installed
                     Conflicts: libstdc++6-4.6-doc but 4.6.4-6ubuntu2 is to be installed
                     Conflicts: libstdc++6-4.7-doc but 4.7.3-12ubuntu1 is to be installed
 libstdc++-5-doc : Conflicts: libstdc++-4.8-doc but 4.8.5-2ubuntu1~14.04.1 is to be installed
                   Conflicts: libstdc++-4.9-doc but 4.9.3-8ubuntu2~14.04 is to be installed
                   Conflicts: libstdc++6-4.4-doc but 4.4.7-8ubuntu1 is to be installed
                   Conflicts: libstdc++6-4.6-doc but 4.6.4-6ubuntu2 is to be installed
                   Conflicts: libstdc++6-4.7-doc but 4.7.3-12ubuntu1 is to be installed
 libstdc++6-4.6-dbg : Conflicts: libstdc++6-4.4-dbg but 4.4.7-8ubuntu1 is to be installed
 libstdc++6-4.6-doc : Conflicts: libstdc++6-4.4-doc but 4.4.7-8ubuntu1 is to be installed
 libstdc++6-4.7-dbg : Conflicts: libstdc++6-4.4-dbg but 4.4.7-8ubuntu1 is to be installed
                      Conflicts: libstdc++6-4.6-dbg but 4.6.4-6ubuntu2 is to be installed
 libstdc++6-4.7-doc : Conflicts: libstdc++6-4.4-doc but 4.4.7-8ubuntu1 is to be installed
                      Conflicts: libstdc++6-4.6-doc but 4.6.4-6ubuntu2 is to be installed
 libstdc++6-4.8-dbg : Conflicts: libstdc++6-4.4-dbg but 4.4.7-8ubuntu1 is to be installed
                      Conflicts: libstdc++6-4.6-dbg but 4.6.4-6ubuntu2 is to be installed
                      Conflicts: libstdc++6-4.7-dbg but 4.7.3-12ubuntu1 is to be installed
 libstdc++6-4.8-dbg-armhf-cross : Conflicts: libstdc++6-4.7-dbg-armhf-cross but 4.7.3-11ubuntu1cross1.85 is to be installed
 libstdc++6-4.9-dbg : Conflicts: libstdc++6-4.4-dbg but 4.4.7-8ubuntu1 is to be installed
                      Conflicts: libstdc++6-4.6-dbg but 4.6.4-6ubuntu2 is to be installed
                      Conflicts: libstdc++6-4.7-dbg but 4.7.3-12ubuntu1 is to be installed
                      Conflicts: libstdc++6-4.8-dbg but 4.8.5-2ubuntu1~14.04.1 is to be installed
 libstdc++6-5-dbg : Conflicts: libstdc++6-4.4-dbg but 4.4.7-8ubuntu1 is to be installed
                    Conflicts: libstdc++6-4.6-dbg but 4.6.4-6ubuntu2 is to be installed
                    Conflicts: libstdc++6-4.7-dbg but 4.7.3-12ubuntu1 is to be installed
                    Conflicts: libstdc++6-4.8-dbg but 4.8.5-2ubuntu1~14.04.1 is to be installed
                    Conflicts: libstdc++6-4.9-dbg but 4.9.3-8ubuntu2~14.04 is to be installed
E: Unable to correct problems, you have held broken packages.

Comment: There isn't actually a package called `libstdc++` (possibly you are trying to install `libstdc++6`? Because of the `++` characters, when `apt` doesn't find an exact match it treats the package name as a *regular expression* so in this case it's trying to install any package whose name matches `libstd` followed by one or more `c` - many of which conflict, as you can see.
Comment: @steeldriver: that is clearly the answer and imho should be an answer rather than a comment (although it would help to be able to explain how to avoid treating the string as a regex). The manpage for `apt` says that it will treat package names as regexes if they include `.`, `?` or `*` without mentioning `+`, so the behaviour is not exactly expected.
Comment: Did you recently add any ppas?
Answer: There isn't actually a package called libstdc++ (possibly you are trying to install libstdc++6?)
When apt doesn't find an exact match to a package name, it treats the given string as a regular expression. In this case the ++ causes it to try to install any package whose name matches libstd followed by one or more c - many of which conflict, as you can see.
Unfortunately I have never managed to figure out how to turn off this behaviour (nothing I have tried in the past using escape characters has seemed to work) - the only solution I know is to be careful to give an exact package name where any regex characters might be misinterpreted, and to make sure the package catalog is up-to-date i.e.
sudo apt-get update
sudo apt-get install libstdc++6

Comment: this should be accepted. Concerning the turn-off: one could write an alias or function which wraps the package name inside a `^PACKAGE$`
Answer: First run these commands
sudo apt-get update && sudo apt-get upgrade
sudo apt-get install build-essential
sudo apt-get install aptitude

and then try
sudo apt-get install libstdc++6

or try this search result and install one desired package from listed http://packages.ubuntu.com/search?keywords=libstdc%2B%2B
Comment: Oh and why installing `aptitude` if you don't use it for installing `libstdc++6`?
Comment: +1 Good answer, but isn't the `libstdc++` included in the `build-essential`s?
Comment: Thanks for your reply Kev. I tried to give some sort of possibilities in case of not success. And aptitude for handling his error.
Comment: sudo apt-get update
apt-get: error while loading shared libraries: /usr/lib/x86_64-linux-gnu/libstdc++.so.6: invalid ELF header
Answer: LD_LIBRARY_PATH=/usr/local/lib64/:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH
sudo add-apt-repository ppa:ubuntu-toolchain-r/test
sudo apt-get update
sudo apt-get install gcc-4.9 g++-4.9

Comment: Could you explain why the user must do this and what each command does?  (just in case someone else reads your answer and decides to just copy-paste it for the wrong problem?)  **;-)**

sudo apt-get install libstdc++


How effective is a heat pump for AC and a heat pump/furnace for heating in New England?

Question: We currently have a central AC unit and oil furnace. The AC is broken and the furnace is old, so we are thinking of replacing both sometime in the next year.
We are considering replacing the AC with a heat pump and the oil furnace with a gas furnace in the hopes that the gas company will bring a line down our street from the main road sometime before the furnace needs to be replaced.
From my understanding, the heat pump could also be used to heat the house up to a certain point in the winter.
I don't know a whole lot about heat pumps, so I'm wondering how effective a heat pump would be at cooling and heating the house (currently just the first floor, about 800 sq ft, and basement), both in terms of cost effectiveness and actual comfort level of the house. Should a pump be able to cool our house on 100+ degree days to, say, 70-75 degrees? Will it be able to get our house warm enough in the winter in a reasonable amount of time?
I'm told the units will somehow be set so that the furnace kicks in automatically when needed, but I'm wondering how that is actually determined. I don't want to be sitting in a cold house for hours waiting for the furnace to realize the heat pump isn't going to do the job.
I've also heard the pump is cheaper for heating, but I am wondering about the specifics. How much cheaper would a heat pump be to run? Both run on electricity to some extent, but does the heat pump use more electricity to warm the house than the furnace, and, if so, is it enough to make up for the cost difference?
Any other pros/cons I should be thinking about?
Comment: Oh, and as for cost, the electricity runs the fan (just as any furnace) and the compressor pump (to extract the heat). In terms of total energy costs used, it's a lot less than a fuel-based heating source as none of the energy sources you are paying for are being used to heat the air. Essentially, you are getting the heat for 'free' but still paying to extract it/circulate it in your house.
Comment: I am not going to try to compete with the long winded answers below, but gas is cheaper for heat in at least 3 of the states I have lived in. In Oregon for example a ~3000 as ft home cost over 500 per month with electric heat. I changed to gas and cut the price in less than half, I later changed to a heat pump and for most months my bill reduced even further, but when the temps got below 27 degrees my system at the time switched to electric heat and my bills doubled. Today I live in a smaller home but today's split systems are efficient down into the teens some lower.  It depends on the system
Comment: @EdBeal: Heat pumps are HUGELY more efficient than resistive heating, though that advantage decreases at lower temperatures -- to the point where they may indeed cost less to operate than gas, oil, or wood pellet systems. I have a high efficiency gas furnace driving FHW; switching to heating with the heat pumps seems to have reduced my total energy usage considerably. Your mileage may vary; Boston isn't exactly Canadian temperatures most of the time but isn't exactly Georgia either. Of course I did improve wall insulation at about the same time, but the spreadsheet is still sorta impressive.
Comment: @keshlam I basically said the same thing, with the problems with heat pumps not working well at - temps to the point an emergency heat source other than the heat pump is needed, once it gets below the operating temp the heat pump just don't work,no matter how efficient , then restive, gas or wood burning heat sources are needed. Since I posted this in 2018 I have seen the operating temperature of several brands drop 10-20 degrees F.
Comment: A ground-loop heat pump is very efficient. So if that's the route you're thinking of going, definitely a good choice. However, I assume you are maybe talking about an air source pump, which is less efficient. It will work, but won't be very efficient when the temp gets too low (and may not be the best for your sole source of heat if you have extremely low temperatures). For A/C, though, it'll be just fine (as it is, in essentially, a big A/C unit.)
Comment: Sorry; missed the fact that this was resurfacing of an old question. Wish they'd mark those more clearly.
Answer: Heat pumps are quite common in Central Oregon where summer daytime highs are often over 100°F and nights below 25°F.  I have been in many a heat pump rental house in winter at below 10°F in a wide range of efficiencies from below eight to over 20 SEER.  They work fine.
For units with a SEER of over 14 or so, the backup heat does not kick in (except for defrost cycles) in cold, dry weather and the thing pumps a lot of heat into the house with air register temperatures over 110°F.  These are all air source units—there is no groundwater in the desert.  Natural gas is available and cheap, but about half of the owners choose heat pumps, the remainder choosing central air plus a gas furnace.  The recent trend seems to be favoring heat pumps more.
A close friend had a ground source heat pump installed in his Willamette Valley home (temperate, moist climate).  It was beautifully quiet, compact, and tremendously efficient.  When I asked if he would do it again, he said "No.  The expense of excavation would not pay for itself in his lifetime." (He was about 32 at the time).  For a level lot in nice sandy loam with the water table about 6 feet deep and good water flow from 2 feet deep and below, it cost $45,000 twenty years ago just to install the ground loops.  I can't imagine what it would cost now.

I'm told the units will somehow be set so that the furnace kicks in automatically when needed, but I'm wondering how that is actually determined.

I have owned two heat pump systems (okay three:  one was an upgrade replacing another).  Backup or emergency heat (same physical thing) is activated under any of several conditions:

During defrost cycles—which only occur during system "heat" operation.  The heat pump outdoor fan is turned off, the system reverses to cooling mode to melt frost and ice built up on the outdoor unit.  To keep from blowing cold air indoors at a time heat is expected, the backup heat is turned on to remove the chill.  My most stupid heat pump, a 1980s relic, used a timer which ran a defrost cycle for 4 minutes out of every 45 minutes (of system "on" time) whether it was needed or not.  The other two systems were much smarter and learned under what conditions defrosting might be needed, would engage defrosting every hour or two, somehow detect if it wasn't needed and return to heating within a minute.  Otherwise the defrost cycle could run up to 3 or 4 minutes.
When the thermostat (which are necessarily specialized for heat pumps) is switched into emergency heat mode.  You would do this if you did not want to run the heat pump because a tree fell on it or something.
When a simpler thermostat's setpoint is more than 4°F above the current room temperature, or when a smart thermostat determines that the heat pump is not going to get the temperature to the setpoint anytime soon.

I've also heard the pump is cheaper for heating, but I am wondering about the specifics. How much cheaper would a heat pump be to run? Both run on electricity to some extent, but does the heat pump use more electricity to warm the house than the furnace, and, if so, is it enough to make up for the cost difference?

Yes, a heat pump uses more electricity than a furnace, which only blows air inside.  A heat pump blows around air outside and inside, plus it runs a hefty refrigeration compressor.  The seasonal energy efficiency ratio (SEER) is a measure of how much heat is moved compared to how much energy was input to move the heat. An electric furnace or electric baseboard heater would have a SEER very close to 3.8.  A new window air conditioner is now required (in the U.S.) to be at least 8.0, and for an Energy Star rating, at least 14.0.  Ratings of 10–12 were recently common in low end heat pumps, but the required minimum is 13.0 since 2005.  As the rating increases, so does the purchase price.
My Portland, Oregon, condo came with an electric furnace.  When it was installed in the 1970s, electricity cost 2.2 cents per kilowatt hour; today's price is $0.07–0.11 depending on the power company.  During a particularly cold winter storm c. 2004, my electric bill made it to $300 per month, mostly due to some compromised windward windows—normal winter electricity ran $50–70.  I replaced the electric furnace with an 18 SEER heat pump costing $7,000; a 15 or 16 SEER version was $5,000 IIRC.  Afterward, my electric bill was $45 in normal winter weather and up to $60 in severe cold, most of which was probably to run a bank of five computers 24x7.  While the economics may not make perfect sense, I am sure the more "normal" electric rates which most areas have would easily make the break-even point plenty soon enough.
I am really happy with having a heatpump.  I would consider doing a ground source if there were a cheap way to bury the tubing, but otherwise the air source is just fine.
Answer: You don't have to worry about a heat pump being inadequate for cooling tasks, they are available in a large range of sizes. For really large buildings, they can be ganged together. 800 sf is a walk in the park for residential sized units.
I don't know the specifics of what determines when the backup furnace kicks in. IIRC, it is the combination of a lower thermostat set point and the outside temperature. It kicks on when the pump is not keeping up or it's too cold for it to run efficiently. I can assure you you will not be sitting for hours waiting for backup heat. No customer would sit still for such a system.
While it is true that heat pump heat is free, you are just paying to move it around, if you've had heat wave cooling bills before, you know moving heat around is far from cheap. Only a careful analysis of the various options, considering both operational and installation costs, as well as life cycle replacement, can you make a proper decision about which system is most cost effective. The correct solution will vary by small changes in energy costs and climate.
In cold climates, a ground heat source system should at least be considered because it will reduce or eliminate the need for backup heat. If you are concerned about your carbon footprint, do not forget most electricity generated in the US is by burning fossil fuels. Your footprint from using a heat pump will vary greatly depending on where your local power is coming from. Heat pumps make a lot of sense for many people, especially if they are investing in cooling equipment anyway. But everyone's situation is unique, so the best solution can be arrived at only after careful rational analysis of all the factors.
Comment: Even if your electricity comes from burning fossil fuels, the efficiency of a heat pump can't be beaten because they are over 100% thermally efficient. Something around 300% efficiency is common, so it's more efficient to burn fossil fuels at a power plant including losses at the plant and in the line, and run a heat pump than it is to burn fossil fuels directly for heat in your home.
Answer: We had a heat pump in Pennsylvania , 1 hour north of Philadelphia, used for heating and cooling.   We now , after 25 years in that home we built, have gas forced air and a central AC unit.  There is no comparison.  The gas heat is cheaper, stays I the room, and feels warmer. I was always cold with the heat pump, even when it kicked on to residence heat . The heat pump only provides cheap heat until you get to temps of below 32 and then it becomes less efficient and more expensive.  If you can get gas heat, by all means do it.
We had oil in our first home, summer /winter hock up and even that was better than the heat pump in Pennsylvania.  South of Philadelphia , with milder winter temps is better for heat pumps no matter what he contractors and electric companies tell you.
Answer: How well the heat pump warms the house depends on the capacity of the heat pump  and how well insulated the house is.
Heat pumps definitely act a lot slower than furnaces, the temperature just kind of creeps up. In fact, in my house in New Hampshire, the temperature actually gets lower when the heat pump comes on because it starts blowing cold air around for 10 minutes.
The way backup heat works in my house is that if the temperature gets 5-degrees lower than the thermostat, then the furnace comes on. Once the temperature gets to be about freezing, the heat pump is more annoying than helpful. During the fall and spring when the temperature is in the 50s and 60s, the heat pump is very useful because otherwise the furnace would be coming on and off all the time.
As far as efficiency is concerned, it is definitely cheaper to run the heat pump when the temperature is above 45 degrees. Also, a heat pump is a lot cheaper than an air conditioner. Of course, with some $15,000 heat pump it can take a long time to justify that even if you are saving $100 a month.
Answer: Nota bene: I realize this is an old question but I thought I'd add an answer since this question was recently bumped and there's apparently been recent interest in the topic.
Here in the Midwest, and I believe much the same applies to New England, heat pumps would be sized for the desired summer cooling capacity and you just kind of get what you get for winter heating capacity.  If there's snow on the ground every winter then building codes likely require some kind of backup heat to any heat pump.  I know people will want to argue on if this is necessary given recent advances in heat pumps but building codes are written in blood so good luck on getting that changed any time soon.
If the desire is to get rid of the oil furnace and leave open the option for natural gas later then look into a furnace that is compatible with LPG and natural gas.  LPG from a tank isn't always exactly cheap, and there's likely building codes involved there too, but it would likely mean leaving a minimal cost transition to natural gas heat.  I've seen furnaces that are built for LPG but come with a natural gas conversion kit, and this conversion kit is often tossed out by the installers.  Save that kit if it's there.
There's a reason electric resistance heat is not all that popular, it is cheap to install but very expensive to run.  A heat pump will mean not needing electric resistance heat for the entire winter but for New England you'd likely be using that resistance heat for far more than you'd like.  There may even be local building code that doesn't allow resistance heat without a fossil fuel furnace.  Putting in a natural gas furnace without any natural gas service (yet) isn't likely to fly past the inspector's radar.
There's not likely anything against putting in resistance heat but there's not likely to be any cost savings in doing so.  If the heating capacity calculations show the required electric demand exceeds the supply to the home then that's an added expense and/or some kind of building code hassle.
I have a heat pump and calculating the costs versus natural gas has so many variables that it is difficult to tell if I'm saving any money.  For some people the calculations will be far simpler and/or with quite obvious results.  The point is that I doubt anyone would be able to determine if there is a cost savings with the information known so far, and it could take a lot more information to figure this out for the calculations to be moot the next year as electrical and fuel fees change.
Oil heat isn't really a thing around here but I understand oil heat is still popular in New England.  Oil heat has been there a long time, running natural gas can be difficult with all the hills and such, and conversion to LPG can raise concerns with little old towns of homes packed in tight since a pressurized tank of LPG can be a hazard to neighbors in a way that an oil tank is not.  There's a lot of wide open space in the Midwest, we can plant those LPG tanks well away from any occupied structure.
Comment: Interesting. I last had a heat pump system in an apartment I was renting in PA back in the '90's, and I had almost exactly Sue's experience (but a bit worse). Its now 1 decade later for her, and 3 decades later for me, and I get a lot of people telling me they are much better now, even better than gas. I'm skeptical. You don't easily forgive a system that leaves you cold and with August-level electricity bills in the winter.
Comment: I'll see claims that heat pumps are good enough now to not need any backup heat, even in cold places like Minnesota.  Experience tells me not to believe them, and even if I did then building codes are not likely to allow a heat pump without a backup.  Looking into fireplaces and electric wall heat units I find they are not likely allowable as backup heat, they are only for "supplemental" heat.  Putting in a fireplace to make a space look nice and feel comfortable will help but this is not likely to circumvent building code requirements for a proper furnace.  YMMV, of course.
Comment: @MacGuffin -- the building code requirement for heating is a performance-based requirement for a minimum of 68degF maintained 3' off the floor on a design heating day. (IBC 1203.1, IRC R303.10)  Even in MN, a good low-ambient minisplit unit can meet this criterion without issue and without supplemental heat provided the building envelope is well-designed (i.e. properly air sealed and insulated, or in other words, a low-load envelope design)
Answer: It depends on where you are in New England. Darien CT and Lyme NH aren't similar climates. Where I live the air temperature drops to -30°F and the ground water from my well is in the 40's year round. Heat pumps can run in low ambient temperatures, they are not efficient that way. Unlike the western states the air in NE will condense requiring the machine to pump heat outside to defrost it frequently. Unfortunately the bulk of the heating cost is when it's coldest, so the savings of using a heat pump when it's mild outside while real, aren't a large fraction of the annual heating cost. The added cost of a ground loop for heat pump is large, roughly the same as drilling 2 new water wells. If its undersized it will freeze underground and be utterly useless as a heat source for months, but the cost of a generously sized ground loop dwarfs decades of heating bills. The recommended system takes advantage of the low cost of adding heat pump functionality to an ac system. A good two stage thermostat will do a good job cutting off the heat pump and switching to the furnace. There are also fancy systems that use outdoor temperature to guide a changeover.
Bottom line, if you're in southern CT on the coast consider the heat pump seriously, elsewhere it's likely to be an inadequate heating plant.
Answer: I've installed a whole house Mitsubishi  heat pump system.
It's whisper quite allowing normal conversation standing beside the dual fan outdoor unit.
I whole  house, a two level bungalow , keeps an even temperature throughout.
It is 100% efficient to -23C then tapering off to zero efficiency at -40C when the heaters would kick in.  We live in Souther Ontario when I've not seen -23C.
In that most of Ontario runs off nuclear or water power the electricity is green energy.
The local gas company provided a $6,500 rebate when it was installed.
The Federal Central Mortgage and Housing authority provides up to 40K loans for 10 years at zero percent interest.
It replaced a 22 year old hybrid system whose AC was working round the clock to keep up during the hot weather.
A similar sized quality gas electric replacement system costs about 3K less than the heat pump system.
The Mitsubishi system comes with a 10 year parts and labour warranty. I have used my supplier for over 20 years.
My wife is extremely happy with the installation.
I expect my annual energy costs to be lower and much lower in the future without carbon tax on gas usage and trending lower electrical energy costs in Ontario.
Remember it a personal choice.
Hope this helps
Regards
Frank
London. Ontario, Canada.
Comment: Forgot to mention an energy audit was done on my house showing it's super efficient.
Comment: This was useful until you got off track on the green energy/federal kickbacks/etc. tangents.


How to estimate solar production on my roof, considering shade from trees

Question: I am considering solar panels, and I have some trees in the neighbor's yard immediately to the south of my house. What's a relatively accurate way to estimate annual electrical production from a given kW solar panel system that considers shade from the trees? I have gotten estimates from different installers, and they are both lacking in detail (I'm not sure if it considered the trees at all). Regardless, I would feel more confident in a third party tool or service to estimate production.
I have tried Project Sunroof, but I am not sure how recent their data is as it relates to the height of the trees.
Comment: How much and how heavy of shade do the trees give to your roof?  Heavy dark shade on most of the for most of the day, probably less than 5% of production.  Light shade on 10% of the roof for an hour, will probably not lose much.
Answer: I'd start out by taking pictures of your roof every half hour or so and scale them to get an accurate figure on how much sun hits your roof on a daily basis and where to place the panels. You'll have to get some historic information on your yearly days of sunshine to figure out the yearly sunshine. Then throw in your number of panels and the output per panel. This is how we used to do stuff before the internet.. :-)
Comment: There was a _before_ the internet? _Mouth hangs open in awe and wonderment..._
Comment: Nice idea. Is there an independent vendor I can hire to do this for me? I'm not confident I'd be doing the math right. If so, what are these sorts of vendors called so that I know what to search for?

I could have a solar installer do this, but that seems like an obvious conflict of interest if they're trying to sell me panels.
Comment: @MikeEng The problem is most "solar consultants and engineers"  are associated with installation companies so you're right back where you started.