Search whether a document exists in a JSON API, not by primary identifier

Question: I am building a JSON API and have a user resource. A user has id as its primary identifier and some other fields: facebook_id, linkedin_id and so on.
I need to check whether a certain user exists, only by having one of the other fields (e.g.: facebook_id). I cannot use /users/<id> and check whether it returns a 404 because I don't have the primary identifier.
I thought about using a /users/exists?<field>=<value>, but I'm not sure whether this is the correct approach with JSON API.
My questions are, what endpoint should I create, what code should it return in case the document exists or not, and what body?
Answer: You can use the facebook id as a parameter in the query string, something like:
GET /users?facebookId=12345

if the http status code response is 200 then the user does exist and the content is an user resource, for example:
/users?facebookId={fb_id}:
    get:
      summary: ...
      description: ...
      parameters:
        - name: fb_id
          in: path
          required: true
          type: integer
      responses:
        "200":
          description: ...
          schema:
            $ref: '#/definitions/userResource'

Comment: The reference also states about collections, you can either return an 200 status code with a payload and an empty array for the data attribute or a 403 status code with an empty response
Comment: Okay, but if it doesn't exist, a request to `/users` should also respond with `200` but return an empty list. Or am I wrong?
Comment: According to the [JSON API reference](http://jsonapi.org/format/#fetching) you have to return a 404 status
Comment: It's still not clear, the reference only states about trying to fetch an individual resource. It doesn't make sense to return a 404 for a search on a collection - it will always return something, worst, an empty array.


Relative risk from logistics regression in R

Question: I can't seem to find a way to get relative risk (instead of odds ratio) in R via glm() function. However, the equivalence seems to be glm() with poisson family and log link, which I suspect will yield the relative risk (or relative proportion, depending on the problem) when the coefficients are exponentiated. Is this correct?
For example, let's say that:

y is a binary variable (1/0)
x1 is a continuous variable
x2 is a binary variable
x3 is a binary variable

y ~ x1 + x2 + x3 with glm() with family=poisson(link="log") yielded the following coefficients:

(intercept)=-2.08
x1         =-0.02
x2         =-0.004
x3         =0.25

And then when the coefficients get exponentiated:

(intercept)=0.12
x1         =0.98
x2         =1
x3         =1.29

Does the exponentiated coefficients means:

Relative proportion of y increases by 0.98 times (or decreases by 2%) for every one unit increase of x1?
Relative proportion of y is unchanged regardless of the choice in x2
Relative proportion of y increases by 1.29 times (or increases by 29%) when x3=1 compared to x3=0?
Answer: The interpretation of the exponentiated coefficient from a Poisson regression as a relative risk depends on how data were collected.
This paper by GY Zou is a very well known paper for showing that Poisson regression + robust covariance estimation yields estimates of relative risk + good coverage of the resulting confidence interval.  The thing to note here is that there is a caveat on the sampling design:  the data must be from a prospective study.
The procedure would NOT produce valid estimates of the relative risk in, say, a case control design because the frequency of cases may not reflect the true frequency in the population.


LineType e shape em ggplot2 no R

Question: Estou usando o seguinte código para plotar 3 funções:
ggplot(data.frame(x = c(0, 2)), aes(x)) +
    stat_function(fun = exp, geom = "line")+
    stat_function(fun = dnorm ,geom = "line")+
    stat_function(fun = cos, colour = "blue")

Gostaria que que a forma das linhas que desenham as 3 funções acima, fosse dessa forma:

Ou seja, a primeira função fosse pontilhada com triângulo, a segunda com asteriscos e a terceira com pontos. As formas (triangulo, asteriscos e pontos) podem ser qualquer uma (quadrado, círculo ...) . Como eu faço para adicionar uma legenda com as respectivas formas para cada linha?
Answer: Em primeiro lugar vou criar um vetor com os valores de x nos quais eu quero que os pontos sejam plotados. No caso, quero todos os pontos entre 0 e 2, com espaçamento de 0.25:
x <- seq(0, 2, by=0.25)

Com este vetor eu vou criar um data frame com x e os valores das funções que me interessam:
dados <- data.frame(x,
                    exp=exp(x),
                    dnorm=dnorm(x),
                    cos=cos(x))

Por fim, ploto tudo utilizando um geom_point para cada conjunto de pontos da função e um stat_function para cada função. Note que cada geom_point tem uma shape atribuída a ele. Além disso, atribuí parâmetros de colour iguais para geom_point e stat_function.
ggplot(dados, aes(x=x, y=exp)) +
  geom_point(aes(colour="exp"), shape=1) +
  stat_function(fun = exp, geom = "line", aes(colour="exp")) +
  geom_point(aes(x=x, y=dnorm, colour="dnorm"), shape=2) +
  stat_function(fun = dnorm, geom = "line", aes(colour="dnorm")) +
  geom_point(aes(x=x, y=cos, colour="cos"), shape=4) +
  stat_function(fun = cos, geom = "line", aes(colour="cos")) +
  labs(x="Eixo X", y="f(x)", colour="Legenda")

Perceba também que não defini as cores das linhas e dos pontos como vermelha, azul e verde. Preferi chamá-las de exp, dnorm e cos. Como é super fácil utilizar paletas de cores no ggplot2, é melhor definir as cores desta forma, pois a legenda fica mais intuitiva e fica trivial mudar as cores através do comando scale_color_brewer.
ggplot(dados, aes(x=x, y=exp)) +
  geom_point(aes(colour="exp"), shape=1) +
  stat_function(fun = exp, geom = "line", aes(colour="exp")) +
  geom_point(aes(x=x, y=dnorm, colour="dnorm"), shape=2) +
  stat_function(fun = dnorm, geom = "line", aes(colour="dnorm")) +
  geom_point(aes(x=x, y=cos, colour="cos"), shape=4) +
  stat_function(fun = cos, geom = "line", aes(colour="cos")) +
  labs(x="Eixo X", y="f(x)", colour="Legenda") +
  scale_color_brewer(palette="Dark2")

Comment: Perfeito! Vlw!!!

LineType e shape em ggplot2 no R


Python BeautifulSoup: Retrieving review related information from Google Play Store

Question: I am writing a program to retrieve the information related to reviews posted by the users on google play store. It includes reviewer name, rating of review, date of review, like or dislike of review, and text of the review. I am using BeautifulSoup for this purpose. I am facing trouble in retrieving above information. Let me explain by the following example:
I want to retrieve review related information of following weblink:
https://play.google.com/store/apps/details?id=com.education.educationkids&hl=en&showAllReviews=true
Here is the code of my program:
import urllib.request
import bs4 as bs
html = urllib.request.urlopen('https://play.google.com/store/apps/details?id=com.education.educationkids&hl=en&showAllReviews=true').read()
soup = bs.BeautifulSoup(html, 'html.parser')

I want to retrieve the above mentioned information. When I inspect the element I found that div named "fk8dgd" contains all review related information (as shown in the picture).

In order to retrieve the text of the reviewer, I used the following command:
soup.find('div',{'jscontroller':'H6eOGe'}).get_text()

However, the command throw an error:
AttributeError: 'NoneType' object has no attribute 'get_text'

I am not sure where am I making the mistake. Could anyone help me out to fix the issue?
Comment: What does `print(soup.find('div',{'jscontroller':'H6eOGe'}))` output?
Comment: @SamChats It throws an error message AttributeError: 'NoneType' object has no attribute 'get_text'
Answer: The bad reason is that the html is drawn after the page is loaded through the browser.
This loads the page completely through selenium and finds its contents in beautifulsoup.
Here is code
import bs4 as bs
from selenium import webdriver

driver = webdriver.Chrome()

driver.get('https://play.google.com/store/apps/details?id=com.education.educationkids&hl=en&showAllReviews=true')

# html = urllib.request.urlopen('https://play.google.com/store/apps/details?id=com.education.educationkids&hl=en&showAllReviews=true').read()
soup = bs.BeautifulSoup(driver.page_source, 'html.parser')

print(soup.find('div',{'jscontroller':'H6eOGe'}).get_text())


A Percentage of Averages

Question: A company brags about the speed of their service, "75% of our assignments are completed in an average of 20 days."
Is this a meaningful claim? Or is it kind of like saying, "60% of the time, it works every time?"
How might this be calculated?
Thanks
Comment: Each assignment has a certain time until completion. Take the fastest $75\%$ of these processing times and the average is $20$ days.
Comment: I first understood it the other way around: 75% of the tasks are completed in less than average time, which is 20 days. This would also mean that 25% of the tasks take much more than 20 days. But now that I think of it, sonystarmaps's explanation makes more sense.
Comment: $95\%$ time a percentage is used in advertising, it is made up.  Yes, I made that up, but I suspect it is not far from the truth.  The fact that you can parse the sentence in a sensible way does not mean that it has any relationship with reality.
Answer: The assertion makes full sense, though there is some ambiguity in the meaning of "average.". Let $T$ be the waiting time, and let $a$ be the $75$-th percentile of $T$. Let $T^\ast=T|T\le a$.
It is not clear what is meant by average in this case, perhaps mean, perhaps median. So we are told that the mean (or median) of $T^\ast$ is $20$.
Comment: I don't know enough about this subject to understand what you mean with the * and | symbols. But I understand what sonystarmap is saying, and s/he said s/he's providing one possible example of what you wrote. So I'm going to mark yours as the answer.

Thanks
Comment: I was being perhaps unnecessarily technical, the $T^\ast$ is just a name, could have called it $X$. The technical part is $T|T\le a$. This is the waiting time **given** that the waiting time is $\le a$. @sonystarmap gave a good ntuitive description of what is meant by that. The intuitive description is I think adequate for informal purposes, and unaccepting my answer and accepting the other seems to me appropriate (unaccepting is not rejection).
Answer: I just wanted to add an example of the calculation, assuming that average refears to the arithmetic mean, which does not have to be the case as stated in André Nicolas' answer.
Assume you are talking about 8 assignments overall and the processing time of each assignments in day is given by (randomly):
1 3 5 10 3 8 100 4

Now, if you are the company, you advertise your fastest $75\%$, so sorting the list we get
1 3 3 4 5 8 10 100

Now taking the first $75\%$ we are left with
1 3 3 4 5 8

where the arithmetic mean is
\begin{align}
\frac16(1+3+3+4+5+5)= \frac{24}{6}
\end{align}
So the company could advertise, that $75\%$ of their assignments are completed within an average $4$ days.

A Percentage of Averages


Make custom field added to comments available in comment.tpl.php

Question: I added a integer list field called "field_rating" to the core comments. Now I want to use the new field directly in my comment.tpl.php with it's display settings, but I just don't know how to do that despite this should be a no-brainer. Help is much appreciated.
Answer: All you gotta do is add <?php print render($content['field_rating']); ?>


integral, matrices, exponentiation, upper bound, time,linear system, unclear derivation

Question: How do I derive from $\dot{x}(t)=Ax(t)+Bu(t), x(0)=p$ that
$x(t;p)=e^{At}p+\int_0^t e^{A(t-s)}Bu(s)ds$ ?
Here $A$ and $B$ are matrices of suitable sizes: $A$ is $n\times n$ and $B$ is $n \times m$,both constant real matrices, and $\dot{x}$ is derivation of $x(t)$ by $t$.
Comment: variation of constants: define $y(t)$ by $y(t)=e^{-At}x(t)$ (i.e. $x(t)=e^{At}y(t)$), find the ODE satisfied by $y(t)$, and solve it
Comment: Thank you for the hint. Unfortunately it is too coarse for me to see the solution to my question.What shall I do with $u$ there?
Comment: Start with the homogeneous equation, as explained by user8268, then try to find a particular solution for the non-homogeneous equation (the one including $u$), using methods analogous to the single-variable case.
Comment: $dx/dt=d(e^{At}y)/dt=e^{At}(dy/dt+Ay)=e^{At}dy/dt+Ax$ and this should be equal to $Ax+Bu$, hence the equation for $y$ is $dy(t)/dt=e^{-At}Bu(t)$ - now just integrate to find $y(t)$ (don't forget an arbitrary constant) and get back $x(t)$
Answer: Here's my derivation:
from
$\dot x(t) = Ax(t) + Bu(t) \tag{1}$
we write
$\dot x(t) - Ax(t) = Bu(t), \tag{2}$
and multiply through by $e^{-At}$:
$e^{-At}(\dot x(t) - Ax(t)) = e^{-At}Bu(t); \tag{3}$
the left-hand side may be written
$e^{-At}(\dot x(t) - Ax(t)) = e^{-At}\dot x(t) - e^{-At}Ax(t), \tag{4}$
and we note that
$\dfrac{d}{dt}(e^{-At}x(t)) =  e^{-At}\dot x(t) - Ae^{-At}x(t) = e^{-At}\dot x(t) - e^{-At}Ax(t); \tag{5}$
combining (3), (4), and (5) we find
$\dfrac{d}{dt}(e^{-At}x(t)) = e^{-At}Bu(t); \tag{6}$
we integrate (6) 'twixt $0$ and $t$, viz.
$e^{-At}x(t) - e^{-A(0)}x(0) = \displaystyle \int_0^t \dfrac{d}{ds}(e^{-As}x(s))ds = \displaystyle \int_0^t e^{-As}Bu(s)ds; \tag{7}$
we observe that
$e^{-A(0)}x(0) = e^0x(0) = Ix(0) = x(0) = p, \tag{8}$
which we bring over to the right-hand side:
$e^{-At}x(t) = p + \displaystyle \int_0^t e^{-As}Bu(s)ds; \tag{9}$
now a final multiplication by $e^{At}$ reveals
$x(t)  = e^{At}p + e^{At}\displaystyle \int_0^t e^{-As}Bu(s)ds; \tag{10}$
so at last,
$e^{At}\displaystyle \int_0^t e^{-As}Bu(s)ds = \displaystyle \int_0^t e^{At}e^{-As}Bu(s)ds = \displaystyle \int_0^t e^{A(t - s)}Bu(s)ds; \tag{11}$
and voila:
$x(t)  = e^{At}p + \displaystyle \int_0^t e^{A(t - s)}Bu(s)ds. \tag{12}$
Comment: Fiat Lux!   Well done as always. It tickles me that you're taking an integral *'twixt 0 and t*.
Comment: @Omnomnomnom:  Thank you my friend!
Comment: I understand each step but for what it means in English " 'twixt 0 and t " and "voila". Thank you a lot for that detailed answer.
Comment: "'twixt" is an archaic English word for "between", as in the idiomatic phrase "betwixt and between".
Comment: @user122424:  And "voila" is a word the English borrowed from the French; it means, roughly, "there it is!" or "look here!"


How can I retrieve the value of a configuration object from a template?

Question: I have a module that sets the value of a configuration object. I don't know how to retrieve that value from a template file.
In Drupal 7 I just needed variable_get() to get the value. What equivalent code should I use in Drupal 8?
Comment: This should help you => https://www.drupal.org/node/2658626#comment-10798284
Answer: The values saved as configuration items can be accessed using code similar to the following one.
$slogan = \Drupal::config('system.site')->get('slogan');

Since you are asking for a template file, that code should be split in two parts. My example is for the node.html.twig template file, but you can use the same kind of code for other template files too.

In the preprocess function of your template file (e.g. mytheme_preprocess_node(&$variables)) you get the value of the configuration item
$variables['slogan'] = \Drupal::config('system.site')->get('slogan');

In the template file (e.g. node.html.twig), you access that variable
{{ slogan }}

Be sure not to use a variable ($variables['slogan'], in my example) that is already used from the template file, or its preprocess functions.


How do I get an L2TP Foxpass VPN connection working in Windows 10?

Question: I have an office VPN that I need to connect to which uses L2TP/IPsec with a pre-shared key. At home (on my home network) I have two computers: a MacBook Pro, and a Windows 10 machine. I am able to successfully connect to the VPN on the Mac with no issue whatsoever. However the Windows 10 computer, on the same network with the same credentials, cannot connect. I consistently receive this message:

The connection was terminated by the remote computer before it could be completed.

The VPN server is running in Amazon EC2 using this VPN server from Foxpass. I have already taken two steps that I found in other Server Fault answers / guides online to try and remedy the problem. The first was to add a DWORD registry entry with the value of "2" at this path:
<code>HKLM\SYSTEM\CurrentControlSet\Services\PolicyAgent\AssumeUDPEncapsulationContextOnSendRule
</code>
And the second was to select the new VPN connection entry, right-click, Properties, Security Tab, and change the Data encryption dropdown to "Require encryption."
Neither of these worked. I am baffled why my Mac is able to connect from my network while my Windows machine is not. The Mac setup looks like this (there aren't any "special" settings - this is pretty much the default way of how you set up a VPN on Mac):

And the Windows setup looks like this - again this is really just entering in stock settings:

Clearly it is not a fault of the VPN server as I can successfully connect from the Mac. What do I need to do to get it working on Windows?
Comment: "What do I need to do to get it working on Windows?" - The only reasonable answer that can be given is that you need to match the settings on your VPN profile to that which is required by the VPN provider. We can't possibly answer what those settings are for you. At the very least you could provide screenshots of your existing settings.
Comment: I have added screenshots as requested.
Comment: Ok. I'm not opposed to using the modern windows 10 GUI, but it does leave a lot to be desired. You should find the VPN connection in the classic control panel under network connections. Right click it and check the properties. There are a lot more details there. There are a lot more settings to configure such as encryption, hash and lifetime settings. You should look under advanced on the MAC also to compare. More screenshots about that would help. But what you show so far looks ok.
Comment: Usually the problem with Windows and roadwarrior VPN clients is that you need to run them as Administrator as they modify the network settings and normal users are not allowed to do it. Also, you might be hitting some issues with the firewall if you have it enabled. Did you check those two settings?
Answer: Windows defaults the L2TP connection to use CHAP, but you need to go into the adapter settings and switch it to PAP. That, along with the AssumeUDPEncapsulationContextOnSendRule, should get this working.
Comment: That did it! The combination of the registry edit (plus a restart) and switching the protocol to "Unencrypted password (PAP)" under adapter options did it. Thank you!
Answer: Make sure if any certificate is required to be installed for that service to work in Windows. Windows is sensitive about matching certificates and all.
In addition, I suggest you try with less restrictive encryption modes, e.g. "Optional" and troubleshoot from there.


Is multicolinearity problem ignorable under this situation?

Question: When I run the logistic regression, two independent variables have VIF values greater than 10 like 13 or so. Logistic regression is the one I will use to measure the overall change in the dependent variable with one incremental changes in every each independent variable. However, when I run the linear regression model version on my same data, the VIF values I get from all the independent variables are either slightly greater than 1 or around 5 or 6.
Besides, all the coefficients are highly significant all below 0.01.
If so, is it safe to use my logistic regression model to find out the incremental effect of every each independent variable without dropping out any independent variables?
If my purpose is to find an incremental effect of every each independent variable on the overall dependent value in a logistic regression model, is multicolinearity an important problem to consider? Can I ignore it?
If my p-values are all less than 0.01 which is the same indicator as t-value, will I still need to worry about colinearity issue even though my VIF scores for two variables are around 13-14? Based on what you said, if p-value is safe enough, will this be still a problem?
I am also referring to the following website comment: http://www.researchconsultation.com/multicollinearity-multiple-regression.asp
So, in sum, my ultimate goal is to use the final output from the logistic regression model generated from the independent variables and one binary dependent variable. If so, do you think I can ignore the multicolinearity problem?
Answer: Collinearity is a problem only if the model needs to enforce an assumption of the independence of predictors. It's known that the model coefficients usually aren't affected by collinearity, whereas std errors and t-values are. This can and will bias the model selection process. Given your objectives, this may or may not be important. Examples of where IV independence can be important include pricing models where the analyst needs to know what the impact of price changes are clear and free of the influence of the other predictors in the model.
One of the biggest problem with the VIF is that there are no reliable guidelines as to when there is a real problem. In other words, beginning with Regression Diagnostics the 80s book by Belsey, Kuh and Wallace, different authors in different pubs propose differing cutoffs in the VIF to indicate collinearity.
There are more checks for collinearity than the VIF. For instance, are the signs of the parameters consistent with a pairwise correlation? If the sign is reversed, that suggests that the predictor is strongly related with at least one other IV in the model. Have you looked at the partial and semi-partial correlations among your model features? They, too, are useful diagnostic metrics insofar as they can identify where a problem might be. Another thing to look for is endogeneity, one check for which is non-zero association between the residual and each IV.
While all of these indicators and metrics diagnose and suggest a potential problem, none of them are confirmatory. To the best of my knowledge, no such confirmatory test for collinearity exists.
Comment: Where in my response did I say that "p-value is safe enough?" I did say that there is no cookbook recipe for deciding when there is a problem with collinearity
Comment: Thank you so much. If my p-values are all less than 0.01 which is the same indicator as t-value, will I still need to worry about colinearity issue even though my VIF scores for two variables are around 13-14? Based on what you said, if p-value is safe enough, will this be still a problem?
Comment: I am also referring to the following website comment: http://www.researchconsultation.com/multicollinearity-multiple-regression.asp                                                                                My main purpose is to use the dependent variable as one of my input. But I do this while keeping all other independent variables increase by one unit only the variable of my interest increases by 2 unit and I use the resulting dependent variable value for my input. So I have a mixed feeling about the comment on the website link above
Comment: Thanks but my question is if my purpose is to use the dependent variable as my input where I assign value 1 for all the independent variable except one independent variable which I assign value 2 to measure its impact where I only use the overall dependent variable for my input and if I do this for every each indepdendent variable, do I still need to worry about multicolinearity issue?
Comment: Sorry. I don't understand the question
Comment: So I am trying to use the dependent variable output for my own purpose. This output is produced by increasing all the independent variables by one unit while I increase two units only on the independent variable I am interested in. I repeat this for all the independent variables and produce several outputs from the dependent variable. If this is the purpose of my work, do I still need to worry about the multicolinearity?
Comment: It still doesn't make sense to me
Comment: My ultimate goal is to use the final output from the logistic regression model generated from the independent variables and one binary dependent variable. If so, do you think I can ignore the multicolinearity problem?
Comment: In my opinion this is not a yes or no answer. You're the only expert about your project, model and goals. Use your judgement
Comment: This is because I see several sources saying multicolinearity can be ignored when I am using the predicted value of y. One of the sources is follows. How do you think?http://www.stat.tamu.edu/~hart/652/collinear.pdf
Comment: Sorry I didn't mean it and it was my mistake to think you knew the answer.
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/41585/discussion-between-eric-and-djohnson).


Are compact subspaces of compact subspaces are compact subsubspaces?

Question: Similar question in Algebra: Subsubgroups are subgroups of subgroups / Multiplicative Property of the Index
There, we had that for $A \subseteq B \subseteq C$ and $C$ is a group:

If $A$ is a subgroup of $B$ and $B$ is a subgroup of $C$, then $A$ is a subgroup of $C$.
If $A$ is a subgroup of $C$ and $B$ is a subgroup of $C$, then $A$ is a subgroup of $B$.

Now, I want to know for $A \subseteq B \subseteq C$ where $A, B$ and $C$ are topological spaces, do we have any of the following?

If $A$ is a compact subspace of $B$ and $B$ is a compact subspace of $C$, then $A$ is a compact subspace of $C$.
If $A$ is a compact subspace of $C$ and $B$ is a compact subspace of $C$, then $A$ is a compact subspace of $B$.
If $A$ is a compact subspace of $B$ and $A$ is a compact subspace of $C$, then $B$ is a compact subspace of $C$.

Analogue for connectedness: Are connected subspaces of connected subspaces are connected subsubspaces?
Answer: 1 & 2 are true, and 3 is false.
I refer to Topology by James Munkres. Let $A, B$ and $C$ have respective topologies $\mathscr T_A, \mathscr T_B$ and $\mathscr T_C$, where $\mathscr T_A$ is the subspace topology of $A$ in $B$, and $\mathscr T_B$ is the subspace topology of $B$ in $C$. Note that by Exer 16.1 (*), $\mathscr T_A'$, the subspace topology of $A$ in $C$, is equal to $\mathscr T_A$.

Pf: Let $A$ be covered by sets open in C:

$$A \subseteq \bigcup_{D \in \mathscr D} D, \tag{1}$$
for some $\mathscr D \subseteq \mathscr T_C$. By Lemma 26.1 (*), $A$ is a compact subspace of $C$, if we can find find some finite subcollection of $\mathscr D' \subseteq \mathscr D$ that covers $A$ i.e.
$$A \subseteq \bigcup_{D \in \mathscr D'} D.$$
Observe that by taking intersection of both sides of $(1)$ with $B$, we get
$$A = A \cap B \subseteq [\bigcup_{D \in \mathscr D} D] \cap B = \bigcup_{D \in \mathscr D} [D \cap B],$$
where, for every $D \in \mathscr D$, $D \cap B$ is open in $B$, by definition of $\mathscr T_B$. Thus, $A$ is covered by sets open in $B$. Hence, since $A$ is a compact subspace of $B$, we have a finite subcover $\mathscr D'' \subseteq \mathscr D$ of $A$:
$$A \subseteq \bigcup_{D \in \mathscr D''} [D \cap B].$$
Observe that
$$\bigcup_{D \in \mathscr D''} [D \cap B] \subseteq \bigcup_{D \in \mathscr D''} D$$
Therefore, we can choose $\mathscr D' = \mathscr D''$. QED

Pf: Let $A$ be covered by sets open in B:

$$A \subseteq \bigcup_{D \in \mathscr D} D$$
for some $\mathscr D \subseteq \mathscr T_B$. By Lemma 26.1 (*), $A$ is a compact subspace of $B$, if we can find find some finite subcollection of $\mathscr D' \subseteq \mathscr D$ that covers $A$ i.e.
$$A \subseteq \bigcup_{D \in \mathscr D} D.$$
By definition of $\mathscr T_B$, every $D \in \mathscr D$ has a partner $E_D \in \mathscr T_C$ s.t. $D = B \cap E_D$. Thus, we can collect all the $E_D$'s in some $\mathscr E \subseteq \mathscr T_C$, namely $\mathscr E: = \{E_D | D = B \cap E_D \ \text{for some} \ D \in \mathscr D \}$ s.t.
$$\bigcup_{D \in \mathscr D} D = \bigcup_{E_D \in \mathscr E} [B \cap E_D].$$
Observe that $$A \subseteq \bigcup_{D \in \mathscr D} D = \bigcup_{E_D \in \mathscr E} [B \cap E_D] \subseteq \bigcup_{E_D \in \mathscr E} E_D.$$
Thus, $A$ is covered by sets open in $C$. Hence, since $A$ is a compact subspace of $C$, we have a finite subcover $\mathscr E' \subseteq \mathscr E$ of $A$:
$$A \subseteq \bigcup_{E_D \in \mathscr E'} E_D.$$
Observe that by taking intersection of both sides with $B$, we get
$$A = A \cap B \subseteq \bigcup_{E_D \in \mathscr E'} [B \cap E_D] = [\bigcup_{E_D \in \mathscr E'} E_D] \cap B.$$
Therefore, we can choose $\mathscr D'$ to be made up of the $D$'s in $\mathscr D$ that have a partner $E_D \in \mathscr E'$. QED

$$[0,1] \subseteq (-14,77) \subseteq \mathbb R$$

Note: That $B$ is a compact subspace of $C$ is not used. Therefore, we have for $A \subseteq B \subseteq C$:

If $A$ is a compact subspace of $B$, then $A$ is a compact subspace of $C$.
If $A$ is a compact subspace of $C$, then $A$ is a compact subspace of $B$.

(*)
Exer 16.1

Lemma 26.1


Limit Supremum of Sequence Created by Interleaving 2 Bounded Sequences

Question: I'm studying for an upcoming departmental exam, and this was one of the questions given on a previous year's exam.

Let $(a_{n})$ and $(b_{n})$ be real, bounded sequences, and let $(c_{n})$ be the sequence created by interleaving the terms of $(a_{n})$ and $(b_{n})$,
$$(c_{n}) = (a_{1}, b_{1}, a_{2}, b_{2},\cdots)$$
Prove that
$$\limsup(c_{n})\leq \max\{\limsup(a_{n}), \limsup(b_{n})\}.$$
Further, if both $(a_{n})$ and $(b_{n})$ both converge to $\gamma$, then $(c_{n})$ converges to $\gamma$ also.

The second part is pretty straightforward, no problems there. I've tried a couple of different things to solve the first part, mostly playing around with the various definition of $\limsup$ (supremum of subsequential limits, limit of the supremum of the $m$-tail, the "eventually less than $t$" definition, etc), as I am not sure one would work best here. What really confused me was at one point, I thought it should be the opposite, that the inequality should be reversed:

If you let $A, B,$ and $C$ be the set of subsequential limits of $(a_{n}), (b_{n})$, and $(c_{n})$, respectively $(b_{n})$, then clearly, both $A\subseteq C$ and $B\subseteq C$, as both $(a_{n})$ and $(b_{n})$ are already subsequences of $(c_{n})$. This would then imply that $\sup A\leq\sup C$ and $\sup B\leq\sup C$, and hence, that $\max\{\sup A, \sup B\}\leq\sup C$, which is the opposite of what we are to prove.

I'm probably completely wrong with this and missing something painfully obvious, but if anyone can come up with a proof of the original problem and tell me why my "proof" is wrong, I would greatly appreciate it. Bonus points if you can use the first part to imply the second part, which is what I would imagine the test wants.
Answer: You have not done anything wrong. You just proved the easy inequality but you are asked to prove that the reverse inequality is also true.
Consider any subsequence of $(c_n)$. Then it includes a subsequence of $(a_n)$ or  it includes a subsequence of $(b_n)$. Can you use this to finish the proof?
Comment: Thanks, think I got it. Let $C$ be the set of subsequential limits of $(c_{n})$, let $c\in C$, and $(c_{n_{k}})$ be a convergent subsequence of $(c_{n})$ which converges to $c$. Then, because $(c_{n_{k}})$ contains infinitely many terms of $(c_{n})$, $(c_{n_{k}})$ itself must have a subsequence which equals a subsequence of either $(a_{n})$ or $(b_{n})$, and hence, either $(a_{n})$ or $(b_{n})$ has a subsequence which converges to $c$. Hence, $C\subseteq A\cup B$. Therefore $\sup C \leq \sup A\cup B = max\{\sup A, \sup B\}$, and we have our desired inequality. Sound good?
Comment: @ChrisAustin Yes, the argument is right.


Help with SQL-query finding and updating uid's from non-existing users in comment table

Question: I need help to make a SELECT from the drupal database.
Two or three tables

comment
users
node (maybe)

I want to find all uid's in the comment table from former users but where the uid>0 in the comment table. uid's for former users but whom don't exist in the users table.
I also would like to make an UPDATE-script that can set all uid's from non-existing users in the comment table to zero "0".
This will solve some of the search indexing problem, where it stopps at certain nodes.
Please help me.
Answer: I think this should do it. Make sure you take a backup before running this:
<code>UPDATE {comments} SET uid = 0
WHERE uid > 0
AND cid IN
(
  SELECT cid FROM {comments} AS comment
  LEFT JOIN {users} AS user
  ON user.uid = comment.uid
  WHERE user.uid IS NULL
)
</code>


Custom Filter in cPanel to Auto-Delete Emails with Russian Characters

Question: I get a lot of spam to my email account from Russia. The emails themselves (name, subject, body) are in Russian and I was hoping to create a custom filter in cPanel (not in SpamAssassin but in cPanel itself) to catch these emails and delete them before they hit my inbox. I've tried setting up rules to flag emails with these characters but they still are getting through. This leads me to believe that there is an encoding issue at play here. Unfortunately I do not know how to overcome this. Ideas?
I already have Spamassassin configured to delete emails with a .ru TLD. These emails have other TLDs like .com, etc.
Answer: s/a has a setting for languages,  there is usually comments in the s/a folder - user prefs file, add this
ok_locales en          (only allow English)
see-
http://spamassassin.apache.org/full/3.1.x/doc/Mail_SpamAssassin_Conf.html
(user prefs)
will/dallas
Comment: Being on a shared server I don't think I can change this but it's good to know. Thanks.


How does android:taskaffinity work?

Question: How does android:taskaffinity attribute work?
As per my understanding, pressing the Home key will move the activity to back stack, but it will not be destroyed. I am confused.
Answer: You indeed set a diffrent android:taskAffinity for activity2 and for the other activities. This will force android to make a diffrent stack when (see my example).
 <activity android:name=".activity2" android:taskAffinity="com.example.act2" >
 </activity>

 <activity android:name=".activity1" android:taskAffinity="com.example.act1" >
 </activity>

The following sequence should be correct. for the

Start activity2.
press Home
Start activity1.
Press back -> the homescreen should be showed.

How does android:taskaffinity work?


How to set EditText custom cursor-drawable?

Question: I have the following EditText
<EditText
        android:layout_width="300dp"
        android:layout_height="80dp"
        android:inputType="textNoSuggestions"
        android:maxLines="1"
        android:layout_gravity="end"
        android:textCursorDrawable="@drawable/hammer_cursor"
        android:layout_margin="10dp"
        android:textIsSelectable="false"
        android:longClickable="false"
        android:textColor="#858383"
        android:background="@drawable/backer"
        android:textSize="14sp"
        android:id="@+id/name"
        android:padding="10dp"
        android:hint="message"
        android:textColorHint="#CDCDCD"
        tools:ignore="SmallSp"
        />

in a framelayout. I am trying to make the cursor a hammer but despite having the hammer-drawable available in hdpi,mdpi,xhdpi or even making the hammer-image from android:textCursorDrawable="@drawable/hammer_cursor"smaller the drawable fails to scale correctly to fit the cursor(even when it scales correctly with a smaller hammer-image, it's still blurry). Is there a standard dimension for the EditText-cursor-drawable in android(so I make the hammer-image accordingly) or how can the drawable be set correctly to fit the cursor without any stretching or blurriness of the hammer-image.
Answer: Remove android:hint="Message" this line from your code.
Use vector image instead of any-other image type.
Make new file in your drawable forlder named hammer_cursor.xml and put this code inside this file.
Here is some example of hammer image:
<vector
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:name="vector"
    android:width="31dp"
    android:height="31dp"
    android:viewportWidth="512"
    android:viewportHeight="512">
<path
        android:name="path"
        android:pathData="M 486.391 195.313 C 480.527 189.449 471.039 189.449 465.176 195.313 L 454.57 205.918 L 433.355 184.703 L 369.719 248.344 L 390.93 269.559 L 380.324 280.164 C 374.461 286.027 374.461 295.516 380.324 301.379 L 401.539 322.59 C 407.398 328.453 416.891 328.453 422.754 322.59 L 507.605 237.738 C 513.465 231.875 513.465 222.387 507.605 216.523 Z M 486.391 195.313 M 337.898 237.738 L 422.75 152.883 C 428.613 147.023 428.613 137.535 422.75 131.672 L 337.898 46.82 C 307.703 16.625 267.566 0 224.871 0 L 157.586 0 C 150.977 0 145.145 4.32 143.23 10.648 C 141.313 16.977 143.715 23.938 149.27 27.48 L 226.633 79.055 C 235.137 84.805 240.668 93.918 241.68 104.129 C 242.695 114.363 239.102 124.402 231.832 131.672 C 225.969 137.535 225.969 147.023 231.832 152.887 L 316.684 237.738 C 322.547 243.602 332.035 243.602 337.898 237.738 Z M 337.898 237.738 M 242.438 354.41 C 248.301 348.547 248.301 339.059 242.438 333.199 L 178.797 269.559 C 172.938 263.695 163.449 263.695 157.586 269.559 L 125.766 301.379 L 210.617 386.23 Z M 242.438 354.41 M 17.551 409.445 C -5.852 432.844 -5.852 470.898 17.551 494.297 C 40.949 517.695 79.004 517.695 102.402 494.297 L 189.406 407.445 L 104.551 322.59 Z M 17.551 409.445 M 200.008 248.344 L 242.434 205.918 L 306.074 269.559 L 263.648 311.984 Z M 200.008 248.344"
        android:fillColor="#000"
        android:strokeWidth="1"/>


Linear transformation onto and one to one?

Question: (1)If a linear transformation $T:\mathbb{R}^n\rightarrow\mathbb{R^m}$ maps $\mathbb{R}^n$ onto
$\mathbb{R^m}$ what is the relation between m and n?
(2)If T is one to one what is the relationship between m and n.
For the first question I think $m>n$ because if you try to do for example $R^3 \rightarrow R^4$
you have a matrix $A=4x3$, 4 rows and three columns and this cannot span $R^4$. As you cannot have 4 pivot.
For the second I think $n<m$ because if $R^4 \rightarrow R^3$ because if you have a A=3x4 matrix then one will always be linear independnet.
But I am not sure if my justfication is correct.
Answer: If $T: \mathbb{R}^n \to \mathbb{R}^m$ is onto then $m\leq n$.
If $T: \mathbb{R}^n \to \mathbb{R}^m$ is one-to-one then $m\geq n$.
Note in particular that it is possible to have $m$ and $n$ equal.
To prove this, you can make use of the fact (you might know this, might now) that the dimension of the image of a linear map is always less than or equal to the dimension of the domain. (To prove this fact, try to start with a basis and see what happens.)
Answer: You can represent $T$ as an $m \times n$ matrix. The columns of $T$ span the range.
You can recast your questions as follows:
Under what conditions can $n$ vectors span $\mathbb R^m$? Under what conditions can $n$ vectors be linearly independent in $\mathbb R^m$?
Answer: (1) There's no relation, other than just n and m should be finite.
And for Question 1, m doesnt have to be > n since the A you choose can be 3x4 too. So youll have v(1x3) * A(3x4) = w(1x4) v and w belong to R^n and R^m respectively.
(2) If one-one, the rank of the transformation must be = n and yes therefore, n < m.
Any transform will have an image in R^m. ie the transform T has a 'range' in R^m, which is a subspace of R^m. A subspace will always have dimension less than the parent space ie rank of T (dimension of the range) must be < m.
Secondly, for it to be one-one, the 'nullity' of R^n must be zero. And by rank nullity theorem, n = rank of T + nullity of T, in this case, n = rank of T which is < m. So, n < m. Dont confuse with linear independance. n and m are determined by linear independance, because they're the dimensions for the spaces, so that's taken care of.
Comment: (1): sure? *onto* means surjective here...


How do I forcefully uninstall any module having content?

Question: I want to uninstall the Field module, but this module can not be uninstalled; when I try, I get the following message.

Field API to add fields to entities like nodes and users. Machine
  name: field Version: 8.0.6 Required by: TextNodeAdmin ToolbarAdmin
  Toolbar Extra ToolsFileOptionsAggregator (disabled) ImageAccelerated
  Mobile Pages (AMP) (disabled)Custom BlockBook (disabled)Text
  EditorCKEditorCommentInterface TranslationConfiguration Translation
  (disabled)

How do I forcefully uninstall any module that is having dependency or content inside, for example the Node module, the Views module, or any entity having content in it?
I tried using <code>\Drupal::service('module_installer')->uninstall(['admin_toolbar']);</code> but then my site breaks.
Comment: Is there a reason why you want to uninstall this crucial module?
Comment: @SugandhKhanna Yes, that's what you would expect to happen. No, you can't remove a module on which existing parts of the system depends. The only way to remove a part of the system on which a second part of the system depends, is to remove that second part first. It's what dependencies _are_. If you could just remove the field system when there are existing fields, or remove the module that provides content without removing the content, then they wouldn't be dependencies any more. They'd be optional. And in the context of fields/nodes/etc, that wouldn't make sense
Comment: I'm just experimenting things as how one can remove all traces of any installed module by some piece of code.
Comment: Doing it with the UI with a minimal installation, I ran into a [dead end](http://i.stack.imgur.com/gDCNV.jpg). I can't uninstall Text, which in turn it won't allow me to uninstall Field. Also, as you can tell, it appears Field is the super module/heart of Drupal Core.
Comment: Its not about jss one module - Fields, this is a generic question, I can't figure out as how to uninstall any module which is built with entity concept and entity having content. For example, I made any custom content entity type and add content into it. Now I can not uninstall my custom module until and unless I delete all content or truncate module specific db table. Hope you get my point.
Comment: @Clive I'm going through this link right now, https://www.drupal.org/node/2409673, not sure about this, but I think a little possibility exists.
Comment: @clive can you help me figure out what's wrong with this function `function uninstall(array $module_list, $uninstall_dependents = TRUE) {` [public function ModuleInstaller::uninstall][1]

  [1]: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Extension%21ModuleInstaller.php/function/ModuleInstaller%3A%3Auninstall/8.2.x      It is not uninstalling modules with dependency.
Answer:
For example, I made any custom content entity type and add content
  into it. Now I can not uninstall my custom module until and unless I
  delete all content or truncate module specific db table – Sugandh Khanna.

Unfortunately, in Drupal 8 you can't disable a module, like you can in Drupal 7.
In Drupal 7 you need to disable the module first, which means all module related code stays in DB. Then, if you wanted, you Uninstall to remove everything from DB.
In Drupal 8 the only option is to uninstall the module, which means you have to destroy all traces of your module from the Database. You cannot just disable the module anymore.
Also, to uninstall Flag (as in your comment here), you have to uninstall dependencies first, then and only then, it will allow you to uninstall Flag. Because if module X depends on Flag and somehow you removed flag, it will totally screw up module X, X becomes useless, module X is nothing without Flag. Therefore you need to remove module X first, then and only then it will allow you to remove Flag.
For more info: Why can't I uninstall modules in Drupal 8? (Explained)
Issue: Disabled modules are broken beyond repair so the "disable" functionality needs to be removed
Comment: @SugandhKhanna you have to uninstall dependencies first, then and only then, it will allow you to uninstall Flag. Because if module X depends on Flag and somehow you removed flag, it will totally screw up module X, X becomes useless, module X is nothing without Flag. Therefore you need to remove module X first, then and only then it will allow you to remove Flag.
Comment: Thanks @No Sssweat. So the final conclusion is we can not uninstall dependencies. Or It is just impossible to uninstall Flag


Locale: Browser or OS Setting?

Question: What does it mean when a "locale" is set to e.g. Japanese? Does it mean the browser is set to be ready to recognize Japanese characters? Or, is it more related to an OS setting?
Related to i18n (internationalization and localization), how do we detect that a user who is visiting our site has a e.g. Japanese locale using JavaScript? Will the following simple check suffice?
var userLocale = navigator.language || navigator.userLanguage;
if (userLocale.toLowerCase() == 'ja-jp') { ... }

Can a Japanese locale browser return something else rather than ja-jp?
Thanks beforehand.
Comment: BTW. if Siku-Siku.com is the name of your domain, I would advise you to pick a different one if you ever want to do business in Poland. It sounds just too funny in Polish.
Comment: Thanks, Pawel! What means well in one language can be really funny on another; glad that it isn't something mean or impolite. :)
Answer: First we need to define what Locale is. In the context you are using it is a ISO639 Language Identifier optionally followed by ISO3166 Country Identifier. This is used to determine end user's preferences (like language of localized content or date and time formats and number formats).
Now, Locale could be set in multiple places. OS usually has multiple settings, for example keyboard layout, formatting preferences, language preferences, code pages (for non-Unicode programs), etc.
Apart from that, web browsers usually allow you to choose your own preferences (Safari is an exception here). These preferences are send along with each request to the web server, via HTTP Accept-Language header. This is something you should somehow read on the server side (which unfortunately means some server-side code in PHP, C#, Java, whatever) and maybe passed to your client-side script.
I must state here that something like navigator.language is not the way to go for two reasons:

This is not cross-browser compatible, that is other web browsers would require different code. That is if they allow reading this information in the first place.
This setting usually refers to web browser's language (the language web browser's user interface is translated to) and has nothing to do with actual user's preference.

So to answer your question: no, this check will not suffice.
Comment: Is the HTTP Accept-Language cross-browser compatible?
Comment: Accept-Language is one of Hyper-Text Transfer Protocol (HTTP) headers, therefore it must be cross-browser compatible.
Answer: That is mostly an OS/browser setting, controlling e.g. language of the OS, date/time format, decimal point/comma, etc. - in other words, settings that vary in different locales of the world. This has no direct correlation with font/character support.
As far as I know, ja-jp is the only standardized Japanese locale/language combination; but as @Siku-siku.com suggested in the comments "(based on real testings using Japanese version of IE/WinXP) also check for ja because that's one of the available options in the IE language setting."
Comment: So, to detect a locale, is it advisable to check against the language preference set in the browser (e.g. `Tools > Internet Options > General > Languages`) or the OS setting (e.g. `Start > Control Panel > Regional and Language Options > Regional Options`)?
Comment: You don't have access to either of these from in-browser JavaScript, so your best bet is the code you posted.
Comment: The above snippet actually pulls in the value set using the latter method (Control Panel), as also discussed here: http://stackoverflow.com/questions/1043339/javascript-for-detecting-browser-language-preference
Comment: As discussed in the question you're linking to, it is rather browser-dependent (and irrelevant) whence this data arrives.
Comment: One suggestion (based on real testings using Japanese version of IE/WinXP) is to also check for `ja` because that's one of the available options in the IE language setting.

Locale: Browser or OS Setting?


Find all $x,y,z$ satisfying $xy=z-x-y$ and cyclic permutations

Question: Find all ordered pairs $(x,y,z)$ real numbers, which satisfy the following system of equations:
$$xy=z-x-y\\xz=y-x-z\\yz=x-y-z$$
Comment: What brought you to tagging this with [[tag:logic]]?
Comment: I think there is no solution when x,y,z are distinct
Answer: Hint:
$$xy=z-x-y \quad \iff \quad (x+1)(y+1)=z+1.$$

 Hence $(x+1)(y+1)=z+1$, $(x+1)(z+1)=y+1$, $(z+1)(y+1)=x+1$.
Comment: what to do next?
Comment: @lokeshsangabattula, then multiply the equations and solve.
Answer: Another hint: Subtracting the third equation from the second reveals a constant value for z as long as x ≠ y (Thank you Calvin).

  $z(x-y)=-2(x-y)$
Comment: Of course, we can only conclude that it's constant if $x\neq y$.
Comment: Mark, +1 for the hint. But you don't need to delete your answer and write a new one. Just click "edit" under your post.
Comment: I know. I screwed up somehow, and had 2 answers. So I killed the other one.
Answer: The groebner basis in lex order is (try sympy)
$$x - z^4 - z^3 + 3z^2 + 2z=0$$
$$y + z^4 + 2z^3 - z^2 - 3z=0$$
$$z^5 + 3z^4 - 6z^2 - 4z=0$$
Note that now the first equation only contains $x,z$, the second only $y,z$ and the third only $z$.
If you factor out one $z$ from the third equation you have a degree four polynomial that is solvable in formulas (or you carry on guessing and factoring for that polynomial).


Problems with haproxy reqrep

Question: Scenario
I've got a haproxy farm of 3 (apache) webservers. 2 are actively balanced, and the third is a backup normally.
Every so often, I want to take the third server out of the backup role and make it a 'patch' server. But I want to do this without changing the url (eg, I don't want to use patch.mysite.com)
What I want to happen is, I visit http://mysite.com/patch and have haproxy give the server a cookie for later use in an ACL, but remove the /patch and send a GET / to the backend server.
Where I'm at now is the ACL is working fine, but the reqrep is not removing the /patch request before sending it to the backend.
Config:
global
    log 127.0.0.1   local0 info

    maxconn 25000
    daemon
    spread-checks 2

defaults
    log     global
    mode    http
    balance roundrobin

    option  httplog
    option redispatch
    option abortonclose
    option forwardfor
    option http-server-close

frontend webfarm :80
  # FILTERING
  acl acl_patch path_end /patches

  use_backend patch if acl_patch
  default_backend default_farm

backend default_farm
  cookie SERVERID insert indirect
  server prod1 192.168.100.18:80 cookie live01 check
  server prod2 192.168.100.22:80 cookie live02 check weight 2
  server prod3 192.168.100.20:80 cookie live03 check backup

  # do not let this cookie tell our internal IP address
  rspidel ^Set-cookie:\ IP=

backend patch
  cookie SERVERID insert indirect
  server prod3 192.168.100.20:80 cookie live03
  reqrep ^([^\ ]*)\ /patch     \1\ /

  # do not let this cookie tell our internal IP address
  rspidel ^Set-cookie:\ IP=

The haproxy log still specifies a GET /patch being sent to the backend. What am I missing about reqrep (I don't care about anything after the /patch directory)?
Answer: First, your rule should also keep the HTTP version part.
Second, why don't you use the "force-persist" statement for this ? It's designed exactly for this role. Just find something in your request that makes it different from your visitors', set a cookie to access it, then you can use this server. This me chanism was made precisely for maintenance operations without having to make the server appear as up for other users.
Alternatively in your case you could also use the "redirect" method, as it supports the "set-cookie" option; In your frontend, you would then replace the use_backend rule with
something like this :
redirect location / code 302 set-cookie SERVERID=live03 if acl_patch

Your browser would then learn this cookie and redirect to the /, where server 3 will handle the request. There's even a clear-cookie option that can be used to get rid of the stickiness if you want.

Problems with haproxy reqrep


Include the included html file in doxygen in the generated latex pdf

Question: Alright, the question seems a bit convoluted. But here's what I am doing. I generate doxygen documentation from my commented code and then generate latex pdfs out of by configuring doxygen to do so.
I have one small problem, when I include an html file using \htmlinclude, that link or file does not get included in the latex generated pdf.
How can I achieve this? i.e. Include the included html in doxygen in latex?
Answer: \htmlinclude definitely won't do this.  From the manual: "The command is equivalent to pasting the file in the documentation and placing \htmlonly and \endhtmlonly commands around it." - so any included with \htmlinclude will only appear in HTML output, not LaTeX.
If you want to insert verbatim HTML (i.e. you're quoting that file of HTML as an example, rather than wanting the HTML to be interpreted by Doxygen) then you could try\verbinclude instead.
Otherwise, I think you need to give a bit more detail about what it is you are trying to achieve.
Comment: \verbinclude doesn't do it for me. To be more precise, it's just an html table that i want to get included in latex through doxygen automatically.
Comment: @RichardMacwan Does the process work correctly if you copy the table into the file where you are currently using \htmlinclude?  Is doing that a substantial problem?  I appreciate it's undesirable from a modularity perspective but I think you're short of options.
Comment: It's just an autogenerated html file(with a table in it) which I wanted to use in my documentation. Manually copying the table creates some problems since it was autogenerated  and I would need to manually edit it which is the same as writing down the table manually in doxygen comments. So I guess I really am short of options :P
Comment: @RichardMacwan Can it be autogenerated as doxygen or markdown text instead of html?  In the doxygen case it won't be much different except perhaps to have a `@anchor` that your could `@ref` from the main text.  Alternatively, can you parse the autogenerated HTML to create a doxygen text file before running doxygen?  Hmm, this is all getting a bit tangled.
Comment: yes it is getting a bit tangled :) But it's not a huge requirement so I'd just put html text directly in doxgen next time. Thanks for the help.


How can I modify from C# the value of an element which is define in a XAML DataTemplate?

Question: I created a "WPF Application Project" in Visual Studio 2013.
I opened the "MainWindow.xaml" file and I wrote the following XAML code:
<Window x:Class="TestProject.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">

<Window.Resources>
    <DataTemplate x:Key="AlphaDataTemplate">

    </DataTemplate>
</Window.Resources>

<Grid>
    <ContentPresenter
        Name="MyContentPresenter"
        ContentTemplate="{StaticResource AlphaDataTemplate}" />
    <Button
        Name="MyButton"
        Click="MyButton_OnClick"
        Content="Change the content of the Label in the DataTemplate"
        Width="320"
        Height="30" />
</Grid>

In this XAML file I created a "DataTemplate" which corresponds to the key "AlphaDataTemplate". The DataTmplate contains just one label with the name "LabelInDataTemplate" where I have hardcoded the "Good morning!" string in the "Content" attribute of the label.
Then I use created a "ContentPresenter" with the name "MyContentPresenter" and I pass as content the "DataTemplate" I previously created (AlphaDataTemplate).
As next step, I created a "Button" with the name "MyButton" and I have set a "Click" event called "MyButton_OnClick"
So far so good...!
The question comes now and actually in C# in the code behind file "MainWindow.xaml.cs". See the code below:
using System.Windows;

namespace TestProject
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
    }
    private void MyButton_OnClick(object sender, RoutedEventArgs e)
    {
        LabelInDataTemplate.Content = "Bye!";   // <-- Tha does not work.
    }
}

}
In this C# code behind file you can see the definition of the "Click" (MyButton_OnClick) event of the Button (MyButton) which appears in XAML.
What I am trying to do in this "Click" event, is to change the value of the "Content" of the "Label" (LabelInDataTemplate) which is in the DataTemplate (AlphaDataTemplate).
Unfortunately, that does not work.
I cannot actually access the "Name" (LabelInDataTemplate) of the "Label", because it is contained in the "DataTemplate" (AlphaDataTemplate)
If anyone has any idea, how could I modify from C# the value of an element which is define in a XAML DataTemplate, please give me feedback. I would really appreciate it.
Thank you in advance.
Answer: Please learn MVVM and use proper DataBinding for this purpose. For sake of solving this problem:

Implement INotifyPropertyChanged interface on your Window class and Define string property like below
public partial class MainWindow : Window, INotifyPropertyChanged
{
    public MainWindow()
    {
        InitializeComponent();

        DataContext = this;

    }

    public string _contentMsg;
    public string ContentMsg
    {
        get { return _contentMsg; }
        set
        {
            _contentMsg = value;
            RaisePropertyChanged("ContentMsg");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    private void RaisePropertyChanged(string propName)
    {
        if(PropertyChanged !=null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propName));
        }
    }

In your xaml bind the ContentPresenter and update your DataTemplate label like
<ContentPresenter
Name="MyContentPresenter"
Content = "{Binding ContentMsg}"
ContentTemplate="{StaticResource AlphaDataTemplate}" />

<DataTemplate x:Key="AlphaDataTemplate">

Now in click handler (I would use Commands here), set ContentMsg to whatever you want
 private void MyButton_OnClick(object sender, RoutedEventArgs e)
 {
      ContentMsg = "Bye!";
 }

Comment: Thank you very much for your feedback. Your solution is aligned with the best practices for developing, but I guess I have to use both your solution and the aforemention solution from Arun Selve Kumar. That is because in the code that I am developing I need to change the "Visibility" attribute of a "Rectangle" from "Visiblility.Hidden" to "Visibility.Visible" and vice versa.
Comment: That is perfectly fine.. but you can also toggle visibility in MVVM way by using Converters..
Answer: I strongly oppose your method of changing the content of label via DataTemplate, However your requirement is possible, but very subtle.
Code
private void MyButton_OnClick(object sender, RoutedEventArgs e)
{
    var alphaDataTemplate = this.Resources["AlphaDataTemplate"] as DataTemplate;
    var label = alphaDataTemplate.FindName("LabelInDataTemplate", MyContentPresenter) as Label;
    label.Content = "It Works";
}

Comment: The solution you posted works perfectly! Thank you very much!  :)


How to enable javascript after page loading to change input attribute to disabled depends on other input value that load from database?

Question: I want to write a Javascript code that can disabled my text input after I checked the checkbox. However I also want to run the Javascript code after the page load.
I have tried some Javascript and succeed. The text input will be disabled if I check the textbox. But, I will read from my database whether to check or uncheck the checkbox, the problem here is If the checkbox is checked because of the database. The text input will not be disabled according to the javascript.

<code><script type="text/javascript">

    $('#checker').on('load', function(){
    if($(this).is(':checked')){

        $('#yourText').prop('disabled', true);

    }else{

        $('#yourText').prop('disabled', false);

    }
});
</script>
</code>
I expect if the checkbox is checked like default or from database, the text input will be disabled.
Comment: Just make sure everything is occurring in the correct sequence.  Is the value from db populated via ajax call or server-side in page render?  The answer to this question will determine your strategy.
Answer: Try this:
<code>$(document).ready(function () {

    if(document.getElementById('checker').checked == true)
    {
        document.getElementById('yourText').disabled = true;
    }
    else
    {
        document.getElementById('yourText').disabled = false;
    }
});
</code>
or you can write it in php
<code>    <?php
        if([databaseField] == "YES")
        {
            $checker = "disabled";
        }
        else
        {
            $checker = "";
        }
    ?>

    <input type="text" name="yourText" id="yourText" $checker>
</code>


Most Compatible Inter-Process Communication protocol

Question: I am working on an media application for which I would like to provide an external API library that would allow another application to communicate with mine an query status information. My application is written in C# and the API DLL will be the same.  Initially my thought was to simply use WCF and Named Pipes since it would provide an extremely easy way to code up the whole interface.
However, I realized that doing this would pretty much preclude any other languages or platforms from communicating with the application if I ever wanted to make, for example, an android or Web remote for it.
So, what protocol could I use that would allow a fast and simple interface from within my C# code, but also allow APIs to be written in other platforms.
Basic requirements are:

Local and Remote communication
Low overhead
Procedure Calls
File transfer (to send media)
Pre-Existing C#, open source library would be nice.

I've looked at a lot of the options, used XML-RPC and JSON-RPC before, but would like to know what the community thinks is the best option.
Answer: I think using WCF it's the best way to do what you want. It will be simple in maintenance, cover all your requirements and easy to extend. Just don't restrict the access to your API only by net.pipe. I think you should use net.pipe, net.tcp and maybe basic http as primary bindings. I mean several endpoints for each service. So, a client app, no matter what language it is written, will be able to choose what binding to use to access your API server.
For example:

C# client app on the same machine - use net.pipe
PHP client app in web - use basic http
Java client app on another machine - use net.tcp

As an example:
http://www.kevingao.net/wcf-java-interop/java-client-and-wcf-server.html


How can we evaluate the predicted values in regression model

Question: I am using regression model to predict values I have. How can evaluate the accuracy of prediction model (I'd like to see how the accuracy of predicted values).
I found different metrics, but it's only used with discrete data.

Classification report
Accuracy score
Confusion matrix

Now, I can generate the summary using .summary() function. As an example here , it's nearly the same in R/Python;
I'd like to evaluate the performance, how good and accurate the predicted values that I got using GLM (with Binomial families ).
Answer: You could use pseudo R-squared measures, such as Nagelkerke, for an overview see:
http://www.ats.ucla.edu/stat/mult_pkg/faq/general/Psuedo_RSquareds.htm
Comment: That seems right, except that a % interpretation is more difficult in the pseudo-R-squared case. It's okay in the linear case, where the ratio is explained against total variance.
Comment: Correct me if I am wrong. If I understand it very well. R-squared is always between 0 and 100%: - 0% indicates that the model is extremely bad.
- 100% indicates that the model explains all the variability of the response data around its mean ==> extremely good.


Image recognition to read 7segment Display

Question: I am implementing SURF to detect Digits inside a seven segment display using some template. But it is not working fine. Is there any way that can be slow but more effective. I am using Emgu Wrapper for OpenCV
Answer: I would suggest you don't use SURF and instead look into using tesserect for character recognition.
SURF is really good for recognising patterns such as logo's and images, but  for characters tesserect will not only produce better results, it's easier to implement!
You can create your own custom fonts to look for if the digits you are trying to read are non-standard.
https://www.youtube.com/watch?v=RqvvXJXuRYY&list=UUxAnMtjN08ryThpgYTBmILg
Try following this tutorial, its really helpful for getting started with OCR.
It's in VB but it won't be hard to write in C# once you have got the logic down.
Hope this helps!
Comment: sorry if this is abit late, there are several ways you can remove noise, look into either using a mixture of dilate/erosion to clean up small bits of noise.

You can also use the canny edge detector, there will be two values you pass into the detector when you use it, look up what these values do, and with a bit of playing around you should be able to find a setting that will pick out your characters but ignore smaller edges
Comment: Tesserect worked fine for cleaner Image, But if I have "Dots" in images or some other small noise, Tesserect reads an extra character. Can you suggest a way to remove noise outside the character area??


Why is my Perl loop off by one at the end?

Question: I have this program which does not work as expected. Help me.
I want to print a row heading.
If input is 4, I want 1|2|3|4 to be output.
It does not work as all, if I hard-code $count value it works partially but the last number is missing.
sub printC {
        my $count = @_;
        # count = 4  # works partially only prints 1|2|3
        for(my $i=1;$i<$count;$i++) {
                print "$i|";
        }
        print $i;
}
$count  = 2;
&printC($count);
print "\n";

Answer: The problem is here:
my $count = @_;

The assignment is happening in a scalar context which assigns the number of elements in array @_ to $count, which your case is 1, as you are passing 1 argument to the function.
To fix this you can do:
my ($count) = @_;

or
my $count = $_[0];

here is another problem:
for(my $i=1.....
    ^^

By using my you've made $i local to the body of for and it'll not be available outside it. So your final print outside the for is not printing anything. To fix this move the declaration of $i outside the loop:
sub printC {
        my ($count) = @_;
        my $i;
        ....

Always make it a point to write
use strict;

at the top of your program which enables you to catch such bugs.
The perl way of doing what your function does is:
print join('|',1..$count);

Answer: A real Perl hacker might write something like this:
sub printC {
  my $count = shift;
  print join "|", (1 .. $count);
}

Once you understand how this works, you'll find you've learned some more about Perl. :-)
Answer: $i does not exist once you've left the for loop because of where it's declared.
You could do
sub printC {
    my ($count) = @_;
    my $i;
    for ($i = 1; $i < $count; $i++) {
        print "$i|";
    }
    print $i;
}

Even simpler:
sub printC {
    my ($count) = @_;
    print join("|", 1 .. $count) . "\n";
}

Answer: One other bit of "being more Perlish" is to not use the C-style for loop.  There is almost never a need to use a C-style for in Perl.
Instead of
for(my $i=1;$i<$count;$i++) { ... }

use
for my $i (1 .. $count) { ... }

They're almost equivalent, except the latter version is both more easily readable and more resistant to off-by-one errors.  (The reason your code was only printing 1|2|3 instead of 1|2|3|4 is because the test in your C-style for was checking $i<$count when it should have been $i<=$count - this is a very common mistake with C-style for loops which for (list) avoids completely.)
Also, don't prefix your sub calls with &.  It's a holdover from Perl 4 which is no longer needed in Perl 5 and has side effects which you probably aren't aware of and probably don't want.  Just use printC($count) instead of &printC($count).
But, yeah, in this particular case, join is probably a better approach than for anyhow.


SQL Server Log File Size Management

Question: I have all my databases in full recovery and have the log backups happening every 15 minutes so my log files are usually pretty small.  question is if there is a nightly operation that causes lots of transactions to happen and causes my log files to grow, should i shrink them back down afterward?
Does having a  gigantic log file negatively affect the database performance?  Disk space isn't an issue at this time.
edit: Using SQL 2005 will be using 2k8 soon.  (I thought i put it in... d'oh)
Answer: There shouldn't be a performance hit having a large log file. You actually would be taking a performance hit needing to regrow the log file each night when the long running operation happens.
If disk space is not an issue and logs are not completely out of control I would leave them be, but as always keep an eye on them.
Comment: @boezo - I'd say there's some evidence to the contrary: http://sqlblog.com/blogs/linchi_shea/archive/2009/02/09/performance-impact-a-large-number-of-virtual-log-files-part-i.aspx

But I'd still avoid auto-growing log files. It's a trade off between maximum performance now, or better performance in the future.
Comment: That is a good article that points to management aspect of the log files and not letting them autogrow. The comment in the post is that if you know you need 10gb just grow it all at once to 10gb. It does not say that having a large log file is bad it says that having a large log file that grew in little chunks at a time is bad.
Answer: Are you running any maintenance overnight, such as a reindex?
Here's a link that may help in deciding whether to shrink:
Also, may I suggest that you update the question with the version of sql that you are using.
Comment: I read that blog entry.  They didn't really address the issue of whether or not a big log file is necessarily bad.  I know that shrinking is a very expensive operation and this would be done during "downtime"  or at least slow time..
Comment: @Rob - I believe there is a slight performance hit for having a large log file (or rather a lot of VLFs), but if you need the extra log space in the future, it is better to pre-grow it rather than let it grow automatically. Ref: http://blogs.msdn.com/grahamk/archive/2008/05/16/slow-recovery-times-and-slow-performance-due-to-large-numbers-of-virtual-log-files.aspx
Comment: It is very different to say large log file VS a lot of VLFs. A well managed log file can grow quite large and perform quite well while a poorly managed large log file can potentially kill performance.
Answer: If there's an operation every night that's growing it then definitely don't shrink it. They obviously need to be that size and will just grow again.

SQL Server Log File Size Management


db_query or db_select for getting content type fields

Question: Originally I was doing something along the lines of $query = "SELECT {}" and then $result = db_query($query). This method works fine for most of my queries until I needed to get the field values and fid from a specific content type. And then be able to call these values when printing inside HTML. Can anyone provide an example of how I would do this?
I had something along the lines of:
<?php
$query = "SELECT node.nid AS nid, 'node' AS field_data_field_news_node_entity_type, 'node' AS field_data_field_news_date_text_node_entity_type, 'node' AS field_data_field_news_teaser_node_entity_type, 'node' AS field_data_field_news_body_node_entity_type, 'node' AS field_data_field_news_video_node_entity_type, 'node' AS field_data_field_news_video_image_node_entity_type, 'node' AS field_data_field_mypdf_node_entity_type
    FROM node
    INNER JOIN field_data_field_news_is_featured ON node.nid = field_data_field_news_is_featured.entity_id AND (field_data_field_news_is_featured.entity_type = 'node' AND field_data_field_news_is_featured.deleted = '0')";
?>

$result = db_query($query);

<?php foreach ($result as $row) : ?>

        <?php print $row->field_mypdf_value; ?>
        <?php print $row->field_mypdf_fid; ?>

<?php endforeach; ?>

Answer: If you have your node object, you can use field_get_items to get the field values from the node.
$items = field_get_items( 'node', $node, 'field_name' );
// now $items is an array of values... you can manipulate...
// then use the field_view_value to build the render array
$specific_item = $items[0];
$item_build = field_view_value( 'node', $node, 'field_name', $specific_item );

Here's a link to the field_view_value API doc.
Use the devel module and sprinkle in some dpm()'s to understand the underlying data. It's pretty neat! :)
Answer: $result = db_query('SELECT field_1, field_2 FROM table_name WHERE bundle = :bundle AND entity_type = :entity_type', array(':bundle' => 'page', ':entity_type' => 'node' )->fetchAll();

Will give you an indexed array of objects with the queried values:
$results will look like this
    array(
      [0] => [standardclass object](
        [field_1] => Value for field_1
        [field_2] => Value for field_2
      )
      // .. One entry for each result ...
      [n] => [standardclass object](
        [field_1] => Value for field_1
        [field_2] => Value for field_2
      )
   )

However querying the database directly is quite a strange thing to do so this might not at all be the best practice way for what you are are trying to achieve. Be sure to look into the field API as mentioned by Purdy.
Read more about the query object and resultsets(There is a lot to say about this but this is a good start).


How to manage reservations with a 2 hours duration without duplicate bookings?

Question: I want to make a calendar view that will show when music teachers are available, so that students can register online and attend a lesson. The courses have all the same duration which is 2 hours. For this, I created a content type called "Lessons" (Fields: title, description, teacher name, teacher email, date/time) and a content type using node reference module for registrations to each specific lesson. In that way students can register online for music lessons.
There are 2 problems with this:

How can I have a fixed 2 hour duration in the day of the calendar view that won't let students register for more or less time than the two hours? I can not just hide the time fileds because the system must show them the time that the lesson takes place?
I want to allow just one user register for each lesson and then the system must show that lesson as booked. To be more specific, I want the calendar to show the whole day seperated in 2-hour periods and which periods are free. When a user registers for a lesson, the lesson changes color (I can do this with css) and is marked as reserved so that the "next" user can only register for another of the open lessons and so on.

Any ideas?
Comment: As for #2, you could use the Flag module.  Let a user "reserve" a lesson by flagging it, and then disallow registration for any lessons that have been flagged.  Please note that on *Drupal Answers*, you will usually get better answers faster if you break each post up into one question rather than two as you have down here.  If you have two fairly different questions, people will feel obligated to answer the whole thing when they may only have a good solution for part of it, discouraging them to respond.
Comment: How is the registration handled now? IS it by just creating a node by the student or are you using any registration module.
Comment: Thanks for your response and for your advice! I will try the flag module right away! As for the registration, I tried the cck signup module but could not manage to understand it correctly. I want to try it again! For the moment, the student creates another content type and registers for the lesson. And I made a view to see who registered for each lesson.
Answer: If you don't want to re-invent the wheel, have a look at these contributed modules that are typically used for this (quotes are from their project pages):

Availability Calendars.

... allows you to add an availability calendar to entities. Example use cases are tourist accommodation, e.g. bed and breakfast, holiday homes or self catered apartments, and car or motor bike rental.
An availability calendar shows your customers at what dates your accommodation is still available and at what dates it is already booked.

Simple Reservation.

... provides a simple and easy way to reserve items which can be created by the administrator. Examples for it's usage can be hotel rooms, boats, cars, airplanes, basically anything you can think of which can be reserved by one individual.
The module provides the possibility to create reservations for other users (dependend on the permissions), and provides also restrictions in the maximum number of reservations a user can make and a maximum time a reservation can be made in advance.
There is NO support for payment, booking and what ever one could imagine beyond the pure and simple reservation, and it is also NOT intended to create more than this simple functionality.


modal boostrap abre e fecha sozinho

Question: Estou com um problema no meu modal bootstrap. Ele é o mais simples possivel, peguei o exemplo do próprio site do bootstrap para testá-lo porém quando clico no botao, ele abre e fecha logo em seguida automaticamente
<button type="button" class="btn btn-warning btn-lg" data-target="#modal" data-toggle="modal" id="botao_pedido">Faça seu pedido</button>

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

            Olá

Answer: Adicionei as libs que o próprio Bootstrap propõem e coloquei seu modal e funcionou normalmente.
<!DOCTYPE html>

        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

        <button type="button" class="btn btn-warning btn-lg" data-target="#modal" data-toggle="modal" id="botao_pedido">Faça seu pedido</button>

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

                        Olá

Answer: Matheus, beleza? Dê uma checada no console do seu navegador.
Provavelmente está reclamando algum import que não tenha sido feito.
Lembre-se que o bootstrap.js depende do jQuery para funcionar.
Pode ser algo neste sentido!
Comment: Console ta normal
Comment: Os 3 imports estão sendo feitos? (bootstrap.min.css, jquery.min.js e bootstrap.min.js).
Se estiverem, teste em outro navegador.
Comment: Apenas complementando... eu rodei sem problemas o seu exemplo aqui no meu navegador (firefox). Versões 3.3.7 do bootstrap e jquery 1.12.4
Comment: Estão sim, consegui resolver a situação mas obrigado pela atenção ao problema
Answer: Li em uns foruns gringos que o problema geralmente é na inserção dos arquivos javascript do bootstrap

é aconselhavel usar apenas o bootstrap.js ou bootstrap.min.js pois ja inclui ele
Answer: Eu estava com o mesmo problema, porém descobri em meu código que tinha havia duas declarações do bootstrap
 -->

Mantive apenas uma e funcionou.
Answer: Meu caso era igual o Lucas.
Haviam duas declaração do arquivo.js do bootstrap,   removi o da versão mais antiga e funciona muito bem agora.

modal boostrap abre e fecha sozinho


Does an OpenID realm have to be the base URL of the web site?

Question: As a continuation of this question, there's an issue I'm having with dotnetopenauth.
Basically, I'm wondering if the realm specified in the RP has to be the actual base URL of the application? That is, (http://localhost:1903)? Given the existing architecture in place it is difficult to remove the redirect - I tried setting the realm to the base OpenId controller (http://localhost:1903/OpenId) and testing manually did generate the XRDS document. However, the application seems to freeze, and the EP log reveals the following error:
2012-10-10 15:17:46,000 (GMT-4) [24] ERROR DotNetOpenAuth.OpenId - Attribute Exchange extension did not provide any aliases in the if_available or required lists.
Code:
Relying Party:
public ActionResult Authenticate(string RuserName = "")
{
UriBuilder returnToBuilder = new UriBuilder(Request.Url);
returnToBuilder.Path = "/OpenId/Authenticate";
returnToBuilder.Query = null;
returnToBuilder.Fragment = null;

Uri returnTo = returnToBuilder.Uri;
returnToBuilder.Path = "/";
Realm realm = returnToBuilder.Uri;

var response = openid.GetResponse();

if (response == null) {
    if (Request.QueryString["ReturnUrl"] != null && User.Identity.IsAuthenticated) {

    } else {

    string strIdentifier = "http://localhost:3314/User/Identity/" + RuserName;
    var request = openid.CreateRequest(
        strIdentifier,
        realm,
        returnTo);

    var fetchRequest = new FetchRequest();
    request.AddExtension(fetchRequest);
    request.RedirectToProvider();
    }
} else {
    switch (response.Status) {
        case AuthenticationStatus.Canceled:
            break;
        case AuthenticationStatus.Failed:
            break;
        case AuthenticationStatus.Authenticated:
            //log the user in
            break;
    }
}

return new EmptyResult();

}
Provider:
public ActionResult Index()
{
    IRequest request = OpenIdProvider.GetRequest();

    if (request != null) {
        if (request.IsResponseReady) {
            return OpenIdProvider.PrepareResponse(request).AsActionResult();
        }

        ProviderEndpoint.PendingRequest = (IHostProcessedRequest)request;
        return this.ProcessAuthRequest();
    } else {
        //user stumbled on openid endpoint - 404 maybe?
        return new EmptyResult();
    }
 }

public ActionResult ProcessAuthRequest()
    {
        if (ProviderEndpoint.PendingRequest == null) {
            //there is no pending request
            return new EmptyResult();
        }

        ActionResult response;
        if (this.AutoRespondIfPossible(out response)) {
            return response;
        }

        if (ProviderEndpoint.PendingRequest.Immediate) {
            return this.SendAssertion();
        }

        return new EmptyResult();
    }

Comment: Can you elaborate on the freeze?  Is it the browser that freezes? Or does the web page just not change at some point in the flow?  Do you go into infinite redirects?
Answer: The answer to your question is "no".  The realm can be any URL between the base URL of your site and your return_to URL.  So for example, if your return_to URL is http://localhost:1903/OpenId/Authenticate, the following are all valid realms:

http://localhost:1903/OpenId/Authenticate
http://localhost:1903/OpenId/
http://localhost:1903/

The following are not valid realms, given the return_to above:

http://localhost:1903/OpenId/Authenticate/  (extra trailing slash)
http://localhost:1903/openid/  (case sensitive!)
https://localhost:1903/  (scheme change)

Because some OpenID Providers such as Google issue pairwise unique identifiers for their users based on the exact realm URL, it's advisable for your realm to be the base URL to your web site so that it's most stable (redesigning your site won't change it).  It's also strongly recommended that if it can be HTTPS that you make it HTTPS as that allows your return_to to be HTTPS and is slightly more secure that way (it mitigates DNS poisoning attacks).
The reason for the error in the log is because your RP creates and adds a FetchRequest extension to the OpenID authentication request, but you haven't initialized the FetchRequest with any actual attributes that you're requesting.
I couldn't tell you why your app freezes though, with the information you've provided.
Comment: Ok, thanks. I'll leave the realm as is then since it seems to be working. I've also removed the fetchrequest and the error went away. "Freezing" was an incorrect term to describe what's happening - I've investigated some more, I'll post a new question. Thanks!


Sending a csv from front-end to backend using axios

Question: I am trying to send a csv file from my front end in reactjs to my back end in nodejs using axios. This csv file is selected via a browse UI button and stored in state using react. After searching online this is my code for the HTTPS request:
let formmData = new FormData();
formData.append('file', this.state.selectedFile);

const {data : QueryResult} = await axios({
    method: 'post',
    url: "https://localhost:...",
    formData,
});

Note: this.state.selectedFile contains an object which when logged on console is:
File {name: "MyFile.csv", lastModified: 1614958303483, …}

I also would like to say that this endpoint works fine when using Postman as seen below:

After printing the request in my back-end in the case this request from my frontend I see:
body: {}

I don't understand what I am doing wrong and this passes nothing to my back-end.
I also saw that this was an open issue with axios on GitHub in the past.
Can this be achieved now with axios or should i use another module? Any ideas?
Answer: You need to do:
await axios({
  method: 'post',
  url: "https://localhost:...",
  data: formData
});

because when you write just "formData", it becomes : { formData: formData } as per (new ES2015 object shorthand property name).
You can also use:
await axios.post('your_url', formData)


When to use trig substitution?

Question: I'm trying to solve this physics equation:
$$E=\frac {\lambda y}  {4\pi \epsilon_{0}} \int_{-\frac l 2}^\frac l 2  \frac {dx} {({x^2+y^2})^\frac 3 2}  $$
However, my calculus is a little rusty and am told I need to do a trig substitution. My question is, when do we use trig substitution?
Comment: When you see a nice pair of squared terms inside a square root like $(x^2+y^2)^\frac 32$, that's a good time.  In particular, let $x=y\tan\theta,dx=y\sec^2\theta d\theta$...  The trigonometric identities like $\cos^2(x)+\sin^2(x)=1$ are the basis for these substitutions since there are ways to rearrange so that a square root is removed from the problem leaving an easier problem to solve.
Comment: http://en.wikipedia.org/wiki/Trigonometric_substitution
Answer: Letting $x=y\tan\theta,$
$$\frac{dx}{d\theta}=\frac{y}{\cos^2\theta}.$$
Hence, your definite integral will be
$$\begin{align}\int_{\alpha}^{\beta}\frac{1}{(y^2\tan^2\theta+y^2)^{3/2}}\cdot\frac{y}{\cos^2\theta}d\theta&=\int_{\alpha}^{\beta}\frac{1}{(y/\cos\theta)^3}\cdot\frac{y}{\cos^2\theta}d\theta\\&=\int_{\alpha}^{\beta}\frac{\cos\theta}{y^2}d\theta\\&=\frac{1}{y^2}[\sin\theta]_{\alpha}^{\beta}\\&=\frac{\sin\beta-\sin\alpha}{y^2}\end{align}$$
where $$-\frac{l}{2}=y\tan\alpha,\ \ \ \frac{1}{2}=y\tan\beta.$$
Here, I used
$$1+\tan^2\theta=\frac{1}{\cos^2\theta}.$$

When to use trig substitution?


Should "together with" be taken as slang for an n-tuple?

Question: When an algebraic structure is defined, it is often defined as a set $S$ "along with"/"together with"/"having" operations $\circ_1, \circ_2, \ldots, \circ_n$, and "denoted" by $(S, \circ_1, \circ_2, \ldots, \circ_n)$.
This is true of metric spaces as well. We often say that a metric space is a set $X$ with some distance function $f: X \times X \to \mathbb{R}$.
But none of this seems very formal to me. Are we -- the reader -- supposed to infer that it in each of these cases, we're really talking about an $n$-tuple (in ZFC)?
So for instance, when a theorem says something like this:
Thm Let $X$ be a metric space. If $X$ is a foo, then $X$ is a noo.
It is formally:
Thm Let $(X, d)$ be a metric space. If (the underlying set) $X$ is a foo, then $X$ is a noo.
I guess I'm just confused as to why tuples are glossed over and replaced with "together with" so often, when it detracts from the "axiomaticity" of the material.
Comment: @AmadeusDrZaius At some point everyone knows that 'together with' means. I think it is a bad idea to use such terms for a beginning student. What does 'together with' even mean? Yes, you're supposed to induce (rather than infer) that an $n$-tuple is at hand. This has little to do with $\sf ZFC$ other than the fact that it is the standard foundational ground for mathematics nowadays.
Comment: In most cases, the reader does not have to know, nor care, whether it is an $n$-tuple in any particular way.  Only a model theorist, when she wants to make this something for her to study, should specify what it is at that nuts-and-bolts level.
Comment: [Related](http://math.stackexchange.com/questions/208682/formalizing-the-idea-of-a-set-a-together-with-the-operations-cdot).
Answer: One can, but I do not think one should.
Also, $n$-tuples are not basic objects of standard set theories, they have to be defined. Take a probability space $(\Omega,\Sigma,\mu)$. Should we take this as $(\Omega,(\Sigma,\nu))$ with some definition of an ordered pair? How about $((\Omega,\Sigma),\mu)$? Or maybe it is a function $f$ with domain $\{0,1,2\}$ such that $f(0)=\Omega$, $f(1)=\Sigma$, $f(2)=\nu$.
? Many other choices are possible, but it doesn't really matter. If a result in, say, geometry essentially depends on how you define $n$-tuples it is probably of no interest to any geometer.
Comment: Then you need to explain what 'together with' means.
Comment: The point isn't that 'a 3-tuple' is ambiguous, it's that a geometer doesn't care about the ambiguity.
Comment: Well, we have to give it *some* definition. Also, if you define $(A, B, C)$ as $\{\{A\}, \{A, B\}, \{A, B, C\}\}$, and so on for other $n$, then there is no ambiguity..
Answer: It's often okay to define a mathematical object without an explicit set theoretic model. If we need a model we can always take a step back and make sure there is one.
Take for example the following definition:

A map $f$ from a set $A$ to a set $B$ assigns to every $a\in A$ a unique value $f(a)\in B$. We write $f\colon A\to B$. Two maps $f,g\colon A\to B$ are equal if and only if $f(a)=g(a)$ for all $a\in A$.

We can use this definition of a map to define surjectivity, injectivity and any other property of maps and work with those without ever thinking about how we would model this in set theory.
Or do you always think of a map $f\colon A\to B$ as a tuple $(F, A, B)$ where $F\subseteq A\times B$ is a right-unique relation, and the $3$-tuple $(F, A, B)$ is really build from Kuratowski pairs $(F, (A, B))$ with $(A, B) = \{\{A\}, \{A, B\}\}$?
Comment: I agree. Though I have never seen a rigorous definition of a category being a $3$-tuple of two classes and a relation in some theory where tuples can hold classes. And I never felt the need to.
Comment: You need to explain what 'assign' means if you're avoiding the set theoretic definition.
Comment: @GitGud Yes, if somebody doesn't know the word, I could explain it (without set theory). I agree that modern mathematics should define every term used in mathematical statements (or at least be able to, if asked for), but to start understanding maps we certainly don't need relations and Kuratowski pairs.
Comment: Defining 'assigning' without set theory is simply shifting the problem to another foundational ground. I agree that in the case of functions, **for starters**, it is best to use something like what you suggested, but this is for purely pedagogical reasons and that's not what's at stake in this question. In regards to 'together with' I think not defining as an $n$-tuple just brings confusion. I know I was confused and found relief in learning the $n$-tuple definition.
Comment: It's true that you don't necessarily need to build up from ZFC [one can take "assign" as an atom of our language], and you make a good point by noting that, but I think it's fair to say that much mathematical sweat and tears has been devoted to being *able* to put everything on a common axiomatic foundation.. so not doing so is an option, but not the option I'm looking for.
Comment: So what I'm getting from all this is that it's okay to use the simplifications that I referenced in my answer as long as we don't conclude things based specifically on that simplification. That is, as long as we never do anything dependent on an algebraic structure being identical with its underlying set, it's okay to talk as if they're one in the same.


Configuração de validação em campos dinâmicos

Question: Tenho um problema que é o seguinte, tenho os campos: Nome, Idade e Texto;
Em uma parte do sistema eu cadastro que o campo Texto só vai aparecer se o campo Nome for igual a PH e o campo Idade ter o valor 20 com as duas condições verdadeiras eu libero então o campo Texto.
A minha dificuldade nessa parte é porque pode ter muitos campos porque o formulário é montado pelo cliente, ou seja, o cliente pode cadastrar 20, 30 campos pra esse formulário e todos terem uma regra especifica pra liberar algum outro campo. Existe algum plugin que verifique ou que faz esse tipo de validação?
Nesse momento eu tentei o seguinte, porém só valida dessa forma se fosse de 1 para 1. Mas nesse caso pode ser de N-1 ou 1-N ou seria melhor criar uma tabela intermediária para tal ação?
$(function () {
    var campoDependente = '#codigo_<?php echo $condicao->atividade_campo_dependente ?>',
            campoTrigger = '#codigo_<?php echo $condicao->atividade_campo ?>',
            valor = '<?php echo trim($condicao->condicao) ?>';

    function mostrar() {

        var val = '';
        var checkbox = $(campoTrigger + ' input:checked');
        var select = $(campoTrigger + ' select > option:selected');
        var input = $(campoTrigger + ' input');

        if (checkbox.length > 0) {
            val = $.trim(checkbox.parent().text());

        } else if (select.length > 0) {
            val = $.trim(select.text());

        } else {
            val = input.val();

        }

        if (val == valor) {
            $(campoDependente).css('display', 'inline-block');
        } else {
            $(campoDependente).css('display', 'none');
        }

    }

    mostrar();
    $(campoTrigger).change(mostrar);

});

Answer: Tens de criar uma lógica de verificações. Podes fazer isso num objeto com regras de verificação. Cada chave poderia ser o name ou id  do input que aparecerá se algumas regras forem verificadas. Dessa maneira haverá uma estrutura que facilmente se monta com JS.
Exemplo da ideia:
var regras = {
    texto: {
        nome: 'PH',
        idade: 20
    }
};

e depois um código que fosse procurar regras e elementos DOM para e verificar tudo:
var inputs = document.querySelectorAll('input');
for (var i = 0; i < inputs.length; i++) {
    inputs[i].addEventListener('keyup', verificador);
}

function procurador(chave, objeto) {
    if (chave in objeto) return chave;
    var match = Object.keys(objeto).filter(function (key) {
        var subObjeto = objeto[key];
        if (typeof subObjeto != 'object') return false;
        return procurador(chave, subObjeto);
    })[0];
    return match;
}

function verificador() {
    var prop = this.name; // saber qual input recebeu keyup
    if (!prop) return;    // caso não tenha nome interromper
        Object.keys(regras).forEach(function (regra) { // iterar as regras
        var regrasLocais = Object.keys(regras[regra]); // regras a cumprir
        var target = document.querySelector('[name="' + regra + '"');
        var valores = regrasLocais.map(function (nome) { // mapear regras com o input respetivo guardando o seu valor
            return document.querySelector('[name="' + nome + '"').value;
        });
        var valida = valores.filter(function (value, i) { // verificar quais inputs têm o valor == ao que é esperado pela regra
            var original = regras[regra][regrasLocais[i]];
            return value == original;
        });
        if (valida.length == regrasLocais.length) target.classList.remove('invalido'); // se todas as verificações tiverem passado
        else target.classList.add('invalido'); // caso falhe a validação
    });
}

jsFiddle: http://jsfiddle.net/vazuLkf0/1/
Um exemplo mais complexo com funções dentro de regras de verificação seria: http://jsfiddle.net/vazuLkf0/5/
Demorou-me um pouco a fazer este código. Achei a pergunta e o problema interessante então coloquei no github também.
Espero ser isto que procuras :)
Comment: Só mais uma coisinha que não citei e quando os campos não são apenas input's tentei colocar aqui na variável **valores** na função verificador tentei agrupar os seletores porém sem sucesso por exemplo tenho campos que são selects nesse caso preciso do .text e não do .value como faria nesse caso ? meio que pegar o texto dos campos universalmente e ficou bom o codigo boa iniciativa de coloca-lo no github
Comment: @PauloHenrique e nesse caso as `option` têm `value`? se não tiverem value o `select.value` retorna o texto/`.innerHTML`
Comment: nesse caso os options tem value sim, exemplo: o `sim` tem valor `27` os numeros nos values são representados os ID no banco de dados, caso o cliente selecionar um deles eu tenho que salvar no banco e depois trazer marcado o valor respectivo e o `.innerHTML` por algum motivo trás o input como vazio mesmo preenchido.