JQuery multiple slideshows with the same previous/next buttons

Question: I'm trying to figure out a frustrating issue.
What I have now :

One ul containing two li, each containing one 3x3 table.
A jQuery "slideshow" script to show one table at once.
Two div on each side of the table (used for the "slideshow", prevButton and nextButton).
Clicking on a td "expands" a specific div covering the whole 3x3 table (prevButton and nextButton are still visible).
Clicking on an expanded div closes it and the table is visible again.
When no div is expanded and the table is visible, the nextButton and prevButton are used to go to the next/previous table.

http://jsfiddle.net/m1djrrj8/
What I'm trying to do :

When a div is expanded (by clicking on a td), the table is covered and the nextButton and prevButton should NOT be used to go to the next/previous table, but rather be used to show the next/previous expanded div.

Rough structure of the fiddle

Understanding with the Fiddle

There are two tables with 9 cells (1,2,3,4,5,6,7,8,9) and (A,B,C,D,E,F,G,H,I), swap from one to another by clicking on the yellow sidebars.
Clicking on each cell opens a specific div :

(1,2,3,4,5,6,7,8,9) displays (sq1,sq2,sq3,sq4,sq5,sq6,sq7,sq8,sq9)
(A,B,C,D,E,F,G,H,I) displays (sqA,sqB,sqC,sqD,sqE,sqF,sqG,sqH,sqI).

when sq1~9 or sqA~I is displayed, I would like to use the yellow sidebars to slideshow sq1 through sq9 or sqA through sqI instead of switching tables.

The JSFiddle is a bit long and I apologize for that, but I would be really grateful if someone could help me out with this one; I'm tearing my hair out!
Comment: After 3 looks at your demo and reading all over again your question it's not clear what's covering what, Li, UL TABLE next prev what?
Comment: I have updated the OP adding a picture of how it is structured (had to upload to tinypic, there is a 10 rep restriction to post images, sorry for the trouble), does that help ?
Answer: ".button" is programmed to swich between
's. So when you click the prev button or the next button, the current
 disappears and the other
 appears.
To get the desired result, you have to change the logic:

Check if a
 covers the table.
If so, hide the
 and show the next
.


Sum of idempotent and nilpotent minimal right ideals

Question: One may decompose the right socle $S_r$ of any unital ring $R$ as $S_r=S_1\oplus S_2$, where $S_1$ is the sum of all nilpotent minimal right  ideals, and $S_2$ is the sum of all idempotent  minimal right ideals of $R$. I want to prove that $S_1$ and $S_2$ are two-sided ideals.
As for $S_1$ (resp. $S_2$) , let $x\in S_1$ (resp.$S_2$) and write $x=r_1+\cdots +r_n$, where $r_i\in I_i$, for some idempotent (resp. nilpotent) minimal right ideal $I_i$. If $s\in R$, it suffices to show that $sx\in S_1$(resp. $S_2$). Each $sr_i$ belongs to $sI_i$.  But I do not know how to link these to expressions $xs$ and $r_is$. Incidentally, I do know that any sum of ifempotent right ideals is again an idempotent right ideal so that $S_2$ is such. Also, it is easily shown that $S_1^2=0$.
Thanks for any help!
Comment: By the way, can you let us know when the publications these questions generate appear? Surely they're getting close, with all the material in response to your questions...
Answer: This seems more or less obvious that they necessarily lie in different Wedderburn components of the socle.
That is, the sum of the collection of minimial right ideals in a fixed isoclass forms an ideal, and the direct sum of these ideals equals $S_r$. Obviously the ones that are idempotent and nilpotent lie in separate components. The sum of the components for nilpotent minimal ideals and the sum of the component for idempotent minimal ideals clearly decompose the socle into two smaller ideals.
Comment: The class of $R$ modules is partitioned by the equivalence relation "isomorphic."  An isoclass is one equivalence class. Lots of proofs of the Artin-Wedderburn theorem use the lemma that the sum of minimal ideals isomorphic to a fixed minimal ideal is an ideal in the ring. The proof that the component ideals intersect trivially goes much like the one you just did for $S_r$ in your last post. Try to prove it yourself, maybe.
Comment: What do you mean by an isoclass? And what is the proof  thereof?
Comment: Please introduce to me a reference as for the cited lemma.
Comment: Sorry, I still do not understand why the two isoclasses in your answer have zero intersection. And, what do you mean by my "last post"?
Comment: Would you please spot it?
Comment: @karparvar I can only guess it [was this](https://math.stackexchange.com/q/2709776/29335) but it's been a whole month and I don't recall this question well.
Comment: @karparvar If $A$ is one particular minimal right ideal, then how could it be contained in the sum of right ideals isomorphic to a minimal ideal $B\not\cong A$?


Creating DNS A Record for 3 domain controllers

Question: I have setup a new domain on our network consisting of 2 domain controllers, dc1, dc2.
I can see the A records for the 2 controllers. But I need to do load balancing so that I can refer to the 2 dcs in single entry.
I have created two A records  with same name for the different IPs, dc.domain.com. Is this the standards procedure?
Comment: **But I need to do load balancing so that I can refer to the 2 dcs in single entry** - Can  you tell us why you want/need to do "load balancing" and what you mean by that statement?
Comment: Thanks. I have an application with about 10,000 users which authenticates against the Active Directory.
Answer: Active directory already has a form of a DNS load balancing. You just look into wrong place.
A record just says which controller has which IP address. Where clients go for each domain service (LDAP, Kerberos, Global Catalog LDAP, et cetera) is configured with SRV records. And if you didn't do anything fancy, you will have SRV records in your domain already point to each domain controller for each service.
Here is the typical structure of the Active Directory domain DNS zone:
example.com.                               3600 IN SOA      dc1.example.com. admin.example.com 66593 900 600 86400 3600
example.com.                               3600 IN NS       dc1.example.com.
example.com.                               3600 IN NS       dc2.example.com.
example.com.                               600  IN A        192.168.3.1
example.com.                               600  IN A        192.168.4.1
_gc._tcp.example.com.                      600  IN SRV      0 100 3268 dc2.example.com.
_gc._tcp.example.com.                      600  IN SRV      0 100 3268 dc1.example.com.
_kerberos._tcp.example.com.                600  IN SRV      0 100 88 dc2.example.com.
_kerberos._tcp.example.com.                600  IN SRV      0 100 88 dc1.example.com.
_kpasswd._tcp.example.com.                 600  IN SRV      0 100 464 dc2.example.com.
_kpasswd._tcp.example.com.                 600  IN SRV      0 100 464 dc1.example.com.
_ldap._tcp.example.com.                    600  IN SRV      0 100 389 dc2.example.com.
_ldap._tcp.example.com.                    600  IN SRV      0 100 389 dc1.example.com.
_kerberos._udp.example.com.                600  IN SRV      0 100 88 dc2.example.com.
_kerberos._udp.example.com.                600  IN SRV      0 100 88 dc1.example.com.
_kpasswd._udp.example.com.                 600  IN SRV      0 100 464 dc2.example.com.
_kpasswd._udp.example.com.                 600  IN SRV      0 100 464 dc1.example.com.
DomainDnsZones.example.com.                600  IN A        192.168.3.1
DomainDnsZones.example.com.                600  IN A        192.168.4.1
_ldap._tcp.DomainDnsZones.example.com.     600  IN SRV      0 100 389 dc2.example.com.
_ldap._tcp.DomainDnsZones.example.com.     600  IN SRV      0 100 389 dc1.example.com.
ForestDnsZones.example.com.                600  IN A        192.168.3.1
ForestDnsZones.example.com.                600  IN A        192.168.4.1
_ldap._tcp.ForestDnsZones.example.com.     600  IN SRV      0 100 389 dc2.example.com.
_ldap._tcp.ForestDnsZones.example.com.     600  IN SRV      0 100 389 dc1.example.com.
dc1.example.com.                          3600  IN A        192.168.3.1
dc2.example.com.                          3600  IN A        192.168.4.1
_msdcs.example.com.                        3600 IN NS       dc1.example.com.
_gc._tcp.Default-First-Site-Name._sites.example.com. 600 IN SRV 0 100 3268 dc1.example.com.
_kerberos._tcp.Default-First-Site-Name._sites.example.com. 600 IN SRV 0 100 88 dc1.example.com.
_ldap._tcp.Default-First-Site-Name._sites.example.com. 600 IN SRV 0 100 389 dc1.example.com.
_ldap._tcp.Default-First-Site-Name._sites.DomainDnsZones.example.com. 600 IN SRV 0 100 389 dc1.example.com.
_ldap._tcp.Default-First-Site-Name._sites.ForestDnsZones.example.com. 600 IN SRV 0 100 389 dc1.example.com.
_gc._tcp.alter-site._sites.example.com. 600 IN SRV 0 100 3268 dc2.example.com.
_kerberos._tcp.alter-site._sites.example.com. 600 IN SRV 0 100 88 dc2.example.com.
_ldap._tcp.alter-site._sites.example.com. 600 IN SRV 0 100 389 dc2.example.com.
_ldap._tcp.alter-site._sites.DomainDnsZones.example.com. 600 IN SRV 0 100 389 dc2.example.com.
_ldap._tcp.alter-site._sites.ForestDnsZones.example.com. 600 IN SRV 0 100 389 dc2.example.com.

If you create sites, you'll get additional records for them. That supposed to make some computer to preferably ask their local domain controller than the remote. Here dc2 belongs to site alter-site and so any computer who is in that site will ask it first. If you leave everything default, both controllers will be in the default site Default-First-Site-Name.
You can alter the load distribution between controllers by altering those SRV records. See "100"'s? These are weights. If you set 67 for one DC and 33 for another, the first one will get 2/3 of requests and another will have 1/3. "0"'s in front of each SRV record are priorities; if you have larger priority servers accessible the lower priority will not be queiried at all. Please look for SRV record description for details; there are plenty explanations in the Internet, including this site.
There are few records which are "not symmetric". For example, SOA record has a particular DNS server name in it. But those are rarely used in this case and this doesn't constitute any bottlenecks.
Also important note about SYSVOL. When clients login, after checking passwords (which involves the Kerberos service), they ask the domain for group policies, and they do this using the domain name, not a particular DC name, like this: \\example.com\SYSVOL (and not, for example, \\dc1.example.com\SYSVOL). You can see a domain apex has several A records, one for each domain controller (4th and 5th lines of the example). The client will use randomly selected A record to connect, so each DC will have roughly the same share.
Answer: You can do load balancing by simply using the domain name. There is usually an A record for each domain controller in the same as parent record.
Note: this is not high availability and should not be considered such.


Alert not working in UpdatePanel VB.Net

Question: Here is what I have tried.
ASPX File:

        <asp:UpdatePanel ID="UpdatePanel1" runat="server">

            <ContentTemplate>
                 <asp:Button OnClick="btnOK1_Click" ID="btnOK1" runat="server" Text="Save" />
            </ContentTemplate>

        </asp:UpdatePanel>

ASPX.VB:
        Protected Sub btnOK1_Click(sender As Object, e As EventArgs)
            Dim alertMsg As String
            Dim alertScript As String
            alertMsg = String.Format("You Selected {0}", "My Message")
            alertScript = String.Format("", alertMsg)
            ClientScript.RegisterStartupScript(Me.[GetType](), "Alert", alertScript)
        End Sub

I tried to get an alert box with a message when clicked a button (Save) from backend. I tried with the solutions from the StackOverflow. But, the codes does not work for me to get an javascript alert box. The event triggers fine and runs through the code. Anyone help me with this?
Answer: replace your code with these

Protected Sub btnOK1_Click(ByVal sender As Object, ByVal e As EventArgs)
    Dim alertMsg As String
    Dim alertScript As String
    alertMsg = String.Format("You Selected {0}", "My Message")
    alertScript = String.Format("", alertMsg)
    ScriptManager.RegisterStartupScript(Page, Page.GetType, "Alert", alertScript, False)

End Sub

Answer: The problem seems to lie with the fact that you are using ClientScript rather than ScriptManager.
ClientScript is used for Synchronous postbacks, whereas ScriptManager for Asycronous.
See this question for more details.

Alert not working in UpdatePanel VB.Net


RoboScript not able click Enable Location OK button in Firebase Testlab

Question: I am trying to test an Google Map based Android app using RoboScript on Firebase TestLab. By default location is disabled on TestLab devices. To enable them we need to simulate a click on OK button on the system prompt. But this click never happens. You can see the screenshot below. The OK button never gets pressed and flow stops here.

I checked the RoboScript json file. Android studio never recorded the OK button click. I tried to create another element like below. But couldn't identify what should be the resourceId for the system dialog.
<code>    {
        "eventType": "VIEW_CLICKED",
        "timestamp": 1512127956674,
        "replacementText": "",
        "actionCode": -1,
        "delayTime": 0,
        "canScrollTo": false,
        "elementDescriptors": [
          {
            "className": "android.widget.LinearLayout",
            "recyclerViewChildPosition": -1,
            "adapterViewChildPosition": -1,
            "groupViewChildPosition": 0,
            "resourceId": "com.entransys.parkeze:id/confirm_linear",
            "contentDescription": "",
            "text": ""
          },
          {
            "className": "android.support.v7.widget.ContentFrameLayout",
            "recyclerViewChildPosition": -1,
            "adapterViewChildPosition": -1,
            "groupViewChildPosition": 1,
            "resourceId": "android:id/content",
            "contentDescription": "",
            "text": ""
          },
          {
            "className": "android.support.v7.widget.FitWindowsLinearLayout",
            "recyclerViewChildPosition": -1,
            "adapterViewChildPosition": -1,
            "groupViewChildPosition": 0,
            "resourceId": "com.entransys.parkeze:id/action_bar_root",
            "contentDescription": "",
            "text": ""
          }
        ]
      }
</code>
So my question is
a) Is there an option to make location enabled before the test starts on the device in Firebase TestLab ?
b) Is there an option to generate clicks on the system level dialog using Robo Script
Edit 1: Added screenshot
Edit 2: Yes, there is confusion between if the ok button is getting pressed or Ok button got pressed [location icon is appearing in appbar] and map is not visible. There is no error and flow stops here.
Comment: Facing the same issue? Have you got any solution?Please suggest.
Comment: Facing the same issue? Have you got any solution?Please suggest.
Answer: I am recording the robo script for my app. It never recorded the actions performed on runtime permissions.


