How to bind rsync to a specific interface?

Question: I have a lot of interfaces configured in my server, each of which connect to a specific nic card and have a separate routing table. These interfaces can be identified by "netstat -a" command.
Now, I want to execute the rsync command connecting only to specific interface. I have this requirement because each of the interfaces will go through a separate tunnel/path and I want a particular rsync command to sync files through a specified tunnel.
Specifically, I want a way to specify the interface name.
Thanks,
Mohan.
Answer: You can specify the address of the interface using --address=x.x.x.x on the command-line.
I don't think there is any way to specify the interface directly, but the ip command can tell you the address for an interface, so you could use something like this:
IP=$(ip -4 -br addr show eth0 | awk '{split($3,a,"/"); print a[1]}')
rsyncd ... --address=$IP

Edit For systems with the "real" iproute2 (anything not busybox-based, essentially), ip can produce JSON output which can be parsed a bit more sanely:
IP=$(ip -j -4 addr show wlo1 | jq .[0].addr_info[0].local)
rsyncd ... --address=$IP

Comment: Thanks Tom. But my concern is that the interface name is widely spread, and their addresses are not so spoken inside the software. So, are there no direct way to specify the interface name ? Say, I know the interface a is for the x business purpose so the software using x business should use interface a. But I can't guarentee the a's address remain same.
Comment: AFAIK there is no way to specify the interface name directly.  You could always get the address for the interface, though - I'll update the answer to include it.
Comment: `ip -4 -br addr show eth0 | awk -F' +|/' '{print $3}'` Multiple separators can be specified to make awk command a little shorter
Comment: I've also added a version which uses the JSON output from `ip`, which can be parsed in more semantically-meaningful ways with `jq`.
Answer: I've written this little perl script to turn interface names to addresses, save it as iftoip (or similar)
#!/usr/bin/perl

use strict;
use warnings;
use IO::Interface::Simple;
use feature qw(say);

my $iface = shift;

my $if = IO::Interface::Simple->new($iface) or die "$!: $iface";
say $if->address;
exit 0;

You can do something similar with bash:
iftoip() {
  ip addr show $1 | grep inet | awk '{print $2}' | cut -d'/' -f1
}

just add the above 3 lines to ~/.bashrc and start a new shell or source ~/.bashrc
Running it produces:
v@juno:~$ iftoip ens33
10.251.17.94
v@juno:~$ iftoip ens34
192.168.78.128
v@juno:~$ echo "IP=$(iftoip ens33)"
IP=10.251.17.94
v@juno:~$ iftoip ens35 #perl
No such device: ens35 at /home/v/bin/iftoip line 10.

or
v@juno:~$ iftoip ens35 #bash
Device "ens35" does not exist.

Answer: This has been tried using 2 interfaces, with different subnets and worked.
rsync -avzP -e 'ssh -b 10.100.16.X' /var/tmp/ent1 10.100.16.X:/var/tmp/;

rsync -avzP -e 'ssh -b 10.100.20.X' /var/tmp/ent2 10.100.20.X:/var/tmp/ ;

Answer: From client to server, over ssh use:
 rsync -avP -e 'ssh -b x.x.x.x' tmp/ server:tmp/


number of linear maps from $E\to E$ that satisfy $f^2=0$ where E is a Z/pZ vector space

Question: let E be $Z/pZ$-vector space of dimension n.
calculate number of linear maps from  $E\to E$ that satisfy $f^2=0$
there is a hint that suggest that to consider the null space and subspace in direct sum with it.
I know that the number subspaces of a given dimension is given a previous post: How to count number of bases and subspaces of a given dimension in a vector space over a finite field?
but I don't know where to start, any help please!
Comment: $f^2=0$ is equivalent to $Im(f)\subseteq Ker(f)$. So pick a subspace $Ker(f)$, a subspace $Im(f)$ of that $Ker(f)$ and then the only choice left is how your function acts on the complement of the kernel, so it's the same thing as an automorphism of $Im(f)$ (because the complement of the kernel has the same dimension as it). You'll get an ugly sum that you may be able to simplify.
Comment: Thank you for answering, can you please clarify?
Comment: @xavierm02 Note, however, that the dimensions of the subspaces must sum to $n$.
Comment: @xavierm02 also, I assume you're talking about the orthogonal complement to the kernel (we must choose a distinguished complement for counting purposes).  Does the "orthogonal complement" still make sense in finite fields?
Comment: @ Omnomnomnom:is there a simpler way to to solve this problem without using orthogonal complement?
Comment: @Omnomnomnom No because I'm counting functions at this point. And while different complements will make the function look different, each complement yields a bijection between the functions I want to count and automorphisms of the image.
Comment: @xavierm02 I'm fairly sure that, for a single fixed kernel, one may choose two different complements, but end up defining the same overall $f$ on $E$. Are you accounting for this?
Comment: @Omnomnomnom Yes. But a single complement is sufficient (and necessary) to define all $f$s.
Comment: @xavierm02 you're right... the existence of a satisfactory choice is sufficient, after all.
Answer: Let $K:=\operatorname{Ker}(f)$ and $I:=\operatorname{Im}(f)$.
$f^2=0$ is equivalent to $I\subseteq K$.
So you first pick a subspace $K$ of $E$ and then pick a subspace $I$ of $K$. The sets of functions you'll attain for different $K$ and $I$ are clearly disjoint so if you manage to count for each $I$ and $K$, you'll then just have to sum over all $I$ and $K$.
Now, suppose $I$ and $K$ fixed. Take some $H$ so that $E=H\oplus K$. Then it is equivalent to give the action of some $f$ on $E$ or to give it on both $H$ and $K$. Since the action on $K$ is trivial, giving the action of $f$ on $E$ is equivalent to giving its action on $H$, i.e. a function $H\to I$ that has image $I$. Since those functions are surjective and both spaces are or equal dimension, those functions will all be automorphisms. Now take $\varphi$ any (fixed) automorphism between $I$ and $H$. The application $( g : H \to I)\mapsto (\varphi \circ g : H \to H)$ is a bijection. So to count the morphisms when $I$ and $K$ are fixed, you just have to count automorphisms of $I$.
Comment: I like the taste of group theory in your answer, Thank you.
Answer: Based on the other answer's explanation, we may compute the total as follows: let $m = \lceil n/2\rceil$.  Then in the notation of the post that you linked, the total will be
$$
\sum_{j=m}^n \binom nj_p \binom{j}{n-j}_p \prod_{k=0}^{j-1}(p^j - p^k)
$$
Comment: I think the right product symbol must start from k=0 and ends on j-1 not j.


Standard Brownian Motion process

Question: I would appreciate the help in the following
$\{x(t): 0\leq t \leq 1\}$ Standard Brownian motion.
$ t^*=\inf\{t\in[0,1]:x(t)=\underset{0\leq s \leq 1}{\sup} x(s) \}$
random variable , $\{y(t): 0\leq t \leq 1\}$ Standard Brownian motion are independent,
$ \mathbb{E}(t^*)<\infty $ then
$\mathbb{E}\left[(y(t^*))^2\right] =\mathbb{E}(t^*)$
I would like to know if this result is true and if it is true, how can I prove it?
Answer: This question is not really about Brownian motion.
You see, $t^*$ and $y$ are independent, which makes:
$$\mathbb{E}( y(t^*)^2 |t^*=t )= \mathbb{E}( y(t)^2 |t^*=t)= t$$
Hence forth what follows.
P/s: $t^*$ and $y$ are independent
Comment: Thanks for the help,  and for the last equality that was used?
Comment: Yes it is it. I think it is the most intuitive way to see the equality in yout post. p/s: There is some technical remark about the conditional expectation that i gave you but i think it is not nessessary.( because it is too pathological)

Standard Brownian Motion process


My neutral Ok button is not showing in my alert dialog for Samsung S5 and J700

Question: Trying to build a mobile application and have tested across some devices, but when it comes to Samsung S5 Notebook and J700 mobile phones, both have been failing because they have failed to display the neutral button in the application, please who might have the slightest clue to solving this particular issue. Thanks.
Here is a sample code below;
new AlertDialog.Builder(context)//new Alert Dialog
            .setTitle("Delete entry")//set title
            .setMessage("Are you sure you want to delete this entry?")
            .setNeutralButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    // continue with delete
                }
             })`enter code here`
            .setIcon(android.R.drawable.ic_dialog_alert)
             .show();

Answer: Maybe you should try with .setPositiveButton this should work.
Check if you are using AlertDialog from support library?
Comment: If i use AlertDialog from a support library, should that affect it?, though i am not using it
Comment: That might be issue check with support import. You also not calling `create()` method on builder object before `show()`.
Answer: just replace with this -
    AlertDialog.Builder builder = new AlertDialog.Builder(context)//new Alert Dialog
            .setTitle("Delete entry")//set title
            .setMessage("Are you sure you want to delete this entry?")
            .setNeutralButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    // continue with delete

                }
            })

            .setIcon(android.R.drawable.ic_dialog_alert);
//                    .show();
    AlertDialog d = builder.create();
    d.show();

Comment: use this import android.support.v7.app.AlertDialog;
Comment: I suggest you to use android.support.v7.app.AlertDialog instead of android.app.AlertDialog, and in that case, the above code will produce the result what you expected.
Comment: You do not need to call `create`, `show` call it internally: `final AlertDialog dialog = create(); dialog.show();`
Comment: At Atahar Hossain, I am using android.app.AlertDialog, i guess a big differenceexit between both
Comment: @Atahir Hossain, Please my progress dialog shows in API 17 beloe but does not show in API23, Please how do i go about styling it.
Comment: Please make sure, whether you are using android.support.v7.app.AlertDialog or android.app.AlertDialog. If you import android.support.v7.app.AlertDialog for your AlertDialog , then it also works in API 23


Simple SQL statement builder for .Net

Question: I've jumped into an ongoing .Net 2.0 web app project for a larger company as a freelancer. Their DAL has lots of functions that manually construct and execute SQL statements -- many of them are long, messy and as a result difficult to understand and debug. I wrote a simple "sql helper" that lets me write things like this:

