What does it mean for a set to be open inside another set?

Question: I am taking an undergraduate analysis course, and last week we began to deal with connectedness. Before defining connectnedness, our instructor gave us an alterative definition of an open set. This is the definition:
Let ${U\subset S\subseteq \mathbb{R}^n}$. ${U}$ is open in ${S}$ if ${U = S\cap V}$, for some ${V}$ open in ${\mathbb{R}^n}$.
I don't understand for what it means for the set ${U}$ to be open in ${S}$, as opposed to it being open in ${\mathbb{R}^n}$. I'm trying to correlate this with the definition of an open set as given in Mathematical Analysis by Apostol, which is that a set ${A \subseteq \mathbb{R}^n}$ is open if ${\forall}$ ${x \in A}$, ${\exists}$ ${\epsilon > 0}$ ${|}$ ${B_\epsilon(x) \subseteq A}$.
Does it even make sense to correlate the two? Or is openness inside a set different from openness in general, and this new definition should be accepted as gospel?
Comment: This means a topology of a set can induce it's topology to a subset of it.
Comment: We need this definition in a setting like the following. Consider the unit circle $S$ in $\Bbb{R}^2$. The circle looks like something we would like to call connected, doesn't it? OTOH if $S$ were the union of two disjoint circles, say both centered at the origin but one with radius $1$ the other with radius $2$, then we would not want that union to be connected.
Comment: (cont'd) So we need a way of writing the union of two disjoint circles as a union of two relatively open sets (relatively open = open as a subset of $S$). Those two sets could be the intersection of $S$ with the open disk of radius $3/2$, and the intersection of $S$ with the open complement of the closed disk of radius $3/2$. So this definition gives us exactly what we need. Also observe that we can now call an open arc (endpoints excluded!)  of the unit circle an open subset of the unit circle even though that arc is certainly not open as a subset of $\Bbb{R}^2$.
Comment: The extra baggage we get is that when we discuss openness of a set we must lug around phrases like *open as a subset of $S$*. You can do quite a bit of multivariable calculus without this extra baggage. For example, we can discuss continuity of a function defined only on the unit circle using the metric alone. But it amounts to the same, and in a more general setting we want to discuss continuity using (relative) open sets.
Answer: The general problem is this: You have a set $X$ (in your case, $\mathbb R^n$), and you've defined a topology on that set, which essentially means, you've defined what it means for a set to be open in $X$ ($\mathbb R^n$). Note that a topology is always defined over some specific set (one of the rules is, the set itself is always open).
Now consider a subset $S$. You want to do topology on that subset, so you need to say what are the open sets on this subset.
Now, the obvious idea would be that a set is open in $S$ iff it is open in $X$. Unfortunately, this only works if $S$ happens to be open in $X$, but you want to do topology also on other subsets. For example, you might consider a straight line (a copy of $\mathbb R$ in $\mathbb R^n$; indeed, in that case you want the topology to be exactly the usual topology of $\mathbb R$, so all the results on $\mathbb R$ that you know are still valid.
But if just taking the open sets as is doesn't always work, what can we do then?
Well, if the open sets don't fit, we just make them to fit. What we do is to just cut away those parts of the open sets $V$ in $X$ ($\mathbb R^n$) that are outside $S$ (that's exactly what $S \cap V$ does), and declare the resulting sets the open sets of $S$. And it turns out that this works perfecly:

It always gives a valid topology, no matter which subset $S$ we consider.
Open sets in $X$ that already happen to be subsets of $S$ are still open as subsets of $S$.
If $S$ happens to be open in $X$, we get the very same result as the first idea.
If $X$ is a metric space (like $\mathbb R^n$) with the topology defined by its metric, then you get the same topology this way as you get when you first restrict the metric to $S$ (making $S$ a metric space in its own right), and then use that metric to define the topology of $S$. Note that this includes, but is not limited to, the example of straight lines in $\mathbb R^n$.
Answer: That's not an "alternative" definition of open set. It's the definition of the so-called subspace topology. It is the best way to define a topology (i.e. which sets are considered open) on $S$ which agrees with the topology of $\Bbb R^n$.
For instance, in $S=[0,1]\subseteq \Bbb R$ (where $\Bbb R$ has the standard topology), we have that $[0,\frac12)$ is considered open, because you can write it as the intersection between $S$ and some open interval, like $(-1,\frac12)$. Of course, something like $(\frac13,\frac23)$ is also open in $S$.
And yes, it makes some sense to correlate the two. A subset $U\subseteq S$ is open iff for any $s\in S$ there is an $\epsilon$ such that $B_\epsilon(s)\cap S\subseteq U$. Or you could consider $S$ as a metric space in its own right (with the metric inherited from $\Bbb R^n$), and in that case you can actually remove the "${}\cap S$" from the above (because the interpretation of $B$ changes), and it will truly look exactly the way your used to.
Comment: So is that the way open sets are defined? As members of a set with an associated topology? (I don't know any topology, just know a few definitions that I looked up while trying to understand the analysis lectures).
Comment: A topology is the collection of all open subsets of a set. In topology that's the _definition_ of an open set. A topological space is a set together with a topology on that set.


How to approach CSS composition/inheritance tricky case styling buttons?

Question: So I have two HTML buttons that have a class: .btn.
The CSS selector has a background-image: linear-gradient(...).
Now I want the buttons to differ only in the value of the background-image property, for instance one button's linear-gradient(...) to go from black to red and the other from black to blue.
How do I achieve this without having to create another selector repeating the content of the .btn? Having also in mind that I have other CSS selectors like .btn:hover and .btn:active that give the illusion of extending/removing the gradient when you hover on the button or leave it clicked.
I thought about taking the background-image:.... property out to another selector like .primary and .secondary which I will then apply to the buttons as a classes as well. But what about .btn:hover which "effect" depends on the actual color the given button has?
Here is what described: https://codepen.io/alejo4373/pen/RqmoWL
Any ideas or suggestions are appreciated, thanks!
Answer: Thanks to @ksav for the great suggestion on using custom properties. Unfortunately their solution doesn't use the power of custom properties. Since they cascade just like regular properties, we can keep all our styles in .btn, .btn:hover, and .btn:active, making them reliant on the custom properties, and just use .btn--primary and .btn--secondary to do nothing more than set the custom properties. Everything is centralized to exactly the class where it needs to be applied, and there's no duplication.

.btn--primary {
  --btn-color-top: #15FF86;
  --btn-color-bottom: #68BB42;
}

.btn--secondary {
  --btn-color-top: #fcbfc4;
  --btn-color-bottom: #811a08;
}

.btn {
  text-align: center;
  color: white;
  text-shadow: 0 0 4px rgb(96, 96, 96);
  border: 1px solid #adadad;
  border-radius: 4px;
  padding: 6px 12px;
  background-repeat: repeat-x;
  box-sizing: border-box;
  font-family: inherit;
  font-weight: 700;
  font-size: 14px;
  line-height: 1.42857143;

  background-image: linear-gradient(to bottom, var(--btn-color-top) 0, var(--btn-color-bottom) 100%);
}

.btn:hover {
  background-position: 0 -5px;
  background-color: var(--btn-color-bottom);
}

.btn:active {
  background-color: var(--btn-color-bottom);
  background-image: none;
  border-color: rgba(27, 31, 35, 0.5);
  box-shadow: inset 0 0.15em 0.3em rgba(27, 31, 35, 0.15);
}
<button class='btn btn--primary'> Primary </button>
<button class='btn btn--secondary'> Secondary </button>

This works because regardless of where the custom property is used (for example in the background-image property of .btn or the background-color property of .btn:active), the value that's resolved is whatever value is determined by normal css cascading rules -- even if that's a different rule from where it's referenced using var! So in the case of the primary button, the values of --btn-color-top and --btn-color-bottom are provided by the definitions in the .btn--primary block when they're called by var in the .btn and .btn:active blocks. And the same thing happens with .btn--secondary.
Note you could also save a class by using the primary styles as the default, and using btn--secondary as an override:

.btn {
  --btn-color-top: #15FF86;
  --btn-color-bottom: #68BB42;

  text-align: center;
  color: white;
  text-shadow: 0 0 4px rgb(96, 96, 96);
  border: 1px solid #adadad;
  border-radius: 4px;
  padding: 6px 12px;
  background-repeat: repeat-x;
  box-sizing: border-box;
  font-family: inherit;
  font-weight: 700;
  font-size: 14px;
  line-height: 1.42857143;

  background-image: linear-gradient(to bottom, var(--btn-color-top) 0, var(--btn-color-bottom) 100%);
}

.btn--secondary {
  --btn-color-top: #fcbfc4;
  --btn-color-bottom: #811a08;
}

.btn:hover {
  background-position: 0 -5px;
  background-color: var(--btn-color-bottom);
}

.btn:active {
  background-color: var(--btn-color-bottom);
  background-image: none;
  border-color: rgba(27, 31, 35, 0.5);
  box-shadow: inset 0 0.15em 0.3em rgba(27, 31, 35, 0.15);
}
<button class='btn'> Primary </button>
<button class='btn btn--secondary'> Secondary </button>
Comment: I tried to add some more explanation. Custom properties are maybe a bit unintuitive but once you get your head around them they're super powerful. Best way I've found to understand them is just playing around with them. I'm going to reorder the css a little bit too; the order doesn't matter at all.
Comment: This is exactly what I needed. Could you expand of whats going on here, it's not very clear to me yet. I read on CSS custom properties but I'm still trying to make sense of the way you used them here. Thanks!
Answer: I would recommend using a second class for the alternative colouring.Here's an example with the class .alt which changes the background gradient to blue. You haven't provided your :hover CSS but this appears to work nicely with the hover in either the red or blue case, without needing more than the single line of styling for .alt.
Let me know if your :hover code is more complicated and I can have a further play. If you're using SCSS then life is a bit easier as you can do something like the following:
.alt {

    background-image: linear-gradient(to bottom,black 0,blue 100%);

    &:hover {

       // Extra styling

    }

}

.btn {
  text-align: center;
  color: white;
  text-shadow: 0 0 4px rgb(96,96,96);
  border: 1px solid #adadad;
  border-radius: 4px;
  padding: 6px 12px;
  background-image: linear-gradient(to bottom,black 0,red 100%);
  background-repeat: repeat-x;
  box-sizing: border-box;
  font-family: inherit;
  font-weight: 700;
  font-size: 14px;
  line-height: 1.42857143;
}

.btn:hover {
  color: white;
  background-color: #68BB42;
  border-color: #adadad;
  background-position: 0 -5px;
}

.alt {
  background-image: linear-gradient(to bottom,black 0,blue 100%);

}

.btn:active {
  background-color: #279f43;
  background-image: none;
  border-color: rgba(27,31,35,0.5);
  box-shadow: inset 0 0.15em 0.3em rgba(27,31,35,0.15);
}

  <button class='btn'> Primary </button>
  <button class='btn alt'> Secondary </button>

Answer: If you are not using a preprocessor, consider using CSS custom properties to store your color variables.

.btn {
  --primary-top: #15FF86;
  --primary-bottom: #68BB42;

  --secondary-top: #fcbfc4;
  --secondary-bottom : #811a08;

  text-align: center;
  color: white;
  text-shadow: 0 0 4px rgb(96, 96, 96);
  border: 1px solid #adadad;
  border-radius: 4px;
  padding: 6px 12px;
  background-repeat: repeat-x;
  box-sizing: border-box;
  font-family: inherit;
  font-weight: 700;
  font-size: 14px;
  line-height: 1.42857143;
}

.btn:hover {
  background-position: 0 -5px;
}

.btn--primary {
  background-image: linear-gradient(to bottom, var(--primary-top) 0, var(--primary-bottom) 100%);
}

.btn--primary:hover {
  background-color: var(--primary-bottom);
}

.btn--secondary {
  background-image: linear-gradient(to bottom, var(--secondary-top) 0, var(--secondary-bottom) 100%);
}

.btn--secondary:hover {
  background-color: var(--secondary-bottom);
}

.btn:active {
  background-color: #279f43;
  background-image: none;
  border-color: rgba(27, 31, 35, 0.5);
  box-shadow: inset 0 0.15em 0.3em rgba(27, 31, 35, 0.15);
}
<button class='btn btn--primary'> Primary </button>
<button class='btn btn--secondary'> Secondary </button>

Updated codepen
Comment: You're not using the cascading action of custom properties, so you're not gaining anything by using them. Also the `active` state of your secondary button isn't working. Thanks for the reminder about custom properties though; see my answer.
Answer: If you do not want to create additional selectors you should just use the child selector ability in the CSS.
.btn:nth-child(1) { background:linear-gradient(#000, #0000ff); }
.btn:nth-child(2) { background:linear-gradient(#000, #ff0000);}

Check out this fiddle for the full answer, hope this helps.
http://jsfiddle.net/yash009/vgexcj86/
Comment: Thanks, but this does not address the fact that `.btn:hover` and `btn:active` depend on the color the button is initially colored to produce the appropriate effect. This correctly changes the initial color but as `.btn:hover`  was never modified and is not variable `.btn:hover` applies with the original/initial color


Explanatory multiple linear regression

Question: I have a data set consisting of 104 responses from an online survey (data have been cleaned) and I want to test the relation between 14 independent variables (12 variables about which hypothesis have been generated + 2 "control" variables) and 1 dependent variable. The hypotheses have been formulated after indications of the literature.
I chose to do a regression analysis even though the sample size in not optimal. After running the "lm()" function in R I got an F-statistic with a p-value below 5% indicating that at least one of the independent variables are related to the dependent variable. What is more by looking at the p-values of the independent variables, 2 of those are below 5%.
What I want to ask is: should I keep all the variables in the model and report the results, or should I re-run the analysis including only the 2 variables with the low p-values?. Or is it better to do variable selection using automated methods e.g. stepwise selection?
My goal is to draw causal conclusions (explanatory regression) about the relation between independent variables and the dependent variable, so using stepwise methods for variable selection does not seem appropriate for my case, as I am not aiming for predictions.
Comment: You can if your goal is to better explain the relationships, but not to perform additional tests.
Answer: Stepwise methods for model selection are generally considered to be a bad idea (see e.g., here), and they have been rendered defunct by modern methods.  These days it is usual to perform model selection either with some form of penalty method (e.g., LASSO or ridge regression) or by fitting all possible models and using partial F-tests to determine the appropriate number of model terms.  All of these methods can be done in R without too much difficulty, though the latter is only computationally feasible if you have a relatively small number of regressor variables (which you do).
All possible models: In your data you have $m = 14$ variables which gives $M \equiv 2^m =2^{14} = 16,384$ possible models.  (For simplicity I will assume that all models have an intercept term.)  It would be feasible to compute all possible models in this case and then narrow your model selection down to those models that minimise residual sums-of-squares for a fixed number of regressors.  To implement this method you can use the leaps package or use custom code here.  Although preferred to stepwise methods, it is worth noting that even this method is somewhat controversial, and some consider it to constitute 'dredging'.
LASSO and ridge regression: These regression methods automatically engage in variable selection by imposing a penalty function on the inclusion of regressors in the model (see e.g., here).  The objective function used in the model minimises the residual sum-of-squares plus a penalty applied to the coefficient estimators.  There is a tuning parameter that you can adjust to penalise inclusion of terms more or less heavily, and this will affect the number of terms in the model.

Explanatory multiple linear regression


Looping through and merging DataFrames with same index, same columns (however a few columns unique to each DataFrame)

Question: Description of task required
I use the following code to merge df and df1 (example data shown) and it works well for what I have needed. However, I need to loop over a large number of DataFrames (df2 for example, but will be df3, df4 etc.) and am not sure how to amend the code. I have DataFrames with the same index, same columns, however a few columns are individual to each DataFrame. I use the following code and it works well, but I wish to amend it so I can loop through df and df1, merge them together, creating requireddata but then repeat this where requireddata is merged with df2. The same logic would continue with requireddata merging with df3 and so on. Any help would be awesome!! :)
df
       ID    AA  TA  TL
Date
2001  AAPL   1.0  44  50
2002  AAPL   3.0  33  51
2003  AAPL   2.0  22  53
2004  AAPL   5.0  11  76
2005  AAPL   2.0  33  44
2006  AAPL   3.0  22  12

df1
       ID    AA  TA  ML
Date
2001  MSFT   3.5  44  12
2002  MSFT   6.7  33  15
2003  MSFT   2.3  22  19
2004  MSFT   5.5  11  20
2005  MSFT   2.2  33  43
2006  MSFT   3.2  22  23

df2 Example
       ID    AA  TA  PP
Date
2001  TSLA   3.3  48  18
2002  TSLA   6.3  38  18
2003  TSLA   2.6  28  18
2004  TSLA   5.3  18  28
2005  TSLA   2.3  38  48
2006  TSLA   3.3  28  28

Code used
dfdates['Date'] # this has dates required for index
df
df1

cols_to_use = df.columns.difference(df1.columns) #compare column difference df and df1
cols_to_use1 = df1.columns.difference(df.columns) #compare column difference df1 and df

dataframe = pd.DataFrame(columns = cols_to_use, index = df['Date']) #dataframe with columns in df1 but not in df
dataframe1 = pd.DataFrame(columns = cols_to_use1, index = df1['Date']) #dataframe with columns in df but not in df1

datatesting = pd.concat([dataframe, df], axis=1) #merge missing columns into df
datatesting1 = pd.concat([dataframe1, df1], axis=1) #merge missing columns into df1

diff = datatesting1.columns.difference(datatesting.columns) #check difference (is 0)
print (diff)
frames = [datatesting, datatesting1] #list of dataframes
requireddata = pd.concat(frames) #merge dataframes

Creates this:
       ID    AA   TA   TL  ML
Date
2001  AAPL   1.0  44  50  NaN
2002  AAPL   3.0  33  51  NaN
2003  AAPL   2.0  22  53  NaN
2004  AAPL   5.0  11  76  NaN
2005  AAPL   2.0  33  44  NaN
2006  AAPL   3.0  22  12  NaN
2001  MSFT   3.5  44  NaN  12
2002  MSFT   6.7  33  NaN  15
2003  MSFT   2.3  22  NaN  19
2004  MSFT   5.5  11  NaN  20
2005  MSFT   2.2  33  NaN  43
2006  MSFT   3.2  22  NaN  23

With looping code, would love for something like this:
       ID    AA   TA   TL  ML  PP
Date
2001  AAPL   1.0  44  50  NaN  NaN
2002  AAPL   3.0  33  51  NaN  NaN
2003  AAPL   2.0  22  53  NaN  NaN
2004  AAPL   5.0  11  76  NaN  NaN
2005  AAPL   2.0  33  44  NaN  NaN
2006  AAPL   3.0  22  12  NaN  NaN
2001  MSFT   3.5  44  NaN  12  NaN
2002  MSFT   6.7  33  NaN  15  NaN
2003  MSFT   2.3  22  NaN  19  NaN
2004  MSFT   5.5  11  NaN  20  NaN
2005  MSFT   2.2  33  NaN  43  NaN
2006  MSFT   3.2  22  NaN  23  NaN
2001  TSLA   3.3  48  NaN  NaN  18
2002  TSLA   6.3  38  NaN  NaN  18
2003  TSLA   2.6  28  NaN  NaN  18
2004  TSLA   5.3  18  NaN  NaN  28
2005  TSLA   2.3  38  NaN  NaN  48
2006  TSLA   3.3  28  NaN  NaN  28

Comment: IIUC, u r merging the dataframes into one. why not just concatenate the dataframes? pd.concat([df,df1,df2]). are there other rules you did not mention?
Comment: If I were you I will use a MultiIndex with Date and ID
Comment: If you want concat `pd.concat([df,df1,df2],sort = False)`
Answer: I believe columns difference is not necessary here, only use concat, columns are aligned correctly:
df = pd.concat([df,df1,df2], sort=False)
print (df)
        ID   AA  TA    TL    ML    PP
Date
2001  AAPL  1.0  44  50.0   NaN   NaN
2002  AAPL  3.0  33  51.0   NaN   NaN
2003  AAPL  2.0  22  53.0   NaN   NaN
2004  AAPL  5.0  11  76.0   NaN   NaN
2005  AAPL  2.0  33  44.0   NaN   NaN
2006  AAPL  3.0  22  12.0   NaN   NaN
2001  MSFT  3.5  44   NaN  12.0   NaN
2002  MSFT  6.7  33   NaN  15.0   NaN
2003  MSFT  2.3  22   NaN  19.0   NaN
2004  MSFT  5.5  11   NaN  20.0   NaN
2005  MSFT  2.2  33   NaN  43.0   NaN
2006  MSFT  3.2  22   NaN  23.0   NaN
2001  TSLA  3.3  48   NaN   NaN  18.0
2002  TSLA  6.3  38   NaN   NaN  18.0
2003  TSLA  2.6  28   NaN   NaN  18.0
2004  TSLA  5.3  18   NaN   NaN  28.0
2005  TSLA  2.3  38   NaN   NaN  48.0
2006  TSLA  3.3  28   NaN   NaN  28.0


Minimum Distance from an Arbitrary Point in Two Dimensions and a Line Using Lagrange Multipliers

Question: I need to find the minimal distance between a point $(x_0,y_0)$ and a line $ax+by = c$ for some constants $a,b,c ∈ ℝ$ using the Lagrange Multiplier Method.
Knowing the distance between two points, $(x_0,y_0)$ and $(x,y)$ is given by the following equation, I know that I need to minimise this equation.
$D = \sqrt{(x-x_0)^2 + (y-y_0)^2)}$
I also know that $D_{min}$ = $D^2_{min}$ , which will make it easier to use the Lagrange Method since I can "discard" the square root.
Then I let:
$f(x,y) = D^2 = (x-x_0)^2 + (y-y_0)^2$
Since this distance must be on the line $ax + by = c$ , I set my constraint:
$G(x,y) = ax + by - c = 0$
Then:
$∇f = <2x-2x_0, 2y-2y_0> ; ∇G =  < a, b >$
Using the Lagrange Method for some constant $λ$, we have:
$∇f = λ∇G \Rightarrow  < 2x-2x_0, 2y-2y_0 >  = λ < a, b>$
Eliminating $λ$, we have:
$y = y_0 + \frac ba (x-x_0)$
Plugging this into my original constraint, $G(x,y)$, we have:
$G(x,y) = ax + b(y_0 + \frac ba (x-x_0)) = 0$
Solving for $x$, we have:
$x = \frac { c+ \frac {b^2}{a}{x_0} - by_0 }{a + \frac {b^2}a}$
Plugging back in once more, we have:
$y = \frac ba \left( \frac { c+ \frac {b^2}{a}{x_0} - by_0 }{a + \frac {b^2}a} \right) - \frac ba{x_0} + y_0$
The Hessian seems to confirm that any critical point of $f$ will be a local maximum of $f$, but the overall complexity of the point I found is making me question whether I took the right approach.
If I plug back these coordinates into $D$, I should get the minimum distance.
$D = \sqrt{\left(\frac { c+ \frac {b^2}{a}{x_0} - by_0 }{a + \frac {b^2}a}-x_0\right)^2 + \left(\frac ba \left( \frac { c+ \frac {b^2}{a}{x_0} - by_0 }{a + \frac {b^2}a} \right) - \frac ba{x_0})^2\right)}$
This seems unnecessarily complicated and wrong. Where did I go wrong (if I did)?
Comment: Have you tried simplifying that horrendous-looking expression that you got for $x$ before proceeding? If nothing else, your solution is undefined when $a=0$.
Answer: Let me restart the problem from scratch.
You want to minimize
$$F=(x-x_0)^2+(y-y_0)^2+\lambda  (a x+b y-c)\tag 1$$ Computing the partila derivatives with respect to $x$ and $y$ and setting them equal to $0$ gives
$$\frac{\partial F}{\partial x}=2(x-x_0)+a \lambda=0 \implies x=x_0-\frac 12 a \lambda\tag 2$$
$$\frac{\partial F}{\partial y}=2(y-y_0)+b \lambda=0 \implies y=y_0-\frac 12 b \lambda\tag 3$$ Now
$$\frac{\partial F}{\partial \lambda}=ax+by-c=-\frac{1}{2} \lambda  \left(a^2+b^2\right)+a {x_0}+b {y_0}-c\tag 4$$
$$\frac{\partial F}{\partial \lambda}=0 \implies \lambda=\frac{2 (a {x_0}+b {y_0}-c)}{a^2+b^2}$$ So, from $(2)$ and $(3)$, after simplifications
$$x=\frac{b^2 {x_0}-a b {y_0}+a c}{a^2+b^2}\qquad \text{and} \qquad y=\frac{a^2 {y_0}-a b {x_0}+b c}{a^2+b^2}$$ making after simplifications
$$(x-x_0)^2+(y-y_0)^2=\frac{(ax_0+by_0-c)^2}{a^2+b^2}$$ which is the square of the well known distance of a point to a straight line.
Answer: There isn't anything wrong with what you did; you just made the algebra more difficult than it needed to become...
From your Lagrange equations, you arrive at  $ \ a(y - y_0) \ = \ b  (x - x_0) \ \ . $   The line you found has slope $ \ \frac{b}{a} \ ,  $ while the given line $ \ ax \ + \ by \ - \ c \ = \ 0 \ $ has slope $ \ -\frac{a}{b} \ . $  So it is worth noting here that you have incidentally demonstrated the proposition from classical geometry that the shortest distance from a line to a point external to the line is along a perpendicular to the line (the so-called "perpendicular distance").
We may alternatively express the result in this manner.  The given line may be parameterized using
$$ ax \ + \ by \ = \ c \ \ \rightarrow \ \ a·(X \ + \ bt) \ + \ b·(Y \ - \ at) \ = \ c $$
$$ \Rightarrow \ \ x \ = \ X \ + \ bt \ \ , \ \ y \ = \ Y \ - \ at \ \ , $$
with $ \ (X,Y) \ $ being a "reference point" on the line.  So a direction vector for the given line is $ \ \overrightarrow{v} \ = \ \langle \ b \ , \ -a \ \rangle \ \ . $  If we make $ \ (X \ , \ Y) \ $ the point on the given line that is closest to $ \ (x_0 \ , \ y_0) \ $ , so that the vector from the external point to that point is $ \ \langle \ (X-x_0) \ , \ (Y-y_0) \ \rangle \ $ , then your result may be understood as
$$ b(X-x_0) \ - \ a(Y-y_0) \ \ = \ \ 0 \ \ = \ \ \overrightarrow{v} \ · \ \langle \ (X-x_0) \ , \ (Y-y_0) \ \rangle \ \  , $$
this dot product telling us that these vectors are perpendicular.
As for the distance formula, if we don't need to have the actual coordinates of the closest point on the line, we can start with the distance-squared equation $ \ D^2 \ = \  (x-x_0)^2 \  + \ (y-y_0)^2 \ $ and use your result $ \ (y - y_0) \ = \ \frac{b}{a} ·  (x - x_0) \ $ to write
$$ \ D^2 \ = \  (x-x_0)^2 \  + \ \left( \frac{b^2}{a^2} \right) · (x-x_0)^2 \ \ = \ \ \left( \frac{a^2 \ + \ b^2}{a^2} \right) · (x-x_0)^2 \ \ . $$
The given line equation may be written as $$ \ ax \ + \ by \ = \ c \ \ \rightarrow \ \ a·(x \ - \ x_0) \ + \ b·( y \ - \ y_0) \ = \ c \ - \ ax_0 \ - \ by_0 \ \ .   $$
We may again apply your result to obtain
$$ a·(x \ - \ x_0) \ + \ b·( y \ - \ y_0) \ \ = \  \ a·(x \ - \ x_0) \ + \ b·\frac{b}{a} ·  (x \ - \ x_0)  $$
$$  = \ \  \left( \frac{a^2 \ + \ b^2}{a} \right) ·  (x \ - \ x_0) \ \ =  \ \  c \ - \ ax_0 \ - \ by_0 \ \ . $$
Upon squaring both sides of this equation, we find
$$    \left( \frac{(a^2 \ + \ b^2)^2}{a^2} \right) ·  (x - x_0)^2 \ \ = \ \ (a^2 \ + \ b^2)·D^2  \ \ = \ \  (c \ - \ ax_0 \ - \ by_0)^2  $$
$$ \Rightarrow \ \ D^2  \ \ = \ \  \frac{(c \ - \ ax_0 \ - \ by_0)^2}{a^2 \ + \ b^2} \ \ \Rightarrow \ \ D  \ \ = \ \  \frac{| \ c \ - \ ax_0 \ - \ by_0 \ |}{\sqrt{a^2 \ + \ b^2}}  \ \ . $$
[Should you require the coordinates of the closest point on the given line, the relations  $ \ \left( \frac{a^2 \ + \ b^2}{a} \right) ·  (X - x_0) \ \ =  \ \  c \ - \ ax_0 \ - \ by_0 \ $ and $ \ (Y - y_0) \ = \ \frac{b}{a} ·  (X - x_0) \ $ will deliver them.]


PySerial and Value Splitting Error

Question: I have encountered an error that has been seriously bothering me, and I have been unable to find a workaround. I have a python program that utilizes PySerial to import serial port values from a pulse oximeter. The problem is, when the function ser.readline() is invoked (in other words, when the python program is told to read values from the Arduino's serial monitor, the Arduino's serial values become distorted and the program returns a value unpack error.
Here is the python program.

import serial
import time
import pylab
import matplotlib.pyplot as plt
import numpy as np
import os
import csv

#time load
timestr = time.strftime("%Y_%m_%d")

#establish serial connection with ACM0
ser = serial.Serial('/dev/ttyACM0', 115200)

#establish variables
thymeL = [ ]
bpmL = [ ]
sp02L = [ ]
array_data = thymeL, bpmL, sp02L

#declare time
thyme = 1

#graph attributes
plt.ion()
plt.title("Pulse [BPM] & SPo2 [%] v. Time [s]", fontsize = "16")
plt.xlabel("Time [s]", fontsize = "14")
plt.ylabel("Pulse (red) [BPM] & SPo2 (blue) [%]", fontsize = "14")

while True:
    data_in = ser.readline()
    print data_in
    data_in = data_in.strip('\n')
    bpm,sp02 = data_in.split(",")

#convert string vals to float
    thyme = float(thyme)
    bpm = float(bpm)
    sp02 = float(sp02)

#print to terminal
    print "Time [s]: %s" % (thyme)
    print "HR [BPM]: %s" % (bpm)
    print "SPO2 [%%]: %s" % (sp02)
    print

#append vectors
    thymeL.append(thyme)
    bpmL.append(bpm)
    sp02L.append(sp02)

#print values to plot
    plt.scatter(thyme,bpm,color="red")
    plt.scatter(thyme,sp02,color="blue")
    plt.pause(0.1)
    time.sleep(0.05)

#update time
    thyme = thyme + 0.5

#write to .csv
    with open(full_path, 'w') as f:
    writer = csv.writer(f)
    for t, b, s in zip(array_data[0], array_data[1], array_data[2]):
        writer.writerow([t, b, s])

The most important snippet of all is:

while True:
    data_in = ser.readline()
    print data_in
    data_in = data_in.strip('\n')
    bpm,sp02 = data_in.split(",")

The Arduino program is as follows:
#include <PinChangeInt.h>
#include <eHealth.h>

int cont = 0;

void setup() {
  Serial.begin(115200);
  eHealth.initPulsioximeter();

  PCintPort::attachInterrupt(6, readPulsioximeter, RISING);
}

void loop() {

  char buffer[32]; // make sure buffer is large enough
  sprintf(buffer,"%d,%d \n",eHealth.getBPM(),eHealth.getOxygenSaturation());
  Serial.print(buffer);
  delay(500);

}

//=========================================================================
void readPulsioximeter(){

  cont ++;

  if (cont == 50) { //Get only of one 50 measures to reduce the latency
    eHealth.readPulsioximeter();
    cont = 0;
  }
}

So, the serial monitor is outputting values like this:
67,95
66,95
67,96

and so on.
But only when ser.readline() is invoked, the values become skewed and are unable to be unpacked by the split(',') function. In the following photo (1) and (2), you can see the distortion of the values right when the ser.readline() is called.
How can I re-word the python OR Arduino program in such a way to circumvent this distortion and allow the values to be split and unpacked without any errors?
Comment: Do the screenshots show the result of the printing of data_in at the python end, or something else? At the Arduino end, I can't see what calls loop - I'd expect to see a while (1) loop(); somewhere.
Comment: How do you know that ser.readline() is being called when (i.e. at the instant that) the data is apparently being corrupted?
Comment: Barny, thanks for your inquiry. The screenshots are the Arduino IDE serial monitor, which I had running as I initiated the python program. Indeed, the distortions of the values in the screenshots are exactly the instance at which ser.readline() is being called. I know this because I also instructed the program to print the ser.readline() before it attempts to split it. Every time that it fails (90% of the time), it will display the very line in the serial monitor that was corrupted (and thus could not be split).
Comment: It sounds like the problem is in the Arduino end. What calls loop()?
Comment: My reasoning is that unless you have invented a telepathic Arduino, or there is something else going on that you aren't mentioning, there is no way for the Arduino to know whether or not the python script is listening. Also, if the data from the Arduino has an extra comma then of course your current code will hiccup. That hiccup is caused by the corrupted serial data, not causing the corruption.
Comment: 1) You are likely correct that simply listening in on the serial monitor of the Arduino could not cause the corruption.

2) The Arduino does not "have" an extra comma. It is programmed to output one comma between two values, then print a new line and repeat. The appearance of an extra comma is the "skipping"/corruption problem that is described.

3) The issuance of void loop() is pretty straightforward in Arduino programs. Can you please be more specific as to what you mean by "What calls loop()?"
Comment: loop() is built-in function of the arduino and does exactly what it says -- loops consecutively. It does not need to be called.
Comment: It looks as though two things are trying to transmit from the Arduino asynchronously of each other. If loop() were being called from an interrupt routine as well as the usual Arduino call to it, that would cause intermixed data to be sent. Or is anything else in your code or the Arduino code trying to send serial data? BTW something is sending those extra characters, so 'no' is almost definitely the wrong answer to that question. Have you got any other interrupt routines active which might be doing something strange?
Answer: So is there any possibility that something else is calling loop() asynchronously, e.g. from an interrupt routine, which might try to simultaneously transmit another string of readings at the same time as the arduino's 'mainline' calling of the loop function? An aside: if the interrupt routine readPulsioximeter() got invoked while the mainline loop() function was between the calls to eHealth.getBPM() and eHealth.getOxygenSaturation() and updated the Pulsioximeter attributes, does your code guarantee to send values from the same reading out onto the serial port?

PySerial and Value Splitting Error


Need help implementing a Case Statement in OpenLayers for varying pin color based on location status

Question: In OpenLayers, I am trying to populate a world map of customer locations with pins that will vary in color based upon a certain status of that location. The status are numebred 0-4 and the first column in the referenced .CSV.
How can I change the color of the pin based on teh status?
import {Map, View} from 'ol';
import {Stamen, Vector as VectorSource} from 'ol/source';
import {fromLonLat} from 'ol/proj';
import WebGLPointsLayer from 'ol/layer/WebGLPoints';
const source = new VectorSource();
const client = new XMLHttpRequest();

client.open('GET', './data/FSI_Site_Data.csv');
client.onload = function () {
    const csv = client.responseText;
    const features = [];
    let prevIndex = csv.indexOf('\n') + 1; // scan past the header line
    let curIndex;
    while ((curIndex = csv.indexOf('\n', prevIndex)) != -1) {
        const line = csv.substr(prevIndex, curIndex - prevIndex).split(',');
        prevIndex = curIndex + 1;
        const coords = fromLonLat([parseFloat(line[4]), parseFloat(line[3])]);
        if (isNaN(coords[0]) || isNaN(coords[1])) {
            // guard against bad data
        continue;
    }
    features.push(
        new Feature({
            status: parseInt(line[0]) || 0,
            geometry: new Point(coords),
        })
        );
    }
    source.addFeatures(features);
};
client.send();

const Sites = new WebGLPointsLayer({
    source: source,
        style: {
            symbol: {
                symbolType: 'circle',
                size: 12,
                color: 'rgb(255, 0, 0)',
                opacity: .5,
            },
        },

});

new Map({
  target: 'map-container',
  layers: [
    new TileLayer({
      source: new Stamen({
        layer: 'toner',
      }),
    }),
    Sites,
  ],
  view: new View({
    center: [0, 0],
    zoom: 2,
  }),
});

I'm thinking a Case Statement will be the way to go but have been unable to figure out how and where to put it. This is my first run at Jave/JSON. My VBS/VBA ways are not helping me out one bit.  Thank you in advance for any help!
Comment: `palette` would be simpler if it works with feature properties - the only example I can find is in a test https://github.com/openlayers/openlayers/blob/main/test/rendering/cases/webgl-palette/main.js  In your case something like
`color: ['palette', ['get', 'status'], ['rgb(255, 0, 0)', 'rgb(0, 255, 0)', 'rgb(0, 0, 255)', 'rgb(255, 255, 0)', 'rgb(255, 0, 255)', 'rgb(0, 255, 255)']],`
Comment: `palette` seems to not woek inside a `symbol` declaration.  A slightly simpler alternative to `case` is `match`, for example
`color: ['match', ['get', 'status'], 0, 'rgb(255, 0, 0)', 1, 'rgb(0, 255, 0)', 2, 'rgb(0, 0, 255)', 3, 'rgb(255, 255, 0)', 4, 'rgb(255, 0, 255)', 'rgb(0, 255, 255)'],`
Comment: Thanks Mike! I have been trying to get pallette to work, no joy. Glad it's not just me. Will try the match out.
Answer: @Mike's comment solved this:

palette seems to not work inside a symbol declaration. A slightly simpler alternative to case is match, for example,
color: ['match', ['get', 'status'], 0, 'rgb(255, 0, 0)', 1, 'rgb(0, 255, 0)', 2, 'rgb(0, 0, 255)', 3, 'rgb(255, 255, 0)', 4, 'rgb(255, 0, 255)', 'rgb(0, 255, 255)']


Uniform Convergence of integrals

Question: If a sequence of functions $f_n$ are uniformly convergent in a given interval $[a,b]$ to a function $f$, are all riemann integrable, then the integral $$\int ^b_af_ndx\rightarrow\int^b_afdx$$ and $f$ is riemann integrable. but is the convergence uniform?
More precisely, is it true that $\forall \epsilon >0, \exists N:\forall n>N$,
$$\left| \int ^b_af_ndx-\int^b_afdx\right|<\epsilon$$
How would I prove it? Or is it obvious?
Comment: It does not really make sense to say that the convergence of the integrals is uniform. They converge, that's all.
Comment: Yes $\int_a^xg(t)dt$ is a function of $x$. But here, you only consider $\int_a^bg(t)dt$. Note that the bounds are fixed.
Comment: OK, but isn't integral itself a function given the primitive exists?
Comment: That makes it more clear. thanks.
Answer: This is tautological. By definition, $\int_a^b f_n$ tends to $\int_a^bf$ means the $\epsilon$ condition you are trying to prove. So if you already know the convergence, there is nothing to do. But actually, I suggest you prove that $\int_a^b f_n$ tends to $\int_a^bf$. It will be a good exercise to clarify these notions.
Hint: the integral is linear and
$$
|\int_a^bg(t)dt|\leq \int_a^b|g(t)|dt\leq (b-a)\sup_{t\in[a,b]}|g(t)|=(b-a)\|g\|_\infty.
$$
Comment: That's the uniform norm, $\sup_{t\in[0,1]}|g(t)|$. That $f_n$ converges uniformly to $f$ means precisely that the sequence $\|f-f_n\|_\infty$ tends to $0$.
Comment: I think for the proof you suggest, noticing $\|\int^b_a(f_n-f)dx\|\le\int^b_a\|f_n-f\|dx<\int\epsilon/(b-a)$ will suffice. Thank you, it was very helpful.
Comment: I wanted to prove the above result(uniform convergence) because I want exchange two limits before integral, e.g. when you have $\lim_{n\rightarrow\infty}\lim_{m\rightarrow \infty}\int^m_af_ndx$. my concern was exchange of possible if and only if integrals are uniformly convergent. But since they are numbers, can I take it for granted and exchange limits?
Comment: Yes. Since your bounds are fixed and you have uniform convergance of the integrands, you can swap limit and integral. That's exactly what $\int_a^bf_n\longrightarrow\int_a^bf$ says.
Answer: It doesn't make sense to speak of uniform convergence in this context. The integrals $$I_n := \int_a^b f_n(x) \, dx \qquad \qquad I:=\int_a^b f(x) \, dx$$ are real numbers which do not depend on another parameter (since $a,b$ are fixed). $$I_n = \int_a^b f_n(x) \, dx \to I=\int_a^b f(x) \, dx \qquad (n \to \infty)$$ is (by the definition of convergence of sequences) equivalent to the following statement: $$\forall \varepsilon>0 \, \exists N \in \mathbb{N} \, \forall n \geq N: |I_n - I| \leq \varepsilon \\ \Leftrightarrow \forall \varepsilon>0 \, \exists N \in \mathbb{N} \, \forall n \geq N: \left|\int_a^b f_n(x) \, dx - \int_a^b f(x) \, dx \right| \leq \varepsilon$$

Uniform Convergence of integrals


Extending to a local frame that agrees with given orientation

Question: Suppose that $(e_1, \ldots, e_k)$ is an oriented basis for $T_pM$ where $M$ is an oriented Riemannian manifold. In general, we know that we can extend to a smooth local frame $(X_1, \ldots, X_k)$ on $U\ni p$ such that $X_i\rvert_p = e_i$ for each $i$.
But can we further stipulate that $(X_1\rvert_q, \ldots, X_k\rvert_q)$ is oriented for each $q\in U$?
I have tried thinking of ways to shrink $U$ in a suitable way. I have played around with using the orientation form $\omega$ on $M$ and with first applying Gram-Schmidt to $(X_1, \ldots, X_k)$, but no progress.
Any help is much appreciated.
Answer: The local frame $(X_i)$ will agree with the chosen orientation form: if $\omega(e_1,\dots,e_k)>0$, then $\omega(X_1,\dots,X_k)>0$ in $U$, because $\omega(X_1,\dots,X_k)|_q=0$ would imply that the $X_i's$ do not form a basis of $T_qM$.
Comment: _"It's possible that an alternating tensor vanishes at a linearly independent tuple, right?"_ No, unless $\omega=0$ at that point. If it vanishes at a linearly independent tuple, it vanishes on any tuple.
Comment: Assume $\omega(e_1,\dots,e_k)=0$ for some basis $(e_i)$. Take any $k$-uple $v_j=a^i_je_i$. Then $\omega(v_1,\dots,v_k)=\det(A)\omega(e_1,\dots,e_k)=0$, where $A$ is the matrix with entries $a^i_j$.
Comment: This solution shows how to restrict $U$ appropriately, but I don't see why vanishing at $\omega \rvert_q$  would imply that the $X_i$ don't form a basis. It's possible that an alternating tensor vanishes at a linearly independent tuple, right?
Comment: You don't need to restrict $U$ in any way. $M$ is orientable and you have fixed an orientation form $\omega$. What I'm saying is that if $(X_i)$ is a frame inside $U$, then $\omega(X_1,\dots,X_k)$ doesn't change sign inside $U$, because if it does there is a point at which it must vanish, and at that point $(X_i)$ would not be a frame
Comment: Got it, thanks for clarifying!
Comment: @Federico : I don't know why $\omega(X_1, \dots, X_k) >0$ in $U$. Where $\omega(e_1, \dots , e_k)>0$ is used? And there is no possibility that $\omega(X_1, \dots , X_k) <0 $? Can you explain more in detail?


How to add the sum in a Webform Report?

Question: I would like to have the total sum of a number field in a report created with Webform Report.
How can I get the total sum of that column table?
Comment: I have found a way to do that. Instead of webform report. I can use Views and Views Aggregator Plus to display the submission data. I can put a function sum to the selected fields.
Comment: I would love to know more about this, Is there some link I can read more about it. Also you can answer your own question and accept it as well to close this question. Thanks.
Answer: Instead of using the Webform Report module, you can use Views and Views Aggregator Plus to display the submission data. You can use the aggregation function sum for the selected fields (to aggregate your webform submission results tables).
Credits: Waluyo Adi Siswanto.

How to add the sum in a Webform Report?


iDRAC6 Virtual Media native library cannot be loaded

Question: When attempting to mount Virtual Media on a iDRAC6 IP KVM session I get the following error:

I'm using Ubuntu 9.04 and:
$ javaws -version
Java(TM) Web Start 1.6.0_16
$ uname -a
Linux aud22419-linux 2.6.28-15-generic #51-Ubuntu SMP Mon Aug 31 13:39:06 UTC 2009 x86_64 GNU/Linux
$ firefox -version
Mozilla Firefox 3.0.14, Copyright (c) 1998 - 2009 mozilla.org
On Windows + IE it (unsurprisingly) works.
I've just gotten off the phone with the Dell tech support and I was told it is known to work on Linux + Firefox, albeit Ubuntu is not supported (by Dell, that is).
Has anyone out there managed to mount virtual media in the same scenario?
Answer: use a 32 bit jre. sun jre 1.6.0 update 16 worked fine for me, as did the 32bit openjdk.
Simply tell firefox to open the jnlp with the 32-bit javaws you install. You may need to run javaws /path/to/your/saved/jnlp to see if there are any 32 bit libraries missing as well. In my case it bitched that it couldn't find libXtst so I just did a yum -y install libXtst.i586 on Fedora 11 and I was working; obviously wiht Ubuntu commands will be a little different, but I'm more or less confident similar steps will get you working...
Answer: im seeing the same thing on an ibm server, and have seen posts for hp servers for the same; I have it working on a 32 bit linux system, but not on a 64-bit system. I rather suspect that a 32 bit library needs to be loaded. On Fedora (x86_64)/RHEL5(i386) here... i'll post back if I manage to figure out just what...
Answer: On Fedora 12 x86-64, you can use the following workaround.  Remove the existing OpenJDK and install the i686 version:
 # yum remove java-1.6.0-openjdk-1:188.8.131.52-33.b16.fc12.x86_64
 # yum install java-1.6.0-openjdk-126.96.36.199-31.b16.fc12.i686

Answer: Unfortunately for me using 32bit java didn't help. But I found this one in iDRAC7_1.66.65_A00_ReleaseNotes.txt:

* Issue 53:
  On servers with RHEL 5.x operating system, after upgrading to Java 1.7.0,
  attempting to launch the Java Virtual Media, Virtual Console, or Boot Capture
  plug-in results in an "Unable to load Native Library" message, and the Virtual
  Media is disabled.
  This issue is caused by the Security Enhanced Linux(SELINUX) "allow_execmod"
  policy being set to "off", preventing the Virtual Media operation.

  Resolution:
  set the 'allow_execmod'  policy to 'on' by running the following command:
  setsebool -P allow_execmod on

  Versions/Systems Affected
  All versions of iDRAC on 12th generation Dell PowerEdge Servers.

Thad didn't help me either, but maybe it will help somebody else.


How to get list as a value from another model of a serializer key's value in DRF serializer?

Question: Models:
class SellerHub(BaseModel):
    name = models.CharField(blank=False, max_length=255)
    address = models.TextField(
        blank=True,
    )
    status = models.BooleanField(default=True)
    contact_person = models.CharField(blank=False, max_length=255)
    hub_type = models.ForeignKey(SellerHubType, on_delete=models.CASCADE)
    latitude = models.DecimalField(
        max_digits=22, decimal_places=16, blank=True, null=True
    )
    longitude = models.DecimalField(
        max_digits=22, decimal_places=16, blank=True, null=True
    )
    image = models.ImageField(
        default="default_images/default_seller_hub.png",
        upload_to=seller_hub_image_path,
    )
    status = models.BooleanField(default=True)

    class Meta:
        app_label = "seller_hub"

    def __str__(self):
        return self.name

class SellerHubPhone(BaseModel):
    seller_hub = models.ForeignKey(SellerHub, on_delete=models.CASCADE)
    phone = PhoneNumberField(blank=False, max_length=255)
    status = models.BooleanField(default=True)

    def __str__(self):
        return f"{str(self.phone)} for {self.seller_hub.name}"

Serializers:
from rest_framework import serializers
from seller_hub.selectors import seller_phone
from phonenumber_field.serializerfields import PhoneNumberField

class SellerHubPhoneSerializer(serializers.Serializer):
    phone = PhoneNumberField()

class SellerHubSerializer(serializers.Serializer):
    id = serializers.IntegerField()
    name = serializers.CharField(max_length=255)
    address = serializers.CharField()
    image = serializers.ImageField()
    phone = serializers.SerializerMethodField("get_phone")

    def get_phone(self, obj):
        hub_phone = seller_phone(obj)  # Returns a queryset of SellerHubPhone objects
        print("Phone: ", hub_phone)
        serializer = SellerHubPhoneSerializer(hub_phone, many=True)
        return serializer.data

This is my current output:
"data": [
    {
        "id": 1,
        "name": "Test Seller Hub",
        "address": "Test seller Address",
        "image": "http://127.0.0.1:8000/media/default_images/default_seller_hub.png",
        "phone": [
            {
                "phone": "+8801777777777"
            },
            {
                "phone": "+491783379222"
            }
        ]
    }
]

Expected Output:
"data": [
    {
        "id": 1,
        "name": "Test Seller Hub",
        "address": "Test seller Address",
        "image": "http://127.0.0.1:8000/media/default_images/default_seller_hub.png",
        "phone": [
             "+8801777777777",
             "+491783379222"
        ]
    }
]

Here SellerHub might have multiple phone numbers, so I am using SellerHubPhone and adding the SellerHub as a foreign key. I want to get all the phone numbers of a SellerHub using The SellerHubPhone Model object and the output should look like the expected output JSON.
How to get the expected output by changing the serializer?
Answer: You can return a list of phone, I am not sure but this can help you
def get_phone(self, obj):
    hub_phone = seller_phone(obj)  # Returns a queryset of SellerHubPhone objects
    print("Phone: ", hub_phone)
    serializer = SellerHubPhoneSerializer(hub_phone, many=True)
    return [x.phone for x in serializer.data]

Answer: After getting the idea from @mecaTheclau answer I tried this solution. This one worked for me. As the returning objects were OrderedDict, I had to change his solution.
  def get_phone(self, obj):
        hub_phone = seller_phone(obj)  # Returns a queryset of SellerHubPhone objects
        print("Phone: ", hub_phone)
        serializer = SellerHubPhoneSerializer(hub_phone, many=True)
        return [next(iter(x.values())) for x in serializer.data]


Help understanding an explanation about minimum description length principle

Question: I'm reading about MDL principle and my problem is on a book called: "Guide to intelligent data analysis", 2nd edition page 106.
I have added here a picture of the page I'm having trouble with. Could someone decode what the author is saying in the highlighted area:

It seems abstract and confusing...I get confused when he says that the original data is contained in the decompression rule itself?!...huh?... and because of that I don't understand the rest of it :/
Thank you for any help
Comment: With *decompression rule* the author means *decompression program* or *algorithm*. Otherwise this seems to be written perfectly clear.
Comment: not to me it isn't :) I need better details
Comment: Thanks for sharing. The perspective in the text you shared is very interesting.
Answer: Suppose we had a data set. Something like this
1   M   17  B
2   F   23  W
3   M   19  A
....

where the first variable is ID, second is sex, third is age and fourth is race ethnicity.
then, we create a code where 1 means
1   M   17  B
2   F   23  W
3   M   19  A
....

and then we say "Our data set is 1, using our code".
This shifts all the complexity from the actual code number to the code algorithm. It's sort of silly, and the author is saying it is one extreme. The other extreme is to list the full data set.
In between.... well, that's the tricky part. We could say "The data has XXX men, XXX women, average age XXX, and is mostly White"; but there are a ton of other reasonable representations.


Winding number of a loop

Question: I am reading a paper and unfortunately I have found a problem.
I have a continuos map $[0,1]\times [0,1]\to U_q(\mathbb{C})$, where $U_q(\mathbb{C})$ are unitary matrices. We can consider the map $(\lambda,\mu)\to det(Y_{\lambda,\mu})$ obtained by the restriction to the boundary of the square $[0,1]\times [0,1]$. Now the author says "Since $(\lambda,\mu)\to Y_{\lambda,\mu}$ is continuos on $[0,1]^2$, the winding number of the restriction of $(\lambda,\mu)\to det(Y_{\lambda,\mu})$ to the boundary must be zero". Unfortunately, I don't understand why the winding number is $0$. Can anyone help me?
I thank you in advance for the help.
Comment: Does the word "homotopic" mean anything to you yet?
Answer: Let us think of $S^1$ as $S^1 = \{ z \in \mathbb{C} \, | \,|z| = 1 \}$. If you have a continuous map $f \colon S^1 \rightarrow S^1$ that extends to a map $\tilde{f} \colon D \rightarrow S^1$, where $D = \{ z \in \mathbb{C} \, | \, |z| \leq 1 \}$ is the closed unit disc, then the extension $\tilde{f}$ provides a homotopy $F_t \colon [0,1] \times S^1 \rightarrow S^1$ defined by $F_t(\theta) = \tilde{f}(te^{i\theta})$ from $F_0 \equiv \tilde{f}(0)$ to $F_1 = f$. Thus, $f$ is homotopic to a constant map and so the winding number of $f$ is zero. Alternatively, if you have a map $\tilde{f} \colon D \rightarrow S^1$, then $f(e^{i\theta})$ has winding number zero. Now replace $D$ with $[0,1]^2$.
Comment: @ levap: Thank you very much for the answer. Now everything is clear.

Winding number of a loop


Eigen value minimization-Proof

Question: The two minimization problems below are equivalent:
$\min\{\mathrm{trace}(AX^TBX): XX^T=I_n\}=\min\{\mathrm{trace}(AQ^T\tilde{B}Q): QQ^T=I_m\}$, where $A,\tilde{B}$ and $Q$ are square matrices of the same size, $A,B$ are also p.s.d and $X$ is a $m \times n, (m >n) $ rectangular matrix.
The solution to this latter minimization problem is well known: the extrema of the trace are the extrema of $\{\sum_{i=1}^m\lambda_i(A)\lambda_{\sigma(i)}(\tilde{B}): \sigma\in S_m\}$, where $\lambda_i(M)$ denotes the $i$-th eigenvalue of a real symmetric matrix $M$ and $S_m$ is the symmetric group of order $m$.
Suppose $A$ and $\tilde{B}$ are orthogonally diagonalized as $A=U\Lambda U^T$ and $\tilde{B}=V\Sigma V^T$, where $\Lambda = \mathrm{diag}(\lambda_1(A), \lambda_2(A), \ldots, \lambda_m(A))$ contains the eigenvalues of $A$ arranged in ascending order and $\Sigma$ is analogously defined, but the eigenvalues are arranged in descending order. That is, if $\lambda_1(B),\ldots,\lambda_n(B)$ are arranged in ascending order, and for $\Sigma=\mathrm{diag}\left(\lambda_n(B),\ldots,\lambda_1(B),0,\ldots,0\right)$
Then am looking for a 'detailed proof' that the minima is reached at an $X^*$ given by:
\begin{align}
X^* &= VU^T \begin{bmatrix}I_n\\ 0_{(m-n)\times n}\end{bmatrix}.
\end{align}
for my better understanding.
Answer: It is a bit easy to show for the square case. For the rectangular case, it becomes cumbersome due to heavy notational stuff. You need to have the following inequality for the positive (semi) definite matrices
\begin{align}trace(AB)\geq\sum_{i=1}^{N}\alpha_i \beta_{N-i+1}\end{align}
where $\alpha_ 1\geq\alpha_ 2...\geq\alpha_ N$ are the eigenvalues of $A$ and $\beta_ 1\geq\beta_ 2...\geq\beta_ N$ are eigenvalues of $B$. The lower bound is achieved when $A$ and $B$ commute and the corresponding eigenvalues are in order (ie ascending for $A$ and descending for $B$).
Now $X$ is orthogonal, Define $\hat{B}=X^{H}BX$. Note that $B$ and $\hat{B}$ will have same eigenvalues. This implies $trace(A\hat{B})\geq \sum_{i=1}^{N}\alpha_i \beta_{N-i+1}$. Thus it is enough to design $X$ such that we can attain the (universal) lower bound for every $X$. This is possible only if $X=VU^{H}P$. Here $U$ and $V$ comes from eigen decomposition of $A$ and $B$. $P$ is a suitable permutation (which is orthogonal) matrix which rearranges the eigenvalues. Since you have already assumed the required order, it should be identity.
Comment: also- any views on if the objective function considered in this question is Convex-as in is this solution a point where a  global minima is reached?
Comment: Note that $trace(AX^{T}BX)=vec(X)^{T}(A\otimes B)vec(X)$. Since $A$ and $B$ are positive (semi)definite, this implies the objective function is a convex quadratic. But note that this doesn't imply the optimization is itself convex as the orthogonality constraint is not convex. But in this case, due to the constraint, whatever $X$ you come up with (which obeys the constraint), the inequality always holds. For any other $X$ (which obeys the constraint), you can't reduce the objective value than the lower bound. Hence, it should be the solution

Eigen value minimization-Proof


How get values from radio button in jsp and pass them to java servlet

Question: I have problem with passing values from jsp to java servlet.
My class Student has follow fields: id, firstName, lastName, precenseStatus.
Field precenseStatus is empty and a want to set "Obecny", "Nieobecny" or "Spóźniony" string value at it in jsp.
I pass to jsp list of Student object (students).
jsp:
<form action="updatePrecensesServlet" method="post">

                    Imię
                    Nazwisko
                    Obecność

                <c:forEach var="student" items="${students}">

                        <c:out value="${student.firstName}"  />
                        <c:out value="${student.lastName}" />

                            <form role="form">
                                <c:if test="${student.precenseStatus == 'Obecny'}">

                                        <input checked type="radio" name="${student.precenseStatus}" value="Obecny"/>Obecny

                                        <input type="radio" name="${student.precenseStatus}" value="Nieobecny"/>Nieobecny

                                        <input type="radio" name="${student.precenseStatus}" value="Spóźniony"/>Spóźniony

                                </c:if>
                                <c:if test="${student.precenseStatus == 'Nieobecny'}">

                                        <input type="radio" name="${student.precenseStatus}" value="Obecny"/>Obecny

                                        <input checked type="radio" name="${student.precenseStatus}" value="Nieobecny"/>Nieobecny

                                        <input type="radio" name="${student.precenseStatus}" value="Spóźniony"/>Spóźniony

                                </c:if>
                                <c:if test="${student.precenseStatus == 'Spó?niony'}">

                                        <input type="radio" name="${student.precenseStatus}" value="Obecny"/>Obecny

                                        <input type="radio" name="${student.precenseStatus}" value="Nieobecny"/>Nieobecny

                                        <input checked type="radio" name="${student.precenseStatus}" value="Spóźniony"/>Spóźniony

                                </c:if>
                                <c:if test="${student.precenseStatus != 'Obecny' &&
                                              student.precenseStatus != 'Nieobecny' &&
                                              student.precenseStatus != 'Spó?niony'}">

                                          <input type="radio" name="${student.precenseStatus}" value="Obecny"/>Obecny

                                          <input type="radio" name="${student.precenseStatus}" value="Nieobecny"/>Nieobecny

                                          <input type="radio" name="${student.precenseStatus}" value="Spóźniony"/>Spóźniony

                                </c:if>
                            </form>

                </c:forEach>

        <button name="students" value="${student}" scope="request" type="submit" class="btn btn-success">Zatwierdź</button>
    </form>