Positive linear function over $\mathbb{Q}^n$ vs. $\mathbb{R}^n$

Question: Let $V^n$ be $n$-dimensional vector space over $\mathbb{R}$ with some fixed basis, $U \subseteq V^n$ -- its subspace, generated by linearly independent vectors $v_1, \dots, v_m$ of zeros and ones. Suppose there is a linear function $f\colon U \to \mathbb{R}$, such that $f(v_i) > 0$ for every ($1 \leq i \leq m$). Even further, $\vec{1} \in U$ (the vector of all ones) and $f(\vec{1}) = 1$.
I'll call a vector $a = (a_1, \dots, a_n)$ positive if $a \neq \vec{0}$ and $a_i \geq 0$ ($1 \leq i \leq n$). Now suppose, for every positive vector that is in $U$ and has rational coefficients (in $V^n$ and thus in $U$), we have $f(a) > 0$. Is this true for vectors with irrational coefficients as well?
I can easily prove that for such a vector $a \in U$ I have $f(a) \geq 0$ (I intersect $U$ with a subspace of $V^n$ of all vectors with zero coefficients exactly where $a$ has them, pick a basis (of rational vectors) there and then I can approach $a$ with rational vectors, close enough to it to remain positive). But what if for any such vector $f(a) = 0$? I need to prove this can't happen (or, of it can, what are the conditions when it cannot).
My one path is to try and prove that for every positive $a \in U$ there is a positive rational vector $a' \in U$ with every $a'_i \leq a_i$, but I run into all sorts of troubles trying to do that. Another would be to prove something about the numbers $f(v_i)$ themselves using the fact there is a combination of those with rational coefficients that equals $1$. Finally, I can pick $(v_i - \frac{f(v_i)}{f(v_{i+1})}v_{i+1})$ (with $1 \leq i \leq m-1$) as a basis of the subspace orthogonal to the values vector in $U$ and it's easy to show none of those is positive in $V^n$, but I still can't find the reason why some linear combination of those can't be (with some of the coordinates equal to zero) and it seems to be even harder to do directly.
I bet there is some obvious solution I'm completely missing.
Answer: You already have shown $f(a)\ge0$ for all $a\in U$, $a\ge0$.
Let me write $f(a)=f^Ta$, and set $B:=(v_1\dots v_m)$.
I want to apply Farkas Lemma, which is not an ``obvious solution'', it is rather a last resort :)
We know $f^Ta\ge0$ for all $a\ge0$ with $a=Bz$ for some $z$.
Let me set
$$
A^T:=\pmatrix{I & 0 \\ I & -B\\ -I & B}, \
y:=\pmatrix{a\\z}, \ b=\pmatrix{f\\0}.
$$
Then we have $b^Ty\ge0$ for all $y$: $A^Ty\ge0$. Hence the first assertion of Farkas Lemma is true, and there is $x\ge0$ with $Ax=b$,
or in our notation
$$
x= \pmatrix{x_1\\x_2\\x_3}\ge0 , \
\pmatrix{I & I & -I\\ 0 & -B^T & B^T} \pmatrix{x_1\\x_2\\x_3} = \pmatrix{f\\0}.
$$
This implies $f-(x_2-x_3)\ge0$, and $B^T(x_2-x_3)=0$. Hence $x_2-x_3\in U^\perp$. This implies $(f-(x_2-x_3))^Ta = f^Ta$ for all $a\in U$.
Hence, we can replace $f$ by the non-negative vector $f-(x_2-x_3)$ without affecting the action of $f$ on vectors from $U$.
Let now $a\in U$, $a\ne0$, with $a\ge0$ and $f(a)=0$. Since $f$ has non-negative coefficients it follows $f_i=0$ for all indices $i$ such that $a_i\ne 0$. As you have argued we can approximate $a$ by rational positive vectors $a_k$ in $U$ that are zero on the same indices as $a$. Then $f(a_k)=f^Ta_k=0$ follows, a contradiction. Hence $f(a)>0$ for all nonzero non-negative $a\in U$.
Comment: $v_1$ and $v_2$ are vectors of zeros and ones, thus positive. Also, that condition holds.
Comment: Now $f((1, 2)) < 0$ which is not the case (for every positive rational it has to be $>0$).
Comment: @rm-rf Completely overhauled the answer to contain a proof of your desired statement. Hopefully, it is true this time.
Comment: Nice! Yes, it seems perfectly true, and I love the trick with using $\pm I \mp B$ to cut away all the junk in $\mathbb{R}^{m+n}$, that's just clever :-)

Also, I stepped upon another formulation of Farkas lemma that simply states that if $Bz \geq 0 \implies g(z) \geq 0$ for some linear $g$, then $g(z) = v^TB$z for some $v \geq 0$ so I can reference that directly without repeating the entire matrix dance.

Thanks a lot!


file not found with DocumentBuilderFactory

Question: Before posting this question i had search all the places to get some similar question, I had found questions but no answer worked for me, I used getResources, that approach also gave me a error saying Undefined Method, using this or Context also dint work, I just need to read and write a xml in android app and the xml should be stored in my app in res folder or any other folder which is standard, Right now i am using the below code, Please help  me with this. Thanks a lot ..Max
                DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
                DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();

                Document doc = docBuilder.parse (new File("savecredentials.xml"));

Using getResources doesnt help, How to use getResources when it is undefined, and if i use context it doesnt work , Any simple solution for this one.
Comment: ok, can you add whole code for class and activity also for xml file?
Answer: You had write new File("savecredentials.xml") which means you are reading savecredentials.xml from application folder.You had not set path of res folder.
You have to mentioned path from where you are reading file.
For example if you had a file in asset folder then you can write
    AssetManager mg = getResources().getAssets();
            InputStream myInput = null;
            try {
                myInput = mg.open("File name");
                if(myInput != null) {
                    System.out.println("File exists in assets");
                }
            } catch (IOException ex) {
                System.out.println("File not exists in assets");

            }

XmlPullParserFactory factory = null;
factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser xpp = null;
xpp = factory.newPullParser();
InputStreamReader reader = new InputStreamReader(myInput);
xpp.setInput(reader);
int eventType = 0;
eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
    if(eventType == XmlPullParser.START_TAG) {

    } else if(eventType == XmlPullParser.END_TAG) {

    } else if(eventType == XmlPullParser.TEXT) {
    }
    eventType = xpp.next();
}

This code is for check weather file is exist in asset or not ?
And read from res folder
Click here
Comment: what is c in the above context, Also i dont have a database to open I have a xml file. and then i need to use the Document doc = docBuilder.parse (new File("savecredentials.xml")); , can you suggest me something in the above context.
Comment: getResouces method is undefined, Using Context or this also doesnt work.
Comment: please read my previous comment and the question i already mentioned that Context is not working.
Comment: getResources() method is for context class so you have to make object and then you have to call this method it will worked for you
Comment: not working please mention what to do with the context, is it Context c = new Context();
Comment: Are you writing this code in Activity, Service or any where else ?
Comment: not in the activity class, its in a class which is written just to handle xml read and write.
Comment: pass the reference of your Activity to that class and using that activity  reference call getResources() method in that class.


Why is the third derivative of cumulant generating function = skewness?