sqlh.addValue("name", name);
sqlh.addValue("address, address);
sqlh.addLiteral("created", "getDate()");

string sql = String.Format("INSERT INTO [Table1] ({0}) values ({1})", sqlh.getInsertFields(), sqlh.getInsertValues());

It handles nulls and also works for updates. That's about it.
Ideally I would be using Microsoft Data Application block or LINQ or something, but major architectural changes are not possible at this point. This method has saved me a lot of time, but seems like a problem best solved by using a "community-approved" solution.
Is there a popular, light-weight solution that achieves similar results, from Microsoft or otherwise?
EDIT
While the SqlParameter solutions described so far are an improvement over a purely manual statement building method, I think I still prefer my solution, where adding or removing a field from the query affects only a single line. Anything better? thanks
Comment: What does your getInsertValues() do?
Comment: getInsertFields() => "[name], [address], [created]"
getInsertValues() => "'bill', '123 Street', getDate()"
Answer: I created my own stored procedure to create insert statements based on a given table schema, I thought I was pretty awesome. Then I found this:

CREATE PROC sp_generate_inserts

EDIT
I know that I found about that script as a result of a previous SO post, but I can't find it now, if someone else does or knows, please edit/or add to comment and I will edit.
Answer: You have several options from Microsoft: ADO.NET or Linq2Sql are the popular ones at this time. But link you mentioned, it will take a good amount of work to convert from generating SQL to an ORM.
To make the creation of SQL more straight-forward and safer, you should consider using SQL Parameters. Here is an example:
using (SqlCommand saveCommand = DbUtil.CreateSqlCommand(context.Transaction)) {
    saveCommand.CommandText =
        "INSERT INTO Hit (" +
            "Id, PersonId, TeamId, PlayerId" +
        ") VALUES (" +
            "@Id, @PersonId, @TeamId, @PlayerId" +
        ")";

    DbUtil.AddParameter(saveCommand, "@Id", SqlDbType.UniqueIdentifier, Guid.NewGuid());
    DbUtil.AddParameter(saveCommand, "@PersonId", SqlDbType.UniqueIdentifier, hit.PersonId);
    DbUtil.AddParameter(saveCommand, "@TeamId", SqlDbType.UniqueIdentifier, hit.TeamId);
    DbUtil.AddParameter(saveCommand, "@PlayerId", SqlDbType.UniqueIdentifier, hit.PlayerId);

    saveCommand.ExecuteNonQuery();
}

That will separate your parameter list from the SQL. Also the SQL we be much more legible. The DbUtil in the example is just a helper function I wrote to create my sql command from a connection or transaction. Also similar to your sqlh.addValue, I have a DbUtil.AddParameter that works by taking in the command, variable name, data type and value. Here's a sample including overloaded methods:
internal static SqlParameter CreateSqlParameter(
    string parameterName,
    SqlDbType dbType,
    ParameterDirection direction,
    object value
) {
    SqlParameter parameter = new SqlParameter(parameterName, dbType);

    if (value == null) {
        value = DBNull.Value;
    }

    parameter.Value = value;
    parameter.Direction = direction;
    return parameter;
}

internal static SqlParameter AddParameter(
    SqlCommand sqlCommand,
    string parameterName,
    SqlDbType dbType
) {
    return AddParameter(sqlCommand, parameterName, dbType, null);
}

internal static SqlParameter AddParameter(
    SqlCommand sqlCommand,
    string parameterName,
    SqlDbType dbType,
    object value
) {
    return AddParameter(sqlCommand, parameterName, dbType, ParameterDirection.Input, value);
}

internal static SqlParameter AddParameter(
    SqlCommand sqlCommand,
    string parameterName,
    SqlDbType dbType,
    ParameterDirection direction,
    object value
) {
    SqlParameter parameter = CreateSqlParameter(parameterName, dbType, direction, value);
    sqlCommand.Parameters.Add(parameter);
    return parameter;
}

internal static SqlParameter AddParameter(
    SqlCommand sqlCommand,
    string parameterName,
    SqlDbType dbType,
    ParameterDirection direction
) {
    SqlParameter parameter = CreateSqlParameter(parameterName, dbType, direction, null);
    sqlCommand.Parameters.Add(parameter);
    return parameter;
}

Answer: SqLCommand and SQLParameter objects might be of use to you:
  Dim sc As New SqlClient.SqlCommand

  Dim sp As New SqlClient.SqlParameter("@value", SqlDbType.VarChar)
  sp.Value = "test"

  sc.Parameters.Add(sp)
  sc.CommandText = "select column1, column2 from table where column3=@value"

  sc.ExecuteReader()

Its vb.net but you get the idea.  This will help prevent sql injection, and looks neat and is readable too.
Dont forget to setup your connection string etc.
Comment: he knows about those. that's what he's trying to abstract.

Simple SQL statement builder for .Net


PoissonDistribution- Demand problems

Question: I am still not too familiar with Poisson Distribution and recently I have come across a question like the following
A grocery store purchases one item for $X$ dollars and sells it for $Y$ dollars.
If the item is unsold, they can not refund it. The demand for the item varies according to a $Poisson(\lambda)$ distribution. The question is what is the number of items that the store should order from the supplier....
I can't seem to wrap my head around this type of question as I cant find a way to apply the Poisson distribution.
Can anyone elaborate on this to me?
Comment: Are you having a *specific* question, then post it *exactly*  ?
Comment: @true blue anil Sorry, I have seen a couple of similar questions like this. So I think it would be a good idea to post the form and ask for a general solution.
Answer: Hints:
Consider the following questions - you might not want to try to find closed forms:

If the shop buys $n$ items for $X$ each, how much does it spend?
What is the probability that shop the sells $N$ items (with $0 \le N \lt n$)? Use the Poisson distribution here
What is the shop's revenue if it sells $N$ items (with $0 \le N \lt n)$?
What is the probability that shop the sells at least $n$ items? Use the Poisson distribution here and you might want to leave this as a sum
What is the shop's revenue if it sells $n$ items?
What is the shop's expected gross revenue if it cannot sell more than $n$ items?
What is the shop's expected net profit if it orders $n$ items?
What would the previous answers be if you replaced $n$ by $n+1$?
What is the change in net profit if you replaced $n$ by $n+1$?
For which $n$ does the change in net profit first become negative?
Comment: How should I calculate the gross revenue and net profit I'm a bit confused
Comment: also How would I calculate the cumulative Poisson Distribution if n is unknown or very large?
Comment: Expected gross revenue is the sum of the product of the probability of particular sales and the value of those sales. Expected net profit is expected gross revenue minus the cost of purchasing the stock.  You can either leave the cumulative Poisson as a sum, or use the incomplete or regularised Gamma function, or approximate using the normal distribution.
Comment: if the Poisson Distribution is $\lambda$, wouldnt it  be the number of items the store should purchase?
Comment: I would expect the answer to also depend on $X$ and $Y$

PoissonDistribution- Demand problems


Unsupervised Clustering with Extra Information

Question: I have a task to cluster an almost entirely unlabelled dataset. After reading the literature on semi-supervised clustering, I have not found any algorithms that suit my very particular needs.
Basically I have one true class A for which we have all samples, i.e. if something is labelled A it's definitely A, and if an object is not labelled A then it's definitely not A. This is the extent of the true labels.
Then I have an unknown number of other classes. There are some objects that I know must belong in the same class. For instance, I may know objects 1, 2 and 4 are of the same class, and objects 3, 5 and 6 are of the same class, but they could also all actually be one big class - that is unknown.
I also know some objects that cannot be in the same class. For instance, I may know objects 1 and 3 cannot be in the same class. Combined with above information I would have identified two definitely distinct classes B and C.
I am thinking of trying to construct a distance matrix with distances 0 or near zero between objects that I'm sure are in the same class, and very large distances between objects I'm sure are not in the same class, then use Euclidean distance between object features determine all other distances. Then I plan to use hierarchical clustering on this distance matrix. (So if object 7 was close to object 3 in the feature space, then we could cluster that in as class C too).
Would anyone happen to know any other methods to incorporate such information into a clustering? Or alternatively have any critiques of what I've proposed thus far?
Answer: There is PU Learning(Learning from Positive and Unlabeled data), but as far as I know it is used for binary classification where you have a positive data and and unlabeled data which a mixture of the positive and negative data, so what you can do is use a PU learning algorithm to classify your true class A and the other classes (Not A ), then After filtering class A, you can apply clustering algorithms to what is left of your data(other classes)!
There is this survey that you teach about PU learning PU learning and there is this python library that you can use pulearn
I hope this is the setting that you are talking about !
Comment: Awesome, thank you for your reply! I did come across PU Learning in the literature but also found that it only ever seemed to apply to binary classification. Since my data is instead Positive and Negative (where negative is many different classes) rather than Positive and Unlabelled, I can already just remove class A and cluster on the other classes. I suppose I figured that I could use knowledge of class A labels to evaluate how good the clustering is, and then use that knowledge for a final relabelling after that. So I don't think PU Learning is quite what I was looking for, but is close!


Question on checking character type on Python

Question: I'm currently working on my homework and the first line code is provided and cannot be changed. I am able to run in PyCharm but not able to run in Hackerrank to submit my homework.
I have tried to find what's wrong with my code but I think the problem is related to input. I think teacher wants us to use input as variable?
def check_character_type(input):
    # Write your code
    ch = input
    if ch[0].isalpha():
        print("alphabet")
    elif ch[0].isdigit():
        print("digit")
    else:
        print("special")
    return ch

check_character_type(input)

When I run the code in Hackerrank, error message are
Traceback (most recent call last):
  File "Solution.py", line 29, in <module>
    check_character_type(input)
  File "Solution.py", line 21, in check_character_type
    if ch[0].isalpha():
TypeError: 'builtin_function_or_method' object is not subscriptable

Comment: input is a built-in function..don't use that as a variable name...what does your input variable look like
Comment: my teacher told me to get the input from function parameter, not from input function.
so I dun know how to deal with this...
Answer: your issue as mentioned in the last answer and comments it that you are using the function named input as the name of your variable...try it like this:
inp = 'test'

def check_character_type(inp):
    # Write your code
    ch = inp
    if ch[0].isalpha():
        print("alphabet")
    elif ch[0].isdigit():
        print("digit")
    else:
        print("special")
    return ch

check_character_type(inp)

output:
alphabet
'test'

if by "I think teacher wants us to use input as variable" you mean that you're supposed to provide input before hand, then do this first:
inp = input('Enter the input')

Answer: The issue here is you have named the parameter to your function input, which is a reserved function provided by Python used to read input from the STDIN. You then alias this to ch and attempt to subscript it, effectively trying to access an index of a function (which you can't).
The solution would be to change your parameter name from input to something like in or s instead, something that isn't a reserved keyword.
Comment: Thank you but I just asked my teacher and he said he wants to use input as parameter. I am so struggling on this. He told me to return "digit", "alphabet" and "special" instead or print
Comment: Ah ok, in that case change your last line to `check_character_type(input())`. Do let me know if that works!
Comment: As for the returning bit, you might want to change your `print()` statements to `return` instead, so for example you would do `return "alphabet"` instead of `print("alphabet")`
Comment: Sorry I am very new to Python and programming and I ask a lot of stupid question.
so the question is ( if the input is a string instead of one character, take the first character of the string )

here is my code so far
```python
def check_character_type(input):
    # Write your code
    ch = input
    if ch[0].isalpha():
        return "alpabet"
    elif ch[0].isdigit():
        return "digit"
    else:
        return "special"

check_character_type(input())
```

the error is EOFError: EOF when reading a line
and there is no output in the test file :((( T.T
Comment: I see, so Hackerrank does seem to expect a print. In that case, make your last line into `typ = check_character_type(input())` and add a line below it saying `print(typ)`. Also would it be possible to include a link to the Hackerrank question?
Comment: When I make my last line into your suggestion, I could run the programme perfectly in Pycharm. But when it comes to Hackerrank, error message:
```python
input = input()
EOFError: EOF when reading a line
```
also, there is no output in Hackerrank
I am in a introduction course on python so I think the solution should be quite straight forward.
thank you very much. I tried many time and so struggle
Comment: No worries, could you include a link to the HackerRank question you are attempting so I could take a look at the specifications?
Comment: Thank you .
 the link is https://www.hackerrank.com/tests/9fi3b67soo2/f5aeb7828d647fac9ae0cf193fb6601f
Comment: I do not have the authorisation to take a look at the question. Could you paste your code into pastebin.com and link it here instead? It would make it easier to look for bugs.
Comment: sure here it is https://pastebin.com/tFgh4hBU
or if it doesnt work finally I could give you my access to Hackerrank thank you so much
Comment: Ok, could you try commenting out the last 2 lines and running it? (The line with `typ = check_character_type(input())` and `print(typ)`? So that way the code doesn't print anything.
Comment: Ohh I just remove the last line of the programme and it finally works.  You help me a lot .

Thank you very much~~~
Comment: All of this and the working solution is in my answer


Can we change the algorithms used for computing trends when decomposing time series?

Question: Classical decomposition consists of the following steps for additive or multiplicative decomposition:

Compute trend via a moving average (MA)
De-trend the series to get seasonal variation (either by subtraction or division if additive or multiplicative respectively)
De-seasonalize the series similarly to get the residuals.

Technically, does it really matter if the in the first step we change the algorithm to a weighted MA or a triangular/Gaussian MA or even simple exponential smoothing? The STL/LOWESS decomposition has a different way of computing the trend by local clustering/weighting/regressing. We could then proceed to further decompose in additively or multiplicatively, right? (I currently lack the insight into the decomposition steps of LOESS and am only extrapolating.)
Thus, in theory, we should be able to switch the algorithm for computing the trend and then continue on with either an additive or multiplicative decomposition IMHO (or a mix of both?). Is this commonly practiced? Is there a reason why we can't mix and match the decomposition steps by choosing the most relevant ones that best address the situation?
For my purpose, the decomposition graphs are a useful tool for monitoring purposes only and was curious if there were any rules being broken if I did something like that?
Answer: Yep we can absolutely change the underlying algos and mix-and-match.  For example if you know that the trend process is random noise around the mean with a switchpoint to a new mean then you probably want to use that for your trend rather than a moving average which will be wonky around the switchpoint. The only thing to be real concerned about is your trend model biasing the seasonality piece or vice versa.  That's why certain configurations work way better, for example complex splines before seasonal estimation could smoothen it out too much and give you wonky trend.
These ideas are at the core of a dev package I whipped up: Thymeboost. It combines time series decomposition with boosting (thus the name!) but it enables you to mix and match but also apply a learning rate to each individual signal (level/trend, seasonality, exogenous factor). If you use python you can try it out:
pip install ThymeBoost

And some examples with some randomly generated time_series but I really need to formalize some documentation:
from ThymeBoost import ThymeBoost as tb
boosted_model = tb.ThymeBoost(trend_estimator = 'linear',
                              split_cost = 'mse',
                              global_cost = 'maicc',
                              fit_type = 'local',
                              seasonal_period = 0,
                              verbose = 1)
output = boosted_model.fit(time_series)
boosted_model.plot_results()

Here 'local' in fit type specifies to look for changepoints, alternatively we can pass 'global' here to just fit on the whole dataset.  And to your point we really can use whatever base estimator for trend so lets use arima:
from ThymeBoost import ThymeBoost as tb
boosted_model = tb.ThymeBoost(trend_estimator = 'ar',
                              arima_order = (2,1,2),
                              split_cost = 'mse',
                              global_cost = 'maicc',
                              fit_type = 'local',
                              seasonal_period = 0,
                              verbose = 1)
output = boosted_model.fit(time_series)
boosted_model.plot_results()

Using verbose the model prints results from each round:
Round 0 cost: -1344.0438903501597
Using Split: 101
Round 1 cost: -1971.2578426717146
Using Split: 151
Round 2 cost: -1953.8696120415427
Boosting Terminated
Using round 1

So it found a changepoint at 101 where the coefficients of the arima will be different. That is close enough to the true changepoint at 100 if you ask me!  Round 0 is always fit with with the median of the data since this approach is heavily influenced by gradient boosting and it has a nice interpretation of saying 'there is no trend'.  Although for your case you may just want to fit all your different models globally for the first round.
Now let's try with 3 changepoints to see what happens:
from ThymeBoost import ThymeBoost as tb
boosted_model = tb.ThymeBoost(trend_estimator = 'linear',
                              split_cost = 'mse',
                              global_cost = 'maicc',
                              fit_type = 'local',
                              seasonal_period = 0,
                              verbose = 1)
output = boosted_model.fit(time_series)
boosted_model.plot_results()

Oof, that's pretty bad.  Looks like it is a problem with how I propose the segments since I don't want to exhaustively try every data point, so let's increase the number of proposals (and you will see I commented out approximate_splits = True if set to False it will try every point):
from ThymeBoost import ThymeBoost as tb
boosted_model = tb.ThymeBoost(trend_estimator = 'linear',
                              split_cost = 'mse',
                              global_cost = 'maicc',
                              fit_type = 'local',
                              seasonal_period = 0,
                              #approximate_splits = True,
                              n_split_proposals = 25,
                              verbose = 1)
output = boosted_model.fit(time_series)
boosted_model.plot_results()

Looks a lot better but it is slow to react to the third changepoint at x = 200.
You can also call plot_components() to see each component.  And finally for seasonality just add seasonality_estimator = 'harmonic' or 'naive' for fourier or simple averaging.  In terms of the seasonal_period you can pass like 12 for monthly data or alternatively [12, 3] for multiple seasonalities. The full list of trend algos is: 'linear', 'mean', 'ewm', 'median', 'ar', 'ses'(simple exp smoothing), 'des' (holt smoothing), and 'loess'. And exogenous_estimator has 'ols' and 'decision_tree'.
There are also options for polynomial expansions and regularization and the learning rate piece I mentioned earlier but I really need to fully document it but hopefully this can give you some ideas and you can try out some of the mix-and-matching and hopefully it doesn't break!
Probably too much of a plug but this question was geared towards my fun little package.
Comment: I always subtract (iteratively with boosting) although there is a param called additive which can be True or False.  If it is false then I take the log of my series which turns the whole decomp into multiplicative (while still subtracting in the maths).  I need to add just seasonality being multiplicative which would then be dividing as you describe but it adds some code complexity.  It would be independent of the trend algo and is something you could mix-and-match in something like a grid search to find the best algos/parameters which also comes in the package but it's easy enough to iterate.
Comment: What a wonderful exposition with your example library. Was genuinely insightful. Yes, adding more documentation would be helpful. For my needs I am not using Python but am open to experimenting. Will give this a shot to tinker with it and see. If I may ask, how do yo compute/deseasonalize the series? Do you "subtract" or "divide" or is it dependent on the trend algorithm. That'll help me close the loop in my understanding of the decomposition process.


python filter rewrite filter

Question: Working code
def not_double_cap_word(word):
    cap_count = 0
    for ch in word:
        if str.isupper(ch):
            cap_count += 1
    not_double_cap = (cap_count < 2)
    return not_double_cap
...

    words_no_double_caps =list(filter(not_double_cap_word,words_alnum))

What would be a different solution, say maybe using lambdas or other patterns in Python? The above creates a new list of words with any word with more than two caps removed. one two TWo => one, two.
Comment: I don't follow your output how does `one two TWo` become  `one, two`.
Comment: What do you mean "using lambdas"? `lambda` is just a different way of writing the same kind of function that `def` gives you, one that doesn't allow you to use statements or give the function a name but does allow you to do it in the middle of an expression. Why do you think you want that?
Answer: You can definitely simplify that not_double_cap_word function, but it's still going to be the same basic solution.
First, you can use ch.isupper() instead of str.isupper(ch). Calling a method the normal way is always easier than calling it as an unbound method and passing the self explicitly.
Next, we can replace the explicit for loop with sum over a generator expression:
cap_count = sum(ch.isupper() for ch in word)

And we don't really need to define not_double_cap, cap_count < 2 seems simple enough to return directly. So:
def not_double_cap_word(word):
    cap_count = sum(ch.isupper() for ch in word)
    return cap_count < 2

But really, this whole thing is probably simple enough to inline directly into the main expression. While you could do that by defining a function with lambda, there's no reason to. In general, map and filter are good when what you want to do to each thing is call a function that you already have lying around; comprehensions are better when what you want to do is an expression that you'd have to wrap in a function (lambda or otherwise) to pass to map or filter. Compare:
words_no_double_caps = [word for word in words_alnum
                        if sum(ch.isupper() for ch in word) < 2]
words_no_double_caps = list(filter((lambda word: sum(map(
                           lambda ch: ch.upper(), word)) < 2), words_alnum))

(I think I got the parens on the second version right. If not… well, if I wanted to program in Lisp, I would.:)
Either way, it's performing pretty much the exact same steps as your original code, but it's more concise. Is it more readable? That's for you to decide. But that's the most important reason to choose one or the other, or something intermediate between the two.
Well, that, and whether or not you need to reuse this logic; if you do, it should definitely be defined with a def statement and given a nice name.
Comment: lambda word: sum(ch.isupper() for ch in word) < 2, it's simpler to just use a comprehension instead of filter. I wanted to see the lambda to see how if is complicated vs comprehension.
Answer: You can rewrite your not_double_cap_word code using sum:
def not_double_cap_word(word):
    return sum(x.isupper() for x in word) < 2

If you just want ti use a lambda with filter and not use the not_double_cap_word function:
print(list(filter(lambda x: sum(s.isupper() for s in x) < 2 ,["one", "two" ,"TWo"])))
['one', 'two']

python filter rewrite filter


Applying sessions in cakephp 3.2

Question: Im using cakephp 3.2 to build an application. Im using the bookmarks tutorial as a basis for my project.  in one of my bookmarks .ctp view files I would like to have a number of select boxes with data specific to the user loggged in. i have two tables namely users and bookmarks. My bookmarks table contains foreign key from users table user_id.
Here's my bookmark table with the fields i would like the dropdowns. id, user_id, title, systemregistration, systemroles, country, province, metropolitan.
Code for my appcontroller
namespace App\Controller;

use Cake\Controller\Controller;
use Cake\Event\Event;

/**
 * Application Controller
 *
 * Add your application-wide methods in the class below, your controllers
 * will inherit them.
 *
 * @link http://book.cakephp.org/3.0/en/controllers.html#the-app-controller
 */
class AppController extends Controller
{

    /**
     * Initialization hook method.
     *
     * Use this method to add common initialization code like loading components.
     *
     * e.g. `$this->loadComponent('Security');`
     *
     * @return void
     */

    /*public function initialize()
    {
        parent::initialize();

        $this->loadComponent('RequestHandler');
        $this->loadComponent('Flash');
    }*/

    public function initialize()
    {
        $this->loadComponent('Flash');
        $this->loadComponent('Auth', [
            'authenticate' => [
                'Form' => [
                    'fields' => [
                        'username' => 'email',
                        'password' => 'password'
                    ]
                ]
            ],
            'loginAction' => [
            'controller' => 'Users',
            'action' => 'login'
            ],
            //'storage' => 'Session'
            'Session'
        ]);
        // Allow the display action so our pages controller
        // continues to work.
        $this->Auth->allow(['display']);
    }

    /*public function initialize()
    {
        $this->loadComponent('Flash');
        $this->loadComponent('Auth', [
            'loginRedirect' => [
                'controller' => 'Bookmarks',
                'action' => 'index'
            ],
            'logoutRedirect' => [
                'controller' => 'Pages',
                'action' => 'display',
                'home'
            ]
        ]);
    }

    public function beforeFilter(Event $event)
    {
        $this->Auth->allow(['index', 'view', 'display']);
    }*/

    /**
     * Before render callback.
     *
     * @param \Cake\Event\Event $event The beforeRender event.
     * @return void
     */
    public function beforeRender(Event $event)
    {
        if (!array_key_exists('_serialize', $this->viewVars) &&
            in_array($this->response->type(), ['application/json', 'application/xml'])
        ) {
            $this->set('_serialize', true);
        }
    }
}

//BookmarksController looks like this

namespace App\Controller;

use App\Controller\AppController;

/**
 * Bookmarks Controller
 *
 * @property \App\Model\Table\BookmarksTable $Bookmarks
 */
class BookmarksController extends AppController
{
    public function internalprotocol()
    {

        $bookmark = $this->Bookmarks->newEntity();

        $users = $this->Bookmarks->Users->find('list', ['limit' => 200]);
        $tags = $this->Bookmarks->Tags->find('list', ['limit' => 200]);
        $this->set(compact('bookmark', 'users', 'tags'));
        $this->set('_serialize', ['bookmark']);

        $bookmarks = $this->paginate($this->Bookmarks);

        $this->set(compact('bookmarks'));
        $this->set('_serialize', ['bookmarks']);
    }
}

//my internalprotocol.ctp looks like this

    <?php echo $this->Form->input('user_id', ['options' => $bookmarks]); ?>

    <?php echo $this->Form->input('title', ['options' => $bookmarks]); ?>

    <?php echo $this->Form->input('systemregistration', ['options' => $bookmarks]); ?>

    <?php echo $this->Form->input('systemroles', ['options' => $bookmarks]); ?>

    <?php echo $this->Form->input('country', ['options' => $bookmarks]); ?>

I would like to populate each of the fields with data specific to the user logged in. Could you please help!
Comment: I can't understand the question. But for session you can do this `$session=$this->request->session();` Then in `$session` You can do all the stuff like `$session->write('foo','bar');`.
Answer: You don't need to do anything. If a login is successful you can access the logged in user details through the Auth component using $this->Auth->user();
If you need to add any more information to the session you can use the Session component like $this->Session->write('User.AscociatedData', $AscociatedData);
Easiest way to access this data in the view is to set authenticated user as a view variable in the controller:
$this->set('user',$this->Auth->user());

then you can accesses the users info in the view with $user e.g$user->fieldName
Not entirely sure what your asking but I hope one of my answers is relevant.
Answer: we only need to show bookmarks for the currently logged in user.
We can do that by updating the call to paginate().Make your index() action from Controller/BookmarksController.php look like:
public function index()
 {
  $this->paginate = [
    'conditions' => [
        'Bookmarks.user_id' => $this->Auth->user('id'),
    ]
];
$this->set('bookmarks', $this->paginate($this->Bookmarks));
$this->set('_serialize', ['bookmarks']);

}
We should also update the tags() action and the related finder method as we done for bookmarks above
Please read the tutorial
http://book.cakephp.org/3.0/en/tutorials-and-examples/bookmarks/part-two.html#fixing-list-view-and-forms

Applying sessions in cakephp 3.2


Visiting points, algorithm

Question: I'm learning for the exam from algorithms and data structures (that I have in a month) and I can't manage with finding efficient algorithm for this problem:

We are given 1 <= n <= 5000 points on the line. Each point has different natural coordinate 0 <= d <= 10^6 and (not necessarily different) natural point-time 0 <= t <= 10^9 in seconds. We can start at any point and in each second change our current coordinate by +/-1. The problem is to visit all the points in such order that every point is visited before elapsing his point-time. Find the minimum total time (in seconds) of this trip, or say it's impossible.

For example, 5 points given (coordinate, point-time):
(1,3), (3,1), (5,6), (8,19), (10,15), it's possible, when we take a trip visiting coordinates: 3 -> 1 -> 5 -> 8 -> 10, we got minimum total time, which is equal to: 11.
My first idea was to sort all the points lexicographically by: (point-time, coordinate), and then visit them in this order. Of course, when there are points between i-th point and (i+1)-th point, we can visit them before visiting (i+1)-th point. But unfortunately, there is no argument why such greedy approach should work, despite the fact that it would be difficult to implement. Maybe I'm trying to solve it too quickly? n is small so, O(n^2) should be ok, I suppose.
I found other examples of the input, thinking maybe it will help me finding the solution. But now I only see that I have to find one permutation of all possible $n!$ permutations.
Input examples:
points (also given by coordinate, point time respectively): (0,4), (1,2), (4,5): surprisingly (I think) we have to visit them: 0 -> 1 -> 4, because any different order does not satisfy condition in one before last sentence in problem text.
points: (0,7), (1,2), (2,1), (3, 4), (4,11), the only funny way is: 2 -> 1 -> 3 -> 0 -> 4, which takes us 10 seconds.
Can anyone help?
Comment: isn't that equivalent to finding a minimum spanning tree on the graph where each point is a node and the vertices are the time it takes to move from one node to another ?
Comment: @AdrienPlisson: I don't understand your reduction, in here nodes have "life time", and it is also a single path - not a combination of different paths. Maybe I am missing your line of thought, care to elaborate?
Comment: Well an greedy approach would be to sort the un-visited points according to `(t - CURRENT_T) - (x - CURRENT_X)` in ascending order. First one is greediest choice and if it goes negative then recursion breaks.
Answer: First sort your points based on coordinate.
I would recommend a dynamic programming approach based on solving the following subproblem for each value of near and far between 0 and n-1:
Given that we are at the near^th point and have already visited all points between near and far (inclusive), then what time must it be if we just have enough time to visit all the remaining points?
The answer to your problem is given by the greatest value v(x) of the subproblem for near=far=x as x varies between 0 and n-1.  If v(x)<0  for all x then you cannot reach all the points.  However, if v(x)>=0 for some x, then you can reach all the points in a time given by "maximum point-time over all points"-v by starting from position x.
The recurrence between cases is based on considering going left or right from the near^th point until you reach the first point that you haven't yet covered.  (This will involve going to an immediate neighbour of either point near, or point far so the recurrence only takes O(1) time to compute)
There are n^2 subproblems, so this approach should take time O(n^2) overall.
EDIT
Python code to implement this approach:
<code>A=[(0,7), (1,2), (2,1), (3, 4), (4,11)]
A.sort()
M=max(a[1] for a in A)
cache={}
def go(near,far):
    """Given that we are at near and have visited all points in [near..far],
    (near can be > or < or = far)
    return the latest time that allows us to visit all points,
    and visit the point near itself."""
    if abs(far-near)==len(A)-1:
        return A[near][1]-1

    key=near,far
    if key in cache:
        return cache[key]

    v=-1
    d = 1 if near<=far else -1
    n = near-d
    if 0<=n<len(A):
        v=go(n,far)-abs(A[n][0]-A[near][0])
    n = far+d
    if 0<=n<len(A):
        v=max(v,go(n,near)-abs(A[n][0]-A[near][0]))

    v=min(v,A[near][1]-1)
    cache[key]=v
    return v

v=max((go(x,x),x) for x in xrange(len(A)))
if v[0]<0:
    print 'Impossible'
else:
    print 'Takes',M-v[0]-1,'seconds starting from point',v[1]
</code>
There is a slight ambiguity as to whether for a point with time 1 you have to reach it at time t<1 or at time t<=1.  This solution uses time t<1 as it matches with your example.
(If the requirement was t<=1, then the solution to (0,7), (1,2), (2,1), (3, 4), (4,11) would be the path 1 -> 2 -> 3 -> 0 -> 4 in 9 seconds)
Comment: I did not follow the solution, can you please formulate better the recursion explanation? (Maybe if I'll read it as well formulated it'll be easier for me to follow).
Comment: I've added some example code - you may well find that easier to understand than my English - apologies!
Comment: If I understand correctly, what @Peter de Rivaz is saying is that, for each potential starting point, we build a list of possible ranges to traverse such that the point we start with is one of the endpoints of that range (e.g. begin at point 1, then ranges are (1,1), (1,0), (1,2), etc.). For each range, compute the latest possible time to begin at our point such that we can cover the whole range. The algorithm uses dynamic programming to compute these times, of which there are a total of n^2. It then chooses a solution that covers all n elements with the latest start time (=most time saved)

Visiting points, algorithm


SVG stroke drawn clipped

Question: I have <svg> inside of a
, but the stroke is giving me issues, it's being clipped by the div's bounding box I think, not sure.
On Chrome and FireFox, the stroke is being clipped.
Surprisingly, on IE11 it's not clipped, but that's still not correct, it should instead be drawn inside the svg. Because if I put two div elements near each other, I don't want to see stroke of one of the svg being drawn on the other. BUT, if there's no other way, this would still be an acceptable solution to me.
Ideally what I need is for the svg to draw its stroke inside. But even how IE 11 is doing would be an acceptable solution for me for now.

.container
{
  width: 300px;
  height: 300px;
}

  <svg version="1.1"
       baseProfile="full"
       xmlns="http://www.w3.org/2000/svg"
       width="100%"
       height="100%"
       fill="yellow"
       stroke-width="10"
       stroke="green">
    <circle cx="50%" cy="50%" r="50%" />
  </svg>

I need a solution which works for any svg, the circle is just an example
Comment: Related - http://stackoverflow.com/questions/7241393/can-you-control-how-an-svgs-stroke-width-is-drawn?
Comment: At present that's not possible. Strokes are in fact drawn half on one side of the path and the other half on the inside. There is no `stroke-position` property. You'll just have to adjust the viewbox of your SVG.
Comment: @Harry Is it really related? I'm not looking to control the stroke really, I was thinking there could be something related to the `div` or `svg`, like margins or padding or something
Comment: If the question is really a duplicate maybe I delete or close this question?
Comment: @DonBox: I think it is (but not sure which is why I just left a comment and didn't vtc). The "control" they mean is about where the stroke is drawn. By default, I think it is drawn half inside and half outside in SVG.
Comment: I find it hard to believe there's no good workaround
Comment: Is there a way to make it draw without clipping? Even if it's drawing outside of the ``. Just like IE is doing
Comment: @Harry I updated my question. Even how IE11 is drawing it would be an acceptable solution, so my question is definitely not a duplicate of that question. Could you please remove the "duplicate" status?
Comment: @DonBox: Did you check the two bullet points in Phrogz' answer in that thread? That would be the solution/workaround. I am not convinced about it being a dupe or not, so I will let the community decide on it. Since you've edited the question, it will go to the review queue anyway.
Comment: For some reason it's not possible to send in another answer but I think you are simply looking for  `overflow: visible;`  style on the SVG itself. You'll see the stroke not clipped.  I don't think you meant what photoshop has for borders as inside / outside / center, that would be just a workaround, drawing the stroke inside the circle. Most user agents are showing svg with hidden overflow.
Answer: The stroke doesn't count with the total radius. Reduce the radius:

.container
{
  width: 300px;
  height: 300px;
}

  <svg version="1.1"
       baseProfile="full"
       xmlns="http://www.w3.org/2000/svg"
       width="100%"
       height="100%"
       fill="yellow"
       stroke-width="10"
       stroke="green">
    <circle cx="50%" cy="50%" r="45%" />
  </svg>

Comment: I need to make it work for any svg. This is just an example. Sorry if I wasn't clear, I will update the question

SVG stroke drawn clipped


Are the two Or-Elims equivalent?

Question: We have:

$\varphi \lor \psi, \neg \varphi \vdash \psi$
$\varphi \lor \psi, \varphi \to \chi, \psi \to \chi \vdash \chi$

Using $2$ and explosion (ex falso), one can prove $1$:

$\varphi \lor \psi$ [premise]
$\neg \varphi$ [premise]

$\varphi$ [assumption]
$\bot$ [contradiction 2 3.1]
$\psi$ [explosion]

$\varphi \to \psi$ [$\to$intro 3.1-3.3]

$\psi$ [assumption]

$\psi \to \psi$ [$\to$intro 5.1-5.1]
$\psi$ [$\lor$elim 1 4 6]

However, can one prove $2$ from $1$ using other intuitionist rules?
Comment: I'm not sure that you can; with *modus tollendo ponens*: $\varphi \lor \psi, \lnot \varphi \vdash \psi$ we can derive (using $\to$-intro) *ex falso*: $\bot \vdash \varphi$.
Answer: No. Write $\triangledown$ for our wannabe disjunction, so we have the rule $\varphi\triangledown\psi,\neg\varphi\vdash\psi$ (and presumably we have $\varphi_i\vdash\varphi_1\triangledown\varphi_2$ as well). Then, to make use of the $\varphi\triangledown\psi$ assumption in $\varphi\triangledown\psi,\varphi\to\chi,\psi\to\chi\vdash\chi$ we need to be able to prove $\neg\varphi$. There is simply no reason this would be provable.
This is even more evident with a computational interpretation. Here's what the beginning of a proof attempt would look like in Agda:
data ⊥ : Set where

¬_ : Set → Set
¬ A = A → ⊥

postulate WOr : Set → Set → Set
postulate Left : {φ ψ : Set} → φ → WOr φ ψ
postulate Right : {φ ψ : Set} → ψ → WOr φ ψ
postulate wOrElim : {φ ψ : Set} → WOr φ ψ → ¬ φ → ψ

orElim : {φ ψ χ : Set} → WOr φ ψ → (φ → χ) → (ψ → χ) → χ
orElim wor l r = r (wOrElim wor (λ x → ? (l x)))

There is no obvious choice of what to put for the ?. Computationally, there's no way to exfiltrate the $\chi$ l produces. In the computational interpretation of classical logic, Peirce's law gives us essentially a throw/catch mechanism so we could implement orElim in a made-up, classical version of Agda with something like:
orElim : {φ ψ χ : Set} → WOr φ ψ → (φ → χ) → (ψ → χ) → χ
orElim wor l r = try {r (wOrElim wor (λ x → throw (l x)))} catch(c) { c }

This isn't a proof that it is impossible, of course. Maybe there's a clever program to do it that I didn't think of. In practice, though, programming experience combined with the computational interpretation of, particularly, intuitionistic logic makes it fairly easy to recognize that there are no data flow paths. As such, things which aren't intuitionistically provable become relatively self-evident.
If you did want to prove that you can't derive 2 from 1, you'd need to do something like an induction on the derivations, or you can make a counter-model, e.g. a topological model.
Comment: +1. I agree with your intuition; in order to use *modus tollendo ponens* we have to produce at a certain point in the derivation $\lnot \varphi$. Without Double Negation or some equivalent, the only way to "generate" the needed $\bot$ is through a contradiction.
Comment: But I do not see any way to produce a contradiction from the premises: $\varphi \lor \psi, \varphi \to \chi, \psi \to \chi$. The set of premises is clearly satisfiable.
Answer: You cannot constructively prove Proof By Cases from the suggestion Or-Elim rule.  Consider the following valuations (found by my computer):
$$\begin{array} {cc|c}
A & B & A \to B \\
\hline
  1 & 1 & 1 \\
  2 & 1 & 1 \\
  3 & 1 & 1 \\
  1 & 2 & 2 \\
  2 & 2 & 1 \\
  3 & 2 & 1 \\
  1 & 3 & 3 \\
  2 & 3 & 3 \\
  3 & 3 & 1 \\
\end{array}$$
$$\begin{array} {c|c}
A & \lnot A \\
\hline
  1  &  3 \\
  2  &  3 \\
  3  &  1 \\
\end{array}$$
$$\begin{array} {cc|c}
A & B & A \lor B \\
\hline
  1 & 1 & 1 \\
  2 & 1 & 1 \\
  3 & 1 & 1 \\
  1 & 2 & 1 \\
  2 & 2 & 1 \\
  3 & 2 & 2 \\
  1 & 3 & 1 \\
  2 & 3 & 2 \\
  3 & 3 & 3 \\
\end{array}$$
And the following logic $L$:
$$\begin{array} {ll}
\text{Axiom Schema:} & \\
\hline
A \to B \to A & \text{Weakening} \\
(A \to B \to C) \to (A \to B) \to (A \to C) & \text{Conditional Modus Ponens} \\
\hline
(A \to B) \to (A \to \lnot B) \to \lnot A & \text{Negation Propagation} \\
A \to \lnot A \to B & \text{Explosion} \\
\hline
A \to (A \lor B) & \text{Or Intro 1} \\
A \to (B \lor A) & \text{Or Intro 2} \\
(A \lor B) \to \lnot A \to B & \text{Disjunctive Syllogism 1} \\
(A \lor B) \to \lnot B \to A & \text{Disjunctive Syllogism 2} \\
\hline
\text{Inferences:} & \\
A, ~ (A \to B) \vdash B & \text{Modus Ponens} \\
\end{array}$$
Taking $1$ as the "true" value, each axiom schema is a tautology; and for modus ponens, implication has the property that if $A = 1$ and $(A \to B) = 1$ then $B = 1$.  So every provable statement is also a tautology.
However, Proof By Cases, $P(A, B, C) = (A \lor B) \to (A \to C) \to (B \to C) \to C$, is not a tautology, specifically $P(2, 2, 2)\ne 1$.  So it is not provable.
However, I suspect that replacing the negation schemas with the classical schemas $(\lnot A \to \lnot B) \to B \to A$ (or equivalent multiple rules for sanity's sake) leads to the Proof By Cases being provable since I've seen it in several logic publications.

KennyLau found the classical proof in a comment:
$$\begin{array} {rll}
 1 & X \lor Y  & \text{Premise} \\
 2 & X \to Z  & \text{Premise} \\
 3 & Y \to Z  & \text{Premise} \\
%
 4 & \quad \quad \lnot Z & \text{Assumption} \\
 5 & \quad \quad \quad \quad Y & \text{Assumption} \\
 6 & \quad \quad \quad \quad Z & \text{Imp-Elim 3,5} \\
 7 & \quad \quad \lnot Y & \text{Contradiction of assumption 5, with 4 and 6} \\
 8 & \quad \quad X & \text{Needs a name, from 1 and 7} \\
 9 & \quad \quad Z & \text{Imp-Elim 2 and 8} \\
 10 & \lnot \lnot Z & \text{Contradiction of assumption 4, with 4 and 9} \\
 11 & Z  & \text{Double negation elimination of 10} \\
\end{array}$$
Comment: Good lord. You actually set out building a model. Effort appreciated.
Comment: I like to think my computer did most of the work.  Also your question interested me and I had to know for sure.
Comment: Which software/program did you use?
Comment: @KennyLau C# for this one
Comment: Shouldn't the arrows in "Proof By Cases" be conjunctions?
Comment: I've used Mace4 to build a model and it looks similar to your model.
Comment: Assuming $\neg C$, then use intuionistic modus tollens to prove $\neg A$, and use our or-elim to prove $B$, whence $C$. Now, use classical modus tollens to derive $C$.
Comment: @KennyLau $A \to (B \to C)$ is equivalent to $(A \land B) \to C$, that is usually how $\land$ is defined.  Your last statement looks right to me, so it is classically equivalent.  I'll edit my post to include it.
Comment: My comment was regarding $(\lnot A \to \lnot B) \to B \to A$ which I named "classical modus tollens"...
Comment: I just noticed I'm doing a constructive proof in Hilbert style and a classical proof in Fitch style.  FeelsBadMan
Comment: I suppose they're easy to convert...
Comment: Btw, I want to say that I don't agree with calling this a model (although I know it is common).  A model theoretic model has some external concept of true/false informally defined (or not defined at all) guiding it's considerations.  Here the concept of true/false is being defined (or bypassed if you prefer).  This is a valuation of propositional logic, much more reliable.
Comment: You can view this as a model of "truth/falsehood" I suppose. The concept of true/false is outside the model.

Are the two Or-Elims equivalent?


Valgrind não mostra qual a linha onde ocorreu o erro

Question: Estou tentando utilizar o Valgrind para o Linux, a fim de checar perdas de memória, entretanto, o erro mostrado no terminal não exibe em qual linha específica ele está.
==4873==  Address 0x4a4e047 is 0 bytes after a block of size 7 alloc'd
==4873==    at 0x483DD99: calloc (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)
==4873==    by 0x109221: getName (in /home/rodrigo/Documentos/VsCodeTest/a.out)
==4873==    by 0x1091D5: main (in /home/rodrigo/Documentos/VsCodeTest/a.out)
Answer: Para fazer com que o valgrind exiba as linhas, você pode primeiro compilar o programa utilizando o GCC com a flag -g que indica para a compilação ser efetuada providenciando informações de debug:
gcc -g meu_programa.c -o meu_programa
Quando executar o valgrind, informe a flag --leak-check com o valor full:
valgrind --leak-check=full ./meu_programa
Valgrind deveria exibir mais detalhes sobre o vazamento de memória identificado. Como exemplo, para um programa onde não liberei a memória de um char* que havia sido alocada anteriormente, a mensagem abaixo foi exibida no meu terminal:
==387== 20 bytes in 1 blocks are definitely lost in loss record 1 of 1
==387==    at 0x483B7F3: malloc (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)
==387==    by 0x1091CD: main (practice.c:8)

Espero ter ajudado de alguma forma.


Closest point on a line segment to the x-axis

Question: Knowing the (x,y,z) coordinates of the two endpoints of a line segment in 3D space, how can I calculate the point on the line segment that is a minimum distance to the x-axis?
EDIT: Assume it is known that neither endpoint of the line segment is the closest point, so we must calculate which point along that line segment is closest.
I see many examples of calculating the minimum distance from a line to a point, but I am not sure how to modify it for my use case.
Thank you.
Answer: Answering edited question (original answer to original question follows):
The distance of a point from the x-axis is $\sqrt{y^2+z^2}$, so it suffices to minimize $y^2+z^2$.  A line can be parameterized as $(x,y,z)=(f(t),g(t)h(t))$ for linear $f, g, h$.  You need to minimize $g(t)^2+h(t)^2$, which is a quadratic polynomial in $t$ and thus an easy calculus problem.

Answer to original question:
Find the minimum distance from the line to the x-axis--and also the minimizing point P.  If P is on your line segment, that's the answer.
Otherwise check the distance of the endpoints of the line segment from the x-axis.  Whichever of those is closer, that's then the answer.
Justification is that this is a convex problem, so there's a unique local minimum along the line, which is also a global minimum.  So on any closed interval, if the global minimum isn't in the interval, the minimum for that interval is at an endpoint.
The exceptional case would be the line could be parallel to the x-axis.  Then any point on the segment would have the same distance, so that would be easy to diagnose.  (Not to mention the formula for the line being (x,y,z)=(t,C,D) would be a dead giveaway...)
Comment: Hi C Monsour.  I appreciate your efforts but it's not quite enough for me to go on.  I have edited my question for clarity, with the knowledge that neither endpoint is the point of minimum distance; the point of minimum distance (in my scenario) is known to be somewhere along the segment, but not at either end.  I am looking for more information regarding calculating that minimum distance point P.  Thank you again.
Comment: Sorry, the way you originally stated the problem, I thought you said you knew how to do the case of a line and wanted to know how to handle a line segment.
Answer: $\newcommand{\bbx}[1]{\,\bbox[15px,border:1px groove navy]{\displaystyle{#1}}\,}
 \newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack}
 \newcommand{\dd}{\mathrm{d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
 \newcommand{\ic}{\mathrm{i}}
 \newcommand{\mc}[1]{\mathcal{#1}}
 \newcommand{\mrm}[1]{\mathrm{#1}}
 \newcommand{\pars}[1]{\left(\,{#1}\,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,}
 \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
 \newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$

The line segment is parametrized as
  $\ds{\vec{p}_{0} + \mu\Delta\vec{p}}$ where $\ds{\vec{p}_{0}\ \mbox{and}\ \vec{p}_{0} + \Delta\vec{p}}$ are the end points and $\ds{0 \leq \mu \leq 1}$. The $\ds{x}$-axis is parametrized as $\ds{\nu\hat{x}}$. The distance between a given point in the segment and a givent point $\ds{\nu\hat{x}}$ in the
  $\ds{x}$-axis is given by
  \begin{equation}
\mrm{d}\pars{\mu,\nu} \equiv
\verts{\vec{p}_{0} + \mu\Delta\vec{p} - \nu\hat{x}}
\label{1}\tag{1}
\end{equation}
  So, you can minimize $\ds{\mrm{d}^{2}\pars{\mu,\nu}}$ respect $\ds{\mu\ \mbox{and}\ \nu}$ with the condition $\ds{\mu \in \bracks{0,1}}$:

\begin{align}
\mrm{d}^{2}\pars{\mu,\nu} & \equiv
\bracks{\pars{\vec{p}_{0} + \mu\vec{p}_{1}} - \nu\,\hat{x}}^{2} =
p_{0}^{2} + \mu^{2}p_{1}^{2} + \nu^{2} + 2\vec{p}_{0}\cdot\vec{p}_{1}\mu -2p_{0x}\nu -2p_{1x}\mu\nu
\\[5mm]
0 & = \partiald{\,\mrm{d}^{2}\pars{\mu,\nu}}{\mu} =
2\mu p_{1}^{2} + 2\vec{p}_{0}\cdot\vec{p}_{1} - 2p_{1x}\nu\,,\qquad
0 = \partiald{\,\mrm{d}^{2}\pars{\mu,\nu}}{\nu} =
2\nu - 2p_{0x} - 2p_{1x}\mu
\\[5mm]
&\left.\begin{array}{rcrcl}
\ds{p_{1}^{2}\mu} & \ds{-} & \ds{p_{1x}\nu} & \ds{=} & \ds{-\vec{p}_{0}\cdot\vec{p}_{1}}
\\[1mm]
\ds{p_{1x}\mu} & \ds{+} & \ds{\nu} & \ds{=} & \ds{{p}_{0x}}
\end{array}\right\}\qquad
\pars{\begin{array}{ll}
\ds{\left. 1\right)} &
\mbox{Find}\ \ds{\mu}\ \mbox{and}\ \ds{\nu}\ \mbox{from those equations.}
\\[2mm]
\ds{\left. 2\right)} &
\mbox{If}\ \ds{\mu \in \bracks{0,1}},\ \mbox{the answer is given}
\\ & \mbox{by evaluation of}\ \eqref{1}\ \mbox{with the values}
\\ & \mbox{of}\ \ds{\mu}\ \mbox{and}\ \ds{\nu}\ \mbox{you already found in}\
\ds{\left. 1\right)}.
\\[2mm]
\ds{\left. 3\right)} &
\mbox{If}\ \ds{\mu \not\in \bracks{0,1}},\ \mbox{the answer is given}
\\ & \mbox{by}\ \ds{\min\braces{\mrm{d}\pars{0,\nu},\mrm{d}\pars{1,\nu}}}.
\end{array}}
\end{align}


Como é testado o kernel Linux ou programas escritos em C?

Question: Quando utilizamos linguagem Java, utilizamos o JUnit para testar os códigos. Mas os códigos escritos em C, como o kernel Linux, como é testado?
Answer: Em tese pode-se usar qualquer metodologia de teste e qualquer ferramenta que ajude este processo em C pode ser usada.
Em Java você usa JUnit, outros programadores usam outra coisa.
Até onde eu sei o Autotest é usado pela comunidade de desenvolvimento do Linux Kernel.
Pelas informações que eu li há iniciativas de testes independentes também, algumas bem organizadas, como o Linux Test Project.
Além disto a comunidade é muito ativa e nem sempre é usada uma metodologia muito formal como ocorre em certos projetos.
Em alguns tipos de projetos por si só e pelo tipo de programador envolvido, os testes formais se tornam menos necessários. Não espere que tenha um grupo que responsabilidade formal de testar qualquer alteração enviada para o repositório. O Linux é um projeto que mostra que se dá mais ênfase aos testes do que deveria. Um projeto tão complexo e que tem reputação de qualidade se vira bem sem testes ostensivos.
Olhando por outro lado, alguns tipos de projeto sequer são adequados para testes de unidade.
Algumas ferramentas para testes de unidade em C:

AceUnit
API Sanity Checker
GNU Autounit (parece morto)
Automated Testing Framework
Check
CUnit
CuTest
CppUnit
embUnit
Google Test framework


Can I delete a large LDF file in SharePoint?

Question: I've got a LDF file within my SQL 2005 path for SharePoint.  It's 5.8 GB in size.  Can I move it or delete it without killing my SharePoint data??
Answer: LDF files are the transaction log files for SQL server.  I would not delete it directly, but rather..
<code>1. Right click WSS_Content and choose Tasks -> Backup
2. Select backtup type "Transaction log", select destination backup file and click Ok.
3. After backing up the DB, right click WSS_Content and choose Tasks -> Shrink -> Files
4. Select the type log and shrink action (eg release unused space)
</code>
If you don't need the transaction log, you can alter your database to use a 'Simple' rather than 'Full' recovery model, which will not keep these large files around.  MSDN Link
FAIR WARNING: Always have a backup of your database/data/settings before you start mucking with it.
Answer: No, you shouldn't move or delete it (you will be unable to do so anyway if sql server is running)  doing so can corrupt your database and leave it in an inconsistent state.
This is the transaction log  file for your SharePoint database.  It has grown to this size because:

Database is in full recovery and
you've run at least one full backup
You're in simple recovery and you're
database has been under heavy load
with many open transactions and you
transaction file has 'auto grown' to
this size.

The solution for #1 is that you need to start doing regular log backups, or change your recovery model to simple
The solution for #2 is that you shrink the log if you really need the space, otherwise let it be.
EDIT:
If you have space capacity on another drive then you can do a detach/attach moving the log file to another drive to avoid having to re-build the disk to a larger size.   It's best practice to have your log files on different disks to your data files anyhow.  Ensure you do the detach/attach logged in as sa (i.e. don't use integrated authentication)
Comment: Since I've done a complete backup of the Farm could I rebuild the RAID to consume the entire HDD space (currently a partition of 12 GB which is the SharePoint/OS and another one of 220 GB) and then do a restore?
Answer: How large is your .mdf file for that database?  SharePoint databases can grow quite large, and it's possible that 5.8GB is an appropriate size for your log file.
Answer: Dont worry. Go ahead and delete it right through. SharePoint will continue working as expected. If it doesnt, then contact the database guys for help. They can restore anything anywhere.
Comment: Don't just suggest removing files! And please, don't heed such advise without your own investigation into the matter.


Why is my choir director telling a bunch of rednecks to drop their Rs as though they were Londoners?

Question: I currently live in the American South, where every English speaker within a hundred miles speaks with a rhotic accent. Recently, I spent an afternoon with a local choir in practice, and was somewhat perturbed by the instructions given by the director to drop Rs and modify vowels to sound more British — non-rhotic, specifically. I've spent a fair amount of time over the last few years learning some of the finer points of English (especially for second-language learners), so this smacks of trying to teach someone a prestige dialect. Most of my (formal) musical experience has been on the violin, so is there a specific musical reason non-rhotic accents are preferable for singing, or is it just a matter of this person's arbitrary taste based on which dialects currently sound impressive, high-class, and fancy?
Poking around online suggests it may have something to do with certain American vowels constricting airflow slightly; how significant is this effect, and how does this connect to rhoticity?
Comment: Comments are not for extended discussion; this conversation has been [moved to chat](http://chat.stackexchange.com/rooms/38714/discussion-on-question-by-nathan-tuggy-why-is-my-choir-director-telling-a-bunch).
Answer: It's not arbitrary. American accents in choral singing (especially Southern) produce several disadvantages in tone, tuning and volume. Specifically, the American hard "r" forces the speaker/singer to close the jaw and lift the tongue, both of which reduce the air space within the mouth and the back of the throat, reducing resonance. The result when singing is that volume drops, tone becomes thinner and "wider", and pitch falls off the center as the resonant space and mouth movements push the pitch sharp or flat.
In much the same way, most American spoken vowels drive choral directors crazy when used to sing any language including English. Long E is probably the most difficult to get American singers to pronounce correctly because it's the hardest to achieve with the "tall" mouth position, but if you "widen" the vowel in typical American style, the tone goes thin for much the same reasons as hard Rs. Long A is most often pronounced as a dipthong "ay", closing the vowel to the same wide, thin "ee" as the note progresses. Long I is most often pronounced "eye" with a combination of the problems of A and E. Long O is usually OK, unless you want the "ecclesiastical Latin" pronunciation of "aw" for Church Latin (American singers trend that toward "oh"), while long U is typically squeezed into a flat "ew" sound when a tight, round "ooh" is usually favored.
Your accent or affect in spoken American English and the affect that you use to sing in English (or really any language) are very different, which makes teaching European-style choral singing to Americans that much harder. It's very true that if you were to speak the way you're supposed to sing, you'd sound like a third-generation heir or heiress fresh out of the Ivy Leagues; in other words, a pompous jackass. However, that same accent is critical for a "tall, round" tone that is pleasing to the ear when used for sustained tones.
For American popular music, pure, round vowels aren't as important; you have a mike in your face amplifying and compressing your vocal dynamics to even out the diction issues, and you're trying to sound like an ordinary person, especially in country and southern rock where the "twang" in your voice is a hallmark of the genre. That's not the style in most choral music.
Comment: It's possible to sing an American "r" well, but it's probably seen as easier to teach people to drop them than to teach them how to sing them well. (In my opinion the problem is at least as much about muscle tension as about resonance.) The problem with that approach, though, is that you can't drop them all.
Answer: It's common for a certain musical style to be associated with a certain accent. Adele ditches her Norf Laaaaaaandan accent for a distinctly American sound when she's belting out her latest soul-tinged ballad. Birmingham (UK)-born Ali Campbell of reggae act UB40 does a half-decent job of sounding like a Jamaican. On the flip side, punk singer Joey Ramone's accent is distinctly Cockney street urchin.
The expectation with a lot of choral singing is for

Very open vowel sounds
An emphasis on steady vowel sounds. With diphthongs, one part of the sound tends to be de-emphasised to maintain a steady sound.
Consonants being de-emphasised both in time and volume

All these aspects would seem counter to the use of an emphasised 'r' sound - and while they might seem to be British traits, they are found in a lot of European choral singing, much of which would have originally been (and often still is) in Latin rather than English. Much may come down to what makes a coherent, resonant sound in a large, highly-reverberant stone building.
It is also partly just down to expectations, and you can probably think of singers and groups who do perfectly well singing a 'foreign' style in their native accents. Likewise, if the vast majority in your choir strongly wish to try to sing with a more local accent, and you have the knowledge and experience to make that work, why not?
Answer: It's a bit old-fashioned, and reasons have to do with placement (our accent has a lot of nasalization of vowels) and airflow restriction (try saying "er" as you normally do, and then the way the Brits do it, and you'll see that you don't restrict the airway as much in the latter).
However, while these reasons may be musical reasons, they are also pretty arbitrary. There's no reason that your singing has to sound like a Hollywood actress fresh out of 1940's diction school, as Celine Dion demonstrates in the example below.  In fact, broadcasters, actors and singers were all taught a particular sort of accent back in those days, and the rules your director is mentioning are artifacts of that accent.  See this (at 2:12, near the end):

While technically fabulous (much better than Dion from a purely technical standpoint IMO), Kate Smith sounds pretty dated here with "God Bless America":

She sounds dated mainly because of the way she does her vowels and her r's (that "Transatlantic" accent), although she manages it somehow without sounding entirely affectatious.  Here's Celine Dion's version:

Compare "Stand beside, her, and guide her" in each, and you'll see that Dion uses more of a rhotic "er" than Smith does and sounds just fine. (She also says "Gaw bless America" and Smith doesn't, but that's something for another discussion.  Smith was technically superior to Dion in every way, but that isn't what makes music in the end.)
There are those who would argue that rhotic vowels and er's and all that don't work in ensemble, and I would respond that they do in my experience.  There's no reason that you can't make any sound you want in sung music.  The issue is more consistency and clarity than anything else.  My feeling is that your director has taken a traditional approach to vowels, and it isn't the only valid one.
Comment: Most of Britain actually is rhotic. The non-rhotic accents are the prestige ones of the south-east. RP and its relatives.
Comment: Celine dion is a Canadian.


Erro em insert com ADOCommand

Question: Em Delphi XE4, SQL Server 12, conectado por ADOConnect.
ADOCommand1.commandText sendo 'insert into tabela (a,b,c) (1,1,1)'
Funciona como esperado, se já existir um registro. Mas se for o primeiro registro aparece a mensagem:

"Uma linha vazia não pode ser inserida, a linha deve ter pelo menos um
  valor de coluna definido"

Apesar da mensagem, o registro é incluído, verificado por uma query posterior.
Comment: Faltam detalhes mas creio que no segundo INSERT não estão passados valores para o objeto.
Comment: Acho que a sintaxe correta seria `INSERT INTO TABELA (a, b, c) **VALUES** (1, 1, 1)`, não?
Answer: A Sintaxe esta incorreta
Seria assim
SQL.ADD('insert into tabela (a,b,c) VALUES (1,1,1)');

Answer: Não falta a palavra reservada INTO?
insert into tabela (a,b,c) INTO (1,1,1)
Comment: a sintaxe correta é `INSERT **INTO** tabela (campo1, campo2) **VALUES** (valora, valorb) `

Erro em insert com ADOCommand


how to test mobile touch event functions on a browser which is installed on my PC?

Question: how can I test the touch event functions I have programmed? I am programming all this on my persona computer. I do not have money to buy a phone with which I can touch the screen and test the touch event functions I programmed.
Please tell me if there is a solution for this problem.
Answer: Just use the Chrome DevTools and turn on the device-mode.
For reference
https://developers.google.com/web/tools/chrome-devtools/device-mode/
Moreover, the link below describe the touch event on mobile, which is different from the click and mouseover event.
https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent
Answer: one way that works on most (any?) browser is to use hammerjs touchemulator in your code
<code><script src="https://cdn.rawgit.com/hammerjs/touchemulator/master/touch-emulator.js"></script>
</code>


If $S$ is a linear transformation from $\mathbb{R}^2$ to $\mathbb{R}^2$ such that $S \circ S = S$, prove that $S$ can be:

Question: We have that $S \circ S = S$, I want to prove that $S$ can be

$S = 0$ (The zero transformation) or
$S(x) = x$ (The Identity transformation) or
$S$ can have a basis $A$ such that $[S]_{A}^{A} = \begin{pmatrix}
1 && 0 \\
0 && 0
\end{pmatrix}$

I have that all of the three propositions are True, 3 is like to say that S can be a projection, in this case, over the $x$-axis, 2 can be done by see that $S(x) = S(S(x)) = x$, but what do you think? I try to find more about in the some books (I study for myself, not attending a school for now, but I love math, I try to solve the most, but some are really strange for me) thanks
Answer: There are 3 mutually exclusive and exhaustive cases. One is, kernel is of dimension 2 in which case you get the zero operator i.e. S=0, second case,  when kernel is of dimension zero in which case you get the identity operator i.e. S=I and third case,  kernel is of dimension one in which case image is of dimension one and you get the matrix you have given in your third case.
Answer: If $\text{im}(S)$, the image of $S$, is $0$-dimensional then $S=0$.
If $\text{im}(S)$ is $2$-dimensional then any vector in $\mathbb{R}^2$ can be written as $S(x)$ for some $x\in \mathbb{R}^2$, so the relation $S(S(x))=I(S(x))$ implies that $S=I$.
Consider the final case where $\text{im}(S)$ is $1$-dimensional. We claim there is a non-zero vector which $S$ fixes. Indeed, take an $x\in \mathbb{R}^2$. If $S(x)=x$ we are done. If not, then the relation $S\circ S=S$ implies that $S$ fixes $y=x-S(x)$. Now take any vector in $\mathbb{R}^2$ which is linearly independent of this $S$-fixed vector and you have the basis for the final case.
Answer: If $S$ is such that $S^2 = S$ then
$$
S^2 - S = 0
$$
and so $S$ is annihilated by the polynomial $x^2 - x = x(x - 1)$. Therefore, the minimal polynomial $\mu_S(x)$ of $S$ divides $x(x - 1)$. This leaves only three possibilities:

$\mu_S(x) = x$ which means that $S = 0$.
$\mu_S(x) = x - 1$ which means that $S = I$.
$\mu_S(x) = x(x - 1)$ which means that both $0$ and $1$ are the eigenvalues of $S$ and therefore we have

$$
S = \begin{pmatrix}
1 & 0 \\
0 & 0
\end{pmatrix}
$$
in the eigenbasis of $S$.
Answer: As others have already pointed out, this is really just a classification of the possible ranks of $S$ ("rank" here meaning the dimension of the image $S(\mathbb{R}^2)$, which can only equal $0,1$ or $2$). Here is a detailed argument that avoids using minimal polynomials:
If $S$ is rank $0$, then $S(\mathbb{R}^2)$ has dimension zero and is hence $\{0\}$, meaning $S$ is the $0$ transformation.
If $S$ is rank $2$, then it is invertible (it has trivial kernel by rank-nullity), so precomposing the equation $S^2 = S$ with $S^{-1}$ gives $S = I$, the identity.
Finally, suppose $S$ is rank $1$. The space $S(\mathbb{R}^2)$ is a subspace of $\mathbb{R}^2$, so take a basis vector $u$ of this subspace. Also note $S(u)=u$ (which can be seen by writing $u=S(x)$ and using $S^2=S$). Since the kernel of $S$ also has dimension $1$, we can pick a basis vector $v$ of this subspace as well. We claim $\{u,v\}$ is a basis of $\mathbb{R}^2$. By dimension it suffices to show $\{u,v\}$ is a linearly independent set. If $\lambda_1u+\lambda_2v=0$, then applying $S$ to this equation gives $\lambda_1u = 0$, so $\lambda_1=0$. But then $\lambda_2v = 0$, so $\lambda_2=0$ as well. This proves the claim.
Finally, put $A = \{u,v\}$. Since $S(u) = (1)u+(0)v$ and $S(v) = (0)u+(0)v$, it has the desired matrix representation
$$[S]_A^A = \begin{bmatrix}1 & 0 \\ 0 & 0\end{bmatrix}.$$
As a final remark: the property $S^2=S$ is called idempotence, and this result generalizes to higher dimension. See, for example, this question.


Is it possible to support multiple domain names on a single web application?

Question: My goal is to create a service that will allow someone to register their own domain (so, many domains being used), and have that domain point to a specific service/template within a single web application.
Is this possible using URL rewriting or some other method? I want to have a vanity domain that would essentially act as the unique identifier within my application...
So instead of www.myapplicationdomain.com/site/1 and www.myapplicationdomain.com/site/2, i could allow a vanity domain that my application would utilize.

www.customwdomain.com = application/site/1
www.bettercustomwdomain.com = application/site/2

Is this possible, or would i essentially have to dynamically create new websites in IIS and drop files in those folders that the domain would point to? I know IIS can support multiple websites on the same host, but I was trying to take it a step further.
I guess my question is very similar to this question:
IIS with multiple domains on one single web application
Some considerations:

Trying to make this work on Azure shared hosting
I don't want to use sub-domains
I want the vanity domain to always be in use (e.g. not a redirect)
Comment: I don't think that addresses what I'm trying to do. I'm not trying to host multiple domains on one server, I'm trying to have one application recognize and react to multiple domains - not sure it is possible.
Comment: check it, it's helpful to you [blog](http://weblogs.asp.net/owscott/iis-url-rewrite-hosting-multiple-domains-under-one-site)
Answer: It is possible.
We have an Ecommerce web application that has many web domains being pointed to it, each with their own unique interface. This is entirely dependent on technologies of the Apache software foundation, and I'm not aware of a way to do this without a web server sorting out domains for the application.

We rely on Apache HTTP server for Virtualhost configurations (the listener & configs for each domain), and for serving static content.
We rely on Apache Tomcat for the single Java app that displays most of the interface and functionality. The Apache HTTP server is configured to pass relevant traffic to the Java app.
Answer: Configure multiple custom domains to an web-app and then add application gateway at the front of the application. Now based on the application url redirect to the updated url of the website.


ring of integers with golden ratio

Question: How to show that the ring of integers of $\mathbb{Q}(\sqrt{5})$, i.e., $\mathbb{Z}[\phi]$ is a principal ideal domain (where $\phi$ is the golden ratio)?
I want to prove that using as elementary algebra-level notions as possible.
Give some advice!  Thank you!
Answer: The ring of integers of $\Bbb Q(\sqrt{5})$ is Euclidean, and hence a PID. The proof is by elementary algebra.
Reference: Prove that $R =\mathbb{Z}\left[\frac{1+\sqrt{5}}{2}\right]$ is a Euclidean domain.
The details of the proof are very similar to the ones of this post:
Proof that $\mathbb Z[\sqrt{3}]$ is a Euclidean Domain
Comment: Thank you for linked. That's great.

ring of integers with golden ratio


Is it possible to use .htaccess to instruct browsers to cache google analytics?

Question: When I run Google PageSpeed Insights I get the following optimization suggestion.

When I click the Leverage browser caching link it sends me to a page that recommends I use Cache-Control or ETags.
Setting up Cache-Control with .htaccess should be simple enough so I included the following lines inside of my existing .htaccess file.
<IfModule mod_headers.c>

<filesMatch "https://www.google-analytics.com/analytics.js">
Header set Cache-Control "max-age=7200, public"
</filesMatch>

<filesMatch "https://www.googletagmanager.com/gtag/js?id=UA-00000000-0">
Header set Cache-Control "max-age=900, public"
</filesMatch>

</IfModule>

I uploaded the .htaccess file, tested it and got the same error.  Even though Google recommends using Cache-Control that doesn't solve the problem.
When that didn't work I tried ExpiresByType but it didn't solve them problem either.
<IfModule mod_expires.c>

ExpiresActive On

<IfModule mod_expires.c>
ExpiresByType application/javascript "access plus 2 hours"
</IfModule>

</IfModule>

Is there a way to use an .htaccess file to instruct browsers to cache these files or is that not possible?
Answer: Nothing in .htaccess can affect a domain outside of your control.
You have a couple options.

Self-host the gtag.js file, which is possible but not recommended.
Proxy the gtag.js file, adding your own headers to it. This addresses the main concern (updates) from the above doc.
Ignore it. It's essentially a false-positive; Google has presumably intentionally set a low cache time for these assets for a reason.