updatePrecensesServlet doPost():
System.out.println(request.getParameterValues("students").toString());

or
System.out.println(request.getParameter("students").toString());

Not works :/
Student{ID=2, firstName=YYY, lastName=XXX, precenseStatus=null}

Comment: Those radio buttons doesn't have a name of `students`. Those radio buttons have a name of `${student.precenseStatus}`. Why? What exactly are you expecting?
Answer: I pass follow list:
Student{ID=2, firstName=YYY, lastName=XXX, precenseStatus=null}
Student{ID=3, firstName=AAA, lastName=FFF, precenseStatus=null}
Student{ID=4, firstName=BBB, lastName=DDD, precenseStatus=null}
Student{ID=5, firstName=CCC, lastName=WWW, precenseStatus=null}

I expecting that I've got list of Students with set precenseStatus field.
for example:
Student{ID=2, firstName=YYY, lastName=XXX, precenseStatus=Obecny}
Student{ID=3, firstName=AAA, lastName=FFF, precenseStatus=Nieobecny}
Student{ID=4, firstName=BBB, lastName=DDD, precenseStatus=Obecny}
Student{ID=5, firstName=CCC, lastName=WWW, precenseStatus=Spóźniony}

But now is still:
Student{ID=2, firstName=YYY, lastName=XXX, precenseStatus=null}
Student{ID=3, firstName=AAA, lastName=FFF, precenseStatus=null}
Student{ID=4, firstName=BBB, lastName=DDD, precenseStatus=null}
Student{ID=5, firstName=CCC, lastName=WWW, precenseStatus=null}

