XSD validation - sequence of attributes - exception

Question: I can't find the problem an tried different things. I would really appreciate any kind of help.
I had a valid .xsd document, but changed some parts of the xml and now I'm unable to get it valid and I don't find the fault. The error-message is below. Does someone see what is wrong there? The exceptions start, where the sequence of attributes starts.
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="urn:Projekt1" xmlns:proj="urn:Projekt1">
    <xs:element name="projekte" type="proj:ProjekteForm"/>

    <xs:complexType name="ProjekteForm">
        <xs:sequence>
            <xs:element name="person" type="proj:ProjekteForms" minOccurs="0" maxOccurs="unbounded"/>
        </xs:sequence>
    </xs:complexType>

    <xs:complexType name="ProjekteForms">
        <xs:sequence>
            <xs:element name="name" type="xs:string"/>
            <xs:element name="link" type="xs:string"/>
            <xs:element name="zhaw" type="xs:string"/>
                <sequence>
                    <xs:attribute name="width" type="xs:integer"/>
                    <xs:attribute name="height" type="xs:integer"/>
                </sequence>
            <xs:element name="homepage" type="xs:string"/>
            <xs:element name="googlemapsx" type="xs:float"/>
            <xs:element name="googlemapsy" type="xs:float"/>
            <xs:element name="facebook" type="xs:string"/>
            <xs:element name="skype" type="xs:string"/>
            <xs:element name="twitter" type="xs:string"/>
        </xs:sequence>
        <xs:attribute name="id" type="xs:integer"/>
    </xs:complexType>
</xs:schema>

Which content is meant down here? On another place in the document, it works also like this.
Message:
Not valid.
Error - Line 16, 52: org.xml.sax.SAXParseException; lineNumber: 16; columnNumber: 52; s4s-elt-must-match.1: The content of 'sequence' must match (annotation?, (element | group | choice | sequence | any)). A problem was found starting at: attribute.
Error - Line 17, 53: org.xml.sax.SAXParseException; lineNumber: 17; columnNumber: 53; s4s-elt-must-match.1: The content of 'sequence' must match (annotation?, (element | group | choice | sequence | any)). A problem was found starting at: attribute.
EDIT:
Maybe it's helpful if I upload also the xml. But the question ist just about the validity of the .xsd.
<?xml version="1.0" standalone="no"?>
<?xml-stylesheet type="text/xsl" href="Projekt1.xsl" xmlns:x="urn:Projekt1" exclude-result-prefixes="x"?>
<x:projekte xmlns:x="urn:Projekt1">
    <person id= "1">
        <name>Franz Mommar</name>
        <link>http://www.dfki.de/~wahlster/Portrait_Photos/</link>
        <zhaw width="100" height="100">Portrait_Wahlster_Photo_by_Jim_Rakete.jpg</zhaw>
        <homepage>http://www.werni.ch</homepage>
        <googlemapsx>285.2342</googlemapsx>
        <googlemapsy>234.3598</googlemapsy>
        <facebook>franzmoammar</facebook>
        <skype>franz.moammar</skype>
        <twitter>franzmoammar</twitter>
    </person>
    <person id= "2">
        <name>Rüdiger Mannheim</name>
        <link>http://www.dfki.de/~wahlster/Portrait_Photos/</link>
        <zhaw width="100" height="100">Wahlster_Anschnitt_gross.jpg</zhaw>
        <homepage>http://www.humor.li</homepage>
        <googlemapsx>45.2342</googlemapsx>
        <googlemapsy>32.3598</googlemapsy>
        <facebook>rüdigermann</facebook>
        <skype>ruedi</skype>
        <twitter>geronimo</twitter>
    </person>
</x:projekte>

Answer: As stated in the error message, a <sequence> element cannot contain any <attribute> elements. Also, looking at e.g. these docs, <sequence> shouldn't be directly nested in <element>.
Also, your <sequence> elements are lacking the xs namespace prefix.
As for a solution, replace <sequence> with <xs:complexType>, and you should be fine.
EDIT: Actually, I'm not sure where your attributes are supposed to go:

Are they supposed to be attributes of the type ProjekteForms? In that case, put them at the end of that complex type definition, together with your id attribute.
Or are they supposed to be attributes of your <zhaw> element? Your sample Xml suggest this, but in your XSD, your definition of <zhaw> does not enclose the sequence with the attributes, as you are using the single-tag-form of the element. Replace <xs:element name="zhaw" type="xs:string"/> with <xs:element name="zhaw">...</xs:element> (with the complex type with attributes inside). Note that you have to omit the type attribute as a type is already specified by the enclosed <xs:complexType> element. In order to allow text content, add the attribute mixed="true" to the <xs:complexType> element.

The latter solution would look like this:
<xs:element name="zhaw">
    <xs:complexType mixed="true">
        <xs:attribute name="width" type="xs:integer"/>
        <xs:attribute name="height" type="xs:integer"/>
    </xs:complexType>
</xs:element>

Comment: I tried you solution and it worked. Thank you very much!!! :)
They are supposed to be attributes from the "zhaw"-element.
Big Thanks!
Answer: You can't have a sequence of attributes in your XSD. zhaw might need to be defined as complexType with simpleContent as can be seen (example) in http://msdn.microsoft.com/de-de/library/ms256106.aspx
<xs:element name="zhaw">
  <xs:complexType>
    <xs:simpleContent>
      <xs:extension base="xs:string">
        <xs:attribute name="width" type="xs:integer"/>
        <xs:attribute name="height" type="xs:integer"/>
      </xs:extension>
    </xs:simpleContent>
  </xs:complexType>
</xs:element>


How to use fragments to emulate back button when I show/hide elements with jQuery

Question: I use jQuery to show/hide elements that correspond to a multi-step solution. Now I've been asked to make the back button functional.
I understand that using fragments can aid here but I'm not sure how. If I set the hash when I show/hide my elements (as I move from step to step) via:
if($(button).hasClass('step-one')) {
        $('.step-two').show();
        window.location.hash = "#step2";
    }

Now I've got my hash set correctly but when I click the back button it only removes the hash. It does a...
window.history.back;

How do I get it to return to the previous step without completely re-architecting what I've done? Or without using a 3rd party plugin like BBQ or Ben Alman's Hashchange plugin?
Thanks for any helpful tips.
Answer: I suggest you try to work with onhashchange..
Try handle your events (show and hide) using this:
$(window).on('hashchange',function(){

    var hash = window.location.hash;
    switch(hash){
        case '#step1':
            console.log('Make something superb!');
            break;
        case '#step2':
            console.log('Make something superb!');
            break;
        case '#step3':
            console.log('Make something superb!');
            break;
        default:
            break;
    }

})

I dont know if this is gonna work... I didnt test it... But i think you can start with this....
I also suggest you to hanfle the hashs with anchors:

Comment: It's definitely a very good start, thank you very much. After implementing this the only problem is that if the hash is #step1 and I click back, the hash is removed but the content stays the same.
Comment: Wasn't thinking, apologies. Thanks for your answer.


How to save dataframe after generating with a custom function (python)

Question: I have a custom function that generates a new column based on an equation, but I cannot see col3 after running the function and printing out the dataframe.
How can I get the new column to save as a pandas dataframe?
Here is what I have done thus far:
#Import modules
import pandas as pd
import numpy as np