Question: From what I know, for random variable $X$, skewness is defined as
$$\mathbb{E}\left(\frac{X-\mathbb{E}(X)}{\sigma}\right)^3$$
or
$$\frac{\mathbb{\mathbb{E}}(X^3)-3\mathbb{E}(X)\sigma^2-\mathbb{E}(X)^3}{\sigma^3}$$
where $\sigma$ is the standard deviation of $X$.
and the third derivative of cumulant generating function is
$$\mathbb{E}(X^3)-3\mathbb{E}(X)\mathbb{E}(X^2)+2[\mathbb{E}(X)]^3$$
These $2$ formulae look totally different, but why the third derivative of cumulant generating function is defined as the skewness of $X$?
Comment: The third derivative of the cumulant generating funcion that you calculated you can also write as
$$
\mathbb E\big[\big(X-\mathbb E[X]\big)^3\big]
$$
by which it takes the form in [Wikipedia Cumulant](https://en.wikipedia.org/wiki/Cumulant#The_first_several_cumulants_as_functions_of_the_moments) *and* is related to the skewness you wrote up there by a simple factor of $1/\sigma^3$.
Comment: They don't just differ by the factor 1/3. The second half of the equations still do not match.
Answer: I am not sure if your second formula is correct. Please check:
\begin{align}
\mathbb{E}\textstyle\left[\left(\frac{X-\mathbb{E}(X)}{\sigma}\right)^3\right]&=\frac{\mathbb E\big[X^3-\mathbb E[X]^3-3\,X^2\,\mathbb E[X]+3\,X\,\mathbb E[X]^2\big]}{\sigma^3}\\
&=\frac{\mathbb E[X^3]-\mathbb E[X]^3-3\,\mathbb E[X^2]\mathbb E[X]+3\,\mathbb E[X]^3}{\sigma^3}\tag{*}\\[3mm]
&=\frac{\mathbb E[X^3]-\mathbb E[X]^3-3\,\mathbb E[X]\,(\mathbb E[X^2]-\mathbb E[X]^2)}{\sigma^3}\\[3mm]
&=\frac{\mathbb E[X^3]-\,\mathbb E[X]^3-3\,\mathbb E[X]\,\sigma^2}{\sigma^3}\,.
\end{align}
The third derivative of the cumulant generating function you have correctly as
\begin{align}
\mathbb E[X^3]-3\,\mathbb E[X]\,\mathbb E[X^2]+2\mathbb E[X]^3\,.
\end{align}
Up to a division by $\sigma^3$ this agrees with (*). Therefore, the derivative of the cumulant generating function is
$$
\mathbb E\big[(X-\mathbb E[X])^3\big]\,.
$$
This is the form in Wikipedia Cumulant and it is related to
$$
\mathbb{E}\textstyle\left[\left(\frac{X-\mathbb{E}(X)}{\sigma}\right)^3\right]
$$
by a simple factor of $1/\sigma^3\,.$
Answer: It suffices to check the case $\Bbb EX=0,\,\Bbb EX^2=1$, for which the cgf is of the form $-\frac12t^2+\frac16ct^3+o(t^3)$, of third derivative $c$. Exponentiating, the mgf is then $1+(-\tfrac12t^2+\frac16ct^3)+o(t^3)$, implying $c=\Bbb EX^3$. Note, however, the fourth cumulant & moment don't coincide, because$$\exp\left(-\frac12t^2+\frac16ct^3+\frac{1}{24}dt^4+o(t^3)\right)=1-\frac12t^2+\frac16ct^3+\frac{d+6}{24}t^4+o(t^4).$$


Manipulação de ping em Python

Question: estou criando um código que da um ping em uma lista de ips. Eu consegui fazer ele pingar e me dar a resposta, mas não consigo fazer a condição que desejo, que é:
SE ping ok:
   continuar os comandos
SENÃO:
   faz outra coisa.

Não sei como manipular a resposta do ping para colocar esta lógica no código, podem me ajudar?
Desculpe, sou iniciante.
Este é meu código:
#coding: utf-8
import sys
import os
import platform
import subprocess
from ips_list import radius

plat = platform.system()
scriptDir = sys.path[0]
if plat == "Windows":
    for ip in radius:
        try:
            line = ip.strip()
            ping = subprocess.Popen(
                ["ping", "-n", "2", "-l", "1", "-w", "100", line],
                stdout = subprocess.PIPE,
                stderr = subprocess.PIPE
            )
        expect:

if plat == "Linux":
    for ip in radius:
        line = ip.strip( )
        ping = subprocess.Popen(
            ["ping", "-c", "1", "-l", "1", "-s", "1", "-W", "1", line],
            stdout = subprocess.PIPE,
            stderr = subprocess.PIPE
        )
        out, error = ping.communicate()
        print out
        print error

Como posso adicionar esta lógica do if.. else nele?
Obrigado!
Answer: Utiliza esta função, funciona em linux e windows, para python 2.7 ou 3:
def ping(host):
    import os, platform

    if  platform.system().lower()=="windows":
        ping_str = "-n 1"
    else:
        ping_str = "-c 1"

    resposta = os.system("ping " + ping_str + " " + host)
    return resposta == 0

A função devolve verdadeiro se o ping obtiver resposta e falso em caso de insucesso.
Answer: eu fiz dessa forma, pegando através de uma lista de IPS e fazendo um loop infinito para verificar cada um:
# -*- coding: utf-8 -*-

import subprocess
import os
import time
ips = ['192.168.0.8','192.168.0.11','192.168.0.12','192.168.0.13','192.168.0.18']

while True:
    with open(os.devnull, "wb") as limbo:
        for ip in ips:

            result=subprocess.Popen(["ping", "-c", "1", "-n", "-W", "2", ip],
                    stdout=limbo, stderr=limbo).wait()
            if result:
                    print ip, "inativo"
            else:
                    print ip, "ativo"

    time.sleep(2)
    print(' -- recomeçar --')

Answer: Agradeço pelo post de vocês e gostaria de por minha contribuição
import subprocess
import os
import time
import tkinter as tk
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg

ips = ['10.0.0.1', '10.0.0.100', '10.0.0.110', '10.0.0.111', '10.0.0.112', '10.0.0.113', '10.0.0.116']

def check_ips():
    for ip in ips:
        try:
            result = subprocess.check_output(["ping", "-n", "3", "-w", "3", ip])
            ip_status[ip] = "ativo"
        except subprocess.CalledProcessError:
            ip_status[ip] = "inativo"

    update_dashboard()

    root.after(5000, check_ips)  # Executar a cada 5 segundos

def update_dashboard():
    for ip, status in ip_status.items():
        label = ip_labels[ip]
        label.config(text=f"{ip}: {status}")

    plot_graph()

def plot_graph():
    plt.clf()
    statuses = list(ip_status.values())
    plt.bar(ips, statuses, color=['green' if status == 'ativo' else 'red' for status in statuses])
    plt.xlabel('IPs')
    plt.ylabel('Status')
    plt.title('Status dos IPs')
    canvas = FigureCanvasTkAgg(plt.gcf(), master=frame)
    canvas_widget = canvas.get_tk_widget()
    canvas_widget.pack()

root = tk.Tk()
root.title("Exemplo")

ip_status = {}
ip_labels = {}

frame = tk.Frame(root)
frame.pack()

for ip in ips:
    label = tk.Label(frame, text=f"{ip}: Verificando...", padx=10)
    label.pack()
    ip_labels[ip] = label
    ip_status[ip] = "Verificando..."

check_ips()

root.mainloop()

Manipulação de ping em Python


What does "Aleatoric and Epistemic uncertainties" mean?

Question: While studying Bayesian Learning, I have encountered the term, Aleatoric and Epistemic uncertainty, but I have just found it a bit confusing to understand. I believe I haven't found good references to understand the term. What do they mean and what could be examples for these two terms? Hope some plain literal explanation.
Comment: This is the rare case (concerning statistical terminology) where consulting an English dictionary will actually help clear things up.
Comment: Also a rare case of a statistical text incorporating terminology from the humanities and, more specifically, critical theory. See, e.g., *The Cultural Studies Reader* https://www.amazon.com/Cultural-Studies-Reader-Simon-During/dp/0415374138/ref=pd_ybh_a_2
Comment: See also https://stats.stackexchange.com/questions/332026/can-we-think-of-a-probability-in-both-the-classical-and-subjective-sense-simulta/332218#332218
Answer: A short and very simplified literal explanation:
Aleatoric: uncertainty about the result of an experiment that we can repeat, e.g. dice roll. What is the probability of rolling a 6? - the view of frequency statistics
Epistemic: uncertainty stemming from insufficient knowledge, e.g. one-time experiment (no repeating). What is the probability that - as a result of global warming - the average temperature will be 2 degrees higher in 2050?
I hope it helped :-)
Comment: Is Aleatoric for Frequentist and is Epistemic for Bayesian?
Comment: In general, I think yes. The epistemic is at most the view of Bayesian statistics, but there is not a strict wall between them. You can use Bayesian approach for frequency problems too. Let we have an apriori distribution and we can make some experiments and then based on these experiments (and taking into consideration the apriori distribution) we get the posterior distribution. :)


AX 2012 FormGridControl.gotFocus not working

Question: I have a problem with the FormGridControl.gotFocus method. The method works if the grid is empty. If the grid contains data it does'nt work...
I this a bug or can i do something else?
Comment: What do you want to achieve? Describe your problem. See also http://stackoverflow.com/a/9296261/4509
Comment: I want to implement a command button for a grid (e.g. Command "Filter by Selection", 2844).
But there is more than one grid on the form. So my first thought was: Check if GridA, GridB or GridC has the focus and than execute the click for the command button.
But that didn't work (because the button has the focus if you click it...).

So my workaround: I implemented i command button for EACH grid and set the focus to the grid. Now the Command button works fine... Or is there a better solution?

Btw: I found the link before and you say don't use gotFocus - is there a special reason for it?
Frank
Comment: Seems okay, though it is an unusual request in the first place.
I cannot totally rule out `gotFocus` coding in very rare occasions. But most of the time it is the wrong path to go.
Comment: Yes you are right. But did you know why gotFocus doesn't work properly?
Comment: Maybe a control in the grid got focus, not the grid itself.
Comment: Hmm... There are no additonal controls there.
Comment: The grid control is a container containing other controls.
Comment: Yes, of course... Anyway this "Event" did not work as I had expected. Seems to make no sense - gotFocus only raised if grid is empty :)
Answer: The gotFocus on container controls may not be activated because a contained control got focus instead. Put another way: setting focus on a control does not activate the gotFocus methods of the containing container controls.
Thus it may be useless as tool for determining, what has focus.
Often a better way is to check the selectedControl of the FormRun class using the contains method:
boolean inGr = element.selectedControl() && group.contains(element.selectedControl());

This cannot be used in buttons of cause because the button gets focus when clicked!
It may be of use in the task method and other control methods.


What's a local angle?

Question: When I was trying to understand the definition of conformal map I got confused. A conformal map is a function $f: U \to \mathbb C$ where $U \subset \mathbb C$ such that $f$ preserves local angles.

But what is the definition of a local angle?

I had no trouble imagining the meaning of oriented angle. But the meaning of local angle... I cannot guess what it is. I tried to find a definition on the internet but the search results were all unhelpful.
Also... in the article it seems that conformal and biholomorphic (=holomorphic and bijective) are used as synonyms.

