Number addition riddle

Question: I got this math "riddle" in one of my math test, and I would love to know how to solve it.
If
$$S = 1 + 2 + 3 + 4 + \ldots + 2015,$$
then a sum of
$$1 + 2 + 3 + \ldots + 2015 + 2016 + \ldots + 4030$$
is equal to: ?
I know the answer is  $2S + 2015^2$, but not how to get it. Could someone explain, please?
Comment: For the terms 2016 and up, write them as $2015+1, 2015+2, 2015+3, \dots$.
Comment: A related question would be to evaluate $2015+201S$ :)
Answer: $$
\begin{align}
&1+2+\cdots+2015+2016+\cdots+4030\\
=\:&S+(2015+1)+(2015+2)+\cdots+(2015+2015)\\
=\:&S+(1+2+\cdots+2015)+(\underbrace{2015+2015+\cdots+2015}_{2015\text{ times}})\\
=\:&S+S+2015\cdot2015\\
=\:&2S+2015^2
\end{align}
$$
If you want to find the value of $S$, you can do the following additional pairing:
$$
\begin{align}
S&=1+2+\cdots+2015\\
&=(2015+1)+(2014+2)+\cdots+(1009+1007)+1008\\
&=\underbrace{2016+2016+\cdots+2016}_{1007\text{ times}}+1008\\
&=1007\cdot2016+1008\\
&=2\,031\,120
\end{align}
$$
Comment: I see, quite easy when I see it like this.. thanks a lot! :)
Answer: Let $S$ be the sum $S=\sum_{n=1}^{2015}\, n$.  Then, we have
$$\begin{align}
\sum_{n=1}^{4030} \,n&=\sum_{n=1}^{2015} \,n+\sum_{n=2016}^{4030} n\\\\
&=\sum_{n=1}^{2015} \,n+\sum_{n=1}^{2015}\, (n+2015)\\\\
&=\sum_{n=1}^{2015} \,n+\sum_{n=1}^{2015}\, n+2015\sum_{n=1}^{2015}\, 1\\\\
&=S+S+(2015)\times (2015)\\\\
&=2S+2015^2
\end{align}$$
As was to be shown.

Number addition riddle


vmstat output incompatible

Question: as you can see when run a vmstat like below.
bash-3.00# vmstat 1 5
kthr      memory            page                     disk              faults        cpu
r  b  w   swap   free    re   mf   pi   po   fr   de sr m1 m1 m1 m2   in   sy   cs    us sy id
2  0  0 12812792 7094520 668  1023 213  939  939  0  0  1  1  1  0  30519 66084 35693 12 7  81
10 19 0 5469784  797392  265  325  583  1119 1119 0  0  1  1  0  0  35404 75227 44916 14 8  78
34 10 0 5577672  846056  570  554  3802 1233 1233 0  0  1  0  0  0  35013 72253 46505 10 10 79
19 0  0 5576352  843112  462  2825 1200 963  963  0  0  0  0  0  0  35070 73182 44379 13 8  78
2  0  0 5582624  854664  1698 1885 134  1198 1198 0  0  2  1  1  0  35688 71013 43705 11 7  82

what is wrong with this ? because the memory usage is about %95.
***---****---****----*****
Since the system is an HA system here is the output for standby machine.
bash-3.00# vmstat 1 5
kthr      memory            page          disk                faults            cpu
r b w   swap   free    re   mf   pi   po fr de sr m1 m1 m1 m2 in    sy    cs    us sy id
1 0 0 13949104 8516736 553  1047 121  21 20 0  0  1  1  1  9  30691 69172 34352 12 7  81
0 0 0 12456136 7171232 1122 2554 4117 0  0  0  0  3  1  2  0  31505 85240 35958 11 8  81
0 0 0 12353888 7147488 1401 664  0    0  0  0  0  0  0  0  0  31647 73507 35881 13 6  81
0 0 0 12345536 7129280 13   40   0    0  0  0  0  0  0  0  0  30787 69357 34695 14 6  80
0 0 0 12345440 7125040 217  1646 0    24 24 0  0  0  0  0  0  31390 73710 38393 12 10 78

Comment: Why is this not what you expect?
Comment: nope it is not. because it is in an HA system and the hot standby machine output :

`bash-3.00# vmstat 1 5
 kthr      memory            page            disk          faults      cpu
 r b w   swap  free  re  mf pi po fr de sr m1 m1 m1 m2   in   sy   cs us sy id
 1 0 0 13949104 8516736 553 1047 121 21 20 0 0 1 1 1 9 30691 69172 34352 12 7 81
 0 0 0 12456136 7171232 1122 2554 4117 0 0 0 0 3 1 2 0 31505 85240 35958 11 8 81
 0 0 0 12353888 7147488 1401 664 0 0 0 0 0  0  0  0  0 31647 73507 35881 13 6 81
 0 0 0 12345536 7129280 13 40 0 0  0  0  0  0  0  0  0 30787 69357 34695 14 6 80`
Comment: sorry the output can not be formatted as well as the initial question!
Comment: one more comment : if you check both outputs you will see that; after second period the problemmatic one's free memory decreases so much. where it is not on the hot standby one.
Comment: Olgun: You can edit your question and add further output to it.  That way you can format it.  Concerning the drop in vmstat output: I believe this to be related to the startup of vmstat itself, I see this on nearly every run of vmstat and I tend to ignore the first couple of lines.
Comment: @OlgunKaya I meant please explain *why* this is not what you expect.
Comment: Can you be very precise about what your concern is? The machine seems to have very little memory free, which is exactly what you want. (Free memory is forever wasted. It's not like if you use 1GB less today you can use 1GB more tomorrow.)
Answer: Solaris? Which version (presumably 8 or 9 from the idle column)? Sun cluster or vcs?
Anyway, ignore the first line since that is an average since boot.
Is a backup running on the passive node, by the way, and causing the minor faults and page-ins on a machine ostensibly doing nothing? And look at the context switches.
On the active node, memory usage at 90 per cent probably is just memory used by whatever you are running: Oracle's SGA, perhaps; and the rest is in use for cacheing. This is normal. The system does seem to be io-bound, at least for the few seconds you show. There is paging in and out but no serious memory pressure, so this probably reflects memory-mapped io. Some swap space is in use but that may reflect pre-allocation rather than any shortfall.
Run: vmstat -s; vmstat -p 10 5. If it is Solaris, also: prstat -a; prstat -t; prstat -a -s rss; and on Solaris 9, echo ::memstat | mdb -k (which can take a while so do not panic). These will show what the system is using memory for, and which applications are using it. If you think your application software is leaking memory, then compare measurements from prstat over time.
If you are consistently io-bound, then run iostat -xn 60 and speak to your storage administrators if appropriate. But that is a separate matter.
Comment: thanks. using some of these commands we found that some sendmail apps stacked ( ~140 ) each using 20 MB of memory. When we restarted the service it seems now the system working as expected load level.

standby machine memory level : 54%
working machine memory level : 82%

which is acceptable
Answer: I'm not sure what's being asked here but you do remember that the first line of the vmstat output shows the average values for the items since the last reboot ? Subsequent lines show the values for the last sampling period, so in general ignore the first line.

vmstat output incompatible


Did any player pianos use card decks?

Question: Wikipedia doesn't mention any. But since Jacquard cards developed from Bouchon tapes in the eighteenth century; and then Hollerith cards evolved back into tapes and then into magnetic tapes (merging with the "wire" recording thread) and magnetic disks and finally into static electric arrays in the twentieth century, ...
did player pianos just stick with one format?
Did anybody try a cardbox?
Comment: *I spared this part because I felt I'd subjected everyone to enough of my imaginings for one night*: The motivation for this question was imagining using such a card-controlled player piano to play "collage" music constructed of "samples" from other pieces. Like an "acoustic" DJ.... (maybe that melody from Moonlight Sonata *really does* lead straight into the shipwreck from Scheherazade!)
Comment: some nice footage of old reproducing instruments here: http://youtu.be/6MsyOe7xCqg
Answer: Actually, "book" style players predate Mr Jaquards loom.
They progression really got started with music boxes & pins stuck in drums or disks.
Next came the "book style" where holes were punched in panels and the panels were hinged together in various ways, and later on the paper rolls that are well known now.
But the real question is related to Hollerith style punch cards and the answer is "kinda yes".
It was never a standard, but several one of a kind instruments were built.
There was an LP in limited release "2 Loves Have I, Jean & Genie" back in the 60s.
Jean Lautzenheizer & her husband equipped the pipe organ in their home near Washington DC
with a reader.  Some selections were played by hand by Jean, and some were sequenced at work and brought home to be read on the reader by her husband.
Comment: Do you know if any *pianos* that used decks?  Organs have rather different mechanical requirements, since the energy for their sound is not expected to come from the key mechanisms.
Answer: Band organs played from a "book" of punched cards joined together to make a continuous strip.  Here's a picture:  http://en.wikipedia.org/wiki/File:Book_music_playing.jpg
Comment: Found the page: http://en.wikipedia.org/wiki/Book_music
Comment: I bet you could make a vamp with a *jacob's ladder*.
Answer: HISTORY AND ORIGINS OF PLAYER PIANOS
Automatic musical instruments have been around for over two millennia.
It all really started in 1800, France, when Jacquard Mills develops a loom controlled by punched cards. The cards programmed looms that created elaborately designed fabrics. They "instructed" the pathway for threads to follow to create the designs and patterns in the cloth.
Here's a link to the full article, in case you haven't seen it:
http://www.playerpianopumporganrestorations.com/historypiano.html
Answer: There are two general styles of punched-media-operated organs.  In one style, the moving holes in the media mechanically actuate the mechanisms to play the notes; in the other style, holes in the media allow air to flow into bellows, which in turns operate valves that play the notes.  The former "key-operated" style requires that the media be strong enough to physically operate the mechanisms; the latter "keyless" style requires that the media be pulled flat against the vacuum holes without leaking.  Consequently, media for the former style are generally in the form of semi-rigid folded cards, while media for the latter are on flexible rolled media which are free of folds.
The only advantage I'm aware of the key-style mechanism is its simplicity.  A major disadvantage is that the media have to bear the stress of operating the mechanism.  The keys of a full-sized piano have to do a fair amount of work; for them to operate directly off punched media without pneumatic relays or other such mechanism; an instrument that requires a relay mechanism will not benefit much from the simplicity of a keyed mechanism.  While I cannot say with certainty that no full-sized player pianos used decks, I find it doubtful.
Answer: The question above asked if there was more than one format.
Yes.
There were many different punching formats used over the years.
The "88 note" is the most famous for pianos, but orchestrions got far more complex.

Did any player pianos use card decks?


Can I use a placeholder to dynamically add text to a string imported from a property file with Spring's @Value annotation

Question: Does anyone know if I can use placeholders with Spring's @Value annotion?
For example:
<code>@Value("${a.url.from.propertiesFile}")
private void setUrl(String myUrlFromProperties)
{
    this.url = myUrlFromProperties;
}
</code>
where my properties file would have:
<code>a.url.from.propertiesFile=/firstPartOfUrl{dynamicBitToAddTo}restOfUrl
</code>
Comment: Doh! This was a pretty obvious solution really...just used this: String urlToUse = url.replace("{dynamicBitToAddTo}", "actualDynamicBitofUrl");
Answer: Yes you can do that.
In this case if you have passed a null value in the parameter then the default value will be taken as defined with the annotation @Value.
But if you are passing a not null value in the parameter then it will not take the default value.
Hope this helps you.
Comment: The code you have shown in your question is itself the example. It is how its done. :)
Comment: Ah OK sorry, I thought you were referring to a different approach.


How to pass the xpath that is stored in variable?

Question: my $V1 = $sel->get_text("//body[\@id='ext-gen3']/div[14]/div[2]/div/div/div/div/div/div/div/div/div/div[2]/div/div/table/tbody/tr/td/div/div");
print($V1 . "\n");