I've selected all radio buttons in jsp of course. I don't left those radio buttons empty.
Comment: From where r u populating ${students} ?
Comment: According to me, you are not able to populate a {Student} in list of students
Comment: I populate list of Student (students) in servlet, then I pass this list to jsp. I want to supplement this on jsp page and response to post method in another servlet
Comment: A lot of radio buttons on one jsp page is a problem.


Mule 4 Database Insert into Oracle Table with Date field issues

Question: Am using Mule 4 ( runtime 4.3 ) running in anypoint studio ( 7.15.0 )
Am trying to do a simple database insert ( Database is Oracle )
Here is the relevant code for insert :
    <db:insert doc:name="Insert emp record"  config-ref="Emp_Database_Config" >
                <db:sql ><![CDATA[ insert into emp ( emp_id, emp_name, start_date ) values ( :empId, :empName , TO_DATE(:startDate, 'YYYY-MM-DD') ) ]]></db:sql>
                <db:input-parameters ><![CDATA[#[%dw 2.0
output application/java
---
{
    'empId' : vars.empId,
    'empName' : vars.empName,
    'startDate' : '3000-01-01'
}]]]></db:input-parameters>

</db:insert>

Here start_date is a Date field in emp table.
Am trying to do a date insert using following code:
TO_DATE('3000-01-01', 'YYYY-MM-DD')