Is a map conformal if and only if it is bijective and holomorphic?
Answer: This means that the derivative of $f$ is a linear map that preserves angles (so it's a combination of scaling and rotation). Maybe it's helpful to look at this picture from Wikipedia: infinitesimally, the grid blocks are being rotated and scaled.
Holomorphic functions with nonzero derivative always have this property; if you write $f'(z_0) = r e^{i \theta}$, then locally at $z_0$, $f$ is a scaling by $r$ and rotation by $\theta$.
No, a conformal map, in the usual definition, is only a local biholomorphism in general - in other words, at any $z_0$, there's an open neighborhood $U$ such that $f : U \rightarrow f(U)$ is a biholomorphism. A counterexample is $f(z) = e^z$ on $\mathbb{C}$, which has nonzero derivative everywhere (so it's conformal) but it's not injective.
Comment: Thank you. But you don't seem to give a definition of ''local angle''. I would like to know what a ''local angle'' is. Could you add a definition?
Answer: Lets say you have two straight lines in the complex plane, $\gamma_1(t) = a_1 + d_1 t$ and $\gamma_2(t) = a_2 + d_2 t$, and lets further stipulate that there are $t_1$ and $t_2$ such that $\gamma_1(t_1) = \gamma_2(t_2)$. Now, $d_1$ and $d_2$ are complex numbers, so we can see that the angle between the lines where they meet is $\arg(d_2) - \arg(d_1).$
If $f:\mathbb{C} \to \mathbb{C}$ is a general function, then $g_1 = f\circ\gamma_1$ and $g_2 = f\circ\gamma_1$ might not be straight lines, but we want to find a way to talk about the angle between $g_1$ and $g_2$. When they were straight lines it was pretty easy, but now, if $f$ is differentiable as a transformation of $\mathbb{R}^2,$ they are only curves. To find their direction at any moment, we define $$g_1'(t_0) = \frac{dg_1}{dt}(t_0) = \lim_{h\to 0} \frac{g_1(t+h) - g(t)}{h}$$ as you would expect, and you can see that this is a complex number if we think of $\mathbb{C}$ as being the codomain of $g_1$, or $\mathbb{R}^2$, if we think of it as being vector valued.
So, we know that $g_1(t_1) = g_2(t_2)$ and we can calculate $\arg(g_2'(t_2)) - \arg(g_1'(t_1))$ to find the angle between these momentary directions. Its this quantity that they are calling the "local angle". Its the right generalisation for the angle between lines to the angle between curves.
It turns out that, if $f:\mathbb{R}^2\to \mathbb{R}^2$ and $f(a, b) = (u(a, b), v(a, b))$ then we can define
$$f' = \begin{pmatrix} \frac{ \partial u }{\partial x} & \frac{ \partial u }{\partial y} \\
\frac{ \partial v }{\partial x} & \frac{ \partial v }{\partial y} \end{pmatrix}$$ and if a curve $c : \mathbb{R} \to \mathbb{R}^2$ is differentiable at $a$ then $(f\circ c)' = f' c'$ where the operation between the terms on the RHS is matrix multiplication. Now, if you think about what the Cauchy-Riemann equations say about complex differentiable functions, then either $f' = 0$ or $f'$ is a rotation and a dilation. So, complex differentiability implies that the derivative of the function is $0$ or it will rotate directions of curves at the same point by the same amount, and then change their length by a scaling factor. This implies you cannot have changed the angle between curves, and so $f$ is conformal if its complex differentiable and its derivative is non zero.
Regarding your second question, $exp$ is conformal and holomorphic, but its not a bijection.
Hope that helps.
Comment: So local angle is like the angle at a point where two curves intersect? It's not clear why it has the name local. It seems no more local than the angle between two lines... after all lines are also curves.
Comment: The other thing that's funny is that there really is only one point of intersection. Okay, with arbitrary curves there will be arbitrarily many but even then the local angle is not defined at every point of each curve. Isn't this a problem?
Comment: You could have a situation where an interval that doesn't intersect the x axis is said to be at an angle of theta relative to the x axis. These sort of relationships are formalised by things called "connections". Its perhaps sensible to rule out this broader interpretation of angle from the one we want. Said more technically, conformal maps preserve the relationship between tangents with the same base, but not "connections" between tangent spaces of points. This is pretty high level manifolds stuff. http://en.wikipedia.org/wiki/Manifold http://en.wikipedia.org/wiki/Affine_connection

What's a local angle?


What does this statement about a forecasting lead time mean?

Question: The ARPA-E PERFORM datasets produced by NREL contain both historical and forecast data on load, wind power, and solar power. NREL offers the following piece of information about the day-ahead forecast data:

Day-ahead forecasts are generated with a 11-hour-ahead lead time, a 48-hour horizon, an hourly resolution, and a daily update rate.

I downloaded the data for wind power in ERCOT (2018) and the two first columns with issue time and forecast time, respectively, are shown below with the first few rows of the dataset (Forecasts quantiles are not included).

Issue time
Forecast time

2017-12-30 18:00:00
2018-01-01 00:00:00

2017-12-30 18:00:00
2018-01-01 01:00:00

2017-12-30 18:00:00
2018-01-01 02:00:00

2017-12-30 18:00:00
2018-01-01 03:00:00

$\vdots$
$\vdots$

2017-12-31 18:00:00
2018-01-01 06:00:00

Given the American Meteorological Society's definition of lead time as "the length of time between the issuance of a forecast and the occurrence of the phenomena that were predicted", I assumed that the difference between the forecast time and the issue time had to be 11 hours. However, from row 1 in the table above, we could see that such difference is 30 hours. For the second row, it's 31 hours. In row seven, we have a difference of 12 hours.
When I saw the issue time was the same for various forecasts, I knew my understanding of forecasting and its nomenclature would be tested. I realized that if I have to choose a set of all forecasts for a fixed $n$ hours ahead, given any $n = 1, 2, ..., 48$, I wouldn't be sure of what forecasts (rows) to select.
There is something I am missing and that's what I'd like understand. What is the lead time here? And what does the difference between the forecast time and the issue mean in this case?
Answer: This might be helpful: https://forecastarbiter.epri.com/definitions/#forecastattrs. Also see this paper https://www.osti.gov/pages/servlets/purl/1762478, which is referenced in the README you got the description from (https://github.com/PERFORM-Forecasts/documentation/blob/main/README.md#forecasts).
My interpretation of the "day-ahead" wind power forecast that you are looking at is:

a forecast is issued once per day at 18:00 [daily update rate], e.g., 2017-12-30 18:00
the first hour included in that forecast is 05:00 the following day [11-hour lead time], e.g., 2017-12-31 05:00
the forecast includes each hour [hourly resolution] out to the one beginning 04:00 (ending at 05:00) on the morning of the 3rd day out [48-hour horizon], e.g., 2018-01-02 04:00.