When i execute the above command, i could print the v1 without error.
My aim is to print the such values ( say around 20). But xpath for each variable varies by the div element only (i.e., div element preeceeding table should be replaced by div[2], and div[2] should be replaced by div[3] in every iteration.
Following snippet does the replacing div[] element. But saying as invalid xpath.
my $xpath = q(//body[\@id='ext-gen3']/div[14]/div[2]/div/div/div/div/div/div/div/div/div/div[2]/div/div/table/tbody/tr/td/div/div);
for my $i (0,2)
{
my @nodes = split qr'/', $xpath;
$nodes[16] .= "[$i]" unless 0 == $i;
#say join '/', @nodes; }
my @somenames = join('/',@nodes);
#print "\n";
#print @somenames ;
foreach my $val (@somenames) {
    chomp($val);
    #my @new_arr = $sel->get_text($val);
    print "\n";
    print $val; ***this prints the xpath value which i needed***
    my $V1 = $sel->get_text("$val"); ***#i'm passing the same xpath here within double quotes but says as invalid xpath***
     print($V1 . "\n");
    my @new_arr = $sel->get_text("$val");
  }
}

Am i following wrong way of passing xpath ? How can i do it ?
Answer: Compare your definition of the XPath string with mine in the previous answer. You inserted a backslash in front of the commercial-at that does not belong.
Comment: @ Daxim : Even though if i remove that backslash, it prints the needed. But when i pass that value into get_text -> () , it says as invalid xpath. Another thing, after running a testcase in selenium IDE & exporting it in perl it appears with backslash.
Comment: even i compared both terms as if ($xpath eq $val) , it outputs as both are equal.


Why is R$^2$ calculated differently in multiple regression than linear regression?

Question: I'm reading an open-source statistics book and I came across this quote:

In multiple regression, the degrees of freedom associated with the variance of the estimate of the residuals is $n - k - 1$, not $n - 1$. For instance, if we were to make predictions for new data using our current model, we would find that the unadjusted $R^2$ is an overly optimistic estimate of the reduction in variance
  in the response, and using the degrees of freedom in the adjusted $R^2$ formula helps correct this bias.

A couple of quick questions:

Does anyone have a better and more intuitive reason behind what is degrees of freedom?
Why is the reason that R^2 is an overly optimstic estimate of the reduction of variance in the response (What does this even mean?)? What is wrong with saying the degrees of freedom is $n - 1$? Why do we need to make this correction?

Here is the actual page:
Comment: "the variance of the estimate of the residuals" is the parameter or the function of the parameters. So the variance of the estimate of the residuals has no the degree of freedom. So my suggestion is ignoring this book.
Comment: This isn't clarifying. What is "the parameter or the function of the parameters"?
Comment: For example, a normal distribution has two parameters: mean and variance $\sigma^2$. Both of them are (unknown) constants. When we have a sample with n subjects from this distribution, we can use the sample mean to estimate the population mean. "the variance of the estimate" of the mean is $\sigma^2/n$.
Comment: Reference please, not just allusion and quotation. "a less estimate"?
Comment: Yeah this book seems bad.
Comment: In statistical estimate, there are two totally different things: Parameter and its estimate. For example, suppose the sample comes from a normal distribution $N(\mu,\sigma^2)$, we want to guess the $\mu$ based on sample. Then we will use sample mean $\bar{X}$ to estimate $\mu$. So $\mu$ is parameter and $\bar{X}$ is estimate. So you need to go previous pages to see if you can figure out that $R^2$ is parameter or estimate or something else? If you cannot, avoid this book.
Comment: Why am I getting downvoted?
Comment: For the question about degrees of freedom see https://stats.stackexchange.com/questions/16921/how-to-understand-degrees-of-freedom
Answer: There are lots of resources for how to think about degrees of freedom. Personally, I like thinking about it as just the number of data points - the number of parameters. When you take a sample mean
$$\bar{X}=\frac{1}{n}\sum X_i$$
you are estimating a quantity without any parameters, so there are $n$ dfs.
For variance $$\frac{1}{n-1}\sum_i(X_i-\bar{X})^2$$
you are using $\bar{X}$ as a parameter that is estimated from the data so the df is $n-1$. There are lots of ways to think about it so I will move on to your next question.
Consider
$$R= 1 - \frac{Var(e_i)}{Var(Y_i)}$$
But what is $Y_i$ in linear regression? Well it is just
$$Y_i= \beta X_i+\epsilon$$
let's define $$\hat{Y} = \beta X_i$$
then we can write the difference between our observed $Y_i$ and our guess for $\hat{Y_i}$ as $$Y_i-\hat{Y_i}$$. But wait a second, that can be negative, and negative error doesn't make sense? Let's just square it so it will always be positive :)
Okay so we get
$$(Y-\hat{Y})^2$$
Now, pretend you had never heard of linear regression and someone came to you with some data on house prices and school quality and said guess the house price at this level of school quality. Well, you have no idea what to do with school quality so you ignore it and just take the average of the house prices, call that $$\bar{Y}$$
This is not a bad guess, especially since you didn't learn about regression. So how much better is our dumb guess than the complicated regression stuff? Well what if we wrote the error as
$$(Y_i-\hat{Y_i})^2+(\hat{Y_i}-\bar{Y})^2$$
So if $\hat{Y_i}$ is just as good a guess as $\bar{Y}$ then the second term goes to zero, but if it is much better than the first term will go zero. Now we have a tradeoff between how using our school district quality increases the quality of our guess (given by the second term), and how much noise is left in the data that our regression line can't pick up (given by the first term).
Okay what does this have to do with $R^2$, well the actual definition above is $$R^2 = 1- \frac{\frac{1}{n}\sum_i(Y_i-\hat{Y_i})^2}{\frac{1}{n}\sum_i(\hat{Y_i}-\bar{Y})^2+\frac{1}{n}\sum_i(Y_i-\hat{Y_i})^2} $$
Why? Well the numerator is the sample variance of our errors, in other words, the variance of the error that our regression line can't capture and the denominator is the variance of the observations.
What do we see there ? $\frac{\frac{1}{n}}{\frac{1}{n}}$ That cancels, giving you the definition in the book. However those are our degrees of freedom, $n$ for the numerator and $n$ for the denominator.
Okay so what happens if we add in another explanatory variable, like number of crimes in the area? Let's look at the numerator of $R^2$. Can this amount ever increase? The objective function of regression is to find coefficients that minimize $$\sum_i(Y_i-\hat{Y_i})^2$$, so given an optimal parameter setting for $b_1$
$$\sum_i(Y_i-(b_1x_1 +b_2x_2))^2$$ the algorithm will find $b_2$ that minimizes this total sum, so there is no way this term will increase because in the worst case regression will just set $b_2=0$. Only if $x_2$ helps explain the residual error better will $b_2 \neq 0$. If we decrease the numerator, we also decrease the second term in the denominator. Lets investigate how this affects $R^2$
$$\frac{x}{x+y} \geq?\leq \frac{x-\delta}{x-\delta+y}$$
$$x(x-\delta+y) \geq?\leq (x-\delta)(x+y)$$
$$x^2-x\delta+xy \geq?\leq x^2-\delta x +xy -\delta y$$
$$0 \geq?\leq -\delta y$$
Since both $y$ and $\delta$ are $>0$ we see that the final inequality must be $0 \geq -\delta y$ so therefore, subtracting a $\delta$ from the numerator and the denominator makes the whole term go down, and therefore makes $R^2=1-that$ go up.
There is exactly the problem with $R^2$, we can artificially inflate it by just adding more parameters to the model. How do we fix this? We just add a term that penalizes models with large number of parameters.
By dividing the numerator by $n-k-1$ where $k$ is the number of parameters(regressors) in our model, we are dividing by a smaller number in the numerator than in the denominator, so the numerator becomes bigger and $R^2$ goes down! Now we have a way of making $R^2$ go down by including parameters that have no correlation.
Comment: Why would we write the error as: $$(Y_i-\hat{Y_i})^2+(\hat{Y_i}-\bar{Y})^2$$


How config git email notification

Question: Could your advice information (script) to config git notification.
We have many projects and team working with them. It will be better if team member could get email notification when another push.
Answer: See How to setup post-receive-email Git hook with Gitolite for an example.
With Gitolite V3, you can set any hook you want, as detailed in "gitolite post receive hook for specific bare repo".

How config git email notification


Assigning icon to custom filetype on android

Question: How do I do it so that when I open the file manager on android, the custom filetype will be shown with a personal icon
Answer: That's not really possible, unless you are the one writing the file manager. There is no built-in "get an icon for a MIME type" system in Android, let alone a way for you to register a custom MIME type there.


Determinant Algorithm

Question: We want to calculate the following determinant $$A(n,k)=\begin{vmatrix} \binom{n}{0} & \binom{n}{1}& \cdots & \binom{n}{k}\\ \binom{n+1}{0} & \binom{n+1}{1}& \cdots & \binom{n+1}{k}\\ \vdots & \vdots& \ddots & \vdots \\ \binom{n+k}{0} & \binom{n+k}{1}& \cdots & \binom{n+k}{k} \end{vmatrix}$$
I observed that the matrix is a square matrix of order $k+1$ and every element $a_{i,j}$ is of the form $$a_{i,j}=\binom{n+i-1}{j-1}$$ and tried applying the identity $$\binom{n}{k}-\binom{n-1}{k}=\binom{n-1}{k-1}$$ by subtracting row $n-1$ from row $n$, row $n-2$ from row $n-1$ etc. and noting that the first column consists entirely of $1$'s, the next column is $n+i-1$, where $i$ is the number of each row. I tried factorising a common factor, but didn't get much further.
Answer: I'll show an explicit example: $A(n,3)$.
$$A(n,3)=\begin{vmatrix} \binom{n}{0} & \binom{n}{1}& \binom n2& \binom{n}{3}\\ \binom{n+1}{0} & \binom{n+1}{1}& \binom{n+1}{2} & \binom{n+1}{3}\\ \binom{n+2}{0} & \binom{n+2}{1}& \binom{n+2}{2} & \binom{n+2}{3}\\ \binom{n+3}{0} & \binom{n+3}{1}& \binom{n+3}{2} & \binom{n+3}{3} \end{vmatrix}$$
Using your idea:
$$A(n,3)=\begin{vmatrix} 1 & \binom{n}{1}& \binom n2& \binom{n}{3}\\ 0 & \binom{n}{0}& \binom{n}{1} & \binom{n}{2}\\ 0 & \binom{n+1}{0}& \binom{n+1}{1} & \binom{n+1}{2}\\ 0 & \binom{n+2}{0}& \binom{n+2}{1} & \binom{n+2}{2} \end{vmatrix}$$
Using cofactor expansion:
$$A(n,3)=\begin{vmatrix} \binom{n}{0}& \binom{n}{1} & \binom{n}{2}\\ \binom{n+1}{0}& \binom{n+1}{1} & \binom{n+1}{2}\\ \binom{n+2}{0}& \binom{n+2}{1} & \binom{n+2}{2} \end{vmatrix}$$
Do you see a pattern?
Comment: That's $A(n,2)$, I was looking for this recursion. Thank you! Cheers!

Determinant Algorithm


What is the UMVUE for $\sigma^2$ in $\mathcal N(0, \sigma^2 )$?

Question: By using the exponential class factorization theorem, I came up with $Y = \sum (x_i)^2$ to be the complete and sufficient statistics for $\sigma^2$ .
Using this sufficient statistic as a condition, would I need to get the MLE to derive the MVUE for $\sigma^2$ ?
I don't know how to proceed to get the MVUE.
Comment: https://stats.stackexchange.com/q/250917/119261
Answer: If $Y$ is complete sufficient, then $f(Y)$ is the unique (up-to null sets) UMVUE of its expectation (Lehmann-Scheffe). In particular, take $f(Y) = Y / n$ and check that $E[f(Y)] = \sigma^2$.


Why does the "individual" race in a biathlon have that name?

Question: In biathlon there are 4 formats for races:

Mass start (12.5km for women and 15km for men)
Individual (15km for women and 20km for men)
Sprint (7.5km for women and 10km for men)
Pursuit (10km for women and 12.5km for men)

In the mass start format the athletes start all together.
In the sprint and individual formats the athletes start every 30 seconds.
In the pursuit format the athletes start with the delay accumulated from the sprint.
So sprint and individual both seem to be "individual" events and I do not understand why the shortest is called "sprint" and the longer "individual".
Comment: I tried to make the question more understandable.  You are asking why they use the term individual for that race, correct?
Comment: I am going to comment that the "Individual" event is the older event (with the original distance of 15K/20K) while the "sprint" event is a newer format to indicate it being "half-an-individual" (in terms of distance) - it becomes a more suitable distance to attract newcomers into the sport.  This is similar to "Olympic" and "Sprint" distances in triathlons.
Answer: This presentation of 2015 IBU World Championships in Kontiolathi shows that "individual" is the oldest format biathlon event, so this definition was enough to distinguish it in 1970s' from the relay.
Literal translation from that Italian article:

anyone who has only recently approached the biathlon will wonder why this format is called "individual" when there are four kinds of individual
  competitions. Simply because this was the only existing format until
  the 70s and "individual" was enough to distinguish it from the
  "relay"

Although the definition of individual is still officially recognized by IBU (here is the link for men's individual rankings), it has become common to name this format simply with the number of kilometers (so twenty for men and fifteen for women).
Also Wikipedia agrees that the individual is the oldest format for biathlon events.
Comment: This doesn't make any sense. I would edit to clarify it but I have no idea where to start.
Comment: This is the truth. The author of italian article is a biathlon journalist as you can see by his [last articles](http://www.neveitalia.it/user/fpaone). I add the translation of the sentences where he explain this trivia
Comment: Again tried to clean up your meaning.  Seems your language didn't come across very clearly, and you made quite a few spelling mistakes and word omissions that threw it off.  I hope I made a little more sense of it, please do verify that how I reformatted it is correct Ale.


Criar padrão de cadastro com repositório C# UI

Question: criei no meu sistema um repositório com EF6, cada cadastro que faço eu acesso os métodos do meu repositório para comitar as ações que eu preciso (Insert, Delete etc...).
O problema é que meu sistema está bem grande e eu preciso ganhar agilidade ao criar cadastros, pensei então em criar um controle com o padrão de tela que eu preciso e nos botões que vão chamar meu repositório para executar as ações eu penso em criar propriedades informado qual é a tabela do meu Model. Alguém tem algum norte para eu criar algo parecido?
Comment: use DI assim você passa a interface
Comment: Você tem algum exemplo?
Answer: Eu faria algo usando Generics:
public interface IComum<T>
    where T: class, IModeloDeDados
{
    IEnumerable<T> Selecionar();
    IEnumerable<T> Selecionar(IEnumerable<Operador> parametros, IEnumerable<string> campos = null);
    void Incluir(T objeto);
    void Atualizar(T objeto);
}

Esmiucei melhor a questão nesta resposta.
Só esclarecendo, neste meu exemplo um Operador é uma classe especial que é transformada em sentença SQL porque o projeto não usa Entity Framework, mas há outras respostas aqui com a implementação suportando expressões lambda.
Faça suas classes de repositório implementarem essa interface, passando como tipo em T o objeto de dados desejado:
public class Pessoas : Comum<Pessoa> { }

Pessoa, neste caso, precisa implementar uma interface IModeloDeDados, para que o repositório não aceite qualquer objeto.


Inserir Alternativas em um Model no Django

Question: Boa noite. Eu sou iniciante no Django, estou tentando fazer uma plataforma simples, tipo um quiz e estou com uma dúvida. Eu tenho a seguinte classe:
class Questao(models.Model):
    subdominio = models.ManyToManyField(SubDominio)
    situacao = models.OneToOneField(Situacao, on_delete=models.CASCADE)
    questao = models.TextField()

    def __str__(self):
        return self.questao

    class Meta:
        verbose_name = "Questão"
        verbose_name_plural = "Questões"
        ordering = ['subdominio__name']

Onde Questão é relacionada com Situação:
class Situacao(models.Model):
    enunciado = models.TextField()
    certificado = models.ManyToManyField(Certificado)

    def __str__(self):
        return '{}...'.format(self.enunciado[:80])

    class Meta:
        verbose_name = "Situação"
        verbose_name_plural = "Situações"

E a variável certificado que é uma relação n pra n é basicamente como se fosse uma certa categoria do Quiz. Enfim, eu gostaria de adicionar no Model Questão várias alternativas: letra a, b, c, etc (sendo que isso eu já adicionaria por exemplo um booleano, indicando qual delas seria a correta). Como eu poderia fazer isso e adicionar as alternativas pela categoria Questão diretamente no Django Admin?
O que eu tinha feito antes era basicamente isso aqui:
class Alternativa(models.Model):
    questao = models.ForeignKey(Questao, on_delete=models.CASCADE)
    resposta = models.TextField()
    correta = models.BooleanField(default=False)

    def __str__(self):
        return self.resposta

    class Meta:
        verbose_name = "Alternativa"
        verbose_name_plural = "Alternativas"

Porém eu sempre tinha que adicionar uma certa alternativa e relacionar com a questão que eu tinha criado, e eu queria algo mais direto ao adicionar a questão mesmo.
Obrigado por qualquer ajuda e caso não tenha sido claro eu tento editar a questão.
--- Editado
Gostaria que ficasse algo parecido com isso:

Teria algo como adicionar essa questão, e eu poderia colocar A, B, C, D ou 1, 2, 3,4 sei lá, aí quando eu selecionasse isso eu adicionaria as opções das alternativas, qual seria marcado como correta e qual não. Entende? Assim eu não teria que adicionar as alternativas uma por uma e fazer uma ligação com a questão no painel.
Comment: A Idea do seu modelo de alternativa está correta. Parece que o problema consiste em definir a tela no admin. Você chegou a customizar o formulário do admin?
Comment: Não cheguei a fazer isso. Como faço? Na minha tela do admin eu só fiz a declaração das classes no admin.py e registrei, nada demais.
Comment: Da para vc simular a imagem da tela que vc prentende e postar na pergunta? pode ser um desenho mesmo.
Comment: Editei a questão e adicionei no final, Sidon. Se puder me ajudar eu agradeço. Obrigado! E desculpa a demora pra responder.
Answer: Olá,
Para fazer o que você gostaria de usar , deveria usar no models.py o modelchoicefield , e usar o modo de escolha com alternativas no forms.py e assim usar if se for letra correta e um else para as demais erradas.
Exemplo forms.py
class quizform(ModelForm)
     model = quiz
      if escolha == "C":
            print ('Acertou Mizeravi')
      else:
            print ('Errrrrrrou')

link como usar no models.py: https://docs.djangoproject.com/pt-br/2.1/ref/forms/fields/#modelchoicefield
Espero ter ajudado
E que a força esteja com você.


how to add static Cost: text before any item cost into listview item row

Question: i am making an app in which i am fetching json data into listview, but i don't know how to add $ symbol with price programmatically while getting data into listview using json parser, here i am placing my code:-
<code>     @Override
          protected ArrayList<HashMap<String, String>> doInBackground(String... params) {
                  HttpClient client = new DefaultHttpClient();
                    // Perform a GET request to a JSON list of all the videos by a specific user
                    HttpUriRequest request = new HttpGet(URL);
                    // Get the response that sends back
                    HttpResponse response = null;
                    try {
                        response = client.execute(request);
                    } catch (ClientProtocolException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    } catch (IOException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }
                    // Convert this response into a readable string
                    String jsonString = null;
                    try {
jsonString = StreamUtils.convertToString(response.getEntity().getContent());
                    } catch (IllegalStateException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    } catch (IOException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }
    // Create a JSON object that we can use from the String
                    JSONObject json = null;
                    try {
                        json = new JSONObject(jsonString);
                    } catch (JSONException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }

                           try{

                 JSONArray jsonArray = json.getJSONArray(KEY_CATEGORY);

   for(int i=0;i < jsonArray.length();i++){

    HashMap<String, String> map = new HashMap<String, String>();
         JSONObject jsonObject = jsonArray.getJSONObject(i);

                        map.put("id",  String.valueOf(i));
map.put(KEY_TITLE, jsonObject.getString(KEY_TITLE));
map.put(KEY_DESCRIPTION, jsonObject.getString(KEY_DESCRIPTION));
map.put(KEY_COST, jsonObject.getString(KEY_COST));
map.put(KEY_THUMB_URL, jsonObject.getString(KEY_THUMB_URL));

                    itemsList.add(map);

                  }
                    return itemsList;
            }catch(JSONException e)        {
                 Log.e("log_tag", "Error parsing data "+e.toString());
            }

                return null;

                }
</code>
JSON Data:-
<code>{
"pizza":[
{
    "title" : "Pizza Item 1",
    "description" : "Lorem ipsum dolor sit amet, consectetur adipisicing elit",
    "cost" : "10.00",
    "imageUri" : "http://www.pizzahut.com.au/images/menu/Pizza-Lge-BBQ_Meatlovers.png"
},
{
    "title" : "Pizza Item 2",
    "description" : "Lorem ipsum dolor sit amet, consectetur adipisicing elit",
    "cost" : "9.00",
    "imageUri" : "http://www.pizzahut.com.au/images/menu/Pizza-Lge-BBQ_Meatlovers.png"
}
</code>
.........
Answer: Just appending it in the Map value should work.
<code>map.put(KEY_COST, jsonObject.getString(KEY_COST)+"$");
</code>


open ports on a cisco/linksys wrt54g2 v1.5

Question: Im upgradeing my router from a netgear fvs318
one of the problems im running into is on the old net gear i have opend ports under the "Add Service " for our voip
<code>udp 69
tcp 80
tcp 2000
udp 22026-62025
</code>
but on the new linksys/cisco rotuer i don't see any option to just open a port i see port forwarding (which i dont want because i have more than one phone) and port triggering that i have no idea what that does.
does anyone know either how to allow open ports on this router or how to use port tiggering to allow my phones to work with the ports listed above?
Answer: Almost all VoIP boxes do not need any ports opened at all. They just make an outbound connection to the SIP gateway and keep that connection open. What model VoIP box do you have?
Comment: cisco 7960 voip phone
Comment: Who is your SIP Gateway? Are you VPNing it to your work or similar?
Answer: I am not sure I understand what you are asking, but here goes:
Port forwarding is for inbound traffic. If you have multiple phones, they cannot all be on the same inbound port. As far as outbound is concerned, it does not matter unless you are restricting outbound traffic, the wrt54g does not restrict outbound traffic by default.
If you only have a single public IP address, each port can have only a single destination via port forwarding. Pick an internal device / IP address to map it to.


Group objects in $\mathbf{Ab}$ and $\mathbf{Grp}$

Question: Aluffi suggests (II.10.4) proving that every abelian group has exactly one structure of group object in the category $\mathbf{Ab}$, and asks about what would be a group object in $\mathbf{Grp}$ (II.10.5).
So, let's assume that $\circ : G \times G \rightarrow G, \iota : G \rightarrow G, e : 1 \rightarrow G$ are the corresponding elements of some group object over $G \in \mathbf{Ab}$ (if they exist, but the existence is easy), and all the diagram commutativity requirements hold for them. Also let's explicitly mention they are morphisms in $\mathbf{Ab}$ which implies they are abelian group homomorphisms.
Previous exercise that I worked out suggests proving that if $(G, \cdot)$ is a group and $\circ : G \times G \rightarrow G$ is a group homomorphism such that $(G, \circ)$ is also a group, then $\circ$ and $\cdot$ coincide. It feels natural to piggyback on it and just prove that $(G, \circ)$ has a group structure with the inverse being $\iota$ and identity being the element chosen by $e$ (which we'll also call $e$), and then the uniqueness immediately follows (and, moreover, it follows that the group object over $G$ is $G$ itself, in a sense).
So let's just check the group structure:

$g_1 \circ g_2$ as a group operation on $G$ is well-defined and "typechecks", since $G \times G$ is just the cartesian product (with the right group structure on top) in $\mathbf{Ab}$.
$\forall g : G. e \circ g = g = g \circ e$ — holds, since the left-identity diagram requires that $\circ (e, g) = g$, and similarly for the right-identity.
$\forall g : G. \exists g' : G. g'g = gg' = e$ — satisfied by taking $g' = \iota(g)$ and using the commutativity of the diagrams involving $\iota$.
Associativity holds similarly.

All good. $(G, \circ)$ has a group structure, so it coincides with $(G, \cdot)$, so we're done.
Now let's get to $\mathbf{Grp}$. Basically the same argument as above should also hold, since I don't think I've used any abelianness, so the group object in $\mathbf{Grp}$ over $G$ coincides with $G$ itself. But I know that group objects in $\mathbf{Grp}$ are abelian groups too, so where am I mistaken?

I noticed this question has been asked a few times here, but I'm rather curious about any holes in my argument than just getting the proof done.
Comment: Google Eckmann-Hilton argument.
Comment: The exercise that I (try to) reduce the problem to is an an instance of that argument, isn't it?
Comment: Yes it is, and whatever proof you will come up with, it will be a variation on that argument.
Answer: The inverse map $\iota$ is now not just a function, but a morphism in the category $\mathbf{Grp}$.
We already know that if $g\cdot h$ is an object in $G$, then $(g\cdot h)^{-1} = h^{-1}\cdot g^{-1}$.  Because of your previous exercise (Eckmann-Hilton), this carries over to the group object: $\iota(g\circ h) = \iota(h)\circ \iota(g)$.
Now because $\iota$ is a group morphism, we also have $\iota(g\cdot h) = \iota(g)\cdot \iota(h)$. This additional property establishes that $\iota(g)\circ \iota(h) = \iota(gh) = \iota(h)\circ \iota(g)$, which proves commutativity.
Your proof was entirely correct; you just didn't use the fact that $\iota$ is a group morphism, which means that (because the multiplication structure is the same) the group object, and hence the original group, must be commutative. (Noncommutative groups don't have corresponding group objects because their inversion operator fails to be a homomorphism of groups.)
Comment: I believe group objects only exist for commutative groups: Group objects in $\mathbf{Grp}$ are commutative (a group is commutative just if inversion is a group homomorphism), and by Eckmann-Hilton, $\cdot$ and $\circ$ coincide, so the original group $G$ itself must be commutative.
Comment: That's the last part that I have trouble understanding. Let's say I have $g_1, g_2 \in G$. What happens to $g_1 \circ g_2$ if $g_1 g_2 \neq g_2 g_1$? Or does this mean that group objects only exist for those groups that are commutative?
Comment: @0xd34df00d: Perhaps the observation $(ab)^{-1}=b^{-1}a^{-1}$ will clarify why inversion is not a morphism.


About setwise convergence on open sets of nearest neighbor algorithm.

Question: Let $(\Omega,\mathcal{F},\mathbb{P})$ be a probability space and $(\mathcal{X},d)$ be a complete, separable, locally compact metric space. Suppose that $X,X_1,X_2,X_3,... : \Omega\to\mathcal{X}$ are $\mathbb{P}$-i.i.d. random variables.
Define: $$\forall m\in\mathbb{N}, \pi_m: \mathcal{X}\times\mathcal{X}^m\to\{1,...,m\}, (x,x_1,...,x_m)\mapsto \min\left(\operatorname{argmin}_{k\in\{1,...,m\}}\left(d\left(x,x_1\right),...,d\left(x,x_m\right)\right)\right).$$
Define:
$$\forall m\in\mathbb{N}, Z_m:\Omega\to\mathcal{X}, \omega\mapsto X_{\pi_m\left((X(\omega),X_1(\omega),...,X_m(\omega)\right)}(\omega).$$
If $A$ is a open set of $(\mathcal{X},d)$, is it true that:
$$\limsup_{m\to+\infty}\mathbb{P}_{Z_m}(A)\le\mathbb{P}_{X}(A)?$$

Edit 1: or maybe that there exists a constant $C>0$ independent of $A$ such that:
  $$\limsup_{m\to+\infty}\mathbb{P}_{Z_m}(A)\le C\cdot \mathbb{P}_{X}(A)?$$

If it is false in general, what if we add the hypothesis that $\mathcal{X}=\mathbb{R}^n$, $d$ is the Euclidean distance and $\mathbb{P}_X$ is absolutely continuous w.r.t. Lebesgue measure in $\mathbb{R}^n$?

Edit 2: in this last case, we have that if $B$ is a ball of $\mathbb{R}^n$, then $\mathbb{P}_X(\partial B)=0$ so, since $\mathbb{P}_{Z_m}\to \mathbb{P}_{X}$ in distribution (as explained below by WoolierThanThou), we have that $\mathbb{P}_{Z_m}(B)\to\mathbb{P}_{X}(B), m\to \infty$. Now, since by Besicovitch covering theorem there exist an universal constant $C_n\in\mathbb{N}$ such that every open subset $A$ is the union of at most $C_n$ open sets $A_1,...,A_{C_n}$ each of them is a disjoint countable union of open balls, say $A_i = \cup_{j\in I_i} B_{i,j}$, we have that:
  $$\mathbb{P}_{Z_m}(A)\le \sum_{i=1}^{C_n}\mathbb{P}_{Z_m}(A_i)= \sum_{i=1}^{C_n}\sum_{j\in I_i}\mathbb{P}_{Z_m}(B_{i,j}) = (*)$$
  Now, if only we could exchange the limit and the series, we obtain that
  $$(*)\to \sum_{i=1}^{C_n}\sum_{j\in I_i}\mathbb{P}_{X}(B_{i,j})= \sum_{i=1}^{C_n}\mathbb{P}_{X}(A_i)\le \sum_{i=1}^{C_n}\mathbb{P}_{X}(A) = C_n \mathbb{P}_{X}(A) $$
  Can anyone see a reason why could we exchange the limit an the series?
Comment: hey! hope you're doing well. do you still care about this problem?
Answer: Well, $Z_m$ converges to $X$ in probability! For any, $\varepsilon>0,$ we have, by independence and identical distribution,
$\mathbb{P}(d(Z_m,X)\geq \varepsilon)=\mathbb{P}( \cap_{k=1}^m (d(X_k,X)\geq \varepsilon))=\mathbb{P}( d(X_1,X)\geq \varepsilon)^m$,
which goes to $0$, so long as we can show that $\mathbb{P}( d(X_1,X)\geq \varepsilon)\neq 1$. Clearly, the universe is broken if this isn't true, but you can note that if $(x_n)_{n\in \mathbb{N}}$ is a dense, countable subset of $\mathcal{X}$, then $\mathcal{X}=\cup_{n=1}^{\infty}B(x_n,\frac{\varepsilon}{2}),$ and hence, there must be some $n_0\in\mathbb{N}$ such that $\mathbb{P}(X\in B(x_{n_0},\frac{\varepsilon}{2}))\neq 0.$ Hence, by the fact that they're i.i.d., $\mathbb{P}(X,X_1\in B(x_{n_0},\frac{\varepsilon}{2}))\neq 0$, establishing the desired.
Of course, one might ask, does convergen in probability still imply weak convergence of the underlying measures? Well, assume $Y_n\to Y$ in probability with $Y_n$ and $Y$ $\mathcal{X}$-valued and fix $C\subseteq \mathcal{X}$ closed.
 Then, for any $\varepsilon>0$, denote $C_{\varepsilon}=\cup_{x\in C} B(x,\varepsilon)$
$$\mathbb{P}(Y_n\in C)\leq \mathbb{P}(d(Y_n,Y)\geq \varepsilon)+\mathbb{P}(Y\in C_{\varepsilon})$$
By continuity of measures (and the fact that $C$ is closed), we in particular find that
$$\limsup_{n\to\infty}\mathbb{P}(Y_n\in C)\leq \limsup_{n\to\infty} \mathbb{P}(Y\in C_{1/n})=\mathbb{P}(Y\in C),$$
which is equivalent to weak convergence of distributions in a complete, separable space.
Adding these things up, we get for $A\subseteq \mathcal{X}$ open, by weak convergence, that $\liminf_{m\to\infty} \mathbb{P}(Z_m\in A)\geq \mathbb{P}(X\in A)$, so your hypothesis is only true if $\lim_{m\to\infty}\mathbb{P}(Z_m\in A)=\mathbb{P}(X\in A)$.
Comment: I agree :) but I can't show that it holds true in general that $\lim_{m\to\infty}\mathbb{P}(Z_m\in A) = \mathbb{P}(X\in A)$
Comment: I haven't put it in the abstract setting since I'm aware of the fact that only requiring $Z_m \to X$ in distribution wouldn't imply in general that $\mathbb{P}(Z_m\in A)\to \mathbb{P}(X\in A)$ for $A$ open... so I hoped that maybe some hidden property of $Z_m$ may guarantee that fact
Comment: @WoolierThanThou see my answer below.
Answer: Here's a proof for $\mathbb{R}^n$ with Euclidean distance and Lebesgue measure restricted to disk of radius $\frac{1}{\sqrt{\pi}}$.
The idea of the proof (specifically to contrast the flawed proof above) is to use the symmetry/averaging in $x$. In fact, averaging in $x$ allows for a simpler expression for $P(Z_m \in A)$.
Note $P(Z_m \in A) = \int_{x \in \Omega} \int_{x_1,\dots,x_m \in \Omega} 1_{\text{closest $x_i$ to $x$ is in $A$}} = \int_{x \in \Omega} m\int_{x_1,\dots,x_m \in \Omega} 1_{\text{$x_1$ is closest to $x$ and $x_1 \in A$}} = \int_{x \in \Omega} m \int_{x_1 \in A} \mu(B_{d(x,x_1)}(x)^c)^{m-1}d\mu(x_1)d\mu(x) = m\int_{x_1 \in A} \int_{x \in \Omega} (1-|x-x_1|^2)^{m-1}d\mu(x)d\mu(x_1) \le m\int_{x_1 \in A}\int_0^{2\pi}\int_0^1 (1-r^2)^{m-1}r dr d\theta d\mu(x_1) = \mu(A)$.

The following answer is (seriously) flawed. It proves that, in some metric spaces, there is some $x$ so that if you always do nearest neighbor algorithm relative to $x$, the $Z^x_m$ measure of a set $A$ can be arbitrarily (multiplicatively) larger than the $X$-measure of $A$. However, as Bob pointed out, in this problem, you do nearest neighbor algorithm relative to an $X$-randomly chosen point of $\mathcal{X}$.

All of it is false.
Let $\mathcal{X} = \{0 \le |z| < 1\} \subseteq \mathbb{R}^2$, $d$ the standard Euclidean metric, and $P$ pushforward to the Lebesgue measure (i.e. we choose points randomly). Let $A_N = \cup_{k \ge N} \{\frac{1}{2^{10^{2k+1}}} < |z| < \frac{1}{2^{10^{2k}}}\}$. Clearly $A_N$ is open for each $N$. Also, $\mu(A_N) \to 0$ as $N \to \infty$. But, for each $N \ge 1$, we have that $\limsup_{m \to \infty} P_{Z_m}(A) = 1$. Indeed, with $x$ the origin, $$P(|Z^x_m| \in [\frac{1}{2^{10^{2k+1}}},\frac{1}{2^{10^{2k}}}]) \ge 1-P(|Z^x_m| < \frac{1}{2^{10^{2k+1}}})-P(|Z^x_m| > \frac{1}{2^{10^{2k}}})$$ $$\ge 1-m\frac{\pi}{(2^{10^{2k+1}})^2}-(1-\frac{\pi}{(2^{10^{2k}})^2})^m,$$ so we can take $m = 2^{3\cdot 10^{2k}}$ to see that $P(Z^x_m)$ is exponentially close to $1$. $\square$
Comment: Thx for the counterexample! I would just edit for the sake of completeness that you are assuming e.g. that $\mathbb{P}_X$ is something like the Lebesgue measure on the unit ball in $\mathbb{R}^2$ in this counterexample
Comment: Maybe I'm taking a blunder... but isn't this a counterexample for a neighbor function with $x$ as a fixed point? In this question $x$ isn't fixed but varies according with $X$ (see the definition of $Z_m$ ). So, assuming that we are using the lebesgue measure and disintegrating, it seems that all works fine except for $X=x$ where $x=0$, which is a probability zero event that vanishes in the integration...
Comment: @Bob hey, I just woke up. Thanks for the nice problem. Regarding your second comment, I was confused about this in both of your questions. $\pi^x_m$ is supposed to have $m$ inputs, but in both of your problems it has $m+1$. [EDIT: ah, this problem it does have $m+1$ inputs. I think your other problem has a typo]
Comment: You are perfectly right... I'm a victim of the copy/paste paradigm :)
Comment: @Bob Give me some time to reread this problem. I might ask to clarify the meaning of this problem. But I think you are right that I misinterpreted this problem.
Comment: Yeah, so the problem here is really, I guess, that $X_j$ doesn't have the same distribution as $X$ (which is degenerate).


Maze solving in C

Question: I'm working on a maze solving algorithm in C but having some output not expected, here's my code:
#include <stdio.h>

// Maze size
#define N 6

//define boolean
#ifndef MYBOOLEAN_H
#define MYBOOLEAN_H

#define false 0
#define true 1
typedef int bool;

#endif

int endX = 5;
int endY = 4;
int startX = 0;
int startY = 0;
//function prototype
bool solveMazeUtil(int maze[N][N], int x, int y, int sol[N][N]);

int main()
{
    int maze[N][N] = {{1,0,0,0,0,0},
                      {1,1,1,1,1,0},
                      {0,1,0,0,0,0},
                      {0,1,0,0,0,0},
                      {1,1,1,0,1,1},
                      {0,0,1,1,1,0}};

    mazeGo(maze);
    return 0;
}

//print the solution
void printSolution(int sol[N][N])
{
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < N; j++)
            printf(" %d ", sol[i][j]);
        printf("\n");
    }
}

//checking if in correct path
bool isSafe(int maze[N][N], int x, int y)
{
    // if not, return false
    if (x >= 0 && x < N && y >= 0 && y < N && maze[x][y] == 1)
        return true;
    else
    return false;
}

bool mazeGo(int maze[N][N])
{
    int sol[N][N] = { { 0, 0, 0, 0, 0, 0 },
                      { 0, 0, 0, 0, 0, 0 },
                      { 0, 0, 0, 0, 0, 0 },
                      { 0, 0, 0, 0, 0, 0 },
                      { 0, 0, 0, 0, 0, 0 },
                      { 0, 0, 0, 0, 0, 0 }};

    if (solveMazeUtil(maze, startX, startY, sol) == false) {
        printf("No solution");
        return false;
    }

    printSolution(sol);
    return true;
}

//actual maze solving
bool solveMazeUtil(int maze[N][N], int x, int y, int sol[N][N])
{
    // if (x, y) is goal return true
    if (x == endX && y == endY) {
        sol[x][y] = 1;
        return true;
    }

    // Check if maze[x][y] is valid
    if (isSafe(maze, x, y) == true) {
        // mark x, y
        sol[x][y] = 1;

        //try move right
        if (solveMazeUtil(maze, x + 1, y, sol) == true)
            return true;
        //try move down
        if (solveMazeUtil(maze, x, y + 1, sol) == true)
            return true;
        //try move left
        if (solveMazeUtil(maze, x - 1, y, sol) == true)
            return true;
        //try move up
        if (solveMazeUtil(maze, x, y - 1, sol) == true)
            return true;
        // If none of the above movements work then unmark x, y
        else
        sol[x][y] = 0;
        return false;
    }

    return false;
}

I am expecting an output like this:
 1  0  0  0  0  0
 1  1  0  0  0  0
 0  1  0  0  0  0
 0  1  0  0  0  0
 0  1  1  0  1  1
 0  0  1  1  1  0

But the result is:
 1  0  0  0  0  0
 1  1  0  0  0  0
 0  1  0  0  0  0
 0  1  0  0  0  0
 0  1  1  0  0  0
 0  0  1  1  1  0

And if I set the endX and endY (the position of goal) to (4,4), it works:
 1  0  0  0  0  0
 1  1  0  0  0  0
 0  1  0  0  0  0
 0  1  0  0  0  0
 0  1  1  0  1  0
 0  0  1  1  1  0

But if I set endX to 0 and endY to 1 the program run but print nothing.
May I ask that where have I made the mistake?
Answer: Below is a corrected version of your code and it gives the expected output. Just a few lines have changed. You can see them with a diff utility. The main idea is that once a spot is occupied, it is no longer safe, so you should keep track of occupied spots and restore them if needed. Also, endY and andX  must have been swapped.
#include <stdio.h>

// Maze size
#define N 6

//define boolean
#ifndef MYBOOLEAN_H
#define MYBOOLEAN_H

#define false 0
#define true 1
typedef int bool;

#endif

int endY = 5;
int endX = 4;
int startX = 0;
int startY = 0;
//function prototype
bool solveMazeUtil(int maze[N][N], int x, int y, int sol[N][N]);

int main()
{
    int maze[N][N] = {{1,0,0,0,0,0},
                      {1,1,1,1,1,0},
                      {0,1,0,0,0,0},
                      {0,1,0,0,0,0},
                      {1,1,1,0,1,1},
                      {0,0,1,1,1,0}};

    mazeGo(maze);
    return 0;
}

//print the solution
void printSolution(int sol[N][N])
{
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < N; j++)
            printf(" %d ", sol[i][j]);
        printf("\n");
    }
}

//checking if in correct path
bool isSafe(int maze[N][N], int x, int y)
{
    // if not, return false
    if (x >= 0 && x < N && y >= 0 && y < N && maze[x][y] == 1)
        return true;
    else
    return false;
}

bool mazeGo(int maze[N][N])
{
    int sol[N][N] = { { 0, 0, 0, 0, 0, 0 },
                      { 0, 0, 0, 0, 0, 0 },
                      { 0, 0, 0, 0, 0, 0 },
                      { 0, 0, 0, 0, 0, 0 },
                      { 0, 0, 0, 0, 0, 0 },
                      { 0, 0, 0, 0, 0, 0 }};

    if (solveMazeUtil(maze, startX, startY, sol) == false) {
        printf("No solution");
        return false;
    }

    printSolution(sol);
    return true;
}

//actual maze solving
bool solveMazeUtil(int maze[N][N], int x, int y, int sol[N][N])
{
    // if (x, y) is goal return true
    if (x == endX && y == endY) {
        sol[x][y] = 1;
        return true;
    }

    // Check if maze[x][y] is valid
    if (isSafe(maze, x, y) == true) {
        // mark x, y
        sol[x][y] = 1;
        maze[x][y] = 0;
        //try move right
        if (solveMazeUtil(maze, x + 1, y, sol) == true)
            return true;
        //try move down
        if (solveMazeUtil(maze, x, y + 1, sol) == true)
            return true;
        //try move left
        if (solveMazeUtil(maze, x - 1, y, sol) == true)
            return true;
        //try move up
        if (solveMazeUtil(maze, x, y - 1, sol) == true)
            return true;
        // If none of the above movements work then unmark x, y
        sol[x][y] = 0;
        maze[x][y] = 1;
    }
    return false;
}

Answer: The other answer probably works, but two quick things with this part of the code:
        //try move right
        if (solveMazeUtil(maze, x + 1, y, sol) == true)
            return true;
        //try move down
        if (solveMazeUtil(maze, x, y + 1, sol) == true)
            return true;
        //try move left
        if (solveMazeUtil(maze, x - 1, y, sol) == true)
            return true;
        //try move up
        if (solveMazeUtil(maze, x, y - 1, sol) == true)
            return true;
        // If none of the above movements work then unmark x, y
        else
        sol[x][y] = 0;
        return false;

First, the else should have brackets since it is a multiline statement. There's another return false below it, so it's redundant without brackets.
Second, the solveMazeUtil() function gets called, then returned before checking the if statement. So for example, you go from (0,0) to (1,0) to (2,0) but there's no 1 at (2,0), then back up and go back to (1,1).
Comment: The `else` does not require brackets because it is not required itself.  If control enters the `if` branch of that `if` / `else` then it executes a `return` statement, so *neither* the assignment to `sol[x][y]` nor the subsequent `return false` is executed in that case, brackets notwithstanding.  With that said, I would account it better code style to put the body of the `else` ***and*** the bodies of all the `if`s in brackets.

Maze solving in C


What's the best technology for passing a stop argument to a service from a .NET-Application by Inter-process Communication?

Question: So I plan to have a button on my GUI of my .NET Application which controls the service. I wanna stop the service when a button is pressed. I want to achieve this with an argument passed between the VB.NET application and the service.
As far as I know, there are 4 available technologies in inter-process communication:

.NET Remoting
WCF Anonymous Pipes
WCF Named Pipes
Memory Mapped Files

What technology is the best one to implement those functionalities?
As this is my first approach with IPC I thank you in advance for in-depth answers :)
Comment: Why so complicated? https://learn.microsoft.com/en-us/dotnet/api/system.serviceprocess.servicecontroller.stop?view=netframework-4.8
Comment: We can't answer "best" questions on SO without an accurate definition of what "best" is to you. You should also bear in mind that after you've defined "best" it may clearly outline that any answers would be subjective, and the questions would be closed as off topic.
Comment: There are many different ways of achieving IPC, even two programs writing to a file in a shared directory and each reading the file, is a form of IPC. Are your app and service always located on the same PC?
Comment: Does this answer your question? [What is the best choice for .NET inter-process communication?](https://stackoverflow.com/questions/84855/what-is-the-best-choice-for-net-inter-process-communication)
Comment: Yes, they are always located on the same PC.
Comment: I actually think after all I've read, Anonymous Pipes might be the best choice, because my programs only act locally and are stored on the local machine. Performance- and workwise I think it's the best one, do you agree ?
Comment: What's wrong with @MatSnow suggestions?  Why over complicate it?
Comment: Actually forgot about it. Might be the best choice in this case. @Chris Dunaway
Answer: According to @MatSnow 's comment under the original question the Service Controller might be the best choice for this problem.
ServiceController Class Stop Method


Can protobuf-net deserialize protected/friend fields in Silverlight?

Question: I have a complex object hierarchy that I've been wrestling with to get passed across the wire in its entirety when using Silverlight with WCF. I've tried DataContractSerializer to death and the main problem is that I'm trying to use Dictionary, with multiple cyclical references and just couldn't get it to work.
I've switched to look at protobuf-net thinking that it might be better all round to use a binary format anyway. I was hoping to be able to just do a lot of find and replace to add the ProtoMember attributes on to the properties. However a lot of the properties that were being serialized with DataMember attributes are declared as Friend (vb.net). I've found that protobuf-net throws an error when deserializing, saying
Attempt by method <blah> to access field <fieldname> failed.

I've found that setting the field to protected causes the same error, and the only way around it is to set the field to public - which is something I don't want to do. Is it possible to do this with a protected setter or similar on the property the field backs? While this would be a pain (many fields/properties and classes) it would at least solve the problem. The serialization on the back end works fine.
If this is not possible, can anyone suggest how I can get a complex object hierarchy with cyclical references that include multiple dictionaries across the wire in their complete form? I realise Silverlight adds a few constraints to this process, but hopefully someone has already succeeded with this.
Note this is Silverlight 5
Answer: In Silverlight: no; the runtime has a higher level of paranoia, and you just can't get at the non-public parts of other types. Even the Silverlight DataContractSerializer page has the caveat:

You can serialize fields and properties, provided they are publicly accessible.

My understanding is that this can't be avoided on Silverlight.
Comment: Thanks for the quick response Marc, and that may have been what I was missing from the start. So just to be completely clear, the only way I'll be able to serialize something in .Net and deserialize it in Silverlight - whether using protobuff-net, DataContractSerializer or another serializer - without writing a lot of custom Onserialize/OnDeserialize type code is if every property has a public Setter (or if it's a field and not a property, that it's public). Thanks.
Comment: Also Marc, I've noticed the note on that same page you link to that says the following:

"You can apply the DataMemberAttribute to both private and public members. "

Hmmm. and to add to the confusion, there's a comment at the bottom:

"You can't serialize private variables using Silverlight 3.0 even though the documentation says you can :( "
Doesn't this conflict with the line you quote?
Comment: @hitch maybe, but they are both from the same MSDN page - so take that up with MSDN ;p Of course, while you can indeed **apply** the attribute to both public/private members, it is less clear whether it will *work* on both ;p That is possibly splitting hairs, but last time I checked DataContractSerializer on SL was public only. It is *possible* that has changed (I'd be interested if it has).
Comment: Thanks again Marc - sadly I'm more inclined to believe you than MSDN. I might do a bit of mass find and replace to make everything public just to test it out, but it looks like it could be the overall problem.
Comment: @hitch can you not try with a `[DataContract] public class Foo { [DataMember(Order=1)] public string Bar {get;set;} }` before you start hacking it all to pieces?
Comment: I was able to shelve it all in TFS then do a major Find & Replace on all private/friend/protected and change to public (purely for testing). I (obviously) no longer get the access errors, but am still having issues with the serialization/deserialization - but these problems exist if I serialize/deserialize in all .Net or serialize in .Net and deserialize in Silverlight. I use the wcf tracing to log the messages when working with DataContractSerializer, and it appeared everything was serializing correctly. I might switch back to using it with everything public and see what I find.


How can I execute native queries in my Model?

Question: I have a requirement to define composite foreign keys in my Model.Looks it is not supported currently. So, i try to run native queries in my model.
I have two tables(vwAlarm, vwYfUserToSiteMappings) Both has two columns.

CompanyId,SiteCode

I want to return single row, by joining both columns from two tables.
Here is my Model;
class Alarm extends Model
{

    protected $table = 'vwAlarm';
    protected $primaryKey = 'AlarmId';

..

 public function Site()
    {
        $rec = \DB::table('vwAlarm')
            ->join('vwYfUserToSiteMappings', 'vwAlarm.SiteCode', '=', 'vwYfUserToSiteMappings.SiteCode')
            ->join('vwYfUserToSiteMappings','vwAlarm.CompanyId', '=', 'vwYfUserToSiteMappings.CompanyId')
            ->first();

        return $rec;
}

Im getting
 QueryException
SQLSTATE[42000]: [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]The objects "vwYfUserToSiteMappings" and "vwYfUserToSiteMappings" in the FROM clause have the same exposed names. Use correlation names to distinguish them. (SQL: select top 1 * from [vwAlarm] inner join [vwYfUserToSiteMappings] on [vwAlarm].[SiteCode] = [vwYfUserToSiteMappings].[SiteCode] inner join [vwYfUserToSiteMappings] on [vwAlarm].[CompanyId] = [vwYfUserToSiteMappings].[CompanyId])

How can I correct my query?
Comment: If you have written Raw SQL Query somewhere. you can directly execute it using `DB:raw()`. Read More https://laravel.com/docs/5.4/queries#raw-expressions
Answer: You should try this:
 $rec = \DB::table('vwAlarm')
        ->join('vwYfUserToSiteMappings AS vwSiteCode', 'vwSiteCode.SiteCode', '=', 'vwAlarm.SiteCode')
        ->join('vwYfUserToSiteMappings AS vwCompanyId','vwCompanyId.CompanyId', '=', 'vwAlarm.CompanyId')
        ->first();

Comment: Thanks it works. . But the answer returns non relavant Site details. How can I return relavent Site entry for that Alarm model. I mean equivalent for //$this->belongsTo//
Comment: I mean returned SIte details are wrong when compare with AlarmTables primaryKey(AlarmId)
Comment: @Ratha Please give me more details
Comment: If you see my Alarm model, I have defined primaryKey as "AlarmId". I have two tables. vwAlarm and vwYfUserToSiteMappings, I'll pass AlarmId from My webform, I expect to return details belongs to that AlarmId. Some details are in vwAlarm table some are in vwYfUserToSiteMappings table. But both table have SiteCode,ComapnyId columns common. SO I try to join them
Comment: @Ratha: Ok let me check it
Answer: Set alias name for table name like below
$rec = \DB::table('vwAlarm')
            ->join('vwYfUserToSiteMappings AS vw1', 'vwAlarm.SiteCode', '=', 'vw1.SiteCode')
            ->join('vwYfUserToSiteMappings AS vw2','vwAlarm.CompanyId', '=', 'vw2.CompanyId')
            ->first();

Comment: Thanks works . But the answer returns non relavant Site details. How can I return relavent Site entry for that Alarm model. I mean equivalent for  //$this->belongsTo//
Comment: I mean returned SIte details are wrong when compare with AlarmTables primaryKey(AlarmId)
Comment: first of all try to build native mysql query and run it in mysql database console and check that did you getting desired result or not .


Understanding the Rao-Blackwell Theorem

Question: I've been reading up a lot on the practical applications of the Rao-Blackwell theorem. I do understand how the Bias and Variance and MSE aspects of the theorem fall in place (i.e. the mathematical proof makes sense), but I do not understand how certain practical applications of the theorem work, based on my own university's materials and highly-recommended third-party textbooks.
These are some of the applications I came across:
Application 1
Let $X = \{X_1, X_2,\ldots,X_n\}$ be a random sample from a distribution with mean $µ$ and variance $σ^2$. Suppose that $S(X) = \sum_iX_i$ is a sufficient statistic for $µ$. We consider $\hat\mu_1 = X_1$ as an initial estimator of $µ$ and seek a better one.
The Rao–Blackwell theorem states that the following estimator is better:
$$\hat\mu^b_2 = \mathbb E(\hat\mu^b_1 | S(X)) = \mathbb E[X_1 | S(X)]$$
This is equal to:
\begin{align*}
\mathbb E[X_1 | S(X)] &= 1/n \,\sum_i \mathbb  E[X1 | S(X)]\\
             &= 1/n \,\sum_i\mathbb  E[(Xi | S(X)]\\
             &= 1/n\, \mathbb  E[\sum_iX_i | S(X)]\\
             &= 1/n\, \mathbb  E[\sum_iX_i | ∑_iX_i]\\
             &= 1/n \sum_i X_i\\
             &= \bar X_n\\
\end{align*}
Note: all the $\sum_iX_i$ figures above refer to a sum over $i$ from $i=1$ to $i=n$.
So now my question is: given we had to be abstract here by not actually calculating conditional distribution probabilities, we had to solve the question above in a very, well, abstract way. First of all, how is it logically possible to equate $\mathbb E[X_1 | S(X)] = 1/n ∑_i \mathbb E[X_1 | S(X)]$? And is it okay to switch $X_1$ with $X_i$, because $X_1$ is a variable, while $X_i$ is sort of a range of variables?
Application 2
Let $X_1,\, X_2$ be i.i.d. random variables of distribution $N(θ,1)$. We have the statistic $\bar{X} = (X_1 + X_2)/2$. Now we want to try and condition our statistic on the non-sufficient statistic $X_1$ to prove we don't get a sufficient statistic in the end. So:
\begin{align*}
X^* &= \mathbb E[\bar X| X_1]\\
   &= (1/2)\mathbb E(X_1 | X_1) + (1/2)\mathbb E(X_2 | X_1)\\
   &= (1/2)(X_1) + (1/2)(θ)
\end{align*}
So they successfully proved $X^*$ is not sufficient. But how did $(1/2)\mathbb E(X_1 | X_1)$ equal $X_1$? Shouldn't it be $θ$?
Application 3
Let X = {X1, X2, ..., Xn} be a random sample from the Bernoulli(π) distribution. We now use the Rao–Blackwell theorem to find an estimator of π which is an improvement on X1.
So we already know ∑X is a sufficient statistic for π. Thus, we are trying to find E(X1 | ∑X). BUT FIRST, consider:
∑E(Xj | ∑Xi) = E(∑Xj | ∑Xi) = E(∑Xj | ∑Xi) = ∑Xi = nx̄
And ∑E(Xj | ∑Xi) = nE(X1 | ∑Xi)
So E(X1 | ∑Xi) = x̄
And like this, they have proved x̄ is a better estimator than just X1. But in the first line, when they switched ∑E(Xj | ∑Xi) with E(∑Xj | ∑Xi), are they talking about switching to E(∑(Xj | ∑Xi)), or E((∑Xj) | ∑Xi)? And is is true that we can substitute ∑E(Xj) = nE(X1)?
So that's about it. Th example of Rao-Blackwellization in Wikipedia and other sources seems to make sense. But if anybody has any idea of how to solve these (might-be-very-silly!) questions, then I would greatly appreciate it.
Comment: There is no such thing as a random variable $X_j|\sum_i X_i$. The conditioning sign can only be used for distributions (and related objects such as expectations). See https://stats.stackexchange.com/a/507250/7224
Comment: Related: https://stats.stackexchange.com/q/374989/119261.
Comment: As I wrote in my previous comment and in the answer I put a link to, $X_j$ is a random variable, which enjoys a conditional distribution given $\sum_i X_i$ and hence whose conditional expectation $\mathbb E[X_j|\sum_i X_i]$ can be considered in a mathematically rigorous manner. (I do not understand why @jld deleted his quite detailed and helpful answer.)
Comment: Hi @Xi'an - yes, X* is indeed not an estimator. But as to the Xj|∑iXi term, I don't fully understand why it is not a random variable - so is any term X|Y not a random variable? Of course, if you're right, then do you have any idea why they were trying to take the expectation of the Xj|∑iXi term?
Comment: @Xi'an, first of all thank you for editing my post. Second of all, so is evaluating ∑E(Xj | ∑Xi) mathematically correct?
Answer: $\newcommand{\E}{\operatorname{E}}$In your application 1, adding more details gives
$$
\E[X_1\mid S(X)] = \frac 1n \cdot n \cdot \E[X_1\mid S(X)] = \frac 1n \sum_{i=1}^n \E[X_1\mid S(X)].
$$
Now since the $X_i$ are an iid sample we have $\E[X_1\mid S(X)] = \E[X_2\mid S(X)] = \dots = \E[X_n\mid S(X)]$ (i.e. it didn't matter that we started with $X_1$. We could have started with any of the $X_i$ so effectively this is a relabeling and iid samples aren't affected by relabeling) so we replace the $i$th $\E[X_1\mid S(X)]$ with $\E[X_i\mid S(X)]$ to get
$$
\E[X_1\mid S(X)] = \frac 1n \sum_{i=1}^n \E[X_i\mid S(X)].
$$
Then the linearity of expectation gives us
$$
\frac 1n \sum_{i=1}^n \E[X_i\mid S(X)] = \E[\bar X_n \mid S(X)] = \bar X_n
$$
since $S(X) = \bar X_n$ (more formally, $\bar X_n$ is measurable with respect to the $\sigma$-algebra generated by $S(X)$ so no "averaging" happens). This shows that the function $\E[X_1\mid S(X)]$ was actually $\bar X_n$ all along.

For application 2 it's the same idea in that there's no "averaging" in $\E[X_1\mid X_1]$, meaning that $\E[X_1\mid X_1]$ is just the function $X_1$.

For application 3,
$$
\sum_{j=1}^n \E\left[X_j \mid \sum_{i=1}^n X_i\right] = \E\left[\sum_{j=1}^n X_j \mid \sum_{i=1}^n X_i\right]
$$
by linearity. But $\sum_j X_j =\sum_i X_i$ so these are the same function and again there's no "averaging" so
$$
\sum_{j=1}^n \E\left[X_j \mid \sum_{i=1}^n X_i\right] = n \bar X_n.
$$

Overall it looks like the common thread here is understanding when $\E[X\mid Y] = X$ so I'd recommend reviewing the relevant properties of conditional expectation. This property is sometimes called pulling out known factors. Here's one example of a proof of it with the discrete case. It's also important to remember that $\E[X\mid Y]$ is a function, not a number, so e.g. $\E[X_1\mid X_1]$ is still a random variable.
For a bit of a sense of why $\E[X\mid X]=X$, i.e. no reduction happens, conditional expectation takes a random variable (or more generally a $\sigma$-algebra) and produces a new random variable (that is unique with probability one) that is simpler in that it has the same "local averages" as the original variable but also doesn't change too rapidly (more technically it has sufficiently simple preimages to be measurable). In $\E[X\mid X]$ we have that $X$ has the same local averages as $X$ and also has the same preimages so $\E[X\mid X]=X$. Here's a resource for a more rigorous treatment and the wikipedia article on conditional expectation has a lot of the terms and definitions.
Comment: @Xi'an Thank you for the comments! I've restored the answer
Comment: In Application 1 and Application 3, it is relevant to note that $S(X)$ is invariant under permutations. There is no such invariance in Application 2, which means the two parts of the conditional expectation differ.
Comment: @Academic005 glad this helps, thanks!
Comment: Hi @jld, thank you so much for the well-written answers. Can't be clearer than this!

Understanding the Rao-Blackwell Theorem


Continuous operators

Question: We have that $T:E\rightarrow \mathbb{R}$ is linear where $E$ is a normed space  we have that $\ker T=\{x\in E, Tx=0\}=T^{-1}(\{0\})$ if we suppose that $\ker T$ is closed, as $\{0\}$ is closed can we conclude that $T$ is continuous  ?
Answer: Suppose $T$ is not continuous. So $T$ is not bounded. i.e. $\exists$ a sequence $x_n$ such that $T(x_n) \to \infty$ as $n\to \infty$. Let $a\notin \ker T$. Then defining $$x_n' = a - \frac{T(a)}{T(x_n)}x_n ,$$ it is clear that $T(x_n') = 0$ and so $x_n'\in \ker T$. Also $x_n' \to a \notin \ker T.$ So $\ker T$ is not closed.  Hence $\ker T$ closed implies that $T$ is continuous.
Comment: Thank you but is my proof is correct ?
Comment: @Vrouvrou No, your argument shows $T$ continuous implies kernel closed, but the reverse is not always true for all operators, but it is for functionals.
Comment: But we suppose that $\ker T$ is closed , the inverse image of the closed set $\{0\}$ is closed @HennoBrandsma
Comment: @HennoBrandsma and in this case $T$ is a functional no ?
Comment: @Vrouvrou yes, so we need the extra argument that we both gave. You cannot conclude in general that if $\ker{T}$ is closed, then $T$ is continuous.
Comment: @HennoBrandsma what is the extra argument ?
Comment: @Vrouvrou see my answer, or the answer above, which are essentially the same.
Comment: so my answer is not sufficient @HennoBrandsma
Comment: @HennoBrandsma can you give me an example of $T:E\rightarrow R$ not continious but $\ker T$ is closed with $E$ a normed space
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/40282/discussion-between-henno-brandsma-and-vrouvrou).
Comment: you are not in the descussion @HennoBrandsma
Comment: @HennoBrandsma are you there please
Comment: @HennoBrandsma is m proof schow that $T$ is continuous on $0$
Answer: We can. Suppose $T$ is not continuous, then $T$ is not bounded, so there is some sequence $(x_n)$ in $E$ such that $T(x_n) \rightarrow \infty$ as $ n \rightarrow \infty$. We can assume WLOG that all $T(x_n) \neq 0$.
We surely have some $p \notin \ker{T}$ (otherwise $T \equiv 0$), and so we can define $y_n = p - \frac{T(p)}{T(x_n)}x_n$, where the fraction is a well-defined scalar. Then $T(y_n) = T(p) - \frac{T(p)}{T(x_n)}T(x_n) = T(p) - T(p) = 0$, so $y_n \in \ker{T}$ for all $n$, and $y_n \rightarrow p$ as the coefficients of $x_n$ tend to $0$. So we have a sequence $(y_n)$ from the kernel that converges to $p$ not in the kernel, so the kernel is not closed. So $T$ is continuous.

Continuous operators


Bootstrap grid with 8 divs of varying height

Question: I'm trying to use bootstrap grid system to arrange 8 boxes of equal width and simiar but varying heights. I want the layout to do either 2x2x2x2, 3x3x2, 4x4 - responsive to screen size.
I can do the responsive layout but the issue I have is getting them to format properly so it doesn't leave whitespace above some of the boxes in some of the arrangements. I've tried varying combinations of clearfix but can't make it work. Is it possible? I assume so! Here's what it looks like:

TITLE

Some text of vaying length .... .... .... ..... ....

TITLE

Some text of vaying length .... .... .... ..... ....

TITLE

Some text of vaying length .... .... .... ..... .... .... ..... ......

TITLE

Some text of vaying length .... .... .... ..... ....

TITLE

Some text of vaying length .... ....

TITLE

Some text of vaying length .... .... .... ..... ....

TITLE

Some text of vaying length .... .... .... ..... .... .... .... ....

TITLE

Some text of vaying length .... .... ....  ....

Comment: I'm guessing the problem is that you get blank spaces below a high div if the first div in the next row can't float all the way to the left because it gets "stuck" to this high div. You could use masonry to arrange the divs "pinterest style", or just put all of the divs in one row in a div with a class "row", and all of the divs in the second row in another div with a "row" class. Class row clears floating and goes to another line as you would like I assume.
Comment: Yes the problem is as described. I have used something similar to masonry somewhere else. Is it not possible to get this arrangement working without it then? I get close with various incarnations of clearfix so was thinking it must be?
Answer: You can use flexbox to get the layout you want. It's not masonry style, but it fixes the blank spaces that you get when an element can't float all the way to the left side of the page. With flexbox you get the first case from your image that you linked in a comment, so elements in the next row will start below the highest element from the previous row.
Just wrap all of the columns inside a div like this (it might work if you just put flexbox on "container" div or "row" but I'm not sure):
html:

TITLE

Some text of vaying length .... .... .... ..... ....

TITLE

Some text of vaying length .... .... .... ..... ....

            ....etc....

css:
.flex-wrapper {
    display: -webkit-box;
    display: -ms-flexbox;
    display: -webkit-flex;
    display: flex;
    flex-wrap: wrap;
}

It works in all browsers except for IE10 and below, but there's a polyfill for those browsers as well so you should be good to go.
EDIT:
You could use the solution that was posted in a comment on another answer to get the masonry style (bootsnipp.com/snippets/OeVbl), and if you want to avoid ems you could use column-count to manipulate the number of columns. If you want a different number of columns on different resolutions just put a different column count in a media query.
.row {
    -webkit-column-count: 3;
    -moz-column-count: 3;
    column-count: 3;

    -moz-column-gap: 15px;
    -webkit-column-gap:15px;
}

Comment: YES! Thanks @Mario !! That works perfectly! What's the pollyfill for IE10?
Comment: Here is the polyfill - github.com/jonathantneal/flexibility
Comment: The flexibility.js is larger that the masonry.js file and I was trying to see if I can avoid more js but this is a good solution. I did try adding a media query to bootsnipp.com/snippets/OeVbl   posted previously:

    `@media all and (max-width: 600px) and (min-width: 0px) {
        .row {-webkit-column-count: 2 !important;;
        -moz-column-count: 2 !important;;
        column-count: 2 !important;; }
    }`

But this didn't work, is still show 1 col at the smaller screen size.


Proper approach for image recognition of ~1000 symbols

Question: We have a dataset of black symbols in grey squares (like attached below).
The symbols are various letters (arabic, greek) as well as numbers in many distinct fonts; altogether ~1000 different images.

We need to build an image recognition model (recognises each of the squares independently, so there are as many classes as there are images). This seems like an enormous task, I would like to know what would be the most suitable approach?
Edit
Let me summarise and clarify what we resolved in the discussion below the post:

each image is an unique label; there are exactly as many unique labels as images
I need to have a system which recognises these exact 1000 images. Noting more. I am new to image recognition therefore I am wondering what kind of model/algorithm should I apply to such exact problem.
However, new examples may indeed come, for example improperly cropped squares, or re-sized images (smaller resolution).
In an extreme case someone might even provide a very improperly cropped square which would include some background around it. The bg may be anything, no constraints. In such case - should I recognize the borders of the squares first and then proceed (how?)

Edit2
After a discussion under this answer I conclude that the question is still open and I cannot accept a solution yet. It seems that proposed CNN would require ~6000 examples per image, which in my case of 1000 symbols is not realistic. That is why I would especially like to learn how should I proceed in this exact dataset (approach? model? algorithm?)
Comment: @maciek With some coding, it sounds like you could create a training and test dataset by creating cropping issues and changes in resolution in new images created from your original data set.
Comment: When you say "unique" label, do you mean that if you have 5 images of the letter A, each has a different label (5 labels in total)? Or do you mean that all images of the letter A are labeled "A"?
Comment: @maciek Okay. Will there be new examples presented to the model later, or is this model intended to 'memorize'/compress this n=1000 dataset only?
Comment: @maciek  Cropping issues can be helped by considering translational invariance, motivating the use of CNN's. You could resize the images and then simply find out if the error rates are acceptable. As I mentioned about Chaitin's work, there will exist no proof that you have the best model. Rather you must rely on testing error.
Comment: Perhaps you could [edit] your post to include the additional details that you've outlined in these comments.
Comment: Are the images labeled?
Comment: I don't think I understand what you mean by "proper". According to Chaitin circa 1960's, I also cannot provide a proof that any given model is the best model. Rather, I recommend you look into classification with convolutional neural networks (CNNs). CNN's learn translationally invariant patterns by convolving trainable filters.
Comment: @Sycorax: yes, each image has a unique label and this label should be learned
Comment: @Galen: Proper, meaning, the most reasonable method to address such a problem, given the specifics of the example I provided. CNN could be one way but it requires a huge training set whereas we just have these 1000 images that should be recognized.
Comment: @Sycorax: 5 different labels
Comment: So you have 1000 images and 1000 labels, and no label is applied to more than 1 image?
Comment: @Sycorax: Correct.
Comment: @maciek Do you have a test set? Or do you only have training data?
Comment: There is no training/testing data. There is just the set of 1000 images that need to be recognized. Whether I divide it or not its up to me but the bottom line is that all of them need to be learned correctly.
Comment: @Galen: I think I would like to know what your opinion would be in both of these cases: (1: no new data) and (2: new examples incoming). But the original question was about (1)
Comment: The reason this is confusing is that it doesn't seem to be a statistical question. If there's no requirement for generalization, then one solution is to parse the images into an array and then for each image in your data set, subtract. The training example with the smallest difference is the label. Is this approach unsuitable? Why or why not?
Comment: @maciek In case (1) I agree with Sycorax: Simply computing the nearest neighbours would be sufficient. However, you could attempt to train a model that is smaller than storing all of the original images...

In case (2) you will encounter issues with generalization error if the new examples are not highly similar to the training examples.
Comment: @Galen: OK, the point is that new examples might be incoming in different resolution or maybe cropped a little improperly...  so slight non-similarities may appear...
Comment: OK, thanks a lot! One more question: What if the square would be on some colorful background? I would like to extract the square first... But I don't know how to recognize borders...
Comment: @Sycorax: OK, Done, waiting for a review.
Answer: You need to collect relevant data.
The 1000 symbols that you have right now are not representative of the task that you want to achieve. You have 1000 symbols that are "perfect" -- they're centered in the square, they're the same size, the backgrounds are uniform gray, they're all the same resolution.
But the problem you're trying to solve isn't about how to label these perfect images; it's about how to address the cases of imperfect images.

However, new examples may indeed come, for example improperly cropped squares, or re-sized images (smaller resolution).
In an extreme case someone might even provide a very improperly cropped square which would include some background around it. The bg may be anything, no constraints. In such case - should I recognize the borders of the squares first and then proceed (how?)

What you need to do is collect examples of the kinds of images that you will be classifying -- the ones with weird backgrounds, improper cropping, are resized, etc.
One shortcut to collect this kind of data is to apply transformations to your perfect images -- translate the character, make the background look like one of the imperfect backgrounds, etc. But this is only a viable strategy insofar as the transformations that you apply are relevant to the transformations you'll encounter when using the model. This is why data collection is important -- you won't know about the transformations that you don't know about, so you'll need to collect examples.

After you've collected data, this seems like a standard character recognition task. One common approach is to use convolutional neural networks, but there are many others.
Comment: Thank you for the explanation; I would like to ask two more things before I accept this: (1) I know about CNN since they are the hottest topic right now, but could you please provide some bullet points with other approaches which you think would be suitable here? (2) How much examples do you think I should collect per 1 image? Does this number depend on the total number of images (1000)?
Comment: Alternative strategies use some feature extraction method (HOG, SIFT) to transform images into fixed-length vectors and then apply a tabular method (random forest, SVM, xgboost, etc).
Comment: Would you have a comment on (2)?
Comment: MNIST is a standard toy problem using handwritten digits; it has 60,000 training images total with 10 equal classes. But it is one of the smaller image datasets.
Comment: Well, that is my problem then; 60,000/10 = 6000 examples per class. This is not realistic for my situation. That is why I ask what would be a proper approach/model in this particular case of 1000 symbols/classes
Comment: My answer explains why your data collection strategy is not suitable for the problem that you want to solve.
Comment: OK, thank you very much then; I have added one more edit to the question accordingly.
Comment: My comment about the size of MNIST digits is not specific to CNNs. Indeed, many of the early results published using MNIST digits were not CNNs. The problem you face is about how to generalize to noisy data; to do that, you'll need to train a model on noisy data. There's no way to escape the necessity of data collection in a statistical project. Maybe the data can be programmatically generated, or maybe not, but you need data that exemplifies to the problem you want to solve. Based on your own description, you don't have suitable data.


Should I write "*a* splitting field" or "*the* splitting field"?

Question: I am studying from Patrick Morandi's Field and Galois Theory, and in section 3, he makes the following definitions.

Let $K$ be an extension field of $F$.

If $f(x) \in F[x]$, then $f$ splits over $K$ if $f$ factors completely into linear factors in $K[x]$.
If $f(x) \in F[x]$, then $K$ is a splitting field of $f$ over $F$ if $f$ splits over $K$ and $K = F(\alpha_1,\dots,\alpha_n)$, where $\alpha_1,\dots,\alpha_n$ are the roots of $f$.
If $S$ is a set of polynomials over $F$, then $K$ is a splitting field of $S$ over $F$ if each $f \in S$ splits over $K$ and $K = F(X)$, where $X$ is the set of all roots of all $f \in S$.

Often, in mathematics, we take care to use the article the only when the object we are talking about is unique in some sense. This sense is made precise by defining isomorphisms, or homeomorphisms, or any such (bijectively) structure-preserving functions between objects.
So, it makes sense to start out by talking only about a splitting field, because a priori we do not know any two splitting fields of a collection $S$ of polynomials over $F$ are unique up to isomorphism. After such an isomorphism has been shown to exist, we might choose to switch the article and only refer to the splitting field of a collection $S$ of polynomials over $F$.
My problem is that Patrick Morandi freely switches between the two articles when referring to splitting fields, both, before and after proving the Isomorphism Extension Theorem (which proves that splitting fields are unique up to isomorphism). This is a bit jarring for me. I would like to know whether there is any standard regarding which article to use when taling about splitting fields.
(I would love it if the answer is "Yes, use the once you've proved the Isomorphism Extension Theorem, otherwise stick to a." But, I fear that this question is all about nitpicking.)
Comment: I normally think this in terms of $F$ and $K$ are sitting in some ambient fixed algebraic closed field. The splitting field really depends on $F\to\bar{F}$ embedding where $\bar{F}$ is the algebraic closure as you know all algebraic closures of $F$ are isomorphic. Once $\bar{F}$ is fixed. Then I would have no trouble to identify the splitting field as there is only 1.
Comment: Probably the reason is that the author obviously knows the isomorphism theorem and is accustomed to say "the splitting field", so a couple of slips in the textbook can't be that surprising. Anyway, you're right: before proving that splitting fields are unique up to an isomorphism fixing the base field, one should use "a".
Comment: @Brahadeesh Not necessarily. I'd keep the distinction when clarity requires it.
Comment: @user45765 I am tempted to add an edit to the question based on your comment. You said "**the** algebraic closure" of $F$, whereas Patrick Morandi refers to it using both articles, **the** as well as **a**, before and after proving that all algebraic closures (of $F$) are isomorphic.
Comment: @user45765 also, based on your comment, if I always think of a fixed algebraic closure $\bar{F}$ of $F$, then it makes sense to refer to **the** splitting field $K$, isn't it? That is what I understand from your comment, please correct me if I am wrong.
Comment: Yes. If you fix an ambient algebraic closure of $F$, then the construction of splitting field is done by adjoining all relevant roots of that algebraic closure. There is no extra freedom once you have fixed algebraic closure. Then you have no trouble to say it is "the" splitting field in that particular algebraic closure. Or I do not know what does one mean splitting field in general. There are lots of identifications here.
Comment: @user45765 Thank you, your comments really helped. Yet, Patrick Morandi says "**the** splitting field" even when he hasn't fixed an ambient algebraic closure, says "**a** splitting field" even when he has fixed an ambient algebraic closure, says "**an** algebriac closure" even when he has fixed an ambient algebraic closure. . . . So, I can only conclude that he isn't following your rule :) but, I think I shall!
Comment: @egreg thank you; and once the isomorphism theorem is proved one should ideally use "the"?
Answer: To summarize a lot of what has been said in the comments (which I tend to agree with), you should use the article "a" before you know the theorem (or if you are talking to someone else who doesn't know the theorem or any context where before we assume we know the theorem, $\dots$). After that, it is uaually safe to refer to "the" splitting field of a polynomial; this frequently happens on this site. However, if there is a need for a distinction between two splitting fields that are not equal (even though they are isomorphic), then we should keep that distinction. But I think such situations are rare.
(Side remark: This reminds me of how in the representation theory textbook by Fulton and Harris, they will put an "$=$" sign for two algebraic structures even when they are only canonically isomorphic but are not equal. I think that the kind of talk we are using here shows up quite a bit in algebra)


How can I set the culture for dotnet logging?

Question: I'm using logging in dotnetcore 3.1. When I use composite formatting of dates in a logger, I get a different format than if I convert the date to a string in my application code.
This code:
ILoggerFactory loggerFactory = LoggerFactory.Create(builder => builder.AddConsole());
_logger = loggerFactory.CreateLogger<Program>();
_logger.LogInformation("TEST date via format string {}", DateTime.Today);
_logger.LogInformation("TEST date with concatentation:" + DateTime.Today);

produces this output (note the change in order of days and months):
TEST date via format string 08/26/2020 00:00:00
TEST date with concatentation:26/08/2020 00:00:00

I'm surprised the logger doesn't inherit the culture from the application. Am I missing something, and if not how can I control the culture of the logger?
Answer: This interested me, and I decided to dig around a bit.
Judging by the dotnet LogValuesFormatter in the Logging repository, when using the braces { }, the call to the Format method uses the invariant culture.
Which, according to the Microsoft docs is set up as MM/dd/yyyy.
However, the concatenation does appear to use the current culture.
I would suggest that if you want to use the braces formatting that you simply call ToString and add the culture in order to cast the date to a string in the current culture, before the formatter gets a hold of it. You could also use string interpolation which uses a similar syntax to the braces, but appears to also use the current culture:
_logger.LogInformation("Current culture is "+  CultureInfo.CurrentCulture.Name);
_logger.LogInformation("TEST date via format string {}", DateTime.Today);
_logger.LogInformation("TEST date via cultured format string {}", DateTime.Today.ToString(CultureInfo.CurrentCulture));
_logger.LogInformation("TEST date with concatentation:" + DateTime.Today);
_logger.LogInformation($"TEST date with string interpolation: {DateTime.Today}");

This code gives me this output:
Current culture is en-GB
TEST date via format string 09/12/2020 00:00:00
TEST date via cultured format string 12/09/2020 00:00:00
TEST date with concatentation:12/09/2020 00:00:00
TEST date with string interpolation: 12/09/2020 00:00:00

Comment: The linked source code illustrates that the answer to my question is "No. I cannot control the culture of the logger". While I'm ambivalent about MS's decision to enforce InvariantCulture, the choice of MM/dd/yyyy for that date format is as objectionable ever :)
 btw @reisclef check your second link, it's the same as the first. Thanks!
Comment: Totally agree with your statement @TrevorJ. And thanks for pointing out the link mistake. That's what I get for answering a question in the late evening! I've corrected it now. :)


How to visually document IT processes?

Question: Our company has 8 departments each housing approximately 12 people on average. I'm the CTO of the company and IT is involved in pretty much all departments. As such, there is a need to define and document all IT processes and also all the tech level scenarios in order for us to understand what we are doing. Could be things like:

What does the order flow look like?
What systems does an order pass?
What responsibilities do all of our administration servers have?
How does our web server backend system work?
Our content delivery network?
And what about backups and redundancy of our mail server?

And so on, the list just grows...
Having this documented visually using some kind of standard methodology is a requirement as loads of texts just introduces too much overhead in terms of rapid understanding. Any such tool must be easy and quick to work with otherwise documentation will NOT happen anyway.
What are you using out there? Any input is much appreciated.
Answer: For just about any kind of functional diagram, I use dia.  It's not the single greatest drawing program in the history of the world, but it works well enough, and it's installable on Windows and MacOS as well as Linux, which is very handy in all the environments I work in.
I have used it to produce some really quite complex network diagrams, and the ability to send it to people for review without worrying what platform they're on is really, really handy.
Comment: Yes, have tried Dia and for custom diagrams it rocks. However, what I'm looking for is something designed for rapid documentation of processes. I tried out LucidChart which is a really cool tool and they have a chart component called SwimLane. Using that component I can define roles and areas within my company as to describe how processes flow cross-department. This is all good BUT it requires ME to define the documentation flow and to create some sort of template for future use. I would love a tool that helps me do more than just provide me with tons of graphics.
Answer: I tend to use Visio. It is a good point that you need to make sure whatever you choose you are sending things out in a format that is useful.
If you don't already have a wiki, I would recommend something like confluence and then an addon like http://www.gliffy.com/. Or you could just use http://www.gliffy.com/ standalone.
I sounds like the bigger question is more about the diagrams themselves. For that I think the best approach is to starting with finding some flow charts or process charts you like and emulate them. It all depends on what you are documenting.
Comment: See my comment above. I've tried more than 10 different flowchart engines and they all do pretty much the same. I'm looking for something more specific to the documentation process itself.
Comment: gliffy is nice, buts its horrible flash. I tried gliffy and moved on to lucidcharts, which is currently serving its purpose and has lovely lovely connectors, which are just cool. However its shapes palate is limited.
Answer: Confluence Wiki and the Gliffy plugin
Really great since it means you do everything regarding documentation in the same place.

Though I do like dia if I didnt have Gliffy, anything but Visio basically.
Answer: I've used Dia in the past as well and it works quite well. I love having something I can use on my Linux box. ;)
But Visio is the best, the added features like SQL database linking, Sharing of your diagram via the web.
Worth the money, and being  a CTO of your organization, look into getting a Technet subscription then you can get Visio at a fraction of the cost.

How to visually document IT processes?


Inject cookie with Nginx reverse proxy

Question: With Nginx as a reverse proxy I'd like to inject a cookie for backend systems to consume.
location /delegate {
  proxy_pass                        <some-url>;
  proxy_set_header Host             $host;
  proxy_set_header X-Forwarded-For  $remote_addr;
  proxy_set_header X-Request-ID     $request_id;
  # some more
  # here: inject a new cookie into `cookie` request header
}

As I want the cookie to be consumed by downstream systems this isn't about the add_header Set-Cookie instruction (which is for the response going back to the client).
Answer: You can provide server with cookies via
proxy_set_header Cookie "name=john; age=30; male=1";

Inject cookie with Nginx reverse proxy