However it fails at runtime with following error:

ERROR 2023-12-02 20:10:45,224 [[MuleRuntime].uber.08:
[emp-sys-v1_to_checkin].process-emp-flow.BLOCKING @7d642671]
org.mule.db.commons.shaded.internal.domain.executor.AbstractExecutor:
An SQLException exception has occurred. java.sql.SQLException: An
SQLException was provoked by the following failure:
java.lang.IllegalArgumentException: Timestamp format must be
yyyy-mm-dd hh:mm:ss[.fffffffff]

Google search provided this mulesoft help article:
https://help.mulesoft.com/s/article/Database-Connector-Timestamp-format-must-be-yyyy-mm-dd-hh-mm-ss-fffffffff-Oracle-DB-Mule-4
Based on this tried appending  as :
'startDate' : '3000-01-01'  ++ " 00:00:00.00000"

However then started getting this error:

'ORA-01858  a non-numeric character was located where a digit was
expected'

Database Connector - Mule 4 1.14.6
Database table is in Oracle and in the table 'emp' , the field 'start_date' is a Date field
If I do a direct database insert via sql plus I can do an insert without issues using :
TO_DATE('3000-01-01', 'YYYY-MM-DD')

Not sure why such a simple activity is failing due to Date issues ....
Edit1:
am aware that Date does hold time
Edit2:
also tried to send data as application/java and still encountering this issue
Answer: Try to match the query format with the argument format:
TO_DATE(:date, 'YYYY-MM-DD HH:mm:ss')