(I'm assuming they use timestamps representing the beginning of intervals, e.g., 05:00 represents the average of the hour ending 06:00).
So, if you wanted to assemble a set of all forecasts n hours ahead, n would have to be between 11 and 59, and you would only get one forecasted value per day. It would also be subjected to any diurnal patterns in solar, wind, or load, which may or may not be problematic, depending on what you want to do with it.
Here's a rough sketch that might be helpful:

Edit: After looking at the description here again and comparing with data in the S3 bucket, it looks like they split data into "day-ahead" and "2day-ahead" datasets. So, I think this description,

Day-ahead forecasts are generated with a 11-hour-ahead lead time, a 48-hour horizon, an hourly resolution, and a daily update rate.

along with my interpretation and my sketch apply to the combined day-ahead and 2day-ahead datasets. Otherwise, there would be overlapping forecast times when the horizon (48 hrs) is longer than one over the update rate (24 hrs). Here's an updated sketch, where I'm guessing at the point where they cut between day- and 2day-ahead:
Comment: Hope it was helpful!
Comment: Hi, Will. Thanks for your answer.
Comment: It was helpful indeed. Thanks a lot.


left join is not returning proper information

Question: I have a table courses and a table volunteer_rosters. courses contains a list of all courses and volunteer_rosters contains a list of volunteers teaching/assisting on the course.
I want to write a query that returns a list of all courses that do not have any volunteers assigned to it. This is what is happening:
courses
-------
id
 1
 3
 4
 5
 6

volunteer_courses
-----------------
id 1 course_id 1
id 2 course_id 1
id 3 course_id 1
id 5 course_id 3
id 6 course_id 3

All of the below queries are returning
course_id 3
course_id 4
course_id 5
Why is course_id 1 (correctly) being left out, but course_id 3 is not???
Course.joins("LEFT JOIN student_rosters ON courses.id = student_rosters.course_id where student_rosters.course_id is null")

Course.joins("LEFT JOIN student_rosters ON courses.id = student_rosters.course_id").where(student_rosters: {id: nil})

Course.includes(:student_rosters).references(:student_rosters).where(student_rosters: {id: nil})

Course.includes(:student_rosters).references(:student_rosters).where('student_rosters.id = ?', nil)

Course.joins("LEFT JOIN student_rosters ON courses.id = student_rosters.course_id").where(student_rosters: {id: nil})

Same exact question, but none of the solutions are working for me:
LEFT OUTER JOIN in Rails 4
Comment: Can you write a working query in regular sql, without all this activerecord stuff?
Comment: This is the query that every query above generates: `SELECT "courses".* FROM "courses" LEFT JOIN student_rosters ON courses.id = student_rosters.course_id WHERE "student_rosters"."id" IS NULL
`
Answer: There's no need to use join. Try this:
select id from Courses
where id not in (select course_id from volunteer_courses)

Comment: Brilliant, I love nested selects. This should have come to me...however learning how to write good sql queries in active record is killing me slowly....for anyone who needs this query in active record I kind of just hacked it because I can't be bothered spending the time learning it.

`Course.where('id not in (select course_id from volunteer_rosters)')
`
Answer: Although there is no need to use joins, using not in is dangerous with a subquery.  It does not do what you really want.  If any row in the subquery returns a NULL value, then the outer query returns nothing.  No rows at all.
For this reason, I strongly recommend using not exists and avoiding not in with subqueries:
select c.id
from Courses c
where not exists (select 1 from volunteer_courses vc where vc.course_id = c.id);

Or the left join version:
select c.id
from Courses c left join
     volunteer_courses vc
     on vc.course_id = c.id
where vc.course_id is null;

In addition, both of these can take advantage of an index on volunteer_courses(course_id).
Comment: I tried your first example

`SELECT "courses".* FROM "courses" WHERE (not exists (select 1 from volunteer_rosters where role = 0))`

and it did not work, it returned nothing while there indeed are rows that should have returned.
Comment: @Yitzhak . . . The query in your comment and the version in my question are not at all the same.


Problem with the density of polynomials.

Question: Problem: Suppose that $X \subset \mathbb{R}^n$ is compact. Let $Y = \{y_1,...,y_p\}$ be a finite subset of $X$. Let $\mathscr{P} = \{p \in \mathbb{P}[x_1,...,x_n]: p(y_i) = 0$ for all $p\}$ (the collection of polynomials that vanish on $Y$). Show that $\mathscr{P}$ is dense on $I = \{f \in C_\mathbb{R}(X): f|_Y = 0\}$.
I'm not quite sure how to proceed with this problem. Is there any suggestion or hint?
EDIT: Dense wrt to the sup norm.
Comment: When dealing with a space of functions, it is especially important to specify what topology you are using. Without that information, your question is not meaningful,
Comment: Sorry, I've only been introduced to the space of functions in the context of the sup norm.
Answer: Hint: Suppose $Y$ is just one point, say $Y=\{a\}.$ By Stone-Weierstrass there exists a sequence $p_m$ of polynomials on $\mathbb R^n$ that converges uniformly to $f$ on $X.$ What can you say about
$$f(y)-[p_m(y)-p_m(a)]?$$


How to use lead or Lag for a Group in oracle or any other analytic function to get desired result?

Question: input
id   name     date   value
1     aa      x      v1
1     aa      y      v1
1     aa      z      v1
2     bb      a      v2
2     bb      b      v2
3     cc      c      v2
4     dd      d      v3
4     dd      e      v3
5     ee      f      v4

output
   id   name     date   value  lead value
    1     aa      x      v1      v2
    1     aa      y      v1      v2
    1     aa      z      v1      v2
    2     bb      a      v2      v2
    2     bb      b      v2      v2
    3     cc      c      v2      v3
    4     dd      d      v3      v4
    4     dd      e      v3      v4
    5     ee      f      v4     null

How to get lead value for a id? i.e for id 1 lead value is v2,for id 2 lead value again is v2(as id 3 value is v2), for id 3 lead value is v3 and so on..
Comment: I don't understand the logic behind your expected lead values.  Can you explain it?
Comment: I want to apply lead function but for a group. Let me explain, for id =1 and name =aa I want next  row value(for id =2 and name = bb i.e v2). For id = 2 and name = bb next row value( for id= 3 and name = cc i.e again v2). For id= 3 and name = cc next row value (for id=4 and name =dd i.e v3). Basically calculating lead() but for a group(id,name).
Comment: Why does `v2` appear across both `v1` and `v2` groups?
Comment: in the input , for id 2 and 3 value is v2 So, For id 1 we want the value for id 2 i.e v2, For id id 2 we want the value for id 3 ie again v2. As v2 appears in the input twice So it is in the output for two groups.
Answer: You can use the below query to get the desired result:
with
CTE1(ID, VALUE) AS
(select distinct id,
 value from table1
 order by id
),
CTE2 AS
(
SELECT A.ID,
  A.VALUE,
  LEAD(A.VALUE) OVER(ORDER BY A.ID) LEAD_VALUE
FROM CTE1 A
)
SELECT A.*, B.LEAD_VALUE
FROM TABLE1 A, CTE2 B
WHERE A.ID = B.ID;

DB_FIDDLE


Howto Allow GZIP for Azure Table Storage Queries

Question: I found when query Azure Table Storage, the payload does not gzip in transfer.
here is the headers checked by fiddler
Send:
GET http://account.table.core.windows.net/sometable() HTTP/1.1
User-Agent: Microsoft ADO.NET Data Services
DataServiceVersion: 2.0;NetFx
MaxDataServiceVersion: 2.0;NetFx
x-ms-version: 2011-08-18
x-ms-date: Mon, 13 Aug 2012 02:23:48 GMT
Authorization: SharedKeyLite xxxxxxxxxxxxx=
Accept: application/atom+xml,application/xml
Accept-Charset: UTF-8
Host: account.table.core.windows.net

Receive
HTTP/1.1 200 OK
Cache-Control: no-cache
Content-Type: application/atom+xml;charset=utf-8
Server: Windows-Azure-Table/1.0 Microsoft-HTTPAPI/2.0
x-ms-request-id: 254e470e-c50d-409b-8429-3d5bc9beabaa
x-ms-version: 2011-08-18
Date: Mon, 13 Aug 2012 02:23:37 GMT
Content-Length: 168553

The xml content which length 168K, if gzipped, only around 40k, so, my question is: where and how can I allow gzip for Azure table queries?
Comment: Route the requests through nginx?
Answer: I don't think Windows Azure storage supports compression.
Comment: Why? Is there a plan for it? Except slow, also cost more.
Comment: I don't know the answers to your follow-up questions.


Identifying structural breaks in regression with Chow test

Question: I have some problems in using (and finding) the Chow test for structural breaks in a regression analysis using R. I want to find out if there are some structural changes including another variable (represents 3 spatial subregions).
Namely, is the regression with the subregions better than the overall model. Therefore I need some statistical validation.
I hope my problem is clear, isn't it?
Kind regards
marco
Toy example in R:
library(mlbench) # dataset
data("BostonHousing")

# data preparation
BostonHousing$region <- ifelse(BostonHousing$medv <=
                               quantile(BostonHousing$medv)[2], 1,
                        ifelse(BostonHousing$medv <=
                               quantile(BostonHousing$medv)[3], 2,
                        ifelse(BostonHousing$medv >
                               quantile(BostonHousing$medv)[4], 3, 1)))

BostonHousing$region <- as.factor(BostonHousing$region)

# regression without any subregion
reg1<- lm(medv ~ crim + indus + rm, data=BostonHousing)

summary(reg1)

# are there structural breaks using the factor "region" which
# indicates 3 spatial subregions
reg2<- lm(medv ~ crim + indus + rm + region, data=BostonHousing)

------- subsequent entry
I struggled with your suggested package "strucchange", not knowing how to use the "from" and "to" arguments correctly with my factor "region". Nevertheless, I found one hint to calculate it by hand (https://stat.ethz.ch/pipermail/r-help/2007-June/133540.html). This results in the following output, but now I am not sure if my interpetation is valid. The results from the example above below.
Does this mean that region 3 is significant different from region 1? Contrary, region 2 is not? Further, each parameter (eg region1:crim) represents the beta for each regime and the model for this region respectively? Finally, the ANOVA states that there is a signif. difference between these models and that the consideration of regimes leads to a better model?
Thank you for your advices!
Best Marco
fm0 <- lm(medv ~ crim + indus + rm, data=BostonHousing)
summary(fm0)
fm1 <- lm(medv  ~ region / (crim + indus + rm), data=BostonHousing)
summary(fm1)
anova(fm0, fm1)

Results:
Call:
lm(formula = medv ~ region/(crim + indus + rm), data = BostonHousing)

Residuals:
       Min         1Q     Median         3Q        Max
-21.079383  -1.899551   0.005642   1.745593  23.588334

Coefficients:
               Estimate Std. Error t value Pr(>|t|)
(Intercept)    12.40774    3.07656   4.033 6.38e-05 ***
region2         6.01111    7.25917   0.828 0.408030
region3       -34.65903    4.95836  -6.990 8.95e-12 ***
region1:crim   -0.19758    0.02415  -8.182 2.39e-15 ***
region2:crim   -0.03883    0.11787  -0.329 0.741954
region3:crim    0.78882    0.22454   3.513 0.000484 ***
region1:indus  -0.34420    0.04314  -7.978 1.04e-14 ***
region2:indus  -0.02127    0.06172  -0.345 0.730550
region3:indus   0.33876    0.09244   3.665 0.000275 ***
region1:rm      1.85877    0.47409   3.921 0.000101 ***
region2:rm      0.20768    1.10873   0.187 0.851491
region3:rm      7.78018    0.53402  14.569  < 2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 4.008 on 494 degrees of freedom
Multiple R-squared: 0.8142,     Adjusted R-squared: 0.8101
F-statistic: 196.8 on 11 and 494 DF,  p-value: < 2.2e-16

> anova(fm0, fm1)
Analysis of Variance Table

Model 1: medv ~ crim + indus + rm
Model 2: medv ~ region/(crim + indus + rm)
  Res.Df     RSS Df Sum of Sq     F    Pr(>F)
1    502 18559.4
2    494  7936.6  8     10623 82.65 < 2.2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Comment: The Chow test assumes that there are no gaussian violations in either the sub-models or in the composite model. Have you verified the gaussian assumptions?
Comment: thank you for your response. yes, the response variable and the residuals of my dataset show some normal distribution.
Answer: The strucchange package contains Chow and F tests for structural changes in regression models. The package comes with a vignette which shows how to use the package.
Comment: thank you for your hint, too! I found this package, but I thought it deals exclusively with time series data. thus, I can use it for cross-sectional data as well. I will give it a try...
Comment: @marco try package [segmented](http://cran.r-project.org/web/packages/segmented/index.html). You might search this site also, the structural breaks came up several times in last few months.
Comment: above I have added first results but I struggled with the interpretation... please, see the example.


Can't send output to label in VB

Question: The piece of code I have makes it so that when the radio button is checked then the whole total is multiplied by 2. The equation is 500 times 2, and the 1000 is being stored but I can't display it somehow.
Code:
    If radMeter.Checked Then
        intTotal = CInt(intMeter.ToString("C"))

    ElseIf radZone.Checked Then
        intTotal = CInt(intParking.ToString("C"))

    ElseIf radBlocking.Checked Then
        intTotal = CInt(intDriveway.ToString("C"))

    ElseIf radHandicap.Checked Then
        intTotal = CInt(intHandicap.ToString("C"))

        If radRepeat.Checked Then
            lblTotal.Text = CStr(2 * CDbl(intTotal.ToString("C")))
        End If

    End If

    'Output
    lblTotal.Text = intTotal.ToString("C")

Specifically at line 13 "radRepeat"
Comment: `CDbl(intTotal.ToString("C"))` ... you take an integer, convert it to string and then parse it again to double. Why do you do that? That does not make sense.
Comment: How exactly is this failing?  When you step through this in a debugger, where does it go wrong?  What are the runtime values when that happens?  Setting the value of `lblTotal.Text` will set the text of that label.
Answer: In your last line:
'Output
lblTotal.Text = intTotal.ToString("C")

You overwrite lblTotal with the current value of intTotal, which you did not multiply by 2 (i.e., you overwrite what you did in line 13).
The easiest way to fix that is to replace
lblTotal.Text = CStr(2 * CDbl(intTotal.ToString("C")))

with
intTotal = 2 * intTotal

Answer: Review your code carefully - you are actually writing TWICE to the label (causing your changes to be overwritten, and never saved in your intTotal variable):
    If radRepeat.Checked Then
       **lblTotal.Text** = CStr(2 * CDbl(intTotal.ToString("C")))
    End If

End If

'Output
**lblTotal.Text** = intTotal.ToString("C")

You should replace:
lblTotal.Text = CStr(2 * CDbl(intTotal.ToString("C")))

With
intTotal = (2 * intTotal)

And then let your last statement write to the label as normal.
If you are trying to NOT change the value in intTotal, but still display the doubled amount in a label, then you should move your label writing into your If... Else... block
Answer: What you may want to try to do, to see if there really is a bug with the code or just a simple logic error is insert a few breaks after each block of code.
What I could possibly see is that that when you have the radio button handicap checked, and additionally have the radio button repeat checked, the code will calculate the value * 2, but after the if then statement closes it will write again to the text field of of the lblTotal, making it seem as though it did not calculate.
I assume of course that you have at least two groups allowing more than one radio button to be checked at a time.
I would suggest the following fix:
If radRepeat.Checked Then
        intTotal = CStr(2 * CDbl(intTotal.ToString("C")))
End If

That way, your output will work for all the previous if/then statements.
Edit:
I realize that this essentially was covered by the comment above me, and cleaned up a bit.
If it were me I would have setup things a bit differently and spare my keystrokes, in the sense that if you are just calculating using integers, wait until the output line to do any converting to string, double, or whatever the case may be.
That would look something like this:
    If radMeter.Checked Then
    intTotal = intMeter

ElseIf radZone.Checked Then
    intTotal = intParking

ElseIf radBlocking.Checked Then
    intTotal = intDriveway

ElseIf radHandicap.Checked Then
    intTotal = intHandicap

    If radRepeat.Checked Then
        intTotal = (2 * intTotal)
    End If

End If

'Output
lblTotal.Text = intTotal.ToString("C")

Of course, this is given that these int(Variables) were properly introduced.

Can't send output to label in VB


Are these matrices transitive?

Question: I have 2 matrices, I don't believe that they are transitive but my friend is insisting that they are both transitive, is he correct?
a) $
    \begin{bmatrix}
    1& 1 & 1 & 1 & 1 &1 \\
    0 & 1 & 0 & 0 & 1 & 0 \\
    0 & 0 & 0 & 0 & 0 & 0 \\
    0 & 0 & 0 & 0 & 0 & 0 \\
    0 & 1 & 0 & 0 & 1 & 0 \\
    1 & 0 & 0 & 0 & 0 & 1 \\
    \end{bmatrix}
$
b) $
    \begin{bmatrix}
    1& 0 & 0 & 0 & 0 &1 \\
    1 & 1 & 0 & 0 & 1 & 0 \\
    1 & 0 & 0 & 0 & 0 & 0 \\
    1 & 0 & 0 & 0 & 0 & 0 \\
    1 & 1 & 0 & 0 & 1 & 0 \\
    1 & 0 & 0 & 0 & 0 & 1 \\
    \end{bmatrix}
$
I'm trying to order them by pairs of relation (using positions as letters, e.g. (a,b)) and failing for both.
Thank you.
Comment: Please avoid "do my homework for me"-style questions. For example, simply telling us where you got the problem from or explaining what you tried would be a big step forward! (For further feedback/help with asking questions, you can ask [here](https://chat.stackexchange.com/rooms/43593/constructive-feedback).)
Comment: The comments on [this question](https://math.stackexchange.com/questions/228898/how-to-check-whether-a-relation-is-transitive-from-the-matrix-representation) explain how to answer this question by squaring the matrix.
Answer: As explained in the comments to this question, one way to check on transitivity is to square the matrix.  If the square has a nonzero entry is a position where the original matrix has a zero, then the relation is non-transitive.  if there is no such entry, then the relation is transitive.
Rather than going to the work of squaring the matrix, let's see if we can spot such an entry in the first matrix.  Since the first row is all $1$s, multiplying any row with a $1$ in the first column will give a non-zero entry.  The first row has no zeros, so that won't help, but the sixth row has a $1$ in the first column, and a $0$ in the second.  That is, $(6,1)$ is in the relation, and $(1,2)$ is in the relation, but $(6,2)$ is not.  The relation is not transitive.
Can you do the second part now?

Are these matrices transitive?


Kerberos works in IE and Chrome, but doesn't in FF and Safari

Question: I have a Kerberos secured page, which I can access successfully in IE and Chrome without retyping my user credentials. So the single sign on worked.
With FF a 401 Error page comes directly and with Safari a loginbox comes and when I insert my user credentials it fails and a 401 Error page appears.
I think it works in Chrome because it guesses the SPN right: http://dev.chromium.org/developers/design-documents/http-authentication look under Kerberos SPN generation.
So my Question is:
Why doesn't it work in FF and Safari, even when login in with the user credentials?
Answer: You have to enable Negotiate in Firefox about:config. Google will help.
Comment: thx.
If other have the problem:
Here is how to: http://grolmsnet.de/kerbtut/firefox.html
And I also had to run "kinit" in the cmd.


Unable to bind data to auto search in Angular5

Question: Hi I am developing web application in Angular 5. I am implementing auto search option using Angular 5. Here I am unable to bind data to suggestions. In suggestions only small dot is displaying rather than property userName. Below is my html code.

UserName: {{username ? username.username||username : 'none'}}

Below is my type Script code.
  filterUsername(query, usernames) {
        let filtered: any[] = [];
        for (let i = 0; i < usernames.length; i++) {
            let username = usernames[i];
            if (username.userName.toLowerCase().indexOf(query.toLowerCase()) == 0) {
                filtered.push(username);
            }
        }
        this.filteredUsernamesSingle = filtered;
    }

Below is my sample data that filtered variable holds.
[{"id":"7fc30bbe-0b3d-447b-a45a-9ebbfbc13cf2","userName":"Mike","upn":"mik@.onmicrosoft.com"}]

Can someone help me to make this work? Thanks a lot.
Answer: Set field value as 'userName'.

Comment: Oh god. How i missed that? You saved my day... Thanks a lot.
Answer:

 Your app.component.html should now look like this:

<input [(ngModel)]="searchText" placeholder="search text goes here">

{{c}}

Your app.module.ts

import { FilterPipe} from './filter.pipe';
@NgModule({
  declarations: [ FilterPipe ],
})

Create the Filter Pipe

import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
  name: 'filter'
})
export class FilterPipe implements PipeTransform {
  transform(items: any[], searchText: string): any[] {
    if(!items) return [];
    if(!searchText) return items;
searchText = searchText.toLowerCase();
return items.filter( it => {
      return it.toLowerCase().includes(searchText);
    });
   }
}


Mudança no valor do Array

Question: Comecei a aprender sobre C, e fazendo algumas questões do URI encontrei um erro que não sei como corrigir. Ao inserir os valores dentro do array tiro, ele insere todos os valores corretamente, mas ao passar pelo scan do array pulo, tiro[0] fica 0. Alguém sabe o motivo disso e como posso corrigir?

A primeira linha da entrada contém um inteiro N que indica o número de casos de teste. Cada caso de teste é composto por 3 linhas.
A primeira linha contém um inteiro T (1 ≤ T ≤ 50) que indica o número de tiros.
A segunda linha contém T inteiros, que representam a sequência das alturas às quais os tiros estão sendo disparados. Cada elemento da sequência será entre 1 e 7, inclusive.
A terceira linha da entrada contém a string "pulos", que representa a sequência de pulos que KiloMan tentará; 'J' significa que ele irá pular e 'S' significa que ele ficará parado
No caso de ele ficar parado a altura ser 1 ou 2, ele será atingido. E caso ele pule e a altura seja 3 ou maior, também será atingido
No final é necessário apresentar o número de vezes que ele é atingido

Casos de teste que estou usando, o primeiro retorna 25 (o certo é 26) e o segundo retorna 6 (o certo é 5)
1
48
6 5 4 4 2 7 1 4 5 1 6 5 6 5 5 4 1 1 2 7 5 6 7 5 5 3 4 7 2 5 6 6 5 3 7 4 1 4 1 2 2 7 3 1 7 7 7 2
JJJSJJSSJSSSJJJSJSSSSJSSJSSJSSJJSJJSSSJJJSJSJJJJ
1
16
4 4 3 3 4 4 5 4 5 6 1 3 5 7 2 3
SSSSJSSSSJJJJSJJ
#include <stdio.h>

int main() {
    int rep, mov, ace, i, i2;
    scanf("%d", &rep);
    for(i = 0; i < rep; i++){
        ace = 0;
        scanf("%d", &mov);

        int tiro[mov];
        for(i2 = 0; i2 < mov; i2++){
            scanf("%d", &tiro[i2]);
        }
        printf("%d\n", tiro[0]); //Valor de tiro continua sendo o mesmo

        char pulo[mov];
        scanf("%s", &pulo);

        printf("%d\n", tiro[0]); //Valor de tiro já virou 0
        for(i2 = 0; i2 < mov; i2++){
            if((tiro[i2] <= 2 && pulo[i2] == 'S') || (tiro[i2] >= 3 && pulo[i2] == 'J')){
                ace++;
            }
            printf("O teste %d, com os valores %d/%c teve %d acerto(s)\n", i2+1, tiro[i2], pulo[i2], ace);
        }
        printf("%d\n", ace);
    }
    return 0;
}

Answer: Não tão off-topic: URI é Universidade Regional Integrada, uma universidade de Erechim, RS. Online Judge é uma plataforma de programação competitiva, ou algo assim.
Esse problema é iterativo: são N casos de teste e cada caso tem um certo número de disparos da tal arma. E para cada disparo a reação será J ou S, jump ou stand still. 2 linhas trazem os pares altura do tiro / atitude do jogador, e a saída para cada série é o número de vezes em que o cara foi atingido.
A decisão é uma tabela: a altura do tiro vai de 1 a 7. No caso de ele ficar parado a altura ser 1 ou 2, ele será atingido. E caso ele pule e a altura seja 3 ou maior, também será atingido. Nada mais. Eis a tabela:
Alt < 3    Pula?      Resultado
   N         N          A Salvo
   N         S          Atingido
   S         N          Atingido
   S         S          A Salvo

No exemplo, essa tabela em C tem os 4 resultados
    int destino[2][2] = {0, 1, 1, 0};  // os resultados

Exemplo em C
Claro que já tendo os 4 casos do exemplo seria melhor poder testar logo com esses e ler de um arquivo, e apenas se desse certo leria da entrada padrão, como o caso do programa no tal Online Judge.
Ler dados do teclado é muito mais chato e complicado que ler de um simples arquivo que você digita no próprio IDE, e vou mostrar no exemplo que pode usar o mesmo código...
Eis os dados de entrada de exemplo
4 repeticoes
9 pulos
1 3 2 3 3 1 2 2 1
JJSSSJSSJ
49 pulos
1 1 1 1 1 1 1 2 2 2 2 2 2 2 3 3 3 3 3 3 3 4 4 4 4 4 4 4 5 5 5 5 5 5 5 6 6 6 6 6 6 6 7 7 7 7 7 7 7
SSSSSSSSSSSSSSJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJ
4 pulos
1 2 2 1
SJJS
1 pulo
1
J

Dependendo de como você ler em C pode até deixar texto no arquivo pra não ter que ficar procurando os testes no meio do arquivo...
E o resultado esperado
4
49
2
0

Então o mais simples é colocar esses dados em um arquivo, como
exemplo.txt

E o programa em C aceita um parâmetro opcional que é o óbvio nome do arquivo. Assim você pode testar com dados de um arquivo que digita no próprio editor, e se não usar o parâmetro o programa lê do teclado mesmo...
Rodando o exemplo
Os 4 testes óbvios: 2J 4J 2S 4S lembrando que com a altura menor que 3 se pular se salva, e com a altura maior que 2 se pular é atingido, e 0 indica que não foi atingido...
SO>./f1-0903
1
1
2
J
0
SO>./f1-0903
1
1
4
J
1
SO> ./f1-0903
1
1
2
S
1
SO> ./f1-0903
1
1
4
S
0

Claro que a saída seria apenas a quarta linha de cada caso, o número de hits.
0
1
1
0

chamando com o arquivo que tem os dados do exemplo
SO> ./f1-0903 exemplo.txt
4
49
2
0

Claro que f1-0903 era o nome do programa na máquina de teste.
E esse é o resultado esperado.
lendo do arquivo OU do teclado
    FILE* ent;
    if (argc > 1)
    {  // veio algo entao e o nome do arquivo
        ent = fopen(argv[1], "r");
        if (ent == NULL) return -1;
    }
    else
        ent = stdin;  // nao veio o arquivo...

Basta isso. Se não vier nada na linha de comando lê os dados do teclado.
Não faz sentido ficar digitando dados a toa para cada teste.
No exemplo usei fgets() para ler os valores que vem sozinhos na linha pra não perder tempo com lances de buffer, e para poder escrever no resto da linha pra não ter que ficar contando no editor :)
Depois de ler o total de testes o programa tem um loop para fazer os testes, e termina.
O loop dos testes lê o total de disparos e o vetor de alturas.
Não é preciso ler o vetor de ações porque de nada serve. Só precisamos saber a ação porque já temos a altura do tiro, e então pode somar direto no número de hits em uma linha de acordo com a tabela que tem acima
            mortes += destino[altura[t] < 3][mov == 'J'];

o programa todo
/*
 EXEMPLO C relativo a questao
https://pt.stackoverflow.com/questions/526544
 e ao problea 1250 do URI Online Judge
 https://www.urionlinejudge.com.br/judge/pt/problems/view/1250
*/
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char** argv)
{
    char  linha[200];
    FILE* ent;
    if (argc > 1)
    {  // veio algo entao e o nome do arquivo
        ent = fopen(argv[1], "r");
        if (ent == NULL) return -1;
    }
    else
        ent = stdin;  // nao veio o arquivo...

    int destino[2][2] = {0, 1, 1, 0};  // os resultados

    fgets(linha, sizeof linha, ent);
    int N   = 0;  // o total de testes
    int res = sscanf(linha, "%d", &N);
    if (res < 0) return -1;

    // os N testes
    for (int n = 0; n < N; n += 1)
    {  // o teste 'n'
        int T = 0;  // disparos
        fgets(linha, sizeof linha, ent);
        res = sscanf(linha, "%d", &T);
        if (res < 0) return -2;
        // os 'T' disparos
        int altura[50];
        for (int t = 0; t < T; t += 1)
        {
            // le o vetor das alturas
            res = fscanf(ent, "%d", altura + t);
            if (res < 0) return -2;
        };  // for(t)
        fgets(linha, sizeof linha, ent);  // le o '\n' da linha anterior

        // calcula as mortes afinal
        char mov;  // movimento
        int  mortes = 0;
        for (int t = 0; t < T; t += 1)
        {   // para cada altura testa se foi atingido
            res = fscanf(ent, "%c", &mov);
            if (res < 0) return -2;
            mortes += destino[altura[t] < 3][mov == 'J'];
        };  // for(t)
        printf("%d\n", mortes);
        fgets(linha, sizeof linha, ent);
    };  // for (n)
    fclose(ent);
    return 0;
}