#Define the custom function
def example(a, b, c):
    """
    Example function, generates a new column based on user inputs
    """

    #Generate input dataframe
    d = {
    'col1': [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],
    'col2': [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
    }

    dataframe = pd.DataFrame(data=d)

    #Create a new column based on an equation
    dataframe['col3'] = dataframe['col1'] * a * b * c

    return dataframe

Calling the function...
example(2, 4, 6)

...gives this output:
    col1 col2 col3
0   1   1   48
1   1   2   48
2   1   3   48
3   1   4   48
4   1   5   48
5   1   6   48
6   1   7   48
7   1   8   48
8   1   9   48
9   1   10  48
10  1   11  48
11  1   12  48
12  1   13  48
13  1   14  48
14  1   15  48
15  1   16  48
16  1   17  48
17  1   18  48
18  1   19  48
19  1   20  48

However, printing the dataframe shows that the column hasn't been added:
dataframe

An error message is generated:
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Input In [4], in <cell line: 1>()
----> 1 dataframe

NameError: name 'dataframe' is not defined

How can I fix this so that col3 is appended onto the original dataframe?
Comment: You already have a dataframe. Why are you using `dataframe = pd.DataFrame(dataframe)`? This doesn't save anything, it creates a copy of the original dataframe, and then replaces it. What do you mean `dataframe = pd.DataFrame(dataframe)`? That name only exists inside the function. It can't be used outside it. It's the same object returned by the function
Comment: Thanks, I have edited that part of the code out.
Comment: Use `dataframe = example(2, 4, 6)` and then call `dataframe`
Comment: That's not saving, that's assigning the result to a variable so it can be used.
Comment: @PanagiotisKanavos could you help me then?
Answer: You need to save it like this. Your functions works perfectly fine:
df = example(2, 4, 6)


Why is a PR curve considered better than an ROC curve for imbalanced datasets?

Question: I have heard from multiple sources that a precision-recall curve is considered better than an ROC curve when testing a classifier on a dataset with a class imbalance.
https://www.biostat.wisc.edu/~page/rocpr.pdf
https://towardsdatascience.com/what-metrics-should-we-use-on-imbalanced-data-set-precision-recall-roc-e2e79252aeba
If this were the case I would expect that if I took an imbalanced dataset and resampled it to be balanced it would produce a significantly different ROC curve that the original dataset.  However in my experience this is not the case according to my experiment or reason.
Can anyone explain to me how the ROC curve can be an okay measure of classification accuracy for balanced datasets, but not for unbalanced datasets, when the ROC curve seems to be essentially the same for both?
Comment: tjeck out https://www.quora.com/What-is-the-difference-between-a-ROC-curve-and-a-precision-recall-curve-When-should-I-use-each
Answer:
precision-recall curve is considered better than an ROC curve when testing a classifier on a dataset with a class imbalance.

This statement is plain wrong.
In general, statements like "X is better than Y" should be taken with a grain of salt. It usually depend on the use case, what is your target, etc. However, the statement above is more wrong than that. Let's take a look.
The PR curves plots the following parameters:
Precision = TP/(TP+FP)
Recall = TP/(TP+FN)
Notice how True Negatives (TN) are absent from the equation?
PR curves are useful when positive examples are rare. If your dataset is imbalanced with rare negatives, you should absolutely not use the PR curve.

As you noticed in your experiment, and as you have correctly reasoned, ROC curves are insensitive to class imbalance. This means that if you balance your data (ie with resampling), the ROC curve does not change (assuming you don't re-train your model).
When the dataset contains only few positive examples, you have a new problem to care about: positive predictive value (= PPV = Precision). Specifically: given an observation is classified as positive, what is the probability that it is really a True Positive? The answer to this question can be surprisingly misleading when positive examples are rare.
PPV and NPV (the complement: given an observation is negative, what is the probability to be a true negative) are usually not an issue in balanced datasets, as they follow the usual sensitivity and specificity. PPV and NPV only become critical in imbalanced datasets, because these two measures are sensitive to class imbalance, unlike ROC curves. So ROC curves can obscure models with poor PPV and NPV, which can be an issue in the case of imbalance. PR curves will immediately highlight models with poor PPV and totally disregard NPV.
So in the end it is up to you to choose which tool to use. Don't use PR curves just because you have imbalance.  Are positive examples rare? Are they rare specifically in your sample? Then stick with ROC curves. Are they rare in the general population? Then you should consider precision and look at the PR curve too. Are negative cases rare? Then stick with ROC curve.
Comment: Balancing may of course affect model training, which is what this preprint is looking at. I was assuming a constant model, I tried to clarify my answer accordingly.
Comment: "This means that if you balance your data (ie with resampling), the ROC curve does not change." I don't think that's necessarily true, see e.g. arxiv.org/abs/1812.10857, esp. pages 7-9.
Answer: That's an interesting question. I don't agree with most people who say that ROC is always terrible for imbalanced data. It really depends on the use case and what you want to say with the ROC curve.
I assume why some people regard ROC as a bad metric for imbalanced problems could be that it focuses mostly on the positive examples and kind of neglects giving the same attention to the other (negative) class.
I.e., in ROC curves, you have TP/P and FP/N.
With Precision-Recall curves, you also focus on the correctly predicted negative examples via recall TN/N (i.e,. the true negatives, TN, are what make the difference).
In either case, I wouldn't say that PRE-REC are always to be preferred over ROC curves, it really depends on the context.
Answer: It is not always true.

PR curve considered better than an ROC curve for imbalanced datasets

It depends on the business problem and performance we need to measure.
ROC looks at TPR and FPR. Hence, looking at ROC only, we can miss FP > TP situation which is low precision. If low precision is not good for our problem, then using ROC only is not a good idea.
We need to ask:

Will FP > TP happen with our data and the model.
Does FP > TP matter for our problem.

If the answer is yes for both, then looking at ROC only is not fit for use to measure the performance. Looking at PR can help identify the low precision.

FP: False Positive
TP: True Positive
FPR: False Positive Rate
TPR: True Positive Rate

Suppose I am running a risky loan business where many customers can be risky. If I evaluate the business performance with ROC only, I may think the performance is good although actually the business is losing money because of FP > TP. Then measuring the performance only with ROC is not fit for the purpose.


Tunneling git from intranet to remote server

Question: I have a server I need to develop on outside of my intranet. I try to ssh into the server and setup a proxy that will allow me to clone the repository.
ssh -D 5555 remote.server
Then I set my ~/.ssh/config to
Host git.server
    ProxyCommand=nc -X 5 -x localhost:5555 %h %p

Where git.server is the domain name of my git server on the intranet.
I get the error ssh: Could not resolve hostname git.server: Name or service not known
What is happening? Is DNS not being forwarded as well? How can I resolve this?
Comment: OpenSSH does not support DNS forwarding over ProxyCommand
Answer: Try this:
Host git.server
    HostName ${IP-OF-YOUR-GIT-SERVER}
    ProxyCommand=nc -X 5 -x localhost:5555 %h %p


$(1+i)$ to the power $n$

Question:
Possible Duplicate:
Complex number: calculate $(1 + i)^n$.

I came across a difficult problem which I would like to ask you about:
Compute
$ (1+i)^n $ for $ n \in \mathbb{Z}$
My ideas so far were to write out what this expression gives for $n=1,2,\ldots,8$, but I see no pattern such that I can come up with a closed formula.
Then I remember that one can write any complex number $a+bi$ like:
$$(a+bi)=\sqrt{a^2+b^2} \cdot \left( \frac{a}{\sqrt{a^2+b^2}}+\frac{b}{\sqrt{a^2+b^2}}\cdot i\right)$$
and $\frac{a}{\sqrt{a^2+b^2}} = \cos(\phi)$ and $\frac{b}{\sqrt{a^2+b^2}} = \sin(\phi)$  where $\phi$ is $\arctan{\frac{b}{a}} $
So it becomes,
$(a+bi)=\sqrt{a^2+b^2} \cdot ( \cos(\phi)+\sin(\phi)\cdot i)$ Taking this entire thing to the power $n$ using De Moivre
$$(a+bi)^n=(\sqrt{a^2+b^2})^n \cdot ( \cos(n\phi)+\sin(n\phi)\cdot i)$$
Substituting my $a=1$ and $b=1$
$(1+i)^n=(\sqrt{2})^n \cdot ( \cos(n\cdot\frac{\pi}{4})+\sin(n\cdot\frac{\pi}{4})\cdot i)$
$\phi$ is 45 degrees hence $\frac{\pi}{4}$
But now I don't know how to continue further and I would really appreciate any help! Again, Im looking for a closed formula depending on n.
Best regards
Comment: I think it would be a lot easier to observe that $(i+1)^2 = 2i$, so therefore $(i+1)^{2n} = (2i)^n$, and $(i+1)^{2n+1} = (2i)^n(i+1)$. No trigonometry or De Moivre's theorem is required here.
Comment: Upvoted for a clear, well-researched question. Voted to close as duplicate.
Answer: You got to this expression:
$$(1+i)^n=\left(\sqrt{2}\right)^n  \left(\cos\left(n\frac{\pi}{4}\right)+i\sin\left(n\frac{\pi}{4}\right)\right)$$
Now, you should note that this expression (without $\left(\sqrt{2}\right)^n$) has periodicity of $8$, i.e. for $n=k$ and $n=k+8$ the value will be the same. So you can just look at $n=0,1,...,7$ and write the answer in the form:
$$(1+i)^n=\left(\sqrt{2}\right)^n\left\{ \begin{array}{cc} 1 & n\equiv0(\mod8)\\ \vdots & \end{array}\right.$$
Comment: Like your way here (+1).
Answer: I think you are making this much too difficult, because:
$$(1+i)^2 = 2i.$$
So $(1+i)^{2m} = (2i)^m = 2^mi^m$.
That takes care of the even powers of $1+i$.
For the odd powers, just multiply by $1+i$ again: $(1+i)^{2m+1} = (1+i)^{2m}(1+i) = 2^mi^m(i+1)$.

If you want to simplify further, you need to know the remainder when $m = \bigl\lfloor \frac n2 \bigr\rfloor$ is divided by 4, so that you can reduce the $i^m$ part.
Say $n$ is even, and $m=n/2 = 4k+j$, where $0\le j<3$; then $n=8k+2j$:
$$\begin{array}{ll}
j & (1+i)^{n=8k+2j} \\
\hline
0 & \hphantom{-}2^m   \\
1 & \hphantom{-}2^mi \\
2 & -2^m \\
3 & -2^mi
\end{array}$$
If $n$ is odd, and $m=(n-1)/2 = 4k+j$, where $0\le j<3$, then $n=8k+2j+1$:
$$\begin{array}{ll}
j & (1+i)^{n=8k+2j+1} \\
\hline
0 & \hphantom{-}2^m+2^mi   \\
1 & -2^m+2^mi \\
2 & -2^m-2^mi \\
3 & \hphantom{-}2^m-2^mi
\end{array}$$
Putting these together into one table, we can just say that $n=8k+j'$, where $0\le j'\lt 8$:
$$\begin{array}{lrl}
j' & (1+i)^{n=8k+j'} \\
\hline
0 & \hphantom{-}2^m &  \\
1 & \hphantom{-}2^m&+2^mi   \\
2 & &\hphantom{-}2^mi \\
3 & -2^m&+2^mi \\
4 & -2^m& \\
5 & -2^m&-2^mi \\
6 & &-2^mi \\
7 & \hphantom{-}2^m&-2^mi
\end{array}$$
(And remember $m=\bigl\lfloor \frac n2 \bigr\rfloor$.)
Answer: You have a closed form already if you do just a little more work:
$$\begin{align*}
(1+i)^n&=\left(\sqrt{2}\right)^n\left(\cos\frac{n\pi}4+i\sin\frac{n\pi}4\right)\\
&=2^{n/2}\left(\cos\frac{n\pi}4+i\sin\frac{n\pi}4\right)\\
&=\begin{cases}
2^{n/2},&\text{if }n\equiv 0\pmod 8\\
2^{n/2}\left(\frac{\sqrt2}2+\frac{\sqrt2}2i\right),&\text{if }n\equiv 1\pmod 8\\
2^{n/2}i,&\text{if }n\equiv 2\pmod 8\\
2^{n/2}\left(\frac{\sqrt2}2-\frac{\sqrt2}2i\right),&\text{if }n\equiv 3\pmod 8\\
-2^{n/2},&\text{if }n\equiv 4\pmod 8\\
-2^{n/2}\left(\frac{\sqrt2}2+\frac{\sqrt2}2i\right),&\text{if }n\equiv 5\pmod 8\\
-2^{n/2}i,&\text{if }n\equiv 6\pmod 8\\
-2^{n/2}\left(\frac{\sqrt2}2-\frac{\sqrt2}2i\right),&\text{if }n\equiv 7\pmod 8\;.
\end{cases}\\
\end{align*}$$
A function defined by cases is still a closed form. You can do better, though, if you allow the exponential form of the complex number: $1+i=\sqrt2 e^{i\pi/4}$, so
$$(1+i)^n=2^{n/2}e^{in\pi/4}\;.$$
Answer: Use: $$\cos(n\theta)=\cos^n(\theta)-\frac{n(n-1)}{2!}\cos^{n-2}(\theta)\sin^2(\theta)+\frac{n(n-1)(n-2)(n-3)}{4!}\cos^{n-4}(\theta)\sin^4(\theta)-...$$ and $$\sin(n\theta)=n\cos^{n-1}(\theta)\sin(\theta)-\frac{n(n-1)(n-2)}{3!}\cos^{n-3}(\theta)\sin^3(\theta)-...$$
Comment: Nice! well-done, my friend, and hoping you're reading this as your new day begins!
Comment: @amWhy: Thanks; So GN to me. ;-)

$(1+i)$ to the power $n$


tsCV auto.arima with xreg results in NAs

Question: I'm using the tsCV function from the forecast package in R. I'm comparing arima with and without xreg. Without xreg I have no problems. But when I add xreg to the tsCV function I get a matrix of NAs.
I thought I might need length(xreg) = length(y) + horizon. But if I do that I get an error: xreg must be of the same size as y.
Here is a reproducible example:
library(forecast)
#> Registered S3 method overwritten by 'xts':
#>   method     from
#>   as.zoo.xts zoo
#> Registered S3 method overwritten by 'quantmod':
#>   method            from
#>   as.zoo.data.frame zoo
#> Registered S3 methods overwritten by 'forecast':
#>   method             from
#>   fitted.fracdiff    fracdiff
#>   residuals.fracdiff fracdiff

stack_data <- ts(rnorm(100), start = 2000, frequency = 12)
stack_data_xreg <- ts(rnorm(100), start = 2000, frequency = 12)

farma <- function(x, h){forecast(auto.arima(x), h = h)}
tsCV(stack_data, farma)
#>              Jan         Feb         Mar         Apr         May
#> 2000  0.40563034  0.17463799 -0.77045150 -1.26653788 -0.54549741
#> 2001 -0.82662134 -0.12712224 -0.16689046 -0.28039922 -0.14633838
#> 2002  1.00869308 -0.10646429 -0.11733494 -0.98269977  2.02888513
#> 2003  0.08992425 -0.04478466  1.33947694  0.61512603 -1.47779195
#> 2004  0.62197916 -0.31285023 -1.87748218  0.05545157  0.79404086
#> 2005  1.34079217  1.16067205 -0.31473379  1.28361957  0.26702644
#> 2006 -0.20387530  0.14089200  0.09655947 -1.68903183 -1.74576484
#> 2007 -1.47340231  2.07289246 -1.88595924 -0.08185593  0.66826102
#> 2008  1.46971617  0.56345483 -1.39370468          NA
#>              Jun         Jul         Aug         Sep         Oct
#> 2000  0.03088558 -1.56988024  0.36739705  0.19510088  0.35736462
#> 2001  0.61791686 -0.34181673 -0.38493804  1.65816962 -0.09582700
#> 2002 -1.40810233 -1.49081572  0.45128015 -0.22893364  0.14057981
#> 2003 -1.18764843  0.05096855  1.36152907 -0.11422859  0.27291010
#> 2004  1.85680313  1.88050368 -1.03857395 -1.92289436  1.04696123
#> 2005  1.03188951  0.89751963  1.92407988  1.35389806  0.89851252
#> 2006 -0.01003884  0.70429687 -0.71814159 -0.42640676  1.37978749
#> 2007 -1.19165002  1.02750038 -0.23383838 -0.76811251  1.02074594
#> 2008
#>              Nov         Dec
#> 2000  1.19798923  1.59771830
#> 2001  0.68061128  0.59334251
#> 2002  0.41844484 -0.90827529
#> 2003  0.05572988 -1.41338097
#> 2004  1.21183965  0.82382650
#> 2005  0.63131654  1.40116039
#> 2006  0.13046189 -1.71495153
#> 2007 -1.62466898  0.63538448
#> 2008
tsCV(stack_data, farma, xreg = stack_data_xreg)
#>      Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
#> 2000  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA
#> 2001  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA
#> 2002  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA
#> 2003  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA
#> 2004  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA
#> 2005  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA
#> 2006  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA
#> 2007  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA
#> 2008  NA  NA  NA  NA

Created on 2019-10-10 by the reprex package (v0.3.0)
I tried to change my farma function as follows:
farma_x <- function(x, h, xreg){forecast(auto.arima(x, xreg = xreg), h = h)}
but that did not work.
I have no problem when I run auto.arima with xreg, only when I try to use tsCV
Answer: You need to split the xreg matrix into two pieces, one used for training and one for forecasting. The following code should fix the problem.
library(forecast)
set.seed(1)
stack_data <- ts(rnorm(100), start = 2000, frequency = 12)
stack_data_xreg <- ts(rnorm(100), start = 2000, frequency = 12)

farma <- function(y, h, xreg) {
  ncol <- NCOL(xreg)
  X <- matrix(xreg[seq_along(y), ], ncol = ncol)
  if (NROW(xreg) < length(y) + h) {
    stop("Not enough xreg data for forecasting")
  }
  newX <- matrix(xreg[length(y) + seq(h), ], ncol = ncol)
  fit <- auto.arima(y, xreg = X)
  forecast(fit, xreg = newX, h = h)
}

tsCV(stack_data, farma, xreg = stack_data_xreg)
#>               Jan          Feb          Mar          Apr          May
#> 2000  0.810097135           NA  1.304257208  0.682981005 -5.610649793
#> 2001 -2.300753372  1.122943604 -0.056166686 -0.024771800  0.936527913
#> 2002 -0.083400817 -0.153262209 -1.469429055 -0.451752087  0.436745959
#> 2003 -0.021221494  1.147379540  0.765396693 -0.093538812 -0.305109643
#> 2004  0.951795652  0.395926226 -0.611855910  0.344129361 -1.123042184
#> 2005 -0.051414670  0.743490403  0.059981832 -0.765007510  0.247113268
#> 2006 -0.935160311 -1.365429702  0.291221704 -0.438080942  0.025365086
#> 2007  0.336816520  1.028414077 -0.271960523  0.389200605  0.306516552
#> 2008 -0.713072219 -1.223829836 -0.476239935           NA
#>               Jun          Jul          Aug          Sep          Oct
#> 2000  0.525713374  0.722321499  0.527858032 -0.569519802  1.544766085
#> 2001  0.844427791  0.591343448  0.907552931  0.859488240  0.078810418
#> 2002  1.355720366 -0.070836700  0.357486229  0.049680596 -1.396737647
#> 2003  0.748322301  0.551776497 -0.709934151 -0.702899128  0.317519688
#> 2004  1.480106472  1.960889994 -0.302600323 -1.088335143  0.491245564
#> 2005 -1.809366181  1.451960439  0.147030897  2.181626321  0.558826680
#> 2006  0.085603679 -0.577727812 -0.592174595 -0.125793946  1.180536801
#> 2007 -0.535583516  1.191666401  1.194077284  0.670606300  1.637822904
#> 2008
#>               Nov          Dec
#> 2000  0.366156757 -0.522869056
#> 2001 -1.986002110  0.624077286
#> 2002 -0.350771686 -0.374158943
#> 2003  0.767824690 -0.059505618
#> 2004 -0.002975468  2.431699557
#> 2005 -0.708162439  0.618942712
#> 2006 -1.534986325  0.583242325
#> 2007  0.437497859 -1.456253804
#> 2008

Created on 2019-10-11 by the reprex package (v0.3.0)
Comment: Thank yo so much. This worked.


cannot resolve symbol at text and rss view

Question: could someone please tell me why I'm getting a Cannot resolve symbol error at the on create and on start method at mRssFeed ? By the way this is only my rss feed fragment class. Thank you.
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class FeedFragmentPortrait extends android.support.v4.app.Fragment {

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    return inflater.inflate(R.layout.feed_fragment_portrait, container, false);

    View rootView = inflater.inflate(R.layout.feed_fragment_portrait, container, false);
    mRssFeed = (TextView) rootView.findViewById(R.id.rss_feed);
    return rootView;
}

@Override
public void onStart() {
    super.onStart();
    InputStream in = null;
    try {
        URL url = new URL("http://www.google.com/feed/main.xml");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        in = conn.getInputStream();
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        for (int count; (count = in.read(buffer)) != -1; ) {
            out.write(buffer, 0, count);
        }
        byte[] response = out.toByteArray();
        String rssFeed = new String(response, "UTF-8");
        mRssFeed.setText(rssFeed);
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

}
Answer: remove this line from the oncreateView
return inflater.inflate(R.layout.feed_fragment_portrait, container, false);

you are returning before initializing mRssFeed
Thats why system could not know what mRssFeed is

Edit

Also you should do all you api calls in background task
@Override
public void onStart(Intent intent, int startId) {
    super.onStart(intent, startId);

        new DownloadInfo().execute("http://example.com/xxx.php");
}

and the Asynctask something like this
class DownloadInfo extends AsyncTask<String, String, String> {
    @Override
    protected String doInBackground(String... url) {
        // constants
    InputStream in = null;
    try {

    HttpURLConnection conn = ((HttpURLConnection) new URL(url[0]).openConnection();
    in = conn.getInputStream();
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024];
    for (int count; (count = in.read(buffer)) != -1; ) {
        out.write(buffer, 0, count);
    }
    byte[] response = out.toByteArray();
    return new String(response, "UTF-8");

} catch (IOException e) {
    e.printStackTrace();
} finally {
    if (in != null) {
        try {
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
        return null;
    }

    @Override
    protected void onPostExecute(String result) {

            if (result != null) {
               mRssFeed.setText(rssFeed);
            }
    }


Rudin Functional Analysis Theorem 3.25

Question: This is probably the first question regarding the theorem in the title...

If $K$ is a compact set in a locally convex space $X$, and if $\bar{co}(K)$ is also compact, then every extreme point of $\bar{co}(K)$ lies in $K$.

I struggle to understand the very first 3 lines of the proof.

Assume that some extreme point $p$ of $\bar{co}(K)$ is not in $K$. Then there is a convex balanced neighborhood $V$ of $0$ in $X$ such that
  $$
(p + \overline{V}) \cap K = \emptyset
$$

Can anyone explain why can we find such a $V$? My guess is that it's due to compacteness of both $\overline{co}(K)$ and $K$ plus the fact that $K \subset \overline{co}(K)$.
Answer: Compactness is not required. $K^{c}$ is an open set containing $p$ and this gives existence of such a set $V$. This has been proved in earlier sections of Rudin's book$.
Comment: The subtlety I'm not getting is the closure of $V$ not $V$ itself.
Comment: $V$ is an open neighborhood of $0$. It is fact that every open neighborhood of $0$ contains the closure of another open neighborhood of $0$. This is what is being used here.

Rudin Functional Analysis Theorem 3.25


Adicionar imagem JsPDF

Question: Tenho este script que gera um pdf de uma div. Más as imagens que contem na div não são geradas no pdf, alguém pode me ajudar?
$('#downloadpdf').click(function()
                {
                    var doc = new jsPDF('landscape', 'pt', 'a4');
                        doc.addHTML($('#dowextrato'), function()
                    {
                        doc.save("relatorio-<?php echo $Pnome; ?>.pdf");
                    });
                });

Answer: Para React:
Crie um HTMLImageElement e use-o como parâmetro da função doc.addImage

import autoTable  from 'jspdf-autotable'
import jsPDF from 'jspdf'

const image = document.createElement('img')
image.setAttribute('src', '/assets/images/imagem.png')

const gerarPDF = () => {
  const doc = new jsPDF()
  autoTable(doc, {
    margin: {top: 40},  //"empurra" a tabela para baixo, deixando espaco para imagem
    head: cabecalho,
    body: dados,
    didDrawPage: data => {
      doc.addImage(image, 'PNG', data.settings.margin.left, 15, 60, 20)
    }
  })
  doc.save('nomeDoArquivo')
}
Answer: Falou você adicionar o parâmetro:
doc.addImage(imgData, 'JPEG', 15, 40, 180, 160)

No site do plugin há um exemplo com imagens.
https://parall.ax/products/jspdf
Nessa demo há um exemplo com imagem em uma div.
https://codepen.io/bennettfeely/pen/RWMObL
Comment: Perfeito era isso mesmo!

Agora, sem querer abusar: "15,40,180,160" quais as posições?
Comment: Os parâmetros são: doc.addImage(imagem, 'formato da imagem', x, y, larguraimagem, alturaimagem);
Comment: Valeu amigo, obrigado mesmo!
Answer: Uso o Angular 11:
TS:

    import { jsPDF } from 'jspdf';

     // PDF Print
async printPDF() {
  let pdf = new jsPDF('p', 'pt', 'a4');
  pdf.html(this.geraEstruturaPDF(), {
  callback: (pdf) => {
     pdf.output("dataurlnewwindow");
  }
})

geraEstruturaPDF(){
        var style = "";

        var html = "";
        html += '';
        html += style;
        html += '
';
        html += `

                  Comprovante de transferência

`
    html += '
';
        html += '
';

 return html;
}

HTML:
<button (click)="printPDF()">Abrir página de impressão</button>

Comment: Sua resposta pode ser melhorada adicionando informações fundamentais. Basta [edit] para adicionar mais detalhes, como citações ou documentação para que outras pessoas possam confirmar que sua resposta está correta. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).

Adicionar imagem JsPDF


How can I use Drush 8 command to enable the site set up bin the Acquia DevDesktop to online mode?

Question: I forgot to put the site back online when I'd finished updating the site. How can I use Drush command to enable the site to online mode?
Answer: You are talking about maintenance mode. If you had use the correct term, you would have been pointed to for example the following question which has the info you need:
<code>drush sset system.maintenance_mode 0
</code>


Anonymous Flag with boost module enabled

Question: I have a node type which allow anonymous to use flag (Non global flag).
The problem is with Boost enabled, all anonymous users have the same flag status at the cached page.
For eg, anonymous A Bookmarked a node and the page get cached, when anonymous B visited the page she has the Bookmarked status as well which is undesirable.
How should i update the flag status by user?
Any suggestions are welcome!!
Answer: I'm not too sure, but you'd need to look into how Flag is handling the anonymous user session cookies. You may have to hack the code to add your own user-id and add it to the cookie...


Is there a hypothesis test that tells us whether we should use GAM vs GLM?

Question: Is there a hypothesis test that's ideally uniformly most powerful or metric that tells us whether we should use GAM vs GLM?
Does there exists some kind of metric i.e. AIC/BIC or loglikelihood to compare whether GAM vs GLM should be used?
May Cross-Validation be used to determine whether GAM or GLM should have been used?
Comment: A GAM is a GLM, just with a sophisticated predictor-generator (using base-splines). And yes, AIC/BIC, logLik and cross-validation are all fine to compare GAM and GLM. Note that mgcv::gam uses generalised cross-validation for fitting (as default), not maximum likelihood, but that shouldn't keep you. Just don't be surprised if the same model will be estimated slightly differently.
Answer: Simon Wood, the author of the mgcv package for R and a statistician who has made significant contributions to GAM theory and methods, has developed well-performing Wald-like tests for smooths. As such, you could fit a model with a linear term and a smooth with no null space and then use the test on the smooth term as a test for non-linearity (on the link scale).
m <- gam(y ~ x + s(x, m=c(2,0)), method="REML")

In the model above we ask for a linear term of x, plus a smooth of x. The m argument specifies that we want the usual penalty on the 2nd derivative of the smooth (measuring wiggliness) but we want a basis with no (0) null space. The null space of the basis is all the functions for which the wiggliness penalty doesn't apply, which includes the flat constant function and the linear function. By removing these two functions from the basis (usually only the flat, constant function is removed as it is confounded with the model intercept) the smooth represents the non-linear aspects of the model fit. Hence if it is significant that suggest non-linearity on the link scale which would not be modelled by the corresponding GLM.
Here's an example from ?mgcv::tprs
library("mgcv")
n <- 100
set.seed(2)
x <- runif(n)
y <- x + x^2*.2 + rnorm(n) *.1
df <- data.frame(x = x, y = y)

We're simulating data with a linear effect of x plus a weak quadratic effect of x, to simulate some small non-linearity. So, is the smooth significantly different from straight line?
m1 <- gam(y ~ x+ s(x, m=c(2, 0)), data = df, method = "REML")
summary(m1) ## not quite

The final output is:
Family: gaussian
Link function: identity

Formula:
y ~ x + s(x, m = c(2, 0))

Parametric coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept) -0.02133    0.05315  -0.401    0.689
x            1.18249    0.10564  11.193   <2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Approximate significance of smooth terms:
        edf Ref.df     F p-value
s(x) 0.9334      8 0.304  0.0781 .
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

R-sq.(adj) =   0.91   Deviance explained = 91.1%
-REML = -70.567  Scale est. = 0.012767  n = 100

We see that the smooth isn't quite significant at the 0.05 level (note the p values are approximate anyway, just like in a GLM, just a little more so as we chose the smoothness parameter too).
This compares with the model containing a smooth that has a null space (i.e. it contains the linear term). Now we see that the full smooth is significantly different from 0, but we cannot separate the linear and non-linear parts of the smooth:
## is smooth significantly different from zero?
m2 <- gam(y ~ s(x), data = df, method = "REML")
summary(m2) ## yes!

Family: gaussian
Link function: identity

Formula:
y ~ s(x)

Parametric coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept)   0.5600     0.0113   49.56   <2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Approximate significance of smooth terms:
       edf Ref.df     F p-value
s(x) 1.933  2.417 413.1  <2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

R-sq.(adj) =   0.91   Deviance explained = 91.1%
-REML = -69.353  Scale est. = 0.012767  n = 100

Notice that these models are essentially the same; the first is just separating out the linear basis function from the smooth basis which we add back in as an explicit linear parametric term.
In this case there isn't much to be gained from the GAM, but the true data generating process would be non-linearity, i.e. the GAM. With more data we'd be able to detect the non-linearity more easily, but this shows the problem of selecting between a GLM and a GAM. As such, unless you have a strong a prior guide that the effect is linear (on the link scale), then you should use a GAM and trust in the wiggliness penalty to decide if we need the non-linear bits.
As such you could just use the second model form (m2). You only need to decompose (m1) if you want an explicit test on the non-linear component.
Notice also that I use method = "REML"; choosing smoothness parameters using REML or ML selection is preferred today as GCV has been shown to undersmooth in circumstances where the GCV criterion is flat around the minimum.
Comment: This is a very informative post. Thank you. I am wondering if the ideas here can be generalized, however. For example, how might you specify testing the signficance of the nonparametric component above say a quadratic parametric model? Would you increase the order of the derivative penalty while retaining a basis with no null space in an analogous way?
Comment: I am away from keyboard just now, but I'm pretty sure I've answered that somewhere before… I think it you were to set `m=c(3,0)` then that would mean constant, linear, & quadratic functions are in the span of the null space and thus removes from that basis. But I'd need to check and the devil might be in the detail.


Creating a controlled form with Grommet throws errors

Question: I am trying to create a basic form using Grommet following the examples at https://v2.grommet.io/form. My specific form looks like this:
import React from 'react';
import { Box, Form, FormField, TextInput, Button } from 'grommet';

const defaultValue = {};

const LoginForm = () => {
  const [value, setValue] = React.useState(defaultValue);

  function handleSubmit(e) {
    e.preventDefault();
    const { email, password } = e.value;
    console.log('pretending to log in:', email, password);
    // doLogin(email, password)
  }

  return (
    <Form
      value={value}
      onChange={nextValue => {
        setValue(nextValue);
      }}
      onReset={() => setValue(defaultValue)}
      onSubmit={handleSubmit}
    >
      <FormField label="email" name="email" required>
        <TextInput name="email" />
      </FormField>
      <FormField label="password" name="password" required>
        <TextInput name="password" />
      </FormField>
      <Box direction="row" justify="between" margin={{ top: 'medium' }}>
        <Button type="reset" label="Reset" />
        <Button type="submit" label="Login" primary />
      </Box>
    </Form>
  );
};

As soon as I start typing into either field, I get the following:
Warning: A component is changing an uncontrolled input of type undefined to be controlled. Input elements should not switch from uncontrolled to controlled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component. More info: ...

Note that I get the exact same error if I replace my form code with a cut/paste from the example in the link above.
I have a fairly reasonable understanding of what the error means, but I have no idea how to fix it in this case. Is Grommet's implementation of controlled form components broken, or am I missing something elsewhere in my configuration or packages that might be causing this?
Answer: The React.js controlled standards are not allowing objects to be undefined.
So the problem starts with how you've defined your defaultValue = {};, since it is an empty object, there is no initial value to the FormField children and that causes them to be undefined and hence the error.
So if you'll change the preset value to be more accommodating to your fields, such as defaultValue = { password: '' }; it will fix your error.
For more reading about React controlled and uncontrolled inputs read this A component is changing an uncontrolled input of type text to be controlled error in ReactJS
Comment: This seems awkward, like the Form component already knows enough from the fields in the form that it should be able to generate a reasonable default. However, it does fix the issue. Thanks!


What properties do you lose when you extend your number set?

Question: So in $\mathbb{R}$ and $\mathbb{C}$ you have both associative and commutative property, but as you extend to $\mathbb{H}$ you lose the commutative property, and $\mathbb{O}$ loses the associativity. What more can you lose once you extend beyond $\mathbb{O}$? Are there some lesser known or weaker properties which holds for all extensions, or are do all such rules eventually disappear as you extend?
Thanks in advance.
[Also if someone could correctly tag this question, that would be nice]
Comment: I will extend $\Bbb R$ by adding a new element $\star$ with the property that $1 + \star = 2$ and $2 - \star = 17$. What property have we lost?
Comment: @MJD I don't know what this property is called, but $\star$ wouldn't have any inverse in addition.
Comment: You've lost more than that; you've lost the property that if $a+b=c$ then $c-b=a$.  Or maybe you've lost the property that every number has an additive inverse.  Or maybe you've lost the property of associativity.  Or…
Comment: This [question](http://math.stackexchange.com/questions/86434) has been [asked](http://math.stackexchange.com/questions/641809) several times [before](http://math.stackexchange.com/questions/335230).
Comment: @Lucian Thanks, although it seems none of those questions have an accepted answer. Where should I find an answer?
Comment: An accepted answer just means that the person who asked the question, who may not know any more than you, bothered to click the check mark. The lack of an accepted answer does not mean that the answers there are not correct or that they will not satisfy you.
Comment: @MJD After having read some of the answers, they don't fully answer the questions. Well isn't this sad, finding out the question has been asked before but not answered ...
Comment: @fvel If they don't fully answer your questions, you should explain why. Then maybe someone can answer whatever is left that you want to know.
Answer: You lose associativity, but retain power associativity: see this Wikipedia article.


trying to set the logging for REALM / Tomcat and Intellij

Question: I am using Intellij 11 and trying to debug REALM and LDAP
i found this article
Configure debug logging for Realms and Authentication
the problem is that i am modifying the CATALINA_HOME/conf/logging.properties and
intellij seems to be ignoring it.
Any suggestions or help would be appreciated
thanks
Comment: IDEA will use a copy of this file under [idea.system.path](http://intellij-support.jetbrains.com/entries/23358108)`\tomcat\\conf\logging.properties`. Check that it's modified as well.
Comment: hello, thanks
when i start the webapp, i can open the logging.properties in system.path location and it has the correct settings (as mentioned in the article) but no REALM debug output at all
Comment: Does it work outside of IDEA if you start Tomcat normally and deploy your app manually?
Comment: yes, if i deploy locally in tomcat it works, just does not work in intellij
Answer: It appears to be a bug in Tomcat integration. I've created an issue in YouTrack, please vote.


How to add a specific menu item in Panels?

Question: I am using Drupal 7. I made use of panels to partition the look of a page. I would like to know whether it is possible to add "A specific menu item" in the panels? I have used node templates to generate this page. I have 6 menu items(main menu), i want only one of them to be present in the panels.
Thanks in advance.
Answer: To the best of my knowledge, Panels can only interact which whole menues.
One option is using Menu block to slice a menu into pieces, exposed as blocks. I don't think menu blocks however can pick one item, though I haven't looked at all the advanced options.
If you just want a single menu item, can you just emulate the markup?
Comment: This is what I do-- I just add 'new custom content' and then cut and paste the code from the menu inside.


Animate a hamburger menu from Tailwind in Angular

Question: I'm using Tailwind UI in an Angular application and can open / close the hamburger menu with the following

    <button type="button" (click)="toggleMobileMenu()"
      class="bg-white rounded-md p-2 inline-flex items-center justify-center text-gray-400 hover:text-gray-500 hover:bg-gray-100 focus:outline-none focus:ring-2 focus:ring-inset focus:ring-indigo-500">
      <svg class="h-6 w-6" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor"
        aria-hidden="true">
        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16M4 18h16" />
      </svg>
    </button>

        <button (click)="toggleMobileMenu()" type="button"
          class="bg-white rounded-md p-2 inline-flex items-center justify-center text-gray-400 hover:text-gray-500 hover:bg-gray-100 focus:outline-none focus:ring-2 focus:ring-inset focus:ring-indigo-500">
          <svg class="h-6 w-6" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor"
            aria-hidden="true">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
          </svg>
        </button>

            Home

toggleMobileMenu() {
  this.mobileMenuOpen = !this.mobileMenuOpen;
}

This is a really simple example.
How do I animate this?
The instructions are :
    Mobile menu, show/hide based on mobile menu state.

    Entering: "duration-200 ease-out"
      From: "opacity-0 scale-95"
      To: "opacity-100 scale-100"
    Leaving: "duration-100 ease-in"
      From: "opacity-100 scale-100"
      To: "opacity-0 scale-95"

and I don't know how to translate that to an angular animation
Comment: Did you checked this one ? https://angular.io/guide/transition-and-triggers Should be as easy as settings classes on specific listeners during your transitions. (I'm not into Angular so cannot help further on)
Comment: I prefer to use the native angular animation, and have that integrated with Tailwind
Answer: Below is an approach I would follow.

Ensure to import BrowserAnimationsModule

@NgModule({
  imports: [ BrowserModule, BrowserAnimationsModule, ... ],
  ...
})

Under your @Component decorator create animations array as below

@Component({
  ,,,,
  animations: [
    trigger("openClose", [
      // ...
      state(
        "open",
        style({
          opacity: 1,
          transform: "scale(1, 1)"
        })
      ),
      state(
        "closed",
        style({
          opacity: 0,
          transform: "scale(0.95, 0.95)"
        })
      ),
      transition("open => closed", [animate("100ms ease-in")]),
      transition("closed => open", [animate("200ms ease-out")])
    ])
  ]
})

In the animations array we have included below

trigger("openClose", [ ...]) which defines the name of our trigger. This will be used in the HTML template to bind to a dom element

define 2 state using state('stateName' In our example above, the state names are open and closed

Under state we define the styles using style({ ... })

We finally define transition using transition(...). This will define the timing and animation style

More on animations Angular animations

Define a getter for the state

get openCloseTrigger() {
  return this.mobileMenuOpen ? "open" : "closed";
}

Bind state to getter to in the HTML

Everything should be ready and your menu should animate as desired
See this demo on stackblitz
Closing the browser on navigation
We can leverage NavigationEnd event to achieve this functionality. When a user is on a specific page, then they will not navigate away from the page hence no NavigationEnd. The menu will remain open but when they navigate to another page, NavigationEnd event will be called and the menu will close
This is the approach
constructor(private router: Router) {}
  navigationEnd$ = this.router.events.pipe(
    filter(event => event instanceof NavigationEnd),
    tap(() => (this.mobileMenuOpen = false))
  );

  ngOnInit() {
    this.navigationEnd$.subscribe();
  }

See this functionality on stackblitz
Comment: Simply set `this.mobileMenuOpen = false;`
Comment: Additionally to @Pieterjan suggestion, we can also add `NavigationEnd` event to watch when user navigates away from the page. When this happens, then we call `this.mobileMenuOpen = false`.  See updated solution
Comment: Yes and I put the entire `trigger` block in a new `ts` file to make it reusable.
Comment: Below is an example of extracted trigger in a new file based on @Pieterjan comment above https://stackblitz.com/edit/angular-ivy-99gnub
Comment: Thank you, this is great - how do I close the menu if the user clicks on an item in it?  Ie, if they click on home they route to there but the menu stays open.  @OwenKelvin
Answer: Here is an approach that uses only tailwind classes for animation. Here is a stackblitz demo
And here is a brief explanation.
Initially for the mobile menu div we set the tailwind classes which keeps the div in a hidden state. and to do so we have used.
scale-95 , opacity-0 and we have also used pointer-events-none to avoid interactions in hidden state.
and when the menu is active we add the following classes.
scale-100, opacity-100 and pointer-events-auto.
and to animate these properties we have used the transition class on the div and the  duration-200 class for the transition duration.
    <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet">

            <button type="button" (click)="toggleMobileMenu()"
          class="bg-white rounded-md p-2 inline-flex items-center justify-center text-gray-400 hover:text-gray-500 hover:bg-gray-100 focus:outline-none focus:ring-2 focus:ring-inset focus:ring-indigo-500">
          <svg class="h-6 w-6" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor"
            aria-hidden="true">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16M4 18h16" />
          </svg>
        </button>

                    <button (click)="toggleMobileMenu()" type="button"
              class="bg-white rounded-md p-2 inline-flex items-center justify-center text-gray-400 hover:text-gray-500 hover:bg-gray-100 focus:outline-none focus:ring-2 focus:ring-inset focus:ring-indigo-500">
              <svg class="h-6 w-6" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor"
                aria-hidden="true">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
              </svg>
            </button>

                            Home

So, just by using the right tailwind classes, you can achieve the animation effect.
Answer: This thread really helped point me in the right direction. Using Angular 14 & TailwindUI Here is what ended up working for me.
I needed to render a notification to display the response from an http request. I have created a NotificationService that I subscribe to that handles the show (emit). I found this SO thread(s) to be super helpful accomplishing that.
// app.component.ts

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css'],
    providers: [],
    animations: [
        trigger('renderNotification', [
            transition(':enter', [
                style({
                    transform: 'translateY(0.5rem)',
                    opacity: 0,
                }),
                animate(
                    '150ms 0ms ease-out',
                    style({
                        transform: 'translateY(0)',
                        opacity: 1,
                    })
                ),
            ]),
            transition(':leave', [
                style({
                    transform: 'translateY(0)',
                    opacity: 1,
                }),
                animate(
                    '100ms 0ms ease-in',
                    style({
                        transform: 'translateX(0.5rem)',
                        opacity: 0,
                    })
                ),
            ]),
        ]),
    ],
})
export class AppComponent implements OnInit {
    showNotification: boolean = false;
    ...
}

            <app-notifications
                class=""
                [@renderNotification]="notification.show"
                *ngIf="showNotification"
                [type]="notification.type"
                [title]="notification.title"
                [body]="notification.body"
                (closeNotificationEvent)="closeNotification()"
            ></app-notifications>

    ...

        <router-outlet></router-outlet>

Hope this helps someone else!


What is the appropriate regression type and approach when dealing with multiple continuous and categorical variables?

Question: I am trying to figure out the best approach to deal with cross-correlated variables in statistical analysis.
I am helping to analyse results of a randomised control trial for an educational intervention for a group of poor pre-school children in three different localities. We set up a trial with an experimental group and an intervention control group in each of the locations where students were randomly assigned to each.
We see a strong effect of age of children and time spent by children on the activities (the participation was voluntary) with the test results. However, one of the locations ended up concentrating a group of children that were most active. We have qualitative explanations for why that is the case, however, we would like to see whether we can tease out the effect of time spent at the activities.
Working in the Python language, I have tried different approaches – hierarchical regression where I have an issue how to input individual variables. Multiple regression where I am uncertain how valid this approach is for binary categorical variables (this holds also for hierarchical version). What is the appropriate analysis for two continuous variables (age, time at activities) and one categorical (three locations) for this problem?
Comment: What are your variables? What is the design of the study? What is the response?
Comment: You should not use stepwise regression.  All the output is incorrect.
Comment: Variables - Time (mins in educational activities), Age (years and months), Locale (municipality where the study took place). In each locality, students were in one of two different educational interventions (experimental and control intervention) but since this was an extracurricular activity they could take different amount of times in each (hence the time variable). At this stage, we are interested in finding out to what extent any of these variables affects their results on cognitive tests that were administered to them at the end of the interventions.
Comment: There is nothing wrong with using a categorical variable (treatment group) with two levels or location (with 3 levels) in regression. Is that what you were wondering?
Comment: Thanks! Yes that was the first thing that I was worried about. The second one is what is the right approach to input individual predictors in step-wise regression when you are facing [multi-collinearity problem](http://stats.stackexchange.com/questions/14500/how-can-a-regression-be-significant-yet-all-predictors-be-non-significant) which is what I am facing. I want to make sure that at each step I make an unbiased input of predictors (i.e. which goes first, second, etc.) and follow the best-practices here.
Answer: First, the "type of regression" (e.g. OLS, logistic ...) depends mostly on the nature of the dependent variable. When that variable is continuous, the usual starting point is ordinary least squares, but there are alternatives.  Your dependent variable appears to be "time spent on an activity" which could be continuous or not, depending on how you measured it.
Second, variable selection for models has been covered many times here.  Stepwise is not a good method.
Third, one assumption of most forms of regression is that the errors are independent. Since you have multiple locations with multiple people at each, this assumption is likely to be violated.  One solution is to use multilevel models.


value of type 'AnyObject' has no member age

Question: here is my code for a program which actually worked for one other application but here when I am using again it is saying Value of type 'AnyObject' has no member 'age'
this is the code i used to save the data to coredata
            let user = User(context: context)
            user.name = username.text!
            user.age = Int16(userage.text!)!
            appDelegate.saveContext()

            print("user name and age saved")

below I am using action button to retrieve core data
@IBAction func retrieve(_ sender: UIButton) {

    do {
        let data = try context.fetch(User.fetchRequest())

        for each in data {

        print("Name : \((each as AnyObject).name! ?? "name!")\nAge : \((each as AnyObject).age!)\n")
        }
    }
    catch {
        // handle error
    }
}

please help me where I am wrong also swift seems unpredictable when using 'User' of CoreData entity sometimes it did not detect
Answer: Do not cast up the concrete type User to unspecified AnyObject
print("Name : \(each.name)\nAge : \(each.age)\n")

If you get compiler errors consolidate the generic syntax of FetchRequest
Comment: No that is not correct, swift force you to accept each as AnyObject
Comment: Then your Core Data environment is wrong. `fetch` with a generic request is supposed to return an array of the associated type. Try this syntax : `try context.fetch(User.fetchRequest()) as! [User]`


Can't connect to MySQL server, "Unknown error"

Question: I'm running a series of server programs on Windows Server 2016 that are using a MySQL server (MariaDB 10.0.27). At first everything is fine, the servers connect to the database, clients can connect to the server programs, everything is within expectations. But after the programs have been running for a few hours I suddenly can't create any new connections to the MySQL server anymore. The server programs are still running, I can connect to them, and they appear to still be using the database server, but when I try to connect to the MySQL server myself I get the following error message:
ERROR 2003 (HY000): Can't connect to MySQL server on '127.0.0.1' (10055 "Unknown error")

At first the error message said the following, but a search led me to increase the number of available TCP ports, as a lack of those was supposedly the cause for that error.
(HY000/2002): An operation on a socket could not be performed because the system lacked sufficient buffer space or because a queue was full.

My MaxUserPort registry setting is now currently 51024. However, the problem didn't disappear, only the error message changed.
Now when I close the server programs I can create new connections again just fine, without changing anything about the continiously running MySQL server, and after I start them again I can also still create new connections for a while. I was thinking it might be a MySQL connection number restriction somehow, but that setting is currently at 1500 in my.ini and I don't see any errors in the MySQL console.
max_connections = 1500

Also, I noticed that once I can't create new connections anymore, I also can't open any websites in my browser, getting the error ERR_CONNECTION_FAILED, which makes me think about that TCP port limit again. But when I run netstat I see less than 300 connections, and it's my understanding that even with default settings this should be fine. I can also start a web server but I can't open anything on it via HTTP from the same machine. I can access the web server's content from the outside though.
I'm at a total loss of what's going on here. Does anyone have an idea?
Comment: Sure sounds like you are hitting some resource limit: memory, handles, processes, open files, DB connections, sockets.  Take a look at your server programs to make sure they are shutting down connections and releasing resources properly.
Comment: @stark Unfortunately I can't change much about the server programs, though I know that they were working as is at some point in the past for someone else, which makes me believe that it's an issue with the system's configuration. What I can say is that the hard drive and the RAM have air to breath, so it's not them. The number of processes in the task manager is perfectly normal as well, not to mention that I can still start applications, and open sockets/connections would appear in netstat, would they not? =/
Answer: The problem turned out to be socket/handle exhaustion. I first used ProcessExplorer to monitor the server processes, and they kept creating new handles, namely sockets, presumably trying to connect somewhere. I guess they didn't properly dispose those connections or something, because over time those several processes accumulated >60k handles each before I couldn't create new connections anymore.
I then used TCPView to monitor the server's connections and they kept trying to connect to something on a local port, where the servers expected a NoSQL server that I didn't know about before. As soon as I ran that database server the programs successfully connected to it and stopped creating new connections in an endless loop.


Aprender o ABC, em linguagem C?

Question: Como faço nesse código, quando ele digitar uma letra lida pelo teclado com o scanf do tipo (char) ela se repetir até o Z?
#include <stdio.h>
#include <stdlib.h>

int main()
{
    char c;

    /*for (c= 'A'; c<='Z'; c++){
        printf("Letra =  %c\n", c);
    } */
    system("pause");
    return 0;
}

Answer: Realize o scanf da letra, e suprima a inicialização do contador no for.
#include <stdio.h>
#include <stdlib.h>

int main()
{
    char c;
    char limit;
    scanf("%c", &c);

    if(c >= 65 && c <= 90){
         limit = 'Z';
    }else{
         limit = 'z';
    }

    for (; c<=limit; c++){
        printf("Letra =  %c\n", c);
    }
    system("pause");
    return 0;
}

Comment: @user24857 Acho que você quis fazer `for(; c<='Z' || c<='z'; c++) {`. Seu `for` "travou" (entrou num loop infinito) porque a segunda condição do "ou" - `'z'` - é sempre verdadeira (pois é diferente de zero). Já `c <= 'z'` pode ou não ser verdadeiro. Só que se você fizer o código assim, ele vai imprimir outros caracteres que não são letras (pois entre os intervalos `a-z` e `A-Z` existem vários símbolos).
Comment: Só funciona com letras maiúsculas. coloquei assim e travou for(; c<='Z' || 'z'; c++) {
Comment: Como faço o ||(ou) então no for para z e Z?

Aprender o ABC, em linguagem C?


Combobox items based on selected item in another combobox

Question: If I have a combobox1 has the items: Fruits & vegetables.
I need to show a nother combobox2 based on the selected item in combobox1.
If the selected item in combobox1 is Fruits, then  combobox2 items are: apple, orange ..etc.
If the selected item in combobox1 is vegetables, then  combobox2 items are: radish, lettuce..etc.
How can I do that using PHP & HTML? (Please consider "PHP & HTML only" as a condition).
Answer: Unfortunately your conditions (PHP & HTML only, not javascript) means you should reload the page/load another page with a form submission after every change on your combobox, as it would be the only way for you to understand what is the selected value since you decided to work only server-side (PHP).
If you decide not to take advantage of javascript (or a javascript framework such as jQuery) you won't be able to modify contents in your page without form submission, therefore you won't be able to change the second combobox elements if you didn't submitted the first combobox selection.
Answer: You can do this:

            <fieldset>
                <form>
                    <select name="combo" id="combo">
                        <option value="">-- Select</option>
                        <option value="1">Fruits</option>
                        <option value="2">Vegetables</option>
                    </select>
                    <select name="comboB" id="comboB">
                        <option value="">--</option>
                    </select>
                </form>
            </fieldset>

Then in the PHP page, you get an array with the data to be added to the drop box, of course you'll also have to send an ajax call to populate the drop box, then in the php page, you have the following:
<?php
    $Options = Array (
        1 => Array (
            'Apple' ,
            'Orange'
        ) ,
        2 => Array (
            'Radish' ,
            'Lettuce'
        )
    ) ;

    forEach ( $Options [ $_GET [ 'option' ] ] as $Item ) {
        printf ( '<option value="%s">%s</option>' , $Item , $Item ) ;
    }

Now, you just need to adjust the validations .. etc.
Comment: @Andry Knupp: I am not familiar with `ajax`, my tools are only PHP & HTML.. any suggestion?
Comment: @Andry Knupp: Can't be done using HTML & PHP only?kindly consider that as a conditon.
Answer: You can do this using jquery
Ex:

<select class="small-input" id="NameCombobox1" name="NameCombobox1">
    <option value="0">Select one</option>
    <option value="1">Fruits</option>
    <option value="2">vegetables</option>
</select>


Conversão de dados Long para Varchar

Question: Estou tentando fazer a conversão de dados de um campo Long para Varchar, porem quando faço o procedimento, esta retornando o seguinte erro:
ORA-01422: a extração exata retorna mais do que o número solicitado de linhas
ORA-06512: em line 4
O codigo que estou utilizando é o seguinte:
DECLARE
  VAR1 LONG;
  VAR2 VARCHAR2(32000);
BEGIN
  SELECT DS_EVOLUCAO INTO VAR1 FROM PRE_MED WHERE HR_PRE_MED = '01/08/2019';
  VAR2 := SUBSTR(VAR1, 1, 32000);
  DBMS_OUTPUT.PUT_LINE(VAR2);
END;
Os campos talves possam exceder os 32000 de espaço do campo, por isso usei o SUBSTR, mas mesmo assim não consigo sucesso.
Comment: Um SELECT em PLSQL deve retornar uma e somente uma linha, para mais de uma linha use um CURSOR, o erro nada tem com o TYPE ( que pode até ter também).
Answer: O select: "SELECT DS_EVOLUCAO INTO VAR1 FROM PRE_MED WHERE HR_PRE_MED = '01/08/2019';"
Deve estar retornado mais de um resultado, tente usar:
"SELECT DS_EVOLUCAO INTO VAR1 FROM PRE_MED WHERE HR_PRE_MED = '01/08/2019' AND ROWNUM < 2;"

Ou aumentar o numero de filtros.
Para imprimir todas as linhas você pode fazer assim:
"DECLARE
  VAR2 VARCHAR2(32000);
BEGIN
  FOR REG IN (SELECT DS_EVOLUCAO FROM PRE_MED WHERE HR_PRE_MED = '01/08/2019')
    LOOP
       VAR2 := SUBSTR(REG.DS_EVOLUCAO, 1, 32000);
       DBMS_OUTPUT.PUT_LINE(VAR2);
    END LOOP;
END;"

Comment: Porem eu preciso que traga todos os registros da data mesmo Bruno, é possível ?
Comment: Pode sim, já editei a resposta
Comment: Obrigado Bruno, agora se voce puder me ajudar, preciso inserir um LIKE '%SEPSE%' para trazer apenas os registros que tenham essa descrição no campo Long. Como consigo?
Comment: Não dá para fazer isso direto da coluna long ou você faz um if usando o varchar2 ou transforma o long em clob, mas neste ultimo caso vai depender da versão do oracle que esta usando.
Comment: Estou na versão 12c, porem acho q alterar o campo não sera viavel sem autorização do fornecedor do sistema... poderia me dar um exemplo de como fazer isso usando if com varchar2?
Answer: Basta criar essa função, passando como parametro a tabela, o campo e o ROWID do registro. A Funcao já converte o LONG para varchar2 limitando em 4000 caractéres.
create or replace function fn_longtovarchar(
       v_table varchar2,
       v_campo varchar2,
       v_rowid varchar2
) return varchar2 is
    t_sql varchar2(4000);
    t_varlong LONG;
    t_vartxt VARCHAR2(4000);
begin

  t_sql := 'select '||v_campo||' from '||v_table||' where rowid = '''||v_rowid||'''';

  execute immediate t_sql into t_varlong;

  t_vartxt := substr(t_varlong, 1, 4000);

  return(t_vartxt);

end;

Comment: Sua resposta pode ser melhorada adicionando informações fundamentais. Basta [edit] para adicionar mais detalhes, como citações ou documentação para que outras pessoas possam confirmar que sua resposta está correta. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).

Conversão de dados Long para Varchar


Feature engineering in marketing analytics in python

Question: Feature Engineering for marketing analytics in Python
I have a data with variables offer_id (e.g. 1,2,5,10....) and product_id (e.g. 6178,4184,5124,...). An offer_id can be applicable to multiple product_id.
How can I make a separate variable for each product_id such that if a particular offer_id is applicable on it then product_id variable get a value 1 otherwise it get a value 0.
The separate variables for each product_id must have either 0 or 1 as value. A value of 0 to indicate an offer_id is not applicable and a value of 1 to indicate that the corresponding offer_id is applicable.
Comment: Welcome to Stack Overflow. Please show the code that you have tried so far.
Answer: you could create new columns by mapping simple functions for each offer type to check for the value in the offer_id column. (if value == 5 return 1, else return 0 etc.).
Similarly, you could use the np.where to achieve the same thing. I.e. create new columns by doing conditional checks of the offer_id column.
eg: df['is_5'] = np.where(df.offer_id == 5, 1, 0)
(i.e. if offer_id == 5, return 1 else return 0).


How to pick two features that can linearly separate two classes as much as possible

Question: I have a few dataset, each has about 120 features/dimensions and two classes (e.g. A and B) in it. Now I'd like to visualize the dataset from just two dimensions without doing any dimensionality reduction. The criteria for picking the two dimensions is that they should separate the two classes as much as possible.
Here is what I have tried:

I tried a decision tree on each dataset and use the top two features with highest importance as the two dimensions. It works for some of them. But since the cutoff chosen by tree is always orthogonal to the axis, which I thought was a bit too restricted, then I tried a second approach
I trained a logistic regression binary classifier on each dataset with L1 regularization, which has the effect of feature selection. Then I order the features by their learned weights, and pick the two features at both ends (i.e. min and max) as the dimensions to visualize. Again, it works for some of the dataset, in contrast to a decision tree, the cutoff doesn't have to be orthogonal to either axis now.

However, I am still not sure if the above two ways are the best one to pick dimensions for visualization. Are there better ways, please?
Answer: You have 120 features and you want to find the pair of features that maximizes some criterion (which you describe as "separat[ing] the two classes as much as possible", but that isn't precise). 120 features means you have 120 choose 2 = 7,140 pairs to consider, which is certainly within the realm of possibility. Just write a double loop in your favorite programming language to evaluate all 7,140 pairs on the criterion.
Be aware that data-dredging like this, although perhaps descriptively useful, is unlikely to generalize. That is, the best pair out of 7,140 in this sample is unlikely to be the best pair in the population, unless the sample is really big.
Comment: I may have 50K features later. Agreed `separat[ing] the two classes as much as possible` is imprecise. There can be many criteria, what about getting the lowest number of misclassed samples (e.g. low information entropy/gini) by fitting a simple linear model. I am not as interested in prediction in this case, but rather inference.


Create function to count occurrences within groups in R

Question: I have a dataset with a unique ID for groups of patients called  match_no and i want to count how many patients got sick in two different years by running a loop function to count the occurrences in a large dataset
for (i in db$match_no){(with(db, sum(db$TBHist16 == 1 & db$match_no == i))}

This is my attempt. I need i to cycle through each of the match numbers and count how many TB occurrences there was.
Can anyone correct my formula please.
Example here
df1 <- data.frame(Match_no = c(1, 1,1,1,1,2,2,2,2,2, 3,3,3,3,3, 4,4,4,4,4, 5,5,5,5,5),
                  var1 = c(1,1,1,0,0,1,1,1,0,0,0,1,1,1,1,1,0,0,0,1,1,1,1,0,1))

I want to count how many 1 values there are in each match number.
Thank you
Comment: Please provide a reproducible example with some data and an expected result
Comment: Does this answer your question? https://stackoverflow.com/q/1660124/12400385
Answer: Some ideas:

Simple summary of all Match_no values:
xtabs(~var1 + Match_no, data = df1)
#     Match_no
# var1 1 2 3 4 5
#    0 2 2 1 3 1
#    1 3 3 4 2 4

Same as 1, but with a subset:
xtabs(~ Match_no, data = subset(df1, var1 == 1))
# Match_no
# 1 2 3 4 5
# 3 3 4 2 4

Results in a frame:
aggregate(var1 ~ Match_no, data = subset(df1, var1 == 1), FUN = length)
#   Match_no var1
# 1        1    3
# 2        2    3
# 3        3    4
# 4        4    2
# 5        5    4

Answer: In base R you can use aggregate and sum:
aggregate(var1 ~ Match_no, data = df1, FUN = sum)

  Match_no var1
1        1    3
2        2    3
3        3    4
4        4    2
5        5    4


Sentiment Analysis Dictionaries - positive, negative, neutral

Question: I would like to classify user comments in reply to articles on news portals, especially in my country. Many comments are tweet-like in length but others can be quite long (a few hundred words).
I tried an example in R (example analysed tweets) that uses Naive Bayes but am not satisfied with the results. I have turned to Python and found quite a few examples.
I have been looking all over the place to see whether I could find all three types of dictionaries but have only managed to find the positive an negative ones. I have looked at quite a few SO posts especially this post and all those others that were suggested to me after typing the question both on SO and CV. The reason I am looking for all three types of dictionaries is that I am following this tutorial and thought that I would replace the positive_vocab and negative_vocab in the example with the contents of Bing & Liu's Opinion Lexicon. So far so good, but in the same example there is also a neutral_vocab with around 10 words.
neutral_vocab = ['movie', 'the', 'sound', 'was', 'is', 'actors', 'did', 'know', 'words', 'not']

So I looked to see whether I could find a "neutral dictionary" of words similar to what Bing & Liu have. Does one such dictionary exist, or is it that the reason I could not find one is that I'm a complete dork and do not really need one as neutral words could be defined as all those words that are not positive or negative?
Could anyone please help me out in this? Thanks.
Answer: People don't usually use these fixed dictionaries of positive/negative/neutral words except for programming exercises. In naive bayes, which is closer to what people actually do, you give each word a score. Negative scores are negative sentiment words and positive scores are positive sentiment words. The words with scores near zero could be thought of as neutral words.
Comment: Ok. Thanks for your kind explanation and my apologies for the late reply.


I want to remove warning: "Replace this with a lock against an object with strong-identity"

Question: I have an ActiveX COM object that is used to play video and its being used in a C# application.  It is declared like so:
private AxVIDEOPLAYERUILib.AxVideoPlayerUI axVideoPlayerUI;

In my code there are locks on this like so:
lock (axVideoPlayerUI)
{
     axVideoPlayerUI.EnableControls = 1;
     axVideoPlayerUI.Visible = true;
     axVideoPlayerUI.ShowOverlay = 1;
     axVideoPlayerUI.OverlayPosition = 3;
     axVideoPlayerUI.Play();
 }

But I get warnings that I want to get rid of:

Warning   1   CA2002 : Microsoft.Reliability :
  'VideoPlayerControl.LoadRecording(RecordVideo, int)' locks on a
  reference of type 'AxVideoPlayerUI'. Replace this with a lock against
  an object with strong-identity.

From this link here http://msdn.microsoft.com/en-us/library/ms182290.aspx it states that the following objects have a weak identity:
MarshalByRefObject, ExecutionEngineException, OutOfMemoryException, StackOverflowException, String, MemberInfo, ParameterInfo, Thread.
But my object doesnt fall into any of these categories.
I have also tried making my object static as described here: C# lock and code analysis warning CA2002 but that gives me errors:

Error 1   Member 'MyNameSpace.VideoPlayerControl.axVideoPlayerUI' cannot
  be accessed with an instance reference; qualify it with a type name
  instead

Does anyone know how I can get rid of the original warning??
Answer: You can just declare a separate object to use for locking:
private AxVIDEOPLAYERUILib.AxVideoPlayerUI axVideoPlayerUI;
private object axVideoPlayerUILock = new object();

and:
lock (axVideoPlayerUILock)
{
   ...

COM Proxies are implemented by System.__ComObject, which in turn derives from MarshalByRefObject. Perhaps the guidance could be clearer that types derived from those mentioned are also not usable.
Comment: The documentation for [marshallByRefObject](https://learn.microsoft.com/en-us/dotnet/api/system.marshalbyrefobject?redirectedfrom=MSDN&view=netframework-4.7.2) seems to just show how to create a new object of that type from another applicationdomain. So the private field here still cannot be accessed from outside, and hence the warning is incorrect - it should only fire when you lock on one of those types, not on a private variable of that type.
Comment: @TamaMcGlinn - when compiling *a* method, the compiler doesn't tend to perform full escape analysis over all fields of classes that it's working with. There's no way *locally* to determine the lifetime of the object referenced by that variable. But it's a warning not an error precisely because it cannot prove that its incorrectly used either.


What is $\lim_{n \rightarrow\infty} \phi(T^{n}v)$

Question: I would please like to check my thinking on solving this problem:

$V$ is a finite dimensional vector space, and $T\in \mathcal L(V)$ is diagonalizable with all eigenvalues of $T$ less than one in absolute value. Given $\phi \in V'$ ($V'$ is the dual of $V$) and $v\in V$, what is $\lim_{n \rightarrow\infty} \phi(T^{n}v)$?

Since $T$ is diagonalizable, it can be represented as a matrix with the eigenvalues on the diagonal and zeros elsewhere. $T^{n}$ then would have the eigenvalues raised to the $n$th power on the diagonals. And since their absolute vales are less than one, as $n$ goes to infinity, the diagonal elements would go to zero. Thus $T$ becomes the zero operator.
Assuming this is correct, then I don't understand the reason the problem is phrased in the context of the dual operator, $\phi$ on $T^{n}v$
Thanks
Answer: $T$ will never become the zero operator because it is NOT the zero operator in the first place. Also, $\phi$ being a linear form on $V$ will map vectors onto scalars. Therefore it makes perfect sense to define $\phi(T^nv)$. As you said, becomes all the eigenvalues of $T$ are less than one in absolute value, it is clear that $\lim_n \|T^nv\|=0$, and therefore $\lim_n\phi(T^nv)=0$.
Comment: Since $V$ is finite dimensional $\phi$ is continuous, and therefore $\lim_n\phi(v_n)=\phi(v)$, where $v=\lim_nv_n$.
Comment: Thanks. I think you meant all the eigenvalues of $T$, rather than $\phi$? I didn't mean to imply $\phi(\dot)$ did not make sense. But I think I am then missing how you get from $\lim_n \|T^nv\|=0$ to $\lim_n\phi(T^nv)=0$, in that it seems you are not taking $\lim_n\phi(0)=0$, as I incorrectly assumed.


Combining duplications for backend blocks in haproxy.cfg

Question: I have this HAProxy config and as you can see I have many duplicated stuff in backends. Is there a way of getting rid of duplications such as stats?
global
    log 127.0.0.1 local0
    log 127.0.0.1 local1 notice
    daemon
    maxconn 2000

defaults
    log global
    mode http
    option httplog
    option dontlognull
    retries 3
    option redispatch
    timeout connect 5000ms
    timeout client 50000ms
    timeout server 50000ms

frontend http-in
    bind *:80
    acl url_a path_reg ^\/a$|\/a\/
    use_backend webservers_a if url_a
    acl url_b path_reg ^\/b$|\/b\/
    use_backend webservers_b if url_b
    default_backend webservers_main

backend webservers_main
    mode http
    stats enable
    stats auth admin:admin
    stats uri /haproxy?stats
    balance roundrobin
    option httpchk
    option forwardfor
    option http-server-close
    server web1 192.168.50.21:80 maxconn 32 check

backend webservers_a
    mode http
    stats enable
    stats auth admin:admin
    stats uri /haproxy?stats
    balance roundrobin
    option httpchk
    option forwardfor
    option http-server-close
    server web2 192.168.50.22:80 maxconn 32 check

backend webservers_b
    mode http
    stats enable
    stats auth admin:admin
    stats uri /haproxy?stats
    balance roundrobin
    option httpchk
    option forwardfor
    option http-server-close
    server web3 192.168.50.23:80 maxconn 32 check

Comment: You could insert another `frontend` bound to an private IP and move the `stats` directives there.
Comment: I've just added `frontend stats ......` and getting `'stats' ignored because frontend 'stats' has no backend capability.` error. Could you please show me an example?
Answer: You could add something like the following to your config:
listen stats
    bind ${PRIVATE_IP}:${PORT}
    stats enable
    stats uri /stats
    stats auth admin:admin

I'm assuming the following points:
You don't want to expose your stats to the public. If this is not the case, just move your stats into your existing frontend directive.
Substitute ${PRIVATE_IP} with an private IP which is available on your machine (or set up one for this), and ${PORT} with an unused port, for example 8080.
Caveat: If you use a different port than 80 in your stats directive, you would have to call your stats page by specifying the port in the url. To prevent and circumvent that:

Bind your frontend to ${PUBLIC_IP}:80, and your listen stats section to ${PRIVATE_IP}:80.


Is there a way to verify that code will work on the 360 while doing XNA dev?

Question: I'm working on a casual game on XNA with the intention of deploying to the Xbox 360.  I'm not going to have access to hardware for a few weeks and I'm on a tight deadline, so I'd like to test that a few things -- Boo and a few custom libraries -- will work properly on the 360.  If they don't, I need to work around them sooner rather than later, so testing this is quite important.
With that explained, is there a way I can go into a 'simulator' of sorts to run code on the .NET Compact Framework for 360 before actually deploying to the 360?
Answer: Well, you could try writing a quick app for a Windows Smartphone, and run it in an emulator. Obviously, this won't work for XNA specific code; but for any runtime libraries that Boo or whatever you're using work on the emulator, they should work on the Xbox.
For the XNA code you write yourself, just compile it against the Xbox 360 target.
Answer: As TraumaPony said. Simply load the main game assembly in to Visual Studio and try to compile it. It won't if you try to make a reference to an assembly outside the those that ship with the 360.
Answer: Aside from making sure that the libraries compile onto the 360, you will need to think about your project's object allocation profile.  Since the compact framework uses a different garbage collector, it's much more sensitive to constant allocations.  When it does a collection, it needs to walk the entire object graph instead of how the desktop collector uses generations.  So you will want to make sure that you're newing up as few objects as possible during runtime :-)
Answer: The key thing here is to understand that only .Net code will run on the Xbox 360, so any custom library you want to use must be a .Net assembly.  The second thing to understand is that the Xbox is running the compact framework, so anything that isn't included in that won't work.  This is easy enough to test against by compiling the project for the 360 like the above post.
To be honest, I took a quick look at Boo, and couldn't tell what it was built in, so I'm not sure if it will work.  I also don't understand the point of using Boo inside of XNA, but that's not what you're really asking.


How to manage your own Master Key in Gcloud KMS

Question: How to have one Master key in Gcloud and create Data Keys to encrypt.
And using the Master Key to decrypt the actual data.?
This is possible in AWS KMS. How to implement the same in Gcloud?
Thanks
Answer: By default, Compute Engine encrypts customer content at rest. Compute Engine handles and manages this encryption for you without any additional actions on your part. However, if you want to control and manage this encryption yourself, you can use key encryption keys. Key encryption keys do not directly encrypt your data but are used to encrypt the data encryption keys that encrypt your data.
If making the analogy with AWS "Master key" concept then "key Encryption key (GCP)" is the master key that is use to encrypt the "data encryption key"
AWS: "Plain Text Data"------>"data encryption key"---->"Encrypted data"
<code> "data encryption key"-----> "Master key(AWS)"----> "Encrypted data key"
</code>
GCP: "Plain Text Data"------>"data encryption key"---->"Encrypted data"
<code>"data encryption key"----->"key Encryption key(GCP)"----> "Encrypted data key"
</code>
As per document-1,You have two options for key encryption keys in Compute Engine:
1- Use Cloud Key Management Service to create and manage key encryption keys. For more information, see Key management. This topic provides details about this option, known as customer-managed encryption keys (CMEK).
2- Create and manage your own key encryption keys. For information about this option, known as customer-supplied encryption keys (CSEK), see Encrypting Disks with Customer-Supplied Encryption Keys.
Encryption: Cloud KMS keys are AES-256 keys. These keys are "key encryption keys" or "Master Keys"(AWS), and they encrypt the "data encryption keys" that encrypt your data.
Cloud KMS allows you to create, import, and manage "cryptographic keys" or "key encryption keys" or "Master Keys"(AWS) and perform cryptographic operations in a single centralized cloud service. You can use these keys and perform these operations by using Cloud KMS directly, by using Cloud HSM or Cloud External Key Manager, or by using Customer-Managed Encryption Keys (CMEK) integrations within other Google Cloud services.
Please note: If you provide your own "encryption keys" or own "key Encryption key" or ""Master key(AWS)" , Compute Engine uses your key to protect the "Google-generated keys" or "data encryption keys"  used to encrypt and decrypt your data. Only users who can provide the correct "key Encryption key" can use resources protected by a customer-supplied encryption key.


Javascript - Eval a Object dynamically to change its value

Question: I got a object name, set1 to set4 , I need to dynamically change their value in a loop with using eval() , or window, below example is using eval(), I had used window[] but still remain same result, that can't successfully changed the object's value with the 'make+set' function.
var set1 = {desc:"111",url:"http://photo1.com"};
var set2 = {desc:"222",url:"http://photo2.com"};
var set3 = {desc:"333",url:"http://photo3.com"};
var set4 = {desc:"444",url:"http://photo4.com"};

function make_set(set,desc,url) {
     set = {};
     set.desc = url;
     set.url = url;
    return set;
}

for (var i = 1; i < 5; i++) {
    tempSet = eval("set"+i);
    tempSet = make_set(tempSet,"new description","new url");
    console.log(tempSet)
};

console.log(set1);
console.log(set2);
console.log(set3);
console.log(set4);

I had overwrite the object with make_set function but still can't successfully changed the value with the function, am I doing it wrong on function? or I missed out anything?
Object {desc: "new url", url: "new url"}
Object {desc: "new url", url: "new url"}
Object {desc: "new url", url: "new url"}
Object {desc: "new url", url: "new url"}
Object {desc: "111", url: "http://photo1.com"}
Object {desc: "222", url: "http://photo2.com"}
Object {desc: "333", url: "http://photo3.com"}
Object {desc: "444", url: "http://photo4.com"}

Comment: Why are you doing this? Use an array.
Answer: You are creating a new object, and setting tempSet to that, not modifying existing sets.
for (var i = 1; i < 5; i++) {
    tempSet = eval('set' + i + ' = make_set(tempSet,"new description","new url")');
    console.log(tempSet);
};

But you really shouldn't use eval.
var sets = [];
sets[0] = {desc:"111",url:"http://photo1.com"};
sets[1] = {desc:"222",url:"http://photo2.com"};
sets[2] = {desc:"333",url:"http://photo3.com"};
sets[3] = {desc:"444",url:"http://photo4.com"};

function make_set(desc, url) {
    return {desc:desc, url:url};
}

for (var i = 0; i < 4; i++) {
    sets[i] = make_set("new description","new url");
    console.log(sets[i])
};

console.log(sets[0]);
console.log(sets[1]);
console.log(sets[2]);
console.log(sets[3]);

Answer: Remove the line set = {};
It's creating a new object, not changing the passed in object.
Live Demo
See the answers to "Why isn't this object being passed by reference when assigning something else to it?" for a more detailed explanation.


components are separated when they are suppose to be in succession vertically

Question: I want the image and the title (JLabel) to both me centered and be at the top of the page but instead the image is at the top of the page and centered but the title is 3/4ths of the way down the page and centered.
<code>    GridBagConstraints c = new GridBagConstraints();
    c.anchor = GridBagConstraints.NORTH;
    c.insets = new  Insets(10, 0, 0, 0);
    c.weighty = 1;
    c.gridy = 0;
    panel.add(image,c);
    c.gridy = 1;
    panel.add(title, c);
</code>
Comment: Also, best to post code that we can *fully* run, meaning a [mre] code post, also with additional text that tells the details of the code.
Comment: Suggestion:  Add [gridbaglayout] tag to the question, and possibly the [swing] tag.
Answer: <code>c.weighty = 1;
c.gridy = 0;
panel.add(image,c);
c.gridy = 1;
panel.add(title, c);
</code>
You don't reset the "weighty" constraint so it is used for both components. Therefore, the "extra" space in the frame is allocated equally to each component. So you see the extra space between the two components.
Add a Border to each component and you will see the actual size of each component.
The solution is to assign set the "weighty" constraint to only the second component so the first component is displayed at its preferred size.
<code>//c.weighty = 1;
c.gridy = 0;
panel.add(image,c);
c.gridy = 1;
c.weighty = 1;
panel.add(title, c);
</code>


Issue when I join three tables

Question: I have three tables TeamTerritoryMapping, UpdQuotaTbl and tblInvoiceFile
When I join the first two tables I am getting the correct result
 select
     TTM.Team, Sum(Upd.Quota) as Quota
 from
     TeamTerritoryMapping TTM
 inner join
     UpdQuotaTbl upd on upd.ITM = TTm.Territory
 where
     upd.Month = 'july'
 group by
     TTM.Team

but when I join the third table for another column revenue from tblinvoicefile, some of the rows are getting duplicated and the end result is becoming higher. Below is the query which I am using to join 3 tables
select
    TTM.Team,
    Sum(upd.Quota) as quota,
    sum(inv.[End MS Sales Revenue]) as Revenue
from
    UpdQuotaTbl Upd
inner join
    TeamTerritoryMapping TTM on TTM.Territory = upd.ITM
inner join
    tblInvoiceFile inv on inv.[Inv Territory] = TTM.Territory
where
    upd.Month = 'july'
    and inv.[End Fiscal Month] = 'July, 2013'

So how can I eradicate the duplicate values in third table, I am getting the correct value when I join two tables ie TeamTerritoryMapping,UpdQuotaTbl and also tables TeamTerritoryMapping.
Comment: Second query doesn't have `group by`.
Comment: It appears you have more than one quota for the same territory somewhere? Either that, or one invoice is mapping to more than one territory?  More than likely it's the duplicate Territory entries in TeamTerritoryMapping.
Comment: @Win If you're only getting a single SUM(), ie one number, you don't need a group by.  He might need an extra level of query with internal group by in this case, but it's a bit more complicated than just "add missing group by".
Comment: @ebyrob Huh, if you do `SELECT field, SUM(value) FROM table` then you most certainly need a `GROUP BY` on `field`. I know it would (kind of) work on e.g. mysql, but the result would be 'unpredictable'. AFAIK the syntax would fail on all versions of MSSQL.
Comment: @deroby I admit I have a heavy MySQL slant but the result of bare aggregate is hardly unpredictable.  (well field might be semi-random in a very few cases.  `GROUP BY 1` to fit the SQL standard certainly won't alleviate that).  Ah ok, he does drop the `GROUP BY` between the two queries, which is suspicious but hardly much to go on.
Comment: @user3417326: Do I understand this correctly; you want to show all TTMs that have at least one upd in July and at least one inv in July. For These you want to have the total quota for July and the total Revenue for July. Yes?
Answer: It looks like tblInvoiceFile has multiple entires for [Invenio Territory] which is causing this issue.  If your intention is to bring in and sum all the [End MS Sales Revenue] for that table you can try something like this
SELECT TTM.Team,Sum(upd.Quota) as quota,sum(inv.[End MS Sales Revenue]) as Revenue
FROM UpdQuotaTbl Upd
    INNER JOIN TeamTerritoryMapping TTM ON TTM.Territory = upd.ITM
    INNER JOIN
        (SELECT [Invenio Territory], SUM([End MS Sales Revenue]) AS [End MS Sales Revenue]
            FROM  tblInvoiceFile
            WHERE [End Fiscal Month] = 'July, 2013'
            GROUP BY [Invenio Territory]) AS inv
        ON inv.[Invenio Territory] = TTM.Territory
WHERE upd.Month = 'july'

Comment: Shouldn't SUM(lots of records) in the end give the same result as SUM(SUM(unique records)) ?
Comment: My bad. The result would be identical for the `SUM` on the `[End MS Sales Revenue])` field from `tblInvoiceFile`, but it would mess up the one on `upd.Quote`. +1
Comment: I'm still not sure how you know **where** the duplication is.  Did I miss a fiddle or a result set somewhere?  (not to mention where you're getting column names not quite matching the original question...)
Comment: I tried using your code but the sub query is summing up the duplicates for revenue when you group by Invenio Territory.
which is giving the same result
Comment: if infact there are dups in tblInvoiceFile then you can simply do a MAX in the subquery instead of SUM.   I thought there was a one to many relationship between the two tables.
Answer: My initial response would be : The reason you're getting some results multiple times is because the ON used to join tblInvoiceFile is not 'unique' enough. If you look at the primary key (or a unique?) of said table you'll probably notice that it involves more than just the Inv Territory field.
To solve it you can do two different things.

Expand the ON clause to include more fields that make the connection unique
Keep the query as it is now but aggregate the results so the invoice information gets SUMmed

The problem is, it seems like you're already SUM()-ing the information (although as noted by Win, you're missing the GROUP BY), so I'm not quite sure why this would not work.
UPDATE: Only now realise that your problem is not doubled records, but doubled values in the first SUM(). Best way to solve this is by PRE-aggregating the values as shown by Abhi.

Issue when I join three tables