'startDate' : '3000-01-01 00:00:00'

Answer: I also faced the same error during inserting date field in oracle db.

An SQLException was provoked by the following failure:
java.lang.IllegalArgumentException: Timestamp format must be
yyyy-mm-dd hh:mm:ss[.fffffffff]

@aled answer will definitely will work for you but the below format worked for me. See if it helps for you
%dw 2.0
output application/java
---
'startDate' : ("'" ++ (|3000-01-01| as Date{format: "yyyy-MM-dd"} as String{format: "dd-MMM-yyyy"}}) ++ "'")

'startDate' : '01-Jan-3000'

Comment: Just a suggestion, for a fixed date replace `"3000-01-01" as Date{format: "yyyy-MM-dd"}` by a Date constant `|3000-01-01|` to avoid an unneeded conversion. If the value is a dynamic string then the conversion to Date is required.


How to add URL to an image in Fabric.js?

Question: Using object.on('selected', function() {}), I can get the image object that is clicked. My intent is to redirect to an URL by clicking it. How can I add an URL to an image, or more general, to an object in Fabric.js?
Answer: You can simply navigate to the target page in the selected event handler:
object.on('selected', function() {
    window.location.href = "http://www.example.com/";
})

Comment: @Henry What do you mean by save? You can just do `object.associatedUrl = 'http://www.example.com/'` and then in the selected handler do `window.location.href = this.associatedUrl;` if that's what you mean.
Comment: I want to save the URL in the object.
Comment: Do you want to save the canvas on database?
Comment: This works well, thank you! Two things that helped me implement: (1) the object has to be selectable, so if you have `journalName.selectable = false` then it won't work, obviously, and (2) it has to go before you `canvas.add(object)`.