sobre seu programa
    int rep, mov, ace, i, i2;
    scanf("%d", &rep);
    for (i = 0; i < rep; i++)
    {
        ace = 0;
        scanf("%d", &mov);

Evite esse tipo de construção. Mesmo sendo um programa para "competição" mostre ao sujeito que estiver usando o programa o que espera ler. E não seria demais mostrar o que leu. Muitas o programa dá errado porque está achando que leu algo e não leu, como ao confundir '0' a letra e 0 o número.
Teste sempre o retorno de scanf(). Como nesse caso só tem um especificador pode retornar 1, 0 ou -1. Se ler o número vai retornar 1, mas se não ler qual o sentido de seguir com o programa? Experimente teclar um x nessa hora...
No for declare sempre a variável de controle do loop. Esse era um problema da linguagem, corrigido há uns 40 anos.
Evite declarar mais de uma variável por linha. Linhas são grátis. E inicialize todas as variáveis. Vai te salvar muitas vezes.
Use nomes mais expressivos, em especial em casos como i e i2 que são globais em main()
Não pode declarar
        int tiro[mov];

deve ser ser um valor conhecido em tempo de compilação, como
    int tiro[300];

Ou deve alocar na hora, como em
    int*    tiro = (int*) malloc(300 * sizeof (int))

exemplo
Recortando e colando de seu programa, compare com um modo comum de escrever isso:
#include <stdio.h>
#include <stdlib.h>

int main()
{
    int rep = 0;
    int mov = 0;
    int ace = 0;

    printf("rep? : ");
    int res = scanf("%d", &rep);
    if (res < 0 ) return - 1;
    printf("rep = %d\n", rep);

    for (int i = 0; i < rep; i++)
    {
        ace = 0;
        printf("mov? : ");
        res = scanf("%d", &mov);
        if (res < 0) return -2;
        if (mov > 512) mov = 512;  // um limite...
        printf("mov = %d\n", mov);

        // le os tiro[0] a tiro[mov-1]
        int* tiro = (int*)malloc(mov * sizeof(int));
        for (int i2 = 0; i2 < mov; i2++)
        {
            res = scanf("%d", &tiro[i2]);
            if (res < 0) return -3;
        }
        // mostra os caras...
        printf("Tiro:\n");

        for (int i2 = 0; i2 < mov; i2++)
        {
            printf("%d ", tiro[i2]);
            if ((i2 % 4) == 3) printf("\n");  // 4 por linha
        }
        printf("\n");
        free(tiro); // apaga o vetor
    }
    return 0;
}

que aloca o vetor 'tiro[]` a cada repetição e apaga ao final
saída
rep? : 1
rep = 1
mov? : 8
mov = 8
1
2
3
4
5
6
7
8
Tiro:
1 2 3 4
5 6 7 8

Comment: +1, mas com ressalva. Só faz sentido, vc verificar retorno de erro, se o erro precisa ser tratado e se você sabe como fazer isso. No caso do `scanf` e programação competitiva, se por alguma razão o seu programa não ler a entrada a sua solução não vai passar o teste e o tratamento que você dá com `return -1;` não acrescenta nada já que o resultado será **WA 100%** que seria o mesmo caso a sua solução fosse incorreta. Aqui, você tem duas alternativas, ignorar completamente o retorno de `scanf()` - o que eu faria - ou tratar invocando `abort()` e o URI informa que houve um runtime error.
Comment: Sim e não, @VanderSantos. Isso porque antes de submeter o programa você precisa dele pronto e testando pelo erro e mostrando o que leu você provavelmente chega mais rápido ao momento de submeter o resultado, e isso é a competição afinal. Depois que estiver certo leva minutos para retirar esses testes. Para estar pronto sem esses testes pode levar muito mais tempo do que leva pra tirar isso.
Comment: Desculpe @arfneto, sou novo aqui no SO. Acabei cometendo um erro sobre o número da questão, corrigi isso agora no enunciado. No caso, o problema que tive é que em algumas ocasiões o valor na posição 0 do array tiro era substituído e não sabia porque isso está acontecendo
Comment: Entendo. Mesmo corrigindo as coisas de que falei persiste a corrupção? Vou ver depois se acho algo
Comment: Não, a corrupção foi corrigida. Pode só me explicar um pouco melhor como funciona o array tiro? Comecei a pouco tempo com C, então estou bem perdido em algumas coisas ainda
Comment: Eu vi o tal problema. O único array de que precisa é o das alturas dos tiros, porque as ações vem juntas. Vou deixar um exemplo que talvez ajude a entender

Mudança no valor do Array


Julia - Transform a matrix to a vector

Question: Appart from allocating a new vector and filling its values one by one with the one of my matrix, how would I resize / refill a matrix of size n x m to a vector of size n x m generalizing the following example:
julia> example_matrix = [i+j for i in 1:3, j in 1:4]
3×4 Array{Int64,2}:
 2  3  4  5
 3  4  5  6
 4  5  6  7

julia> res_vect = [2, 3, 4, 3, 4, 5, 4, 5, 6, 5, 6, 7]
12-element Array{Int64,1}:
 2
 3
 4
 3
 4
 5
 4
 5
 6
 5
 6
 7

An idea I had is:
 res_vect = Int[]
 for j in 1:size(example_matrix,2)
    res_vect = vcat(res_vect, example_matrix[:,j])
 end

I have the feeling it is not the optimal way yet I could not explain why...
Comment: BTW, never initialize a vector with `res_vect = []`, unless you have a very good reason. `[]` creates a `Vector{Any}`, which will poison the other arrays you concatenate it with. Writing `[]` is a _huge_ red flag for performance. You should write `Int[]` if you intend the array to contain `Int`s.
Comment: Thanks @DNF, I didn't know :)
Answer: Julia allows you to do that sort of thing even without copying any data:
julia> m = [i+j for i in 1:3, j in 1:4]
3×4 Matrix{Int64}:
 2  3  4  5
 3  4  5  6
 4  5  6  7

julia> m1 = vec(m)  # m1 points to the same memory address as m
12-element Vector{Int64}:
 2
 3
 4
 3
 4
 5
 4
 5
 6
 5
 6
 7

julia> m2 = reshape(m, 4, 3) # m2 still points to the same memory address as m
4×3 Matrix{Int64}:
 2  4  6
 3  5  5
 4  4  6
 3  5  7

If you are wondering what "points to the same memory address" means have a look at this example:
julia> m2[1,1] = -66
-66

julia> m
3×4 Matrix{Int64}:
 -66  3  4  5
   3  4  5  6
   4  5  6  7

Finally, if at any point you actually need a copy rather than a reference to the same data use copy(m) or as commented by @DNF m[:] (this is a dimension drop operator that returns a Vector with copy of data from any Array).
Comment: To get a vector, using copying, one can just write `y = x[:]`.
Comment: Wow, there is a simple function for what I want! Thanks ;)

Julia - Transform a matrix to a vector


l'Hôpital and substitution give different limits

Question: Find $$\lim_{x \to 0}\frac{\sin x-x+\frac{x^3}6}{x^3}$$
L'Hospital 3 times:
$$\lim_{x \to 0}\frac{\sin x-x+\frac{x^3}6}{x^3} = \lim_{x \to 0 } \frac{\cos x - 1 + \frac{x^2}2}{3x^2}=\lim_{x \to 0}\frac{-\sin x+x}{6x}=\lim_{x \to 0}\frac{-\cos x +1}{6}=0$$
L'Hospital once and Substitution:
$$\lim_{x \to 0}\frac{\sin x-x+\frac{x^3}6}{x^3} = \lim_{x \to 0 } \frac{\cos x - 1 + \frac{x^2}2}{3x^2} = \lim_{x \to 0}\frac{x^2}{6x^2}=\frac16$$
Comment: $\cos x-1+\frac{x^2}2=1-\frac{x^2}2+\frac{x^4}{4!}-\cdots-1+\frac{x^2}2\ne\frac{x^2}2$. But what do you call *substitution* here ?
Answer: The second one is wrong. How did you drop $\frac {\cos x-1} {3x^{2}}$? The limit of this part is $-\frac  16$ which cancels with the limit of the other term.
It is also not clear as to what you mean by 'substitution'.
Comment: Ahh I have incorrectly applied the rule $\lim_{x \to a}\frac{f(x)}{g(x)}=\frac{\lim_{x \to a}f(x)}{\lim_{x \to a}g(x)}$


Localized XIB not showing all IBActions, outlet & images