Help identify the chords in bar 1,5,6 of schubert waltz op9 no31

Question: Please help identity the chords. I couldn't form a chord!
I
Comment: Welcome! I wonder whether you're trouble is that there are "so many notes" in those measures, and how to simplify them down to chords. I think this can be a valid question, but to get the right answer, please use the "Edit" button to explain a bit more about the trouble you're having.
Comment: Sorry, but questions such as this are disallowed for this site. Please read the Help Centre to understand how you could re-phrase the question so it doen't get closed.
Comment: In addition to @Tim's comment that questions like "what chord is this" are off topic here, just checking to clarify if this is part of a class homework assignment. Homework assistance is also off-topic here. If you're asking for some other reason, including that in your question will help get the best answers for you.
Answer: Here are some points that might help clear up confusion:

A measure might contain more than one chord.
A chord might be "spread out" across multiple octaves or beats. For instance, the first beat has two different Es and two Gs in different octaves, and there's a C falling on the second half of the beat. These could all be consolidated and considered together.
There might be "extra notes" that don't belong to a chord. If we're trying to find a "simple," broad analysis, we can ignore these and look for the "main idea" of the chord.

For instance, in m. 1, the very first beat has all the notes for a nice C major triad. These are also the notes of beat three. Beat two is simply made of some half-step "neighbors" of these notes; it's just a type of ornamentation. We move onto these neighbors and then right back onto CM; nothing significant has happened; for basic analytical purposes we can ignore the ornament and just call the measure CM.
Think about this idea and look at mm. 5 and 6 as if they were one measure.


How do you test where a character is in a text based game in C#

Question: I am new to C# programming, and was wondering if i am creating a text based game with 2 rooms, and the player can move between the two rooms (but not around inside them) how do you test which room the player is in? I have tried to use an if else statement, but i am not sure how to get it to go "if not in north room go there when 'Go North' is input"
Comment: what you mean room? maybe u use two different forms?
Comment: post some code chunk so that we can get what you are doing
Answer: Without seeing your code, I guess the easiest way to do that is to have a "location" property in for your characters.
<code>class player
{
    string location = "Room 1";
    ...
}
</code>
and then just update the location every time you move the character


How to get insights from an amalgamation of histograms

Question: I want to see how the age of road traffic accidents victims change throughout the year. Ive done this by amalgamating lists of the ages of victims from 05-16 and created a histogram for each year. Ive tried plotting them all in on one plot using matplotlib in python however the result hard to pull any insights out of.
For python users, ive tried different alpha values to change the opaqueness of each plot and 0.1 shows the best results (image attached) but even then its hard to discern any conclusions.
Comment: 12 years of daily data is a bit much .. Why don't you post the last 5 years of daily data in a csv file and also indicate what country the data is from as holidays/known events may have an effect.
Answer: This is probably a case for small multiples, showing together in a panel many small plots, each showing some aspect.  The structure of your data is not entirely clear, maybe you could show some snippet, or better, post the data (or a link) here?
You say you want to study variation "throughout the year" but then say you show histograms for many different years ... which answers some other question. If you have monthly data, you might show a matrix of 12 histograms, one for each year. If in addition you want to see trends over years, you might make one panel of 12 histograms for each year, if there are not to many.  But please clarify the question, so maybe we can come up with something better.  For an example (in another context) of what I mean with small multiples, see one of the answers here:  Data Visualization: Alternatives to Choropleth maps for spatial data and statistical graphics  Another example can be found here:  Standard deviation visualization for different time series  or  Visualising successive proportions must be some way of making such plots in python, but I cannot tell how as not using python myself.
By the way, your idea of overplotting the histograms and using transparency to see them all, is interesting, but as you have seen yourself, maybe to clever.


async x await x Future

Question: Para que servem as keywords async e await no Flutter?
Algumas dúvidas que tenho são:
1 - Elas pertencem ao Flutter ou ao Dart?
2 - Porque colocar o async no final do seguinte método?
 void _method(TodoItem item) async { }

3 - Porque colocar o await no inicio da chamada do seguinte método?
_results = await DB.query(TodoItem.table);

4 - Qual diferença entre async e await?
5 - Onde o Future entra no meio disso tudo?
Comment: Caramba, esse site é só para profissional!? Peguem leve, parece já vão negativando e votando para fechar sem mesmo ler a pergunta
Comment: @rubStackOverflow ontem teve um discussão sobre isso que tu comentou em uma outra pergunta hahahaha Ta difícil, principalmente a tag Flutter (Parece ser uma tag problema), ta certo que muitas perguntas de Flutter a galera nem se da ao luxo de entender como se fazer uma pergunta aqui, mas não acho válido saírem dando downvote em todas... Ainda mais essa que agrega conhecimento ao site (Como dizem que deve ser).
Comment: @MatheusRibeiro eu vi, `downvote` está banalizado.
Answer: Dart, assim como outras linguagens, trabalha com funções síncronas e assíncronas.
Explicarei de uma forma mais grosseira, mas ai você pesquisa mais sobre:

Função Síncrona
bool tarefaFinalizada() => tarefas[0].finalizada == true;
É uma função que quando a execução do seu sistema chegar nela, ele esperará tudo que estiver dentro dela ser executada, para continuar fazendo o que precisa.
Função Assíncrona
Future<bool> getTarefas() async => await http.get('tarefas');
É uma função que o sistema executa, mas não espera seu término, ele executa esta função e continua fazendo o que precisa.

Ou seja, a função síncrona, você espera a resposta da sua função para executar determinada ação.
Future
Essa função vai retornar um dado do futuro ~~Cuidado com a Skynet
Quando você usa funções assíncronas, você utiliza o Future para indicar que aquela função é assíncrona, ou melhor, que ela vai retornar um valor no "futuro", como por exemplo, vai retornar os valores daqui 5 segundos.
await (Traduzindo pra BR -> "Aguarde")
Espere aqui até que a função termine e pegue o resultado dela.
Você utiliza o await quando faz chamada que retornem um future. Isso faz com que o sistema espere a chamada da função assíncrona terminar para que execute o resto das coisas. Ou seja, transforma uma função assíncrona em síncrona.
Sempre que utilizar uma função que retorne um Future você terá que, em algum momento, adicionar o await para receber o valor correto, caso contrário irá receber sempre um Future<SeuTipo>.
async
Essa função é assíncrona e em algum momento dela talvez eu precise esperar para pegar algum dado.
Você precisa usar o async nas funções onde você vai utilizar o await para indicar que o método vai lidar com funções assíncronas de forma síncrona.
Você pode ler um pouco mais aqui nesses links:

Asynchronous programming: futures, async,
await (Em inglês)
When to use async, await, then and Future in
Dart?
(Em inglês)

Meu conselho...
Estude mais sobre programação e principalmente estude mais sobre a
linguagem Dart e o framework Flutter!
Flutter é sim um framework rápido e prático, mas para quem já entende um pouco sobre programação. É melhor começar já entendendo bem e fazendo as coisas corretamente, do que ir remendando na medida que aprende... Então treine, faça testes, LEIA sempre a documentação do Flutter que é muito bem feita e organizada.
Answer:
Sempre que utilizar uma função que retorne um Future você terá que, em algum momento, adicionar o await

Isso está incorreto, a utilização de uma instância que retorna o valor Future não implica na necessidade de utilização posterior do await.
Comment: Seja bem-vindo ao Stack Overflow em Português. Por favor, não utilize o campo de respostas para fazer comentários sobre outra resposta; para isso você pode utilizar o próprio campo de comentários na resposta.

async x await x Future


How to handle singular jacobian in interior point algorithm?

Question: I am trying to implement a qp solver using interior point algorithm (Mehrotra Predictor-Corrector). In computing the affine directions, the Jacobian can be semidefinite (matlab warns in solving the linear system), what should I do for these cases? Will pseudo-inverse work? Thanks!
Answer: This is a well-known problem in primal-dual interior point methods. In practice, one typically sets the corresponding entry in the Cholesky factor to a large positive value (effectively forcing the corresponding entry in $\Delta y$ to zero.)
You can find a good discussion of this issue and various methods for dealing with the problem in Chapter 11 of Stephen J. Wright's book, Primal-Dual Interior-Point Methods.


How to enumerate running/open apps in app order with applescript?

Question: My end goal is to determine the most-recently-used web browser. I.e., a user may have both Safari and Firefox running, but which were they using most recently?
And so, I'm trying to enumerate the open apps, ordered by their window / visibility.
Does Cocoa / Applescript offer a way to retrieve this information?
Answer: You can use NSWorkspace's runningApplications method and NSRunningApplication's launchDate property to get you close to what you need.
Check out what the output if this code bit looks like in your console:
NSArray * arrayOfRunningApps = [[NSWorkspace sharedWorkspace] runningApplications];
if(arrayOfRunningApps)
{
    for(NSRunningApplication * aUserApp in arrayOfRunningApps)
    {
        NSLog( @"%@ launch time is %@", [aUserApp localizedName], [aUserApp.launchDate description] );
    }
}

As for sorting on some criteria, that's really up to your implementation to do.
A couple caveats:  these api's were introduced as of Snow Leopard (10.6) and
they only work on apps that the user can see (in the dock), not UNIX processes or admin/root daemons or whatever.
And I'm not certain about Applescript yet, but I'm hoping you'll be able to use this information to get to where you need to go.
Comment: Interesting. But do you know of any API to determine the app order? (I.e., that Safari is in front of Firefox?)


Using theme_hook_suggestions in hook_preprocess_page stops html.tpl.php from being used

Question: I've added this line to hook_preprocess_page in template.php:
<code>if (isset($vars['node']) && $vars['node']->type=='landing_page') {
  $vars['theme_hook_suggestions'][] = 'page__'. $vars['node']->type;
}
</code>
This worked fine on my test server however now I have put it on staging and has caused:
A) Only the page template is output - it is not surrounded by html.tpl.php.
B) My preprocess_html function in template.php is not being called at all.
If I comment out the line then html.tpl.php is used again.
This thread is discussing similar but opposite problem.
I'm really stumped on this - any points would be really useful!
Answer: This was being caused by calling an undefined function in my page template.
This wasn't apparent until I started searching the error logs.
Hope this may save someone else some time...


Submit Button is not getting selected..no error also

Question: HTML code:
<button id="welcomeContinue" class="btn btn-primary padlock active-removal" type="submit">

 CONTINUE
</button>
<input class="btn btn-primary padlock disabled" type="hidden" value="" title="Continue" name="continueanonymousSubmit" alt="Continue">
<input type="hidden" value=" " name="_D:continueanonymousSubmit">

code:
driver.findElement(By.id("welcomeContinue")).click();

How can i select submit button and proceed to next page
Comment: Are they(botton, input) in a form?
Comment: Are you sure, you are locating correct element?
Answer:
You can try using submit() method on a button instead of clicking.
Also, may be some info should be added for submitting to work: some required fields should be filled. Check this option
There are may be some JS scripts running that prevent submit for working
Answer: driver.findElement(By.xpath("//button[@type='submit']")).click()


EXCEL Pintar uma determinada quantidade de células

Question: tenho uma planilha que funciona como um gráfico de gantt, que vai do dia 01 ao dia 31, e minha dúvida é simples, baseado no cálculo de dia de um pedido, 12 dias por exemplo, tem como eu fazer com que o excel 'pinte' apenas 12 linhas, de 01 á 12 por exemplo?
Comment: O que você quer parece ser possível com formatação condicional, mas um exemplo mais detalhado é necessário para uma resposta exata.
Comment: Oi @Denis, obrigado pelo retorno.
Answer: Para resolver isso será preciso criar algumas regras. Como não há referência de como fez, as regras a seguir passam a ser estas:
1) Definir a área do Gráfico e valores de mínimo e de máximo:
Vamos supor que a área do seu gráfico compreenda a célula A1 (dia 1) até A31 (dia 31), portanto cada dia do mês é representado pelo número da linha, e que também compreenda as colunas de A até J, que são 10 colunas que representam, cada uma, valores de uma faixa de 10%, totalizando 100% se consideradas todas (de A até J).
Então o valor mínimo é de 0% e o valor máximo é de 100%.
2) Como tratar cada célula do gráfico em função do valor percentual do dia:
No total, as 10 células de A a J somam 100%, então um valor de 34% no dia 1, seria representado pelas células A1, B1, C1 e  D1 (34% está na faixa de até 40%, inclusive). Neste caso, somente estas células devem ser "pintadas".
Então a regra seria a seguinte ("valor" corresponde ao valor percentual relativo a um dia que vai de 0% a 100%):

Valor = 0% => Nenhuma célula é pintada
Valor maior do que 0% e menor ou igual a 10% => A célula da coluna A é pintada (primeiros 10%)
Valor maior do que 10% e menor ou igual a 20% => A célula da coluna B é pintada (mais 10% considerando os primeiros 10% da coluna A totalizando 20%)

... e assim por diante, até:

Valor maior do que 90% e menor ou igual a 100% => A célula da coluna J é pintada (todas as anteriores também são pintadas neste caso, totalizando 100%)

3) "Pintando" as células:
Para a sua necessidade, temos três estados:
a) Sem valor (0%)
b) Com valor (até 100% inclusive) e a data do dia maior do que a do dia apontado (o dia de hoje, por exemplo)
c) Com valor (até 100% inclusive) e a data do dia menor ou igual a do dia apontado
Para tratar o gráfico serão dados valores às células conforme os três estados anteriores, respectivamente:
a) A célula ficará com o valor 0
b) A célula ficará com o valor 1
c) A célula ficará com o valor 2
Para "pintar" as células respectivamente a regra será a seguinte:
a) Branco
b) Azul
c) Laranja
Sendo que a cor laranja indica os dias já corridos incluindo o próprio dia apontado, e a cor azul indica os dias ainda não ocorridos.
4) Fórmula para definir o gráfico e suas cores:
Antes da fórmula, supondo que os valores percentuais de cada dia estejam nas respectivas linhas da coluna K, e que existe uma célula denominada "Ate_este_dia", com o valor do dia apontado; a fórmula da célula A1 que deve ser copiada para todas as outras células que representam o gráfico, deve ser:
<code>=SE(E($K1>0;$K1>=Col()*0,10);SE(A1<=Ate_Este_Dia;2;1);0)
</code>
Agora o gráfico já pode ser "percebido", basta verificar as regiões com valores 1 e 2, falta então "pintar"
Após copiar, você deve selecionar todas as células que pertençam ao gráfico, neste caso a faixa A1:J31 e incluir três formatações condicionais, nas seguintes opções:
<code>Formatar apenas células que contenham

    "Valor da célula"   "é igual a"     0

        Formatar: Preenchimento "Cor Branca"

        Formatar: Fonte "Cor Branca"

Formatar apenas células que contenham

    "Valor da célula"   "é igual a"     1

        Formatar: Preenchimento "Cor Azul"

        Formatar: Fonte "Cor Azul"

Formatar apenas células que contenham

    "Valor da célula"   "é igual a"     2

        Formatar: Preenchimento "Cor Laranja"

        Formatar: Fonte "Cor Laranja"
</code>
Pronto! o valor por dia (quando houver) será representado como um gráfico de Gant com "barras" de cor Laranja para os dias já corridos e azuis para os dias não corridos.


Is there a better way to write business logic to validate mutually exclusive codes?

Question: I have two properties. I need to validate these properties against a rather large matrix showing compatible values.
Sample properties:
public string firstValue { get; set; }
public string lastValue { get; set; }

Sample matrix:
    A   B   C
A   X   O   O
B   O   X   X
C   X   O   X