Question: i m getting a problem with my localized xib.
I have created english version xib first, then made them localized, & added other localization.
it works fine in app also.
But when i open other language xib with IB, i m unable to get all outlets & IBActions.
It seems like it is taking only those one that were present when i created the localized file, & not showing newly added one.
Does file not getting updated?
Note : My other team member done the same thing & they don't have problem.
i also tried to removed & created all new localized file then also no change.
I m unable to identify the problem, i m stuck on this problem & cannot proceed with further development.
Please help .. :(
Answer: If you have Xibs in different languages, they don't get updated automatically when you change the English one.
Instead, you should either merge the new changes using ibtool (type man ibtool in Terminal to learn its options), or use a dedicated application like iLocalize.
In general, it can be quite an issue to update all the localizations all the time and sometimes large changes can't be merged well automatically. You need to be careful about that.


What are "crawling artifacts" in computer graphics?

Question: I am reading a paper where it says something about that. Googling didn't help that much.
The full sentence is in the section 3.1 of this paper:
http://gfx.cs.princeton.edu/pubs/Cole_2010_TFM/cole_tfm_preprint.pdf
Thanks a lot!
C4sh
Answer: I think it means temporal aliasing artifacts when rendering lines in animations. They show up as brighter pixels crawling along the line.
Once you know about those, your enjoyment of computer animated movies will decrease significantly. Sorry about. It cannot be undone. :-)


Display a custom field of a content type in template with PHP?

Question: I'm using Drupal 7.  I have a content type called Widget.  One of the custom fields is field_widget_position.  When I did a <?php print_r($page); ?> in the template, I can see the key-value pair of field_widget_position buried deep in the array.  Is there an easier way to get a handle on field_widget_position instead of typing <?php echo $page['somefield']['somefield2']['somefield3']['etc....']['field_widget_position']; ?>?
Answer: $node->field_widget_position['en'][0]['value']

This is a bad solution.
The right solution is
render(field_view_field('node', $node, 'field_widget_position'));

or
render(field_view_field('node', $node, 'field_widget_position', array('label' => 'hidden')));

if you don't want to print a label.
See http://www.computerminds.co.uk/articles/rendering-drupal-7-fields-right-way for more info.
Answer: I found the answer.
$node->field_widget_position['en'][0]['value']

Comment: More generically: `$node->field_widget_position[$node->language][0]['value']`


making two spans to the right

Question: I am trying to text align two spans to the right.
 close
 x

Somehow, x comes before close as follows:
 x   close

How can I fix it?
Rephrasing the question, I am trying to align two rows to the right like the following:
 1,300,000   x
       100   x

But all I got is:
1,300,000   x
100  x

What's missing here?
Comment: There's a lot of different ways you can do it. You can add `display: block` and align text to right if you want two different lines, for example. Or you can use flexbox instead float. There is no need to use floats now that we have flexbox
Answer: You should align it to the right within a parent element:

     close
     x

Comment: Tried this way and it should have worked but it didn't work so I came up with the two floats as above. Anyway, thanks.
Answer: I used 'text-align: right' instead of 'float'. Worked. Thanks to all.

making two spans to the right


Logistic regression on a dataset with duplicated records

Question: I have a large data set with multiple records per phone number. Each record has two variables - the number of past attempts in the past 60 days (number of times it was called) which range from 0 to 30 or so and a success indicator (0 or 1). I want to model how the number of past attempts impacts the probability of the outcome. There are no other covariates.
I want to model it as outcome~pastAttempts. The problem is that the records are not independent, as they by definition are the same phone numbers. Some phone numbers are listed 1 time, others up to 98 times. Can I use logistic regression for this since the covariate pastAttempts is adjusting for the fact there are repeated observations? If not, what other technique is plausible?
ADD:
The data set covers a time period greater than 60 days and the predictor variable is the number of attempts in the past 60 days. So it is not always increasing but can "reset" along the way since the variable is a "rolling" measure.
here is an example of 4 phone numbers.
Answer: I would use survival analysis rather than logistic regression. The dependent variable is not only a "time to event" it also is probably censored (some people were not reached even with 30 attempts).
I admit I haven't seen survival analysis with a count instead of time, but I think it's a viable idea. It would have some things in common with a discrete time survival analysis model.
Comment: Peter, yeah i am quite familiar with discrete time survival analysis but not sure how that would work - given that there is no time variable or even a manner to index with that I can think of off hand.
Comment: Wouldn't number of tries be a marker for time?
Comment: Interesting idea to use survival analysis, but I am not sure ... I think what one should do depende also on for what use is the resulting model to be put? For instance, if the use of the model is to provide some weights to use in some analysis, then the logistic regression seem the  way to go ...
Comment: @PeterFlom The issue is that the data set contains multiple records per  phone number , where the independent variable is the number of attempts in the past 60 days. Since the data covers a period much larger than 60 days, the variable "resets". I will post an example.
Comment: Would using only the latest record for each phone number work? OR could you create features for each phone number that represents different periods of 60 days. Jan-Feb, Mar-Apr and have a cumulative count for each.


Estilos do meu DataTable não carrega no modal

Question: Estou criando um modal e dentro vou colocar uma tabela com algumas informações, porém, o conteúdo do modal não está sendo estilizável.
Já uso a mesma tabela em outras views e funciona normalmente dessa forma, apenas no modal que não.
A importação dos scripts ocorre corretamente como podem ver no código a seguir:

@section Styles {
    <link rel="stylesheet" href="~/vendor/jquery-bootgrid/dist/jquery.bootgrid.css">
}
@section Scripts {

}

                <button type="button" class="close" data-dismiss="modal">×</button>

Cabeçalho Modal

@Resources.Resources.Acoes

                            @Resources.Resources.Codigo
                            @Resources.Resources.Tag
                            @Resources.Resources.Descricao

                            qwdqwdqwd
                            qwdqwdqwdqwdqw
                            qwdqwdqwdqw

                <button type="button" class="btn btn-primary" data-dismiss="modal">Fechar</button>

<button type="button" class="btn btn-info btn-lg" style="visibility: hidden" id="abrirModal" data-toggle="modal" data-target="#myModal">Abrir janela Modal</button>

Como deveria ficar:
Comment: Importou o jquery-ui.css ?
Comment: @RonaldoAraújoAlves Sim amigo, se eu colocar o grid fora do modal ele funciona perfeitamente.
Answer: Faltou alguns arquivos como jquery.js, boostrap.js e bootstrap.css,
e faltou chamar a funcao que gera a tabela: $("#bootgrid-command").bootgrid();

$("#bootgrid-command").bootgrid();
<link href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet"/>

                <button type="button" class="close" data-dismiss="modal">×</button>

Cabeçalho Modal

@Resources.Resources.Acoes

                            @Resources.Resources.Codigo
                            @Resources.Resources.Tag
                            @Resources.Resources.Descricao

                            qwdqwdqwd
                            qwdqwdqwdqwdqw
                            qwdqwdqwdqw

                            qwdqwdqwd
                            qwdqwdqwdqwdqw
                            qwdqwdqwdqw

                            qwdqwdqwd
                            qwdqwdqwdqwdqw
                            qwdqwdqwdqw

                <button type="button" class="btn btn-primary" data-dismiss="modal">Fechar</button>

<button type="button" class="btn btn-info btn-lg" id="abrirModal" data-toggle="modal" data-target="#myModal">Abrir janela Modal</button>
Answer: Você precisa iniciar o componente com o comando:

Consulte a documentação
Comment: Está dizendo que terei que montar o meu bootgrid com JQuery e não usando HTML + CSS?
Comment: Não. Esse componente que vc está usando depende de uma inicialização conforme coloquei na resposta. Creio que ele precise do jQuery para funcionar. Sem iniciar o componente, ele não faz nada.
Comment: Mas eu uso telas de listagem de registros onde uso a tabela exatamente dessa mesma forma e ele consegue carregar os estilos, é isso que nao estou entendendo.
Comment: Faz um teste com o código que coloquei e veja aí como fica, aí vc me fala. Coloque o código no final do body.
Comment: Não deu certo @Sam, ele da erro de referencia nao definida no console. Ele realmente não está conseguindo carregar os scripts no modal.
Comment: Se puder colar aqui exatamente o erro que mostra no console para eu ver o que é.


When using Automatonymous Statemachine and EF Core to store the state can I combine the state and my entities in one DbContext

Question: I was wondering what the best practices are surrounding using EF Core, the saga state Db and your application DB, and whether you should or should not combine your saga state with your entity in the same table in the database, or even have your saga state in the same database.
Answer: Yes, of course you can put other entities in the same DbContext as your saga state. The only thing special about the SagaClassMap<T> is some of the base initialization, and the SagaDbContext only has a couple of helper methods.


Unable to dismiss AlertDialog

Question: Hi need to show a AlertDialog from a Service.
This is my implementation.
I added the permission:
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>

But I am not able to dismiss the dialog!!!
I click the OK button but id does not go away!!!
And all the system freezes on that dialog !!!
Please help!!!
public class CreditcheckService extends IntentService {
AlertDialog dialog;
public CreditcheckService() {
    super("CreditcheckService");
}

@Override
protected void onHandleIntent(Intent intent) {
    AlertDialog.Builder builder = new AlertDialog.Builder(
            getApplicationContext());

    builder.setMessage(R.string.please_connect).setTitle(
            R.string.unable_to);
    builder.setPositiveButton(R.string.okay_action,
            new OnClickListener() {
        @Override
        public void onClick(DialogInterface arg,
                int which) {dialog.cancel();
        }
    });
    dialog= builder.create();
    dialog.getWindow().setType(
            WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
    dialog.show();
}

Comment: Call dialog.dismiss(); in onClickListenr ()
Comment: @Manveer Chawla thanks Manveer, tried it, without success :-(((
Answer: This is working for my service
              try{
                    new Thread() {
                        @Override
                        public void run() {
                            Looper.prepare();
                            AlertDialog.Builder builder = new AlertDialog.Builder(
                                    getApplicationContext());

                            builder.setMessage("My messgae").setTitle("My Title");
                            builder.setPositiveButton("Ok",
                                    new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface arg,
                                                            int which) {dialog.cancel();
                                        }
                                    });

                            dialog= builder.create();
                            dialog.getWindow().setType(
                                    WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
                            dialog.show();
                            Looper.loop();
                        }
                    }.start();
                } catch (Exception e) {
                    // TODO: handle exception
                    e.printStackTrace();
                }

Answer: try this:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage("")
            .setCancelable(false)
            .setPositiveButton("Yes",null);
    AlertDialog alert = builder.create();
    alert.show();
}

Comment: so if you replace all code with in your onHandleIntent methode you have no sucess? So i think not the code inside the method is your problem... what happens if you let the method empthy?

Unable to dismiss AlertDialog


What are the benefits of MVC Web API over ASMX service in business sense and not as a developer?

Question: I have an ASMX web service which is internally calling some Payment related APIs and is currently processing few thousand orders daily. We are planning to upgrade this wrapper service to Asp.Net Web APIs. How can I explain the business the benefits of this upgrade in a non technical way as they might not be able to understand the technical terms? Budget and resources is not an issue for this upgrade.
Comment: What are *your* reasons to upgrade this wrapper service?
Answer: Web API is better because it is based on HTTP and not SOAP. HTTP contains headers that give information on the content. It is more easier to understand and develop for. Since Web API is in HTTP it means that you are able to reach many more clients. The body of a http message can contain any kind of content.
From a business perspective it is easier to maintain, easier to develop and you are able to reach more clients. It also means that you are able to always extend functionality. With those qualities such as the maintainability and the ease of development means that it is ultimately cheaper and more effective.
In software whatever is easy to maintain and understand is the ultimate king from all angles (financial and technological).