Let the x axis represents the "firstValue" and the y axis represents the "lastValue". The program must validate that invalid combinations denoted by an "X" throw an error to the user.
Sample validation:
if (firstValue == "A")
{
    if (lastValue == "A" || lastValue =="C)
        Console.WriteLine("Invalid Combination");
}

This could obviously be refactored several ways using if\else and switch logic, but when you add many hundreds of values to the matrix it starts to get scary. I decided to create a new class containing one function per row in the matrix.
public class MutuallyExclusiveValidation
{
    public void CheckA(string lastValue)
    {
        if (lastValue == "A" || lastValue == "C")
        {
            Console.WriteLine("Invalid Combination");
        }
    }

    public void CheckB(string lastValue)
    {
        if (lastValue == "B")
        {
            Console.WriteLine("Invalid Combination");
        }
    }

    public void CheckC(string lastValue)
    {
        if (lastValue == "B" || lastValue == "C")
        {
            Console.WriteLine("Invalid Combination");
        }
    }
}

Then I devised something like this to make sure I'm not hitting more code than I need to. The predicate will return a boolean selecting and invoking the validation method that needs to be run. (just a sample, not production code)
    public static void CheckForMutuallyExclusiveValues(string firstValue, string lastvalue)
    {
        var allValidators = GetMutuallyExclusiveValidators(firstValue, lastvalue);
        var requiredValidators = allValidators.First(x => x.Key(firstValue));
        var validationClassInstance = new MutuallyExclusiveValidation();
        requiredValidators.Value(validationClassInstance);
    }

    public static Dictionary<Predicate<string>, Action<MutuallyExclusiveValidation>> GetMutuallyExclusiveValidators(string firstValue, string lastvalue)
    {
        var returnDictionary = new Dictionary<Predicate<string>, Action<MutuallyExclusiveValidation>>();
        Action<MutuallyExclusiveValidation> validation;
        Predicate<string> condition;

        validation = x => x.CheckA(lastvalue);
        condition = x => x == "A";
        returnDictionary.Add(condition, validation);

        validation = x => x.CheckB(lastvalue);
        condition = (x => x == "B");
        returnDictionary.Add(condition, validation);

        validation = x => x.CheckC(lastvalue);
        condition = (x => x == "C");
        returnDictionary.Add(condition, validation);

        return returnDictionary;
    }

This seems to work great, but I can't help thinking there's a better way. Any thoughts?
EDIT: Fabjan's answer is the one I'm going with for this particular problem. Thanks also to Tim Schmelter.
Comment: Why can't you just make a 2D boolean array and check against it?
Comment: Why is `x=c|y=b` invalid?
Comment: @TimSchmelter - If you reference the matrix, invalid combinations (denoted by an "X") are AA, AC, BB, CB, CC
Comment: @TimSchmelter I may have written it incorrectly but the x axis (left to right) comes first.
Comment: @Tresto: is there any logic, so that you f.e. can't use same first/last value or is the matrix arbitrary/predefined by the user?
Answer: Create a 2d array and validate records with it using some method, something like:
class MyClass
{
    bool[,] matrix = new bool[,]
    {
        {false, true, false},  // x1 y123
        {true, false, true},   // x2 y123
        {true, false, false},  // x3 y123
    };

    string[] xValues = { "A", "B", "C" };
    string[] yValues = { "A", "B", "C" };

    public bool IsValid(string value1, string value2)
    {
        return matrix[Array.IndexOf(xValues, value1), Array.IndexOf(yValues, value2)];
    }
}

class Program
{
    static void Main()
    {
        MyClass c = new MyClass();

        Console.WriteLine(c.IsValid("A", "A"));

        Console.WriteLine(c.IsValid("B", "C"));

        Console.WriteLine(c.IsValid("A", "C"));

        Console.ReadKey();
    }
}

Output:
Answer: You could use a Dictionary<string, HashSet<string>> to store the X-value as key and all invalid Y-values as values.
Dictionary<string, HashSet<string>> InvalidValues = new Dictionary<string, HashSet<string>> {
    {"A", new HashSet<string>{"A", "C"}},
    {"B", new HashSet<string>{"B"}},
    {"C", new HashSet<string>{"B", "C"}}
};

Now you can check efficiently if given x- and y-values are invalid:
var emptySet = new HashSet<string>();
var invalidValues = allValues
    .Where(x => InvalidValues.TryGet(x.FirstValue, emptySet).Contains(x.LastValue));
foreach (Value val in invalidValues)
    Console.WriteLine("Invalid Combination: {0}|{1}", val.FirstValue, val.LastValue);

used this extension to linqify Dictionary.TryGetValue:
public static TValue TryGet<TKey, TValue>(this Dictionary<TKey, TValue> dict, TKey key, TValue defaultValue = default(TValue))
{
    TValue value;
    bool success = dict.TryGetValue(key, out value);
    if (success)
        return value;
    else
        return defaultValue;
}

this class:
public class Value
{
    public string FirstValue { get; set; }
    public string LastValue { get; set; }
}

and some sample values:
var allValues = new List<Value> {
    new Value { FirstValue = "A", LastValue = "C" },
    new Value { FirstValue = "A", LastValue = "B" },
    new Value { FirstValue = "B", LastValue = "C" },
    new Value { FirstValue = "A", LastValue = "A" }
};


Reverse proxy TLS version

Question: I have a TMG 2010 (Forefront Threat Manager Gateway 2010) sitting on Windows Server 2003 R2 and I have several websites published through it. One of the websites is sitting on Windows Server 2012 R2. I know that Server 2003 R2 ships with TLS 1.0 and Server 2012 R2 ships with TLS 1.2. When I open the website from the internal network (not going through TMG) Google Chrome shows that the connection uses TLS 1.2. When, however, I open the published website from an external network (going through TMG), Google Chrome says the connection uses TLS 1.0.
How can I let the visitor not use TMG's TLS implementation but the version of the windows server on which the published site sits? Thanks in advance.
Comment: This comes down to the capabilities of the TMG 2010 (whatever that is). It is possible that it may not implement TLS 1.1 or TLS 1.2 (I know of at least one load-balancing/reverse-proxy appliance where the software (VM) version doesn't support TLS 1.1 or 1.2, but the appliance version does. In short, check with your vendor.
Answer: There are a bunch of registry settings you can make, including to enable TLS 1.1 and 1.2 for TMG 2010, according to http://www.isaserver.org/articles-tutorials/configuration-security/improving-ssl-security-forefront-threat-management-gateway-tmg-2010-published-web-sites.html

It's also a good idea to enable new protocols such as Transport Layer
  Security (TLS) v1.1 and v1.2 for modern clients that support them. To
  do this, open the registry and navigate to
  HKLM\System\CurrentControlSet\Control\SecurityProviders\SChannel\Protocols
  and create two new keys called TLS 1.1 and TLS 1.2. Under each of
  these keys create new keys called Client and Server. Within each
  Client and Server key under TLS 1.1 and TLS 1.2 create DWORD values
  called DisabledByDefault set to 0 and Enabled set to 1. Restart the
  TMG firewall for this change to take effect.

The rest of that page looks to be mandatory work for any current TMG deployment.
Comment: Thanks a lot for the advise. So you are saying that it doesn't matter if my underlying operating system is Windows Server 2003 R2? Because I've read that Windows Server 2003 and 2008 do not support TLS 1.1 and 1.2 due to its Schannel implementation. I just wanted to understand what defines the TLS version - the webserver or the underlying operating system. Do you know what defines it?
Comment: Sorry, I didn't consider the fact that it was Win2k3r2. The client only talks to the TMG, which opens an independent connection to the backend. Front end and backend connections are independent. Backend might even be unencrypted, or using different protocol or ciphers (for performance or compatibility)
Comment: Thank you so much. That's what I needed to know. So I need to upgrade the underlying operating system to Windows Server 2008 R2 in order to be able to negotiate TLS 1.1 or 1.2?
Comment: Assuming that TMG 2010 works on that platform, yes. But why not 2012 R2 (I don't know about TMG 2010 requirements)
Comment: Yes, it does work on Windows Server 2008 R2 but not on Server 2012 R2. Thanks a lot.
Comment: Windows settings tend to break out into Schannel client and server settings. When reverse proxying, it's my understanding you use TMG's Schannel Server settings when the client connects to you, and Schannel Client settings when connecting to the next hop - the tunnel is terminated and another tunnel is created to the target internal server which can be of any TLS version. So "fixing" TMG externally doesn't preclude it connecting to SSL 3.0 (or 2.0, or PCT etc) sites internally if the Client settings allow it.

Reverse proxy TLS version


Is there a way to pick a $k$ such that $p_0p_1 + ik$ is always a product of two primes?

Question: Is there a way to pick a $k$ such that $p_0p_1 + ik$ is always a product of two primes? where $p_0, p_1$ are primes, $k < pq$, and $i = 0,1,2,3....$. In other words, you pick $k$ such that no matter what $i$  I use, $p_0p_1 + ik$ is still a product of two primes.
I tried with many examples, and saw that it always failed but I can't prove it logically. Would anyone give me a hint? Thanks in advance.
Comment: $p_0p_1+(p_0p_1)k = p_0p_1 (1 + k)$, no?
Comment: My point is that if $k \neq 0$, then $p_0p_1 + ik$ always has at least 3 prime factors for $i = p_0p_1$.
Comment: @Jon: Why don't you make that an answer?
Comment: @Jon: Is $(1+k)$ prime? We don't know, plus $p_0p_1$ are already two primes.
Comment: @Jon: Ah, I see. Thanks a lot.
Answer: If $k$ is non-zero, then $p_0p_1 + ik$ will have at least three prime factors when $i$ is a non-zero multiple of $p_0p_1$, since in that case $p_0p_1 + ik = p_0p_1 + np_0p_1k = p_0p_1(1+nk)$.
Answer: HINT $\ $ The arithmetic progression $\rm\ p_0\:p_1 + k\ \mathbb Z\ $ contains elements that are divisible by any integer $\rm\:n\:$ coprime to $\rm\:k\:.\:$ Namely $\rm\: n\ |\ p_0\:p_1 + k\ x\ $ for $\rm\ x\equiv -p_0\:p_1/k\pmod{n}\:.\:$ In particular it has elements divisible by arbitrarily many prime factors via $\rm\:n =\:$ products of primes coprime to $\rm\:k\:.$


What to do if PACF is bad after 2 differences?

Question: I am doing time series analysis. My goal is forecasting.
I am trying to fit a ARIMA model. However, after 2 differences, the PACF plots show bad results.
PACF after 2 differences

I even tried 6 differences:
The original plot might be helpful
Answer: Judging from the original plot, your time series does not contain a unit root. The series oscillates around a constant level of approx. 1000, which does not look like a random walk. Therefore, you should not difference at all.
You could probably try a logarithmic transformation as the positive spikes are higher than the negative ones, i.e. there is asymmetry.
Then try to identify the "right" AR and MA lags (if you fail to do that manually, you may always use the function auto.arima in the "forecast" package in R), and you will be good.


Office 365 unified API error "Resource not found for the segment 'UserPhotos'."

Question: A week or two ago, if a user had no photo the Office 365 unified API would return metadata for a photo of size 1X1. Now it's returning the error:
{
  "error": {
    "code": "RequestBrokerOld-ParseUri",
    "message": "Resource not found for the segment 'UserPhotos'."
  }
}

Now the error has started to appear for users that do have photos. It's been getting progressively worse over the last few days, to the point that the API is unusable now. It started off as only a few missing photos, and now only 1 user photo is returned successfully out of over 250 users.
All User Photo endpoints are returning this error. E.g:
https://graph.microsoft.com/beta/me/userphotos
https://graph.microsoft.com/beta/xyz.onmicrosoft.com/users/someUserId/userphotos/48X48
https://graph.microsoft.com/beta/xyz.onmicrosoft.com/users/someUserId/userphoto/$value

The error is occuring in the sandbox too (although I can't be sure the user in the sandbox does have a photo to begin with).
Is there any known workaround or fix for this issue?
Comment: I asked this a few days ago. http://stackoverflow.com/questions/33406065/office365-api-pulling-my-userphoto Someone else has said it doesn't work for them either. I think the userphoto API is broken at the moment.
Comment: @Ampers I just found your question while searching for a workaround. Hopefully we get a fix soon.
Answer: There have been some updates in the API:
http://dev.office.com/blogs/Update-3-on-Office-365-unified-API
to get to the photo, please use /photo instead of /userPhoto
Answer: From this question:
The endpoint is now called "photo" and not "userphoto"
To get the photo information you use:
api/beta/Me/photo

To get the photo you call
api/beta/Me/photo/$value

I haven't been able to get photos for a given size (eg beta/Me/photo/48x48) to work


How are affinely (in)dependent vectors in $\mathbb R^n$ arranged in space?

Question: Consider a finite set of vectors $\{v_i\}_i\subset\mathbb R^n$.
This set is linearly independent if $\sum_k \alpha_k v_k=0$ implies $\alpha_k=0$.
Geometrically, I understand linear dependence as stating that a set of vectors is contained in a hyperplane passing through the origin.
On the other hand, we say that $\{v_i\}_i$ are affinely dependent if $\sum_k \alpha_k v_k=0$ for $\alpha_k$ not all zero and such that $\sum_k\alpha_k=0$.
Is there a similar geometrical intuition to visualise when a set $\{v_i\}_i$ is affinely dependent/independent?
Answer: Your characterization of linear (in)dependence is not quite correct. Every set of vectors is contained in some kind of hyperplane through the origin, namely its span.
Instead, I would say that a finite set of vectors is linearly dependent if they lie in a hyperplane through the origin whose dimension is less than the number of vectors in the set.
And in a similar vein, a finite set of points in $\mathbb R^n$ is affinely dependent if it lies in a hyperplane whose dimension is less than the number of points in the set minus 1. Thus, 3 different points on a line are affinely dependent, but 2 different points on a line are affinely independent.
There is another nice geometric picture of affine independence:

a pair of points is affinely independent if it is the endpoint set of a line segment (which occurs if and only if the two points in that pair are unequal)
a triple of points is affinely independent if it is the vertex set of a triangle
a quadruple of points is affinely independent if it is the vertex set of a tetrahedron
a $k$-tuple of points is affinely independent if it is the vertex set of a $k-1$ dimensional simplex.
Comment: Nice. I suspect that OP was using "hyperplane" to mean "codimension 1 hyperplane", and that the set of vectors was supposed to have $n$ elements in it implicitly. So this was a good chance for OP to learn not only that hyperplane can mean more than that, but also that the number of points matters.
Comment: To Lee's nice geometric picture, let me add an algorithmic restatement. A triple of (distinct) points is *dependent* if it's not the vertex set of a triangle, in which case the set of all convex combinations of its elements forms a line segment...and one of the three points must therefore be expressible as a convex combination of the others. That's more generally true: in an affinely dependent set (which must have at least two elements!), one of the points is a convex combination of the others. The algorithmic application: "so you can remove one of the points without changing the convex hull."
Comment: thanks. Indeed, I was not taking into account that smaller numbers of vectors can also (obviously) be linearly/affinely independent. This is very useful. The observation "affinely dependent means one of the points is convex combination of the others" is also a very nice one.
Answer: As @runway44 says, affinely-dependent means "they're all in hyperplane", although possibly a hyperplane that does not contain the origin. To see this quickly, take the $k+1$ vectors
$$
v_0, v_1 \ldots, v_k
$$
with $$
\sum a_i v_i = 0, \sum a_i = 1
$$
and subtract $v_0$ from each of $v_1, \ldots, v_k$ to get $w_1, \ldots, w_k$.
Then the vectors $w_k$ all lie on a parallel hyperplane through the origin. (It's worth doing the algebra to establish this yourself).
Or, to put it in a more classical form, if we take $v_0$ as the origin of a new coordinate system, then the remaining $v_i$ vectors all lie in a hyperplane.