Ao fazer o diagrama de classes é necessário adicionar todos os métodos e atributos?

Question: Tenho várias classes que possuem diversos atributos e métodos. Ao fazer o diagrama de classes é necessário adicionar todos os métodos e atributos? Existe alguma regra ou consenso sobre a criação desses?
Comment: Alguma das respostas resolveu sua dúvida? Acha que pode aceitar uma delas? Veja o [tour] como fazer isso, se ainda não o fez. Você ajudaria a comunidade identificando qual foi a melhor solução para você. Pode aceitar apenas uma delas. Mas pode votar em qualquer pergunta ou resposta que achar útil no site todo.
Answer: Depende. Você quer fazer certo ou quer fazer de qualquer jeito? Se quer fazer certo então precisa. Nem deveria ter que pensar nisso. O propósito de fazer UML é documentar tudo. Se for para fazer pela metade então pra que fazer?
Na verdade por que está fazendo UML? Se não souber porque e esse motivo não for muito bom, não puder provar que está te dando alguma vantagem, por que fazê-lo? As pessoas estão fazendo muita coisa automaticamente porque viram outras fazendo, elas nem sabem porque estão fazendo aquilo, se tem vantagem.
Um exemplo está em outra resposta. As pessoas usam getters e setters sem pensar. Quase sempre o seu uso está errado, mas tem tanta gente fazendo errado que já parece que é certo. Os mais radicais em orientação a objeto dizem que eles nunca devem ser usados porque são métodos que não tem um propósito específico, ele só serve para encapsular estado, e métodos assim não deveria existir. Os mais pragmáticos consideram que eles só estão encapsulando estado sem ganho algum. A maioria das pessoas não conseguem responder porque criam getters e setters, apenas estão fazendo o que viram outros fazendo (e que fique claro, se for para ter no código, tem que ter no UML, senão esta representação é equivocada, a crítica aqui é ter no código, não só no UML). UML é para fazer pensar no que está fazendo antes de fazer, é para ter certeza se precisa daquilo, se não falta nada, se tudo vai encaixar bem. Quando faz automaticamente não precisa de UML.
UML é burocracia, se não for para fazer certo, não faça. Em outra resposta diz que deve por tudo ou só parte dependendo de as pessoas vão precisar saber se o sistema terá aquilo. Mas é para alguém não saber? Você vai colocar no sistema uma coisa e documentar outra? Que sentido isso faz? UML já é criticada porque ela não costuma ser DRY. Agora ainda vai explicitar que eles devem ser independentes?
As pessoas precisam pensar no que fazem, não seguir regras bobas que elas não sabem porque foram inventadas.
Como usou tag de linguagem tenho que dizer que os termos usados estão corretos para UML, mas para Java não estão.
Answer: Pelo que eu saiba não existe uma regra geral para todos os casos. Isso vai depender muito de quem vai precisar dos seus diagramas, pois UML é uma notação usada na comunicação entre os desenvolvedores. Desenvolvedores tanto aqueles que estão colaborando com você agora e também aqueles que podem continuar o projeto no futuro.
Portanto, é preciso analisar se você ou alguém vai precisar saber se o sistema tem determinado método ou atributo e qual a sua função no sistema. Por isso que muitos falam que getters e setters não precisam ser colocados, pois não são relevantes para maioria das pessoas.


External linking crypto/rc4.a fails

Question: I'm having issues compiling code that deep somewhere in itself it tries to link to go's crypto/rc4 but returns with the following linking error:
truncated object file: /usr/local/go/pkg/linux_amd64/crypto/rc4.a: EOF
crypto/rc4.NewCipher: call to external function
crypto/rc4.init: call to external function
crypto/tls.cipherRC4: relocation target crypto/rc4.NewCipher not defined
crypto/tls.cipherRC4: relocation target type.*crypto/rc4.Cipher not defined
crypto/tls.init: relocation target crypto/rc4.init not defined
crypto/tls.cipherRC4: undefined: "crypto/rc4.NewCipher"
crypto/tls.cipherRC4: undefined: "type.*crypto/rc4.Cipher"
crypto/tls.init: undefined: "crypto/rc4.init"

The following are my go variables:
GOPATH=/home/sfines/workspace/audit_system
GOROOT=/usr/local/go

My Go version is :
go version go1.9.2 linux/amd64
I've made sure that there is only one version of Go installed. I'm at my wits end.
Comment: Could you try the very same VM but with a newly extracted tarball in a completely different directory? (eg: `/home/sfines/go` and set `GOROOT` to that). Keep the install you have though.
Comment: How did you install 1.9.2? Did you `rm -rf /usr/local/go` first, or did you overwrite the previous install? And how did you install it? (official tarball, package)? Code to reproduce it would be great too.
Comment: It was installed a clean VM, so no prior install; installed following the go instructions...
Comment: That's got it, don't know why it got hosed but thanks.
Comment: Could you diff the two installs? My guess is the original extract got killed. You may want to check the install process and have it surface errors properly.
Answer: This is a badly-extracted Go install with missing or partial files. A fresh install (with no errors) fixes the issue.

External linking crypto/rc4.a fails


How to have a Zoom option for text files in android app using android Native coding

Question: I am having a requirement to create a app that has one of function to display the text file . In this there are two button to Zoom in and Zoom out . How should we do this using android native coding?
Answer: I've found an answer that does this using Pinch to zoom: https://stackoverflow.com/a/14306988/1683141
I don't know if it is necesairy for you to actually have zoom in/out buttons or if pinch to zoom will do:
<code>public class MainActivity extends Activity {

    TextView scaleGesture;
    ScaleGestureDetector scaleGestureDetector;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        scaleGesture = (TextView)findViewById(R.id.article);
        scaleGesture.setText("this is some text");
        scaleGestureDetector = new ScaleGestureDetector(this, new simpleOnScaleGestureListener());
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        // TODO Auto-generated method stub
        scaleGestureDetector.onTouchEvent(event);
        return true;
    }

    public class simpleOnScaleGestureListener extends
            SimpleOnScaleGestureListener {

        @Override
        public boolean onScale(ScaleGestureDetector detector) {
            // TODO Auto-generated method stub
            float size = scaleGesture.getTextSize();
            Log.d("TextSizeStart", String.valueOf(size));

            float factor = detector.getScaleFactor();
            Log.d("Factor", String.valueOf(factor));

            float product = size*factor;
            Log.d("TextSize", String.valueOf(product));
            scaleGesture.setTextSize(TypedValue.COMPLEX_UNIT_PX, product);

            size = scaleGesture.getTextSize();
            Log.d("TextSizeEnd", String.valueOf(size));
            return true;
        }
    }
}
</code>
Also, here is for dynamically setting textview layout attributes (so you can also use it for font size): https://stackoverflow.com/a/4632208/1683141
<code>    myTextView.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view){
            //highlight the TextView
            myTextView.setTextAppearance(getApplicationContext(), R.style.boldText);
            myTextView.setBackgroundResource(R.color.highlightedTextViewColor);
        }
    });
</code>
Ofcourse, you'll need the folowing style references in style.xml
<code>   <?xml version="1.0" encoding="utf-8"?>
<resources>

    <style name="boldText">
        <item name="android:textStyle">bold|italic</item>
        <item name="android:textColor">#FFFFFF</item>
    </style>

    <style name="normalText">
        <item name="android:textStyle">normal</item>
        <item name="android:textColor">#C0C0C0</item>
    </style>

</resources>
</code>
And add the folowing to the "strings.xml" file like this:
<code> <color name="highlightedTextViewColor">#000088</color>
 <color name="normalTextViewColor">#000044</color>
</code>


Quadratic Equation Problem....

Question: I am stuck on this problem:

If $\sqrt{x^2+4ax+5}+\sqrt{x^2+4bx+5}=2(a-b)$ then $x=?$

I did the following things
1) For solution to exist a≥b
2) $x^2+4ax+5≥0$ which implies that $16a^2-20≤0$
On differentiating the quadratic $x^2+4ax+5=0$, I get $x=-2a$. Since the parabola is opening upwards the function must lie above or on the x axis at thus x. Therefore, $4a^2-8a+5≥0$
From both of these I got the range of a,b as $R-[-1/2,1/2]$
Beyond this, I am stuck. Any hints?
Answer: We have, on simple manipulation, $$\sqrt {x^2+4ax+5} + \sqrt {x^2+4bx+5} =2 (a-b) $$ $$\Rightarrow x^2+4ax+5 =4 (a-b)^2+ x^2+4bx +5 -4 (a-b)\sqrt {x^2+4bx+5} $$ $$\Rightarrow 4ax -4bx =4 (a-b)(a-b) -4 (a-b)\sqrt {x^2+4bx+5} $$
Assuming $(a-b) \neq 0$, we get, $$x = (a-b) -\sqrt {x^2+4bx+5} $$ $$ \Rightarrow x^2+4bx+5 = (a-b)^2 +x^2 -2x (a-b) $$ $$ \Rightarrow 2ax + 2bx = (a-b)^2+5$$ $$\Rightarrow x = ? $$
Hope it helps.

Quadratic Equation Problem....


Importar um .java em outro .java

Question: Tenho 2 códigos:
Código 1:
class Principal {

public static void main(String[] args){

Pessoas pessoa1 = new Pessoas();
pessoa1.idade = 1;
pessoa1.nascimento = 2;
pessoa1.altura = 0.5;
pessoa1.nome = "texto";

}
}

Código 2:
class Pessoas {

int idade;
int nascimento;
double altura;
String nome;

public static void main(String[] args){

}
}

Já tentei usar o package e import, porém não funcionou. Acho que usei eles errados. Como eu uso eles para usar o código 2 no código 1?
OBS: Os dois códigos estão na mesma pasta.
Comment: Sim os 2 códigos estão na mesma pasta e preciso que o código 1 acesse o código 2 para criar os dados da pessoa1
Comment: Funcionou normalmente comigo.
Comment: aqui da erro falando que `Pessoas pessoa1 = new Pessoas();` diz que não e possível encontrar o simbulo Pessoas
Comment: Então você não está colocando as duas no mesmo package.
Comment: os 2 estão na mesma pasta e o código esta extamente como eu coloquei no post
Comment: Como eu disse, simulei aqui e não deu nada, esse erro ocorre quando uma classe não é oncontrada. Se as duas estivessem no mesmo pacote, não daria este erro.
Comment: como eu boto as 2 no mesmo package? para ver se esse erro some
Comment: Se estiver usando eclipse ou netbeans, é só arrastar a classe para o mesmo pacote que a outra estiver.
Comment: não usso nenhum dos 2 crio os código usando Notpad++, não consigo usar nenhum dos 2
Comment: Sem ide, basta colocar os arquivos na mesma pasta.
Comment: então eu to usando na mesma pasta porem no cmd fala que `Pessoas pessoa1 = new Pessoas();`não e possível encontrar o sinbulo Pessoas
Comment: Bom, então não sei como te ajudar. Pois simulei criando na ide, depois criando manualmente no notepad e cmd, e nas duas formas funcionou normalmente aqui. O problema está em outro procedimento que você está fazendo.
Comment: Que comando você está usando para compilar esses arquivos?
Comment: javac "nome do arquivo".java
Comment: @ClockWork Você está compilando qual arquivo primeiro?
Comment: Coloque o código inteiro, incluindo os imports.
Comment: @PabloAlmeida por incrivel que pareça, o código é só isso mesmo, não tem imports. Se salvar os dois, roda normal, acredito que essa pergunta é um [problema XY](https://pt.meta.stackoverflow.com/q/499/28595).
Comment: @ClockWork Coloque o comando exato que está a utilizar para compilar. Se tem mais de 1 classe a compilar tem de compilar todas, fazendo por exemplo `javac *.java`
Answer: Você tem que compilar o código assim:
javac Principal.java Pessoas.java

Depois, para rodar, faça isso:
java Principal

É muito importante ter os dois arquivos na linha de comando do javac, caso contrário, ele não irá compilar.
Answer: Se ambas estão na mesma pasta, então deveriam estar no mesmo pacote(acesso default como você declarou a classe)
Experimente colocar em pastas diferentes e declarar ambas classes como "public class"
Comment: O fato de não terem o modificador public também não ocasiona o erro. Experimenta criar os dois arquivos sem public e compilar pra você ver. Minha conclusão é que, após testar os códigos do autor da pergunta, o problema não tem nada a ver com nenhum dos códigos.
Comment: Verdade, até tava pensando, só daria problema mesmo caso as duas classes fossem default e estivessem em pacotes diferentes, aí não teria visibilidade, mas acho que não é o caso mesmo.
Answer: Na classe 2, não se deve ter um método main, mas sim um construtor:
public Pessoas(){
}

Já na classe 1, utilize, acima da classe:
import Pessoas;

Comment: Olha, não há nenhum impedimento em ter várias funções `main` em um projeto Java... Sem falar que está no mesmo pacote portanto [não precisa de importação explícita](https://pt.stackoverflow.com/a/248750/64969). E como o @Articuno falou, o construtor padrão não tem nada a ver
Comment: Ainda Retorna class1.java:8: error: cannot find symbol
Pessoas pessoa1 = new Pessoas();
Comment: Creio que isso não tem nada a ver com o problema. O código funciona normalmente sem o construtor. Qualquer classe não abstrata é instanciavel sem ter um construtor explicito declarado

Importar um .java em outro .java


Maintenance page being rendered as an entire page load after the main page load

Question: I've noticed that I've got a maintenance page being rendered in its entire HTML markup format after my pages. The site is not in maintenance mode, and this is not intentional behaviour. I'm trying to debug, but even as a reasonably experienced Drupal developer I still don't understand all the mechanisms at work here. Guidance on that would be welcomed.
I had been using the module CDN, to experiment with integrating a CDN. That was using that area at the bottom of the page, but when I disabled it, and uninstalled it, it has not stopped the problem.
I then enabled Theme developer 7.x-1.x-dev just to help me see what was going on, and the maintenance page render has stopped appearing. I then disabled Theme developer again and it has returned. Does this help anyone to suggest something?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

[...]

This also displays on my admin theme. Does this mean it is not something to do with my custom theme? Is there anything in particular that I could look or has anyone seen this behaviour before?
Comment: Hey hey, thing is, debugging needs to be done by you. Otherwise this question simply is too broad to answer. We don't know your site, your setup, your server, your custom code etc.. So it can basically be everything. Please come back when you found the root of your problem and still don't know how to solve it. Good luck!
Comment: I'm going to try and see if it's a problem with maintenance mode firstly: https://drupal.stackexchange.com/questions/72944/drupal-7-maintenance-mode-message-when-the-site-is-not-in-maintenance-yes-i
Answer: I'm still waiting to see an answer to the question of what causes maintenance mode to be displaying messages. So I don't know specifically whether the recoverable fatal error (this issue) being thrown by the buggy 7.x-2.4 version of XML Sitemap module was what caused the avoidance of a general WSOD/ crash and yet a display of an odd maintenance mode message.
I had not noticed they'd released 7.x-2.5 and so I've updated that which has stopped the behaviour altogether. Happy days :)
Answer: Chiming in late here, but I came across this yesterday after having the same problem. In my case, there was a stray call to dpm() in hook_preprocess_field_collection_item(); The Devel module was disabled in production, so when the page hit the dpm() call, everything broke. I don't know why this caused the page to go into maintenance mode, but removing the Devel debugging function fixed the problem.
Answer: Did you ever find the reason?
I am having the same problem right now and cant find why or how
https://stackoverflow.com/questions/73191467/drupal-7-response-with-two-sets-of-html-a-normal-followed-by-an-in-maintenance
Comment: tbh I can't remember, sorry. Check the logs. Check the /var/sys logs if nothing is obvious check all the logs! You'll have to try and find a thread somewhere and start pulling. I hope you find it!


$\kappa$-stable theories and number of types

Question: How can I show that if $T$ is a $\kappa$-stable theory, then in each model of $T$, over every set of parameters with at
most $\kappa$ many elements, there are at most $\kappa$ many n–types.
Answer: I'm assuming that your definition of $\kappa$-stable is "In each model of $T$, over every set of parameters with at most $\kappa$ many elements, there are at most $\kappa$ many $1$-types".
This is the base case of an induction on $n$. Hint for the inductive step: The $(n+1)$-type $\text{tp}(a_0,a_1,\dots,a_n \,/\, B)$ is determined by the $n$-type $\text{tp}(a_1,\dots,a_n\,/\,B)$ and the $1$-type $\text{tp}(a_0\,/\,B\cup\{a_1,\dots,a_n\})$.


Calculating the fourier series of $f(t)=|t|$

Question: calculate the Fourier series of the $2\pi$-periodic continuation of
$$f(t):=|t|, \quad t\in[-\pi,\pi)\tag{1}$$
We know that
$$f(t)=\sum_{k=-N}^N c_k\cdot e^{ikt}\quad \&\quad c_k=\frac{1}{2\pi}\int_{-\pi}^\pi f(t)e^{-ikt}dt\tag{2}$$
So let's calcualte the $c_k$.
$$c_k=\frac{1}{2\pi}\int_{-pi}^\pi|t|\cdot e^{-ikt}dt=\frac{2}{2\pi}\int_0^\pi t\cdot \cos(tk) dt=\frac{1}{\pi}[t\cdot\sin(tk)]_0^\pi+\frac{1}{\pi}[\cos(tk)]_0^\pi=0\frac{1}{\pi}(-1-1)=\frac{-2}{\pi}\tag{3}$$
Whereas we used the identity $\int_{-a}^a|t|e^{-ikt}dt=2\int_0^a t\cos(kt)dt$ Explanation (wheres the sub $t\to -t$ was used in the 2nd step)
So we get
$$f(t)=\sum_{k=-\infty}^\infty \frac{-2}{\pi}e^{ikt}\tag{4}$$
Sadly I don't have any solutions. Is that correct?
Comment: You can never have a nonzero value independent of $k$ for $c_k$, by Riemann Lebesgue Lemma.
Comment: Yeah of course, that's a stupid mistake.  But do you see any other issue here?
Comment: You will have to calculate $c_0$ seperately.
Answer: Your integration is incorrect. Note that the anti-derivative of $\cos(kt)$ is $\frac{\sin(kt)}{k}$, so we have
\begin{align}
\int t\cos(kt) dt &= t \color{red}{\frac{\sin(kt)}{k}} - \int\frac{\sin(kt)}{k}dt \\
&= t\color{red}{\frac{\sin(kt)}{k}} + \color{red}{\frac{\cos(kt)}{k^2}}
\end{align}
Inserting the limits gives
$$ c_k = \frac{1}{\pi}\frac{\cos(k\pi)-1}{k^2} = \begin{cases} 0, && k \text{ even} \\ \dfrac{-2}{\pi k^2}, && k \text{ odd} \end{cases} $$
Comment: Yeah, that was a stupid mistake. Thanks
Comment: There is a small mistake. $c_0$ is not $0$.
Comment: @xotix Don't forget $c_0$!
Comment: @KaviRamaMurthy I didn't say $c_0$ was $0$. Thanks for reminding us though!
Comment: @Dylan I am a bit confused to the borders of the sum. if I have $\sum_{k=1}^\infty$ it's clear that I have to calculate $c_0$ but when do I have $\sum_{k=-N}^N$ and when do I have $\sum_{k=1}^\infty$ and when do I have $\sum_{k=-\infty}^\infty$?
Comment: Fourier series generally have $k$ go to $\infty$. If it's a real-valued series (with $\sin$ and $\cos$ instead) then you'd have $k \ge 0$. For both versions you have to compute $c_0$
Comment: I have $\sum_{k=-N}^N c_k e^{ikt}$ and $\frac{a_0}{2}+\sum_{k=1}^N a_k\cos(kt)+b_k\sin(kt)$ no? For $N \to \infty$ I get the fourier series, no? So I'd actually have to split the first sum to $c_0 + \sum_{k=1}^\infty c_k e^{ikt} + \sum_{k=-\infty}^{-1} c_k e^{ikt}$?
Comment: Yes, the constant term is "hidden" in there. But $c_k$ should be the same expression for all $k\ne 0$
Answer: The right side of 2nd step of your substitution might be better expanded, assuming $a \ge 0$, as
$
\int_{-a}^0 |t| (\cos(st) + i \sin(st)) \ dt \\
= \int_{-a}^0 (-t) (\cos(st) + i \sin(st)) \ dt \ [ \ \because |t| = -t, t \le 0 \ ] \\
= \int_0^a t (\cos(-st) + i \sin(-st)) \ dt \ [ \ \text{substituting} \  t \to -t \ ] \\
= \int_0^a t (\cos(st) - i \sin(st)) \ dt
$
Comment: Yeah I didn't really like that they continues with $|t|$ but I though Im not going to change it. Thanks


power series with binomial coefficient

Question: Good evening,
I don't know how to find the function associate with this power series :
$$\sum_{n=k}^\infty \binom{n}{k} x^n$$
Should I look for a differential equation ?
Thx in advance
Comment: Have you tried doing it for small values of $k?$
Comment: if k = 0 , $ f(x) = \frac{1}{1-x}$
Comment: Off the top of my head, I would look for something of the form: $$\dfrac{x^k}{(1-x)^{k+1}}$$ While that may not be it exactly, it will probably be something close.
Comment: Good.  What about $k=1?$
Comment: if k = 1, $f(x) = \frac {x}{(1-x)^2}$
Comment: Does this answer your question? [Series of binomial coefficients: $\sum\limits_{n=k}^{\infty}{\binom nk}x^n=\frac{x^k}{(1-x)^{k+1}}$](https://math.stackexchange.com/questions/1941603/series-of-binomial-coefficients-sum-limits-n-k-infty-binom-nkxn-frac)
Answer: \begin{align}
& \sum_{n=k}^\infty \frac{n(n-1)(n-2)\cdots (n-k+1)}{k!} x^{n-k}x^k \\[10pt]
={} & \frac{x^k}{k!} \sum_{n=k}^\infty \frac{d^k}{dx^k} x^n \\
& \text{Pulling out $x^k/k!$ works because $k$ does not change as $n$ changes.} \\[10pt]
= {} & \frac{x^k}{k!} \, \frac{d^k}{dx^k} \sum_{n=0}^\infty x^n \\
& \text{This works because power series can be differentiated} \\
& \text{term by term. Here we need not start at $k$ since the} \\
& \text{derivatives of the first $k-1$ terms are $0.$} \\[10pt]
= {} & \frac{x^k}{k!} \, \frac {d^k}{dx^k} \, \frac 1 {1-x} = \frac{x^k}{k!} \, k!(1-x)^{-(k+1)} = \frac{x^k}{(1-x)^{k+1}}.
\end{align}
Comment: thank you, it's very clear

power series with binomial coefficient


Spectra and long exact sequences

Question: Suppose $X,Y,Z$ are finite CW complexes and let $f \colon X \to Y$ be a fibration with fiber $F$.  Is there now a long exact sequence associated to their suspension spectra in the following sense
$$
\ldots \to [\Sigma^k Z,\Sigma^k F] \to[\Sigma^k Z,\Sigma^k X] \to [\Sigma^k Z,\Sigma^k Y] \to [\Sigma^{k-1} Z,\Sigma^{k-1} F] \to \ldots\
$$
If not, which long exact sequence can on associate with $Z$ and the fibration $f$?
Comment: No. You get a long exact sequence of suspension spectra from the cofiber of $f$.
Comment: I am sorry, I have to ask further. Can you eloborate how such an exact sequence will look like? Feel free to compose an answer which I can accept.
Answer: Given a map $f:X\rightarrow Y$ between CW complexes you form its cofiber $C_f$ to get a cofibration sequence starting
$$X\xrightarrow fY\xrightarrow iC_f\xrightarrow q\Sigma X\xrightarrow{\Sigma f}\Sigma Y\rightarrow\dots.$$
This sequence is stable under suspension, in that you can continue it to the right indefinitely as
$$\dots\Sigma^{k-1}C_f\xrightarrow{\Sigma^{k-1}q} \Sigma^kX\xrightarrow{\Sigma^k f}\Sigma^kY\xrightarrow{\Sigma^k i}\Sigma^kC_f\xrightarrow{\Sigma^k q}\Sigma^{k+1} X\rightarrow\dots$$
In this way, for any space $Z$ you get a contravariant exact sequence
$$\dots\leftarrow[\Sigma^{k-1}C_f,Z]\xleftarrow{\Sigma^{k-1}q}[\Sigma^kX,Z]\xleftarrow{\Sigma^kf^*} [\Sigma^kY,Z]\xleftarrow{\Sigma^ki^*}[\Sigma^kC_f,Z]\xleftarrow{\Sigma^kq^*}[\Sigma^{k+1} X,Z]\xleftarrow{\Sigma^{k+1}f^*}\dots\qquad(*)$$
which is an exact sequence of abelian groups for $k>\geq 2$, of groups when $k=1$ and of sets when $k=0$.
You can also form a covariant sequence
$$\dots\rightarrow[Z,\Sigma^kX]\xrightarrow{\Sigma^k f_*}[Z,\Sigma^kY]\xrightarrow{\Sigma^k i_*}[Z,\Sigma^kC_f]\xrightarrow{\Sigma^k q_*}[Z,\Sigma^{k+1}X]\xrightarrow{\Sigma^{k+1} f_*}[Z,\Sigma^{k+1}Y]\rightarrow\dots\qquad(**)$$
which will not in general be exact. However there is something that can be said. It is certainly the case that that the composition of two consecutive homomorphisms in this sequence is trivial, and the deeper theorem actually states that this sequence is exact in a certain range of dimensions. That is, if the dimension of $Z$ is 'small' relative to $k$, then the sequence will be exact.
Let me elaborate a little. Recall the map $q$ which I introduced in the very first cofibration sequence, and form its homotopy fibre $F_q$ to get a fibration sequence
$$\dots\rightarrow F_q\xrightarrow{r}Y\xrightarrow{q} C_f$$
Now there is a canonical nullhomotopy of the composite $q\circ f$ that aries from the fact that these two maps appear consecutively in a cofibration sequence. Then by the definition of a fibration sequence this means that you get an induced map
$$\theta:X\rightarrow F_q$$
lifting $f$, and it turns out that this map is an $n$-equivalence, where $n$ is a number that depends on the connectivity of $X$ and $Y$ and the homotopical behaviour of $f$ in a way you can calculate.
As the connectivities of $X$ and $Y$ increase, the integer $n$ increases, and the homotopy fibre $F_q$ looks more and more like $X$. In particular, if we replace $q$ by $\Sigma^kq$, form the homotopy fibre $F_{\Sigma^k q}$ and the comparison map
$$\theta_k:\Sigma^kX\rightarrow F_{\Sigma^kq}$$
then this map will be an $(n+2k)$-equivalence. So in particular, as $k$ increases $\Sigma^kX$ looks more and more like the homotopy fibre of $\Sigma^kq:\Sigma^kY\rightarrow\Sigma^kC_f$. Therefore, if $Z$ is a finite dimensional complex there will be a large $k$ for which the covariant sequence $(**)$ I introduced above will be exact.
Now it is not true that $F_{\Sigma^kq}$ is equivalent to the suspenion $\Sigma F_{\Sigma^{k-1}q}$. Indeed, in general it will not even be a suspension. What we have succeeded in doing is only approximating it by a suspension. The point is that as $k$ increases the approximation gets better and better, to the point at which we are dealing with spectra.
In the ideal limit at which $k$ is taken all the way to infinity we move to the realm of spectra. At this point there is no difference between cofiber and fibre sequences, and this is more or less the definition of stability. When dealing with spectra, both the contravariant sequence $(*)$ and the covariant sequence $(**)$ are exact. Just note that there are defined with the cofibre of $f$ rather than its fibre.
Comment: I'd suggest chapters 3-6 of Arkowitz's book *Introduction to Homotopy Theory*.
Comment: Could you give a good reference for the details?

Spectra and long exact sequences


How to quickly compute $2014 ^{2015} \pmod{11}$

Question: Without using Fermat's Little Theorem, how can I quickly solve $2014 ^{2015} \pmod {11}$?
Comment: Just note $2014=11\times 183+1$
Comment: Note that $2013$ is divisible by $11$.
Comment: I suppose you started by computing $2014^1\pmod{11},$ right? What did you get?
Comment: @OmarN $\,2014\equiv 1\,\Rightarrow\, 2014^n\equiv 1^n\equiv 1\ $ by the [Congruence Power Rule.](http://math.stackexchange.com/a/879262/242) $\ \ $
Comment: 1^2015 (mod 11) = 1.  Does that mean 2014^2015 mod 11 = 1?  Is it really as simple as just doing one number at a time?
Comment: ${\rm mod}\ 11\!:\ 2014\equiv 4-1+0-2\equiv 1\ \ $
Comment: @bof I did compute 2014^1 (mod 11), and I got 1.  But I am not sure what to do with the 2015 exponent.  Is there a way to simplify 2014^2015?
Comment: Can you compute $1^{2015}\pmod{11}$?
Comment: I'm not sure what you mean by "doing one number at a time", but it really is that simple. See Bill Dubuque's comments.
Comment: Marios observation above + binomial theorem : every term except the last will be 0 mod 11, and the last is always a number smaller than 11. Then the procedure can be iterated if needed.
Answer: This can be computed in a few seconds of mental arithmetic as follows. First we cast out $11$'s to compute $2014\pmod{11}$ as its alternating digit sum:
${\rm mod}\ 11\!:\ \color{#0a0}{10\equiv -1}\,\Rightarrow\, \color{#c00}{2014}\equiv 2(\color{#0a0}{10})^3\!+\!\color{#0a0}{10}\!+\!4\equiv 2(\color{#0a0}{-1})^3\!\color{#0a0}{-\!1}\!+\!4\equiv\color{#c00} 1\ $ [cast $11$'s - see below]
Therefore $\ \color{#c00}{2014}^n\equiv \color{#c00}1^n\equiv 1\ $ by the Congruence Power Rule.
Remark $\ $ The first line is a special case of casting out elevens, the analog of casting out nines, i.e. $\, \color{#0a0}{10\equiv -1}\,\Rightarrow\,f(\color{#0a0}{10})\equiv f(\color{#0a0}{-1}) = $ alternating digit sum, where $\,f(x)\,$ is the decimal radix polynomial, e.g. above $\, f(x) = 2x^3+x+4,\ f(10) = 2014.\,$ See here for further discussion.
Comment: In the second line, can you tell me where all those numbers are coming from? I am not sure where the numbers in the second line come from.
Comment: @OmarN Because $\,\color{#0a0}{10\equiv -1}\,$ we can replace $\,\color{#0a0}{10}\,$ by $\,\color{#0a0}{-1}\,$ whenever it occurs as an argument of a sum or product (by the linked Cogruence Sum and Product Rules).
Answer: The fundamental fact about modular arithmetic is that
$$ ab \bmod n = (a\bmod n)(b\bmod n)\bmod n $$
(and the analogous fact for addition). Apply this rule 2014 times to
$$ \underbrace{2014\cdot 2014\cdot 2014 \cdots 2014}_{2015\text{ factors}} $$
(and then 2014 more times in reverse to get rid of the intermediate "$\bmod 11$"s) and you get
$$ 2014^{2015} \bmod 11 = (2014 \bmod 11)^{2015} \bmod 11 = 1^{2015} \bmod 11 = 1 $$
Comment: @OmarN [Fermat's Little Theorem](https://en.wikipedia.org/wiki/Fermat%27s_little_theorem), $a^{p-1} \equiv 1 \bmod p$ (and $6=7-1$). You don't need this in the original question, but for cutting down the exponent when $a \not\equiv 1$, it's very useful.
Comment: i.e., as I said, use the [Congruence Power Rule](http://math.stackexchange.com/a/879262/242), an inductive extension of the [Congruence Power Rule.](http://math.stackexchange.com/a/879262/242).
Comment: @Bill: Yes -- but it looked like the OP needed to see a more detailed explanation of why that rule works.
Comment: Indeed! My comment was meant to help the OP connect the dots between our answers.
Comment: @Henning Makholm, I understand your answer and it makes perfect sense.  What if though, we wanted to apply the same logic to $$ 2014^{2015} \bmod 7 = (2014 \bmod 7)^{2015} \bmod 7 = 5^{2015} \bmod 7 = ? $$  How would you find 5^2015 mod 7 without using a calculator?
Comment: @OmarN $5^6 \equiv 1 \bmod 7$, so find $2015 \bmod 6$, which is $5$, and calculate $5^5 \bmod 7$ which is $5^2\cdot5^3 \equiv 4\cdot-1 \equiv \color{red}{3} \bmod 7$.
Comment: This is the part I get lost at.  Where did you get $5^{6}$ from?  I don't understand how we went from $5^{2015}$ to $5^{6}$
Comment: I understand now.  Thank you!
Answer: I like Bill Dubuque's answer, but I definitely didn't use his approach to find $2014 \bmod 11$, just used a discarding version of long division:
$20 \bmod 11 = \color{red}{9} \\
\to \color{red}{9}1 \bmod 11 = \color{green}{3} \\
\to \color{green}{3}4 \bmod 11 = 1$
And then of course $2014^{2015} \equiv 1^{2015} \equiv 1 \bmod 11$.
If $2014$ had been a bigger number, I would probably have used the alternating digits rule for divisibility by $11$, $(0+4)-(2+1) = 1$, because I would have stopped to think before starting the division process :-)
Comment: My way is $\,2014\equiv 4-2+0-1\equiv 1,\,$ which, to me, is simpler, and more general (it is casting out $11$'s - see my remark).
Comment: @BillDubuque - Yes indeed; see my closing thought
Comment: They're both equally quick here for someone who is skilled. I give a general description of the method you use in [this answer.](http://math.stackexchange.com/a/1165347/242) [Horner form polynomial evaluation]


Which programming language for webserver tasks/deployment related scripts

Question: I'm really feeling stupid but I don't find the right search keywords to get something usefull out of google.
The problem:
We are developing symfony1 and symfony2 applications (php). We are developing on windows machines, while our staging and production server are linux. We got some tasks which are done by a shell-script on linux. These tasks include:
- Move files and folders (e.g. Testfiles on the staging folder)
- Set folder permissions
- run various commands
Right now, the shell scripts only are executed on the linux servers as they are not working on the windows machines. We would like to get to a point where we can run one script and, depending on environment, it executes the correct tasks.
Which language to choose for this tasks? I heard good things about python, but don't know if it really fits. I know some Perl, but don't think it's a good tool. Maybe there are languages which are designed for such problems?
Answer: The Good answer: Move to linux on your desktops/laptops. You should be developing on the same platform the application is being served from.
The Hack-it-together-and-it-might-halfway-work answer: install cygwin on your dev machines, and you'll be able to run shell scripts.
Answer: Are you saying that the problem is you're developing on Windows but deploying on Linux, and have scripts you want to run on both? I think you're going to find there are always some quirks unless there are some equivalent to #ifdef's in the script to figure out if it's running on Windows versus Linux, since there will be directory structure differences and such. Is there a reason you can't develop on a Linux system, or virtualize a Linux system on the Windows box so you're developing on the same platform you're building on?
You can get Python for Windows to run natively. And if you're using a UNIX-centric scripting language to do things (like Bash) you could install cygwin under Windows to have a POSIX environment in which to run things.
Personally, I'd virtualize a Linux system and save yourself some porting quirks and headaches. If you're asking for scripts that run under CRON on the server, install Cygwin and script it in Bash.
Answer: There are many cross platform languages that work for system administrative tasks.  Perl, Python, and Ruby are all valid choices.
But those languages will not be able to auto-magically translate things that only make sense on Linux to the closest Windows equivalent.  Setting permissions is different on Windows vs Linux.  You will have to detect the OS and call the correct appropriate functions for that system.

Which language to choose for this tasks?

Choose a cross platform language that you are already familiar with.  If you don't have any strong familiarity with any, pick one that looks cool.
Since you are developing PHP apps, you could always just install the PHP CLI everywhere.  Since you are already using PHP you are familiar with it.  While many might argue that PHP sucks, you can certainly get things done with it, and you are already using it.
Comment: I know I have to do some double code for windows and linux, but that would be fine. The main problem right now is simply that the shell scripts are only running on the servers and the tasks performed need to be done manually on the development pcs. I don't think we'll use php for it, but I'll definitly have a look at python.


Is regression line (for a simple "Y given X" regression, no interaction etc) always unique?

Question: Is it possible for more than one "linear regression" line to fit a given set of points? (i.e.... "least squares" is minimised equally in both cases)
I'm assuming a simple one-variable regression in which we have a single "dependent" variable for a given x-value. It may be that regression is forced "through the origin" for the purpose of the Q (if that matters), so, I know it wouldn't be a great fit.
Or is there something intrinsic about a regression line that means it is unique? I am interested in a 'proof' (could be just an intuitive proof) if it exists, that a regression line must be unique.
Answer: No. Under usual conditions you have a unique solution to OLS equation.
You can always come up with degenerate cases, e.g. $$y=\beta_0+\beta_1 x_1+\beta_2x_2+e$$
If $x_1=x_2$, then any $\beta_1'=\beta_1-c,\beta_2'=\beta_2+c$ will work as well.
The reason is simple. Consider OLS equation: $y=X\beta+e$, you minimize squared residuals $e=y-X\beta$ (vector notation):
$$e^2=y'y+\beta'X'X\beta-2y'X\beta$$
This is a quadratic (on unknown $\beta$) equation, convex, you can apply linear algebra to show that it has a unique solution. Intuitively it's convex, so there's a bottom, just one point. Again, this is under certain reasonable conditions.
Obviously, here I'm skipping the discussion of errors vs. residuals.
Comment: What happens if you have more features than observations?
Comment: @user777, you may end up with infinite number of solutions. Imagine in the model in my example you have only one observation: $y=1,x_1=1,x_2=1$, so you get $1=\beta_0+\beta_1+\beta_2$, and you can plug infinite number of combinations to satisfy it


Trying to understand this solution for a high-school coordinate geometry problem better

Question: $\newcommand{\lrp}[1]{\left(#1\right)}$
The following is a high school level problem in coordinate geometry and the purpose of this post is to understand the solution better or discover other solutions or both.

Problem.
Show that all chords of the curve $3x^2 - y^2 - 2x + 4y = 0$ which subtend a right angle at the origin pass through a common point.

Solution. Let $y = mx+c$ be the equation of a line not passing through the origin and which intersects the given curve at two points.
Consider the algebraic expression
$$
3x^2 - y^2 - (2x - 4y)\lrp{\frac{y-mx}{c}}
$$
which is an expression of the form $Ax^2 + 2Hxy + By^2$, its zero-set is either a pair of straight lines passing through the origin (possibly not distinct) or is just the origin (which happens if $H^2 < AB$).
Further, if indeed the line $y=mx+c$ intersects the curve at two distinct points, then the zero-set of the above is necessarily the pair of of lines passing through the two points of intersection and through the origin.
This is because the algebraic expression vanishes on both the points of intersection.
These lines are perpendicular to each other if $A/B = -1$, since $A/B$ is the product of the slopes of the two lines.
From here it is easy to show that all the lines $y = mx + c$ pass through a common point.

I understand this argument.
But the step where we created the algebraic expression was quite a clever one and it eludes me.
Is there a "deeper reason" as to where this came from?
Also, is there any other way to prove the same?
One may observe that the given curve is a hyperbola and then perhaps write down a 'hard' proof (as opposed to the 'soft' proof above).
But perhaps there are other such elegant or 'more natural' proofs.
Comment: One idea could be to switch over to projective coordinates $(x:y:z)$ and then eliminate $z$.
Comment: Do you think that showing the chords in question going through a common point (i.e., $\bf{\left(\text{1, -2}\right)}$) using methods available in coordinate geometry could be considered as a proof? By the way, the method I am talking about is a kind of layman's attempt to solve this problem and by no means as chic as the solution you have given in your post.
Comment: @YNK I would consider what you describe a proof. If you think you can post it without much then please help us all learn!
Answer: If $x,y$ is one intersection point, then per orthogonality $(-y/z,x/z)$ is the second point for some $z\ne 0$. This second point satisfies the equations
$$
3y^2-x^2+2yz+4xz=0\\
x = -my+cz
$$
This might be confusing, so start again.

Let the second, orthogonal intersection point be $(x_2,y_2)=(-y,x)$. Then the primary intersection point has coordinates $(x_1,y_1)=(x/z,y/z)$ for some $z\ne 0$. Then this point satisfies the equations
$$
3x^2-y^2-2xz+4yz=0\\
y=mx+cz
$$
Elimination of $z$ gives the equation
$$
3x^2-y^2-2(x-2y)\frac{(y-mx)}{c}=0
$$
As this is now independent of $z$, this equation is true for all intersection points. To be valid for the claimed situation, the expanded equation $Ax^2+2Hxy+By^2=0$ has to be valid also for the second point, $Ay^2-2Hxy+Bx^2=0$, etc.

As the coefficients are independent of the point on the ellipse, the triple $(A,H,B)$ has to be proportional to $(-B,H,-A)$, which implies $A+B=0$. Or in full form without divisors
$$
0=[3c+2m]+[-c+4]=2(m+c+2)
$$
This means that the point $(x_3,y_3)=(1,-2)$ is on every such line.
Answer:
$AB$ is one of the chord of the given curve $3x^2-y^2-2x+4y=0$, which subtends a right angle at the origin $O$. $OA$ and $OB$ are the line segments drawn from origin to the two points of intersection between the curve and the chord $AB$. We let the slope of $AB$ to be $\space m$. Since $\measuredangle AOB=90^o$, the slope of the line segment is equal to $\space -\dfrac{1}{m}$.
We start our proof by determining the coordinates of $A$ and $B$ in terms of $\space m\space$ as shown below.
$$3x_A^2-m^2x_A^2-2x_A+4mx_A=0\qquad\space\rightarrow\quad x_A=\dfrac{2-4m}{3-m^2}\qquad\rightarrow\quad y_A=\dfrac{2m-4m^2}{3-m^2}$$
$$3m^2x_B^2-x_B^2-2m^2x_B-4mx_B=0\quad\rightarrow\quad x_B=\dfrac{2m^2+4m}{3m^2-1}\quad\rightarrow\quad y_B=-\dfrac{2m+4}{3m^2-1}$$
Now, we can find the equation of the chord $AB$.
$$\dfrac{y-\dfrac{2m-4m^2}{3-m^2}}{x-\dfrac{2-4m}{3-m^2}}=\dfrac{y+\dfrac{2m+4}{3m^2-1}}{x-\dfrac{2m^2+4m}{3m^2-1}}$$
Simplification after cross multiplying leads to,
$$\left(1+4m-m^2\right)y+\left(6+2m-6m^2\right)x=4-6m-4m^2.$$
Our aim is to show that the line representing this equation passes through a certain point for all real values of $\space m$. If this particular point is $P\space\left(x_P,y_P\right)$, then we can express its $y-$coordinate as,
$$y_P=kx_P,$$
where $\space k\space$ is some  real constant, because both $x_P$ and $y_P$ are also real constants. Therefore, we have,
$$\left(1+4m-m^2\right)kx_P+\left(6+2m-6m^2\right)x_P=4-6m-4m^2.$$
Using this equation, It is possible to express $x_P$ in terms of the constant $\space k\space$ and the variable $\space m$.
$$x_P=\dfrac{4-6m-4m^2}{6+2m-6m^2+k\left(1+4m-m^2\right)}=\dfrac{4-6m-4m^2}{\left(6+k\right)+\left(2+4k\right)m-\left(6+k\right)m^2}$$
However, we need $x_P$ to be free of $\space m$, which is possible if and only if we could find a real constant $n\space$ such that,
$$n\left(4-6m-4m^2\right)= \left(6+k\right)+\left(2+4k\right)m-\left(6+k\right)m^2.$$
When we compare the coefficients of the first and the second terms of the left hand side with those of the right hand side, we get the following two equations,
$$4n=6+k\qquad\text{and}\qquad 6n=-2-4k.$$
$${\large{\bf{\therefore}}}\quad n=1,\quad k=-2,\quad x_P=1, \quad\text{and}\quad y_P=-2.$$
$\underline{\text{Additional}\enspace\text{Information}}$
If a chord of a hyperbola or an ellipse given by the equation $\space ax^2+by^2+cx+dy=0\space$ subtends a right angle at the origin, it passes through the point
$$\left(\dfrac{-c}{a+b},\space\dfrac{-d}{a+b}\right).$$
Comment: Thank you so much for the well-written answer.


CDN module enabling "Far Future expiration" breaks whole site theme drupal 7

Question: CDN module
Version:    7.x-2.6
component -- Origin Pull mode — Far Future expiration
I am using CDN module on drupal 7.22. We are using custom theme where adaptive theme is as base theme for all other users and "seven" theme for admin.
As soon as i check the "Far Future expiration" and save, whole site theme is breaking except admin theme.
And without checking "Far Future expiration" Iam facing http://drupal.org/node/1993600 issue.
Answer: These modules might help you out (quotes added here are from their project pages):

Advanced CSS/JS Aggregation:

On demand generation of CSS/JS Aggregates. If the file doesn't exist it will be generated on demand.
Stampede protection for CSS and JS aggregation. Uses locking so multiple requests for the same thing will result in only one thread doing the work.
Fully cached CSS/JS assets allow for zero file I/O if the Aggregated file already exists. Results in better page generation performance.
Can add JS to any region of the theme & have it work and be aggregated.
Combine CSS files by using media queries.
Prevent more than 4095 CSS selectors in an aggregated CSS file (IE 6-9 limitation).
...

Imageinfo Cache:

... will generate image styles right after an image is uploaded and also on entity save. This will help with front end performance as the needed image style will already have been generated; thus the end user doesn't have to wait for the image to be generated. This can also mitigate some issues with image style generation if your CDN is configured incorrectly as the images will be generated without the request going through the CDN.


Why won't a method execute from within LINQ Where method

Question: In a console app, from a static method in main class Program, I am calling:
internal class Module
{
    public bool EnsureModuleLocalInstall()
    {
        if (CheckModuleUpToDateLocal())
            return true;
        else if (DownloadComponentData())
            if(InstallModuleLocal())
                return true;

        return false;
    }
}

var availableModules = new List<Module>();
... // Add several 'Modules' to list
var installed = availableModules.Where(m => m.EnsureModuleLocalInstall());

I have both set a break-point, and also checked the expected outcome (module installed locally), but from all indications the method 'EnsureModuleLocalInstall' is not being executed.
Am I missing something obvious, or am I expecting too much from the LINQ 'Where' method and should use a LINQ ForEach?
Comment: Do you understand [deferred execution](http://blogs.msdn.com/b/charlie/archive/2007/12/09/deferred-execution.aspx)?
Comment: As a general rule, LINQ is not suitable for defining and running queries with side effects.. Not surprised that you had the expectation of the method getting called, as you **defined** the query.
Comment: Yes, and thank you. Embarrassing- all I needed to do was add a ToList().
Answer: The Where method is implemented using deferred execution, so the query won't actually be run until you iterate over the result. The simplest way to get your list of installed modules is to call ToList on the query return value:
var installed = availableModules.Where(m => m.EnsureModuleLocalInstall()).ToList();

Comment: Thanks Sam, yes as Jesse Good pointed out- it was deferred, and never executed.
Answer: Most LINQ methods (like the Where method) will return to you an implementation of IEnumerable<T> that does not contain the result of the query but instead contains all the information necessary to execute the query. The query is only executed when you start enumerating the IEnumerable<T>. This is called Deferred Execution.
One way to enumerate the IEnumerable<T> is to invoke ToList like this:
var installed = availableModules.Where(m => m.EnsureModuleLocalInstall()).ToList();

Comment: Deferred execution is a synonym of **Lazy evaluation** or laziness. In a computational  context, it is also called Symbolic calculations


caliburn micro: MVVM parent view and child view of parent need to deactivate child

Question: I need some help with reaching my TicketViewModel with Caliburn micro using ContentControl. I want to reach the ticketView(Model) using a button in StartView. (and deactivating startView)
next picture are the interactions i want to have with their CM implementations
https://i.stack.imgur.com/igfWj.jpg
this is the app thus far
https://i.stack.imgur.com/nnIPu.jpg
The header and styleElements are of the ShellView. The center square is a contentcontrol. with default the startview in activated.
As you can see, I want to reach TicketsView using a button in startView(that itself is nested in a contentControl in ShellView), and using a a MenuItem in ShellView.
Code in Shellview
<ContentControl Grid.Column="1" Grid.Row="1" x:Name="ActiveItem"/>
Code in ShellViewModel
public class ShellViewModel : Conductor<object>
{
public ShellViewModel(){
ActivateItem(new StartViewModel());}

public void AlleTicketsPageLaden(){
ActivateItem(new AlleTicketsViewModel());}

Code in StartView <Button Content="Tickets" x:Name="StartTicketKnop"/>
Code In StartViewModel
  public class StartViewModel : Conductor<object>
  {
    public void StartTicketKnop()
    {
      ActivateItem(new AlleTicketsViewModel());
    }

Comment: Either keep a reference to that `public AlleTicketsViewModel AlleTicketsVM {get;set;} = new AlleTicketsViewModel()` or write some kind of service that handles changing items
Answer: You could do the following:
Create class ActivateWindow like this:
 public static class ActivateWindow
    {
        public static ShellViewModel Parent;

        public static void OpenItem(IScreen t)
        {
            Parent.ActivateItem(t);
        }
    }

And in your ShellViewModel constructor
public ShellViewModel()
        {
            ActivateWindow.Parent = this;
        }

Now in any ViewModel you can do the folowing:
ActivateWindow.OpenItem(new YourViewModel());

Comment: I have tried doing this but my OpenItem doesn't call the View's constructor. I don't know what I am missing


replace fragments inside fragment displayed by the viewpager

Question: Please see the wireframe image https://i.stack.imgur.com/6OnJ2.png first.
I am using a ViewPager to display fragments inside a FragmentActivity. ViewPager gets fragments from the attached FragmentPagerAdapter
mViewPager = (ViewPager) findViewById(R.id.view_pager);
mAdapter = new HomePagerAdapter(getSupportFragmentManager());
mViewPager.setAdapter(mAdapter);

Suppose viewpager has 3 fragments to display say Fragment1, Fragment2, Fragment3.
In the above image 'displaying fragment1' is the title for the first fragment, "Fragment1". This fragment is a list fragment and displays a list. Fragment2 and Fragment3 have their own content to display. when the user swipes on the screen, ViewPager will display the next fragment, "Fragment2".
What i want is that, when an item from the list(displayed by Fragment1) is clicked, Fragment1 should be completely replaced with some other Fragment, say Fragment4 (this is different fragment and is not returned by the attached adapter). when Fragment4 is displayed, the actionbar should change its content. whenever user works on Fragment4 and onBackPress or an action from the ActionBar, Fragment1 with the list should be displayed again. Meanwhile ViewPager should behave the same i.e on swipe, and the next fragment(in our case Fragment2) will be displayed.
basically, i want to get the same behavior as in example at :
http://developer.android.com/training/basics/fragments/fragment-ui.html#Replace
In this example the ListFragment is displayed directly inside a FragmentActivity. I am displaying the ListFragment with a ViewPager. I want the same functionality from the above example but inside fragments displayed with ViewPager. This was very difficult to achieve before the release of Android 4.2. this version of android supports nested fragments using getChildFragmentManager() so, i see some hope.
I am trying this on my side for many days and also scanned entire stackoverflow for Q & A related to nested fragments but didn't get what i want.
So, is this possible to achieve? if yes, then how to?
Answer: This was a big problem before Android 4.2 but it seems to easier now with nested fragments, apart from ensuring the back button works. I posted my solution to your question over here: https://stackoverflow.com/a/13925130/467509
My solution answers everything you asked apart from changing the ActionBar.


Plotting interaction effect without significant main effects (not about code)

Question: This is not a question about implementation:
I have a GLMER model with a significant three way interaction.  Neither of the two way interactions or main effects are significant.  I accept this model and leave all lower order effects in the model, but want to plot this three way interaction: x, y, and then z as colour in a ggplot.  I predict responses of y based on data I generate for y and z using said model, but only using the significant fixed effects (the intercept and three way interaction), and plot x, y, z.  Does this seem like an alright thing to do in order to communicate what the interaction means assuming I keep the lower order, non significant effects in the model?
Thanks!
Comment: Some sample reproducible code of what you are trying to do would help a lot.
Answer: If I understand what you are doing, I think it is incorrect; but I'm not sure I understand. First you  say

I predict responses of y based on data I generate for y and z using
  said model, but only using the significant fixed effects

which seems like you used only the significant effects. But then you ask if this is a good way

to communicate what the interaction means assuming I keep the lower
  order, non significant effects in the model?

I think that whatever is in your model should be in your plot. And statistical significance has nothing to do with it. The predicted values based only on a 3 way interaction without the 2 way or main effects can be very different from those from the full model; and, except in very unusual circumstances, they aren't what you want.
That's why you (correctly) keep the lower order terms in the model


Apache HTTP Server 2.4.41 is confusingly serving virtual host pages

Question: My httpd-vhosts.conf looks  like this:
<VirtualHost *:80>
    DocumentRoot "C:/Apache24/htdocs/rodde.net"
    ServerName rodde.net
    ServerAlias www.rodde.net
</VirtualHost>

<VirtualHost *:80>
    DocumentRoot "C:/Apache24/htdocs/coderodde.net"
    ServerName coderodde.net
    ServerAlias wwww.coderodde.net
</VirtualHost>

My C:Windows\System32\drivers\etc\hosts contains:
127.0.0.1 localhost
127.0.0.1 www.coderodde.net
127.0.0.1 www.rodde.net
127.0.0.1 rodde.net
127.0.0.1 coderodde.net

My C:\Apache24\htdocs\rodde.net\index.html contains:

rodde.net works!

My C:/Apache24/htdocs/coderodde.net/index.html contains:

coderodde.net works!

My C:/Apache24/htdocs/index.html contains:

Apache HTTP Server 2.4.41 works!

Finally, httpd.exe -S:
C:\Apache24\bin>httpd -S
VirtualHost configuration:
*:80                   is a NameVirtualHost
         default server rodde.net (C:/Apache24/conf/extra/httpd-vhosts.conf:23)
         port 80 namevhost rodde.net (C:/Apache24/conf/extra/httpd-vhosts.conf:23)
                 alias www.rodde.net
         port 80 namevhost coderodde.net (C:/Apache24/conf/extra/httpd-vhosts.conf:29)
                 alias wwww.coderodde.net
ServerRoot: "C:/Apache24"
Main DocumentRoot: "C:/Apache24/htdocs"
Main ErrorLog: "C:/Apache24/logs/error.log"
Mutex default: dir="C:/Apache24/logs/" mechanism=default
PidFile: "C:/Apache24/logs/httpd.pid"
Define: DUMP_VHOSTS
Define: DUMP_RUN_CFG
Define: SRVROOT=c:/Apache24

My problem is this: '

When I visit rodde.netor www.rodde.net, I see the text rodde.net works!, as I should.
When I visit coderodde.net, I see the text coderodde.net works!, as I should.
However, when I visit www.coderodde.net or localhost, I see the text rodde.net works!.
Comment: Are you sure your main httpd config file is set to look for vhosts in a separate file? I have to add this IncludeOptional conf/vhosts/*.conf
Comment: I use a single `httpd-vhosts.conf` file.
Answer:
default server rodde.net (C:/Apache24/conf/extra/httpd-vhosts.conf:23)

This is your default server i.e. the default virtual host. It is used every time there's no matching explicit ServerName or ServerAlias. That's the case when you visit e.g. http://localhost.

port 80 namevhost coderodde.net (C:/Apache24/conf/extra/httpd-vhosts.conf:29)
        alias wwww.coderodde.net

This virtual host has two names: coderodde.net and wwww.coderodde.net, with four w's. That's why it won't match www.coderodde.net with three w's, and the default virtual host is used, instead. That's called a typo.
Comment: Kiitos paljon, kamu!


Two Drush bam-backup errors: Command not Found & Could not find a Drupal setting.php file at

Question: I am trying to use Drush to backup a standard 7.12 local installation, but I am getting two error messages when running drush bam-backup:
The drush command 'bam-backup' could not be found.
Run `drush cache-clear drush` to clear the commandfile cache
if you have installed new extensions.

Could not find a Drupal settings.php file at ./sites/default/settings.php.

The bam module is enabled in my system.
Regarding the second issue, I have checked in the corresponding directory and it contains a default.settings.php file, but no settings.php file.
Is this a configuration issue, or a more fundamental bug? How can use Drush to backup my installation? Thanks.
P.S.:
I am on Windows 7 and I have used the Windows installer available here to install Drush. The bam version is 7.x-2.2 and Drush version is 5.0-dev.
Answer: Where is the settings.php file for your Drupal installation?
The problem Drush is having is that it cannot figure out where your settings.php file is.  By default, Drush only looks in sites/default.  There are a few ways that you can select the site you want if it is not in sites/default.  One is to cd to the directory that contains the settings.php file, then run your command.
cd /path/to/drupal/sites/mysite
drush status

The other way is to specify the site you mean via the --uri parameter:
drush --root=/path/to/drupal --uri=mysite.com status

Once the status command works per the above advice, try calling bam-backup again.
Comment: I re-installed a standard local 7.12 system with bam only. I created a content type and a corresponding node instance. I went to the root of my site and called drush status -> It worked. I called drush bam-backup -> It failed. I searched the whole directory for a settings.php file -> There is no such file in my directory structure !?!
Comment: Ok, I think I know what the issue is. I am using Acquia Dev Desktop to import the installation and create a new database when installing Drupal. But it does not create a settings.php file itself. Yet, if this file is not available, drush cannot access login info to the database... So my bad here.
Comment: It can be the permission on settings.php file


Show that $A+I$ is singular.

Question: Let A $\in \mathbb{F}^{n \times n}$. If $AA^T = I$ and $\det A < 0$, show that $A+I$ is singular.
So far, I attempted to use the result that $\det (A+I) = \det A + \det I + tr(A)$ to show that $\det(A+I) = 0$ in order to conclude that $A+I$ is singular.
Do anyone have an alternative to prove this statement?
Comment: Since $A$ is orthogonal, all of its eigenvalues are either $1$ or $-1$, and since $\det A<0$ at least one of them is $-1$, which means $A+I$ has $0$ as one of its eigenvalues.
Comment: @Vim But $\mathbb{F}$ may not be $\mathbb{R}$.
Comment: @MANMAID I guess that $\mathbb F$ must have a partial order compatible with the field operations. On could define such an partial order on $\mathbb C$ by using the order on $\mathbb R$ together with $z\le z$ otherwise. Then $\det A<0$ would make sense.
Comment: @velutluna good point. But i suspect the statement would be wrong for $\Bbb C$.
Comment: perhaps may be then $det(A) $ may be complex and then $det(A)<0$ will not make any sense.
Comment: Is the result $\det (A+I) = \det A + \det I + tr(A)$ true always?
Comment: @MANMAID well, I think it fails for even one by one matrices...
Comment: @Vim just take $A=-I$
Comment: @Vim Apparently the statement is true for any partially ordered field where $0\le 1$, this includes $\mathbb C$ supplied with a suitable PO. Especially it's true for any field if we replace the condition $\det A<0$ with $\det A\ne 1$.
Comment: It is not true that the eigenvalues of an orthogonal matrix are $\pm 1$, think of a rotation matrix.
Answer: We can apparently assume that the field $\Bbb{F}$ is ordered. Otherwise it does not make sense to say that the determinant is negative. Most obviously we can exclude fields of characteristic $p>0$.
We were given that $AA^T=I$. Therefore $\det(A)^2=\det(AA^T)=1$, and we can conclude that $\det A=\pm1$. The assumption $\det A<0$ thus leaves $\det A=-1$ as the only alternative (an axiom of an ordered field is that $1>0$ and it follows that $-1<0$).
But, we can then calculate as follows
$$
\begin{aligned}
\det (A+I)&=\det(A+AA^T)\\
&=\det(A(I+A^T))\\
&=\det A \cdot \det(I+A^T)\\
&=(-1)\cdot \det(I+A).
\end{aligned}
$$
So
$$
\det(I+A)=-\det(I+A).
$$
In a field of characteristic $\neq 2$ the equation $x=-x$ forces $x=0$. Therefore $\det(I+A)=0$, and $A+I$ is singular.
Comment: The transposes have the same determinant $(I+A)^T=I^T+A^T=I+A^T$.
Comment: As far as I see it you don't have to rely on a total order for the question to make sense. The only thing you need in the last step is that $\det A\ne 1$ which is guaranteed if $0\le 1$.
Comment: NIce! but how $\det(I+A^{T}) = \det(I+A)$,any trick to this?
Comment: A nice observation @skyking.
Answer: Note that if any one eigenvalue of a matrix say $B$ is zero then $B$ is a singular matrix.Since determinant of a matrix is the product of its eigenvalues.
In your case $A$ is an Orthogonal matrix!
and since $det(A) < 0$ implying there is atleast one eigenvalue $-1$ .
Now we need to analyse matrix $A+I$ , since $A$ has an eigenvalue $-1$ so $A+I$ will have an eigenvalue as $0$ implying $det(A+I) = 0$ and hence singular.
Hope this helps!
Comment: What if the field we're working above isn't the reals?
Comment: Yes,good catch.I think if its not then there is a possibility that $det(A)$ may be complex and $det(A)<0$ may not make any sense?
Comment: Real orthogonal matrices can have any complex numbers on the unit circle as their eigenvalues. Consider $$R(\theta)=\pmatrix{\cos\theta&-\sin\theta\cr \sin\theta&\cos\theta\cr}.$$ Its eigenvalues are $e^{\pm i\theta}$.
Comment: Nice! but in your case I think in your example $det(R(\theta)) = 1 > 0$ , just as per the question i thought that since it is true for all orthogonal matrices $A$ there may be a case that $det(A)$ is complex and since user has added a condition that $det(A)<0$,then comparing them wouldnot make any sense?
Comment: Correct, @BAYMAX. My example matrix has $\det =1$. The point was to refute the claim that the eigenvalues can be $\pm1$ only. If the determinant of an orthogonal matrix is $-1$, it turns out that then $-1$ must be an eigenvalue, but that needs to be proven first I think :-)
Comment: Yes we need to prove that first @JyrkiLahtonen,BTW is my answer incorrect?.

Show that $A+I$ is singular.


MAPE is high for daily sale prediction

Question: I have daily sales data from 2011 to 2013. I have to do prediction for 2014.I have used arima and exponential method to predict the daily sale, but it is not giving the better result. MAPE is around 25%.
y=ts(x,frequency=7)
fit <- auto.arima(y)
fc <- forecast(fit, h=265)
plot(fc)
fit <- ets(y)
fc <- forecast(fit,h=265)
Below is the link for data:
https://drive.google.com/file/d/0B5en_TDcZWi3QWNjMzd3ZkdIcW8/edit?usp=sharing
Is there a way to improve the MAPE? I am new to time series,I would appreciate any kind of help.
Comment: What country is the data from as holidays can have an impact? What type of data is it?
Comment: It is a daily sales data of a store. The country is US. I tried using holiday also. Still getting the same MAPE
Answer: I looked closely at your data and the 2014 data is much much lower and couldn't have been predicted to be that low.   Every January to March is high in the historical data and the model can't be blamed for this massive shift downwards.  What you need to do is consider the MAPE at many different origins not one.  When you do that you will see that as the first observations in 2014 data are lower that the model respond to the lower level of the data and your MAPE will get better.
Comment: It means that you need to look at forecasts from today, tomorrow, the next day and then calculate a WMAPE(weighted) and not just from one point in time.
Comment: "MAPE at many different origins not one", could you please explain this sentence? I am getting it. Thanks.

MAPE is high for daily sale prediction


Unable to publish Citrix Xenapp over Internet (WAN)

Question: I have installed a xenapp server which is working fine in a local environment but when it comes to publish application over WAN it says
Could not connect to server
however its opening the webpage for citrix signin and I am able to sign in & can see all the published apps, but when I click any of them it downloads. ica application file and the gives the error.
Note: I have installed certificate and citrix receiver, I have done port mapping on router that's why I am able to open the citrix login page..
Answer: Have you also opened up the required ICA ports to the servers in your farm?
Depending on how you have things configured, you will also need to open ports TCP/1494 and/or TCP/2598 to your server farm or from your secure gateway device (or netscaler) to your XenApp application servers.
Comment: Yes I had done that as well, I also tried without firewall on. Did not work in both the cases..


ScorePayload doesn't get called on CustomSimilarity

Question: I followed this blogpost but in lucene.net:
https://lucidworks.com/post/getting-started-with-payloads/
This is how my custom Similarity Looks like:
public class PayloadSimilarity : DefaultSimilarity
{
    public override float ScorePayload(int doc, int start, int end, BytesRef payload)
    {
        var score = PayloadHelper.DecodeSingle(payload.Bytes, start);

        return score;
    }
}

Then as the blog post mentions I set the similarity for the Searcher and as well as for the indexer.
In luke I can see that the Payload is there. And if I search for the payloads it doesn't give me back anything so I think the payload is there but the Searcher doesn't takes into the account.
I'm using Query Parser with the combination of Searcher and the custom similariity.
The explain shows that my custom similarity was used but it doesn't show that ScorePayload was used, and of course it doesn't break in the ScorePayload function if I put a breakpoint there.
Thanks in advance for your help!
P.S: And this is how I build the Analyzer:
    public static Analyzer WithTermBasedBoosting(char delimiter) => CustomAnalyzer
        .WithTokenizer("WhitespaceTokenizer")
        .AddTokenFilter("DelimitedPayloadTokenFilter")
        .With(delimiter,new SingleEncoder())
        .Build();

For the sake of simplicity I created another Analyzer with the fewest things:
    public static Analyzer MyDelimited(char delimiter) => Analyzer.NewAnonymous(createComponents: (fieldName, reader) =>
    {
        Tokenizer source = new WhitespaceTokenizer(CustomAnalyzer.Version, reader);

        TokenStream filter = new DelimitedPayloadTokenFilter(source, delimiter, new SingleEncoder());

        return new TokenStreamComponents(source, filter);
    });

Answer: Seems that the answer was simple, you can't use a normal QueryParser as it doesn't takes into account the payload. I found out a QueryTerm type namely PayloadTermQuery and now my Query looks like this:
public List<ResultModel> Query(string indexName,string searchTerm, int top = 100, float score = 2f)
        {
            var searcher = GetSearcher(indexName);

            //Query query = new QueryParser(Version, IndexFields.Text, _queryAnalyzer).Parse(searchTerm);

            Query query = new PayloadTermQuery(new Term(IndexFields.Text, "GMBH"), new AveragePayloadFunction());

            var rowsToReturn = top == 0 ? int.MaxValue : top;

            var hits = searcher.Search(query, rowsToReturn).ScoreDocs;

            return hits.Where(x => x.Score >= score)
                .Select(hit => hit.ToResultModel(searcher, query))
                .ToList();
        }

However would be great to use QueryParser with the combination of the CustomSimilarity.


Unit Testing a class that uses RegistryManager C# Azure IoTHub

Question: I am trying to test my class that uses RegistryManager to communicate with IoThub.
The problem I'm facing is that when creating a mock class that inherits from RegistryManager I'm able to override all the methods except for ExportRegistryAsync. I get a red line under override and if I remove the override statement I get this error when I build the project:

Error    4    'MockObjects.MockRegistryManager' does not implement inherited abstract member 'Microsoft.Azure.Devices.RegistryManager.ExportRegistryAsync(string, string)'    Tests\MockObjects\MockRegistryManager.cs    9    18

Code:
public class MockRegistryManager : RegistryManager
{
    private static List<Device> _devices;

    public MockRegistryManager()
    {
        _devices = new List<Device>();
    }

    public override Task OpenAsync()
    {
        throw new NotImplementedException();
    }

    ...

    internal override Task ExportRegistryAsync(string storageAccountConnectionString, string containerName)
    {
        throw new NotImplementedException();
    }

    internal override Task ExportRegistryAsync(string storageAccountConnectionString, string containerName, CancellationToken cancellationToken)
    {
        throw new NotImplementedException();
    }

}

Is there a better way to test a class that uses RegistryManager?
Any help will be very much appreciated.
Comment: what do you mean by red line under override? is it compiling or not if you override?
Comment: you could abstract the methods and properties you will be using into an interface so that you can mock it with out tightly coupling to `RegistryManager`. You should not try to mock class you don't own.
Comment: Can you show a snippet of the class that uses or depends on the `RegistryManager`
Comment: According to the [source code on GitHub](https://github.com/Azure/azure-iot-sdks/blob/master/csharp/service/Microsoft.Azure.Devices/RegistryManager.cs#L269), those methods are **internal** to the framework, which means that you should not be able to override them in your project.
Comment: @Nkosi Here is the class that uses the `RegistryManager`: [pastebin](http://pastebin.com/KAZdSAnM)
Comment: How should I unit test the code without communicating with iothub?
Comment: abstract away the tight coupling to the RegistryManager. drafting up an answer for you now.
Answer: Given you current version of the class to be tested
public class Registry {
    private readonly RegistryManager _registryManager;

    public Registry(RegistryManager rm) {
        _registryManager = rm;
    }

    public async Task<string> GetDeviceKey(string deviceId = null) {
        if (deviceId == null) {
            throw new Exception("Todo replace");
        }
        var device = await _registryManager.GetDeviceAsync(deviceId);
        if (device == null) {
            throw new Exception("TODO replace");
        }
        return device.Authentication.SymmetricKey.PrimaryKey;
    }
}

If you want to test this then you will have problems with the RegistryManager. You need an abstraction of the services you want to use so that you can mock/fake them for testing without having to use the real thing.
something like
public interface IRegistryManager {
    Task<Device> GetDeviceAsync(string deviceId);
}

This will then allow you to refactor your class like this
public class Registry {
    private readonly IRegistryManager _registryManager;

    public Registry(IRegistryManager rm) {
        _registryManager = rm;
    }

    public async Task<string> GetDeviceKey(string deviceId = null) {
        if (deviceId == null) {
            throw new Exception("Todo replace");
        }
        var device = await _registryManager.GetDeviceAsync(deviceId);
        if (device == null) {
            throw new Exception("TODO replace");
        }
        return device.Authentication.SymmetricKey.PrimaryKey;
    }
}

Which now allows your Registry class to be completely testable. You will notice that other than the type of the registry manager field nothing else needed to be changed. nice.
You can now make a fake RegistryManager or mock one up using testing frameworks as needed.
When you need to make the actual calls in your production code you just wrap the real thing in your interface and pass it into your Registry class
public class ActualRegistryManager : IRegistryManager {
    private readonly RegistryManager _registryManager

    public ActualRegistryManager (RegistryManager manager) {
        _registryManager = manager;
    }

    public Task<Device> GetDeviceAsync(string deviceId) {
        return _registryManager.GetDeviceAsync(deviceId);
    }
}

One of the good things with this approach is that you now only need to expose the functionality you really need to dependent classes.
Using Moq and FluentAssertions I was able to mock up and test the Registry class with the following test
[TestMethod]
public async Task Registry_Should_Return_DeviceKey() {
    //Arrange
    var expectedPrimaryKey = Guid.NewGuid().ToString();
    var deviceId = Guid.NewGuid().ToString();
    var fakeDevice = new Device(deviceId) {
        Authentication = new AuthenticationMechanism {
            SymmetricKey = new SymmetricKey {
                 PrimaryKey = expectedPrimaryKey
            }
        }
    };
    var registryManagerMock = new Mock<IRegistryManager>();
    registryManagerMock.Setup(m => m.GetDeviceAsync(deviceId))
        .ReturnsAsync(fakeDevice);
    var registry = new Registry(registryManagerMock.Object);

    //Act
    var deviceKey = await registry.GetDeviceKey(deviceId);

    //Assert
    deviceKey.Should().BeEquivalentTo(expectedPrimaryKey);
}

Hope this helps.


(Standalone) Software for plotting graphs of large amounts of data and allowing you to scroll/zoom

Question: I've got some temporal data taken from a data logger that I'm trying to plot in a graphical form (as a line graph). Because it's a large amount of data, plotting it one one big graph (e.g. in Excel) makes it difficult to explore the visualised data as you can't really zoom in and scroll through the data. What I'm looking for is some standalone software that can plot the data as a line graph, but also allow the user to easily scroll through the graph along the horizontal (time) axis and be able to zoom that axis in and out. Ideally, the software would be free and be GUI driven. Does anyone know of any such software?
Thanks,
Comment: You may find some of the suggestions at this link helpful: http://stackoverflow.com/questions/1890434/javascript-library-for-drawing-graphs-over-timelines-zoomable-and-selectable
Comment: Thanks, although these are software libraries and I was looking for standalone software.
Answer: A survey of interactive plotting software with a 10 million point scatter plot benchmark on Ubuntu 18.10
I have published this survey at: https://stackoverflow.com/questions/5854515/large-plot-20-million-samples-gigabytes-of-data/55967461#55967461
Here is a copy of the summary of results:
Does it handle 10 million points:
VisIt       Yes
Paraview    Barely
Mayavi      Yes
gnuplot     Barely on non-interactive mode.
matplotlib  No

Does it have a lot of features:
VisIt       Yes, 2D and 3D, focus on interactive.
Paraview    Same as above.
Mayavi      3D only, good interactive and scripting support, but more limited features.
gnuplot     Lots of features, but limited in interactive mode.
matplotlib  Same as above.

Does the GUI feel good:
VisIt       No
Paraview    Very
Mayavi      OK
gnuplot     OK
matplotlib  OK

Answer: Gnuplot is free, open source and highly versatile and what I use and I think it will meet your needs. You can point and click with the mouse to zoom in and out on any part of a graph, and you can even write a script to scroll through the data as if watching a film.
Comment: @JeanV.Adams unfortunately, I've found that gnuplot cannot handle 10 million points interactively nicely: https://stats.stackexchange.com/questions/73939/standalone-software-for-plotting-graphs-of-large-amounts-of-data-and-allowing/405613#405613
Comment: Interesting.  I hadn't heard of this before.  I found the zoomable stuff on the canvas page, http://gnuplot.sourceforge.net/demo_canvas_4.6/, and had to use Firefox to see it (Chrome didn't work for me).
Answer: After much searching, I have found exactly the software I am looking for:
http://www.datplot.com/
Simple, GUI-driven software that allows you to import raw data and plot graphs, with dynamic scroll and zoom.
Comment: I'm looking for a Mac OS alternative. Any idea?
Answer: You could also try Plotly - it's a web-based interactive graphing app
Comment: Welcome to the site, @ronsolo. At present this is more of a comment than an answer. Would you mind expanding it? What is it about Plotly that makes it a good choice for the OP?
Answer: I have launched a software recently www.winplotter.com, which suits the needs you specified.
Comment: flaggers: it is not forbidden to mention software you're involved with if you clearly identify your association with it (which was done) and if it is actually a suitable answer to the question. The OP needs to do more on that front to explain it's suitability in the context of the question (which things that were asked for does it actually do?) but unless it doesn't relate too the question at all, that just makes it a poor answer rather than spam.
Comment: Can you explain why this software meets the criteria stated in the question?


list of options to be used in trans_primitives and agg_primitives

Question: I am looking for the complete list of options to be used in trans_primitives and agg_primitives. For instance, my data is not time series and for new features, I would like to try mathematical functions (add, multiply, divide,...) to create new features.
Thanks
Answer: You can find a list of all the available primitives in the Featuretools API Documentation or by visiting primitives.featurelabs.com.


Does the Scarlatti's 'Cortege' really sound like Gaudeamus Igitur?

Question: Every time I hear https://imslp.org/wiki/Keyboard_Sonata_in_E_major%2C_K.380_(Scarlatti%2C_Domenico), I think I'm hearing the melody for the third and fourth lines of https://en.wikipedia.org/wiki/Gaudeamus_igitur. In particular, the Scarlatti comes to a cadence and then launches into a second melody which is the source of this earwormy moment. Does this make any sense in terms of musical history?
I suppose there are two questions here: (1) does it make any sense for Scarlatti to have been listening to university students, or (2) is there something about the structure of the two melodies that makes the resemblence?
Comment: You would be surprised as to how much of Bachs great discography was partially composed by the students he mentored.
Answer:
(1) does it make any sense for Scarlatti to have been listening to university students?

Of course.  Why wouldn't he?  (It's not clear, to the casual researcher at least, that university students in Italy would have been singing this melody in those days, however; Wikipedia says that the melody was first published in Leipzig a quarter century after Scarlatti's death.  It also says without citation that the melody was known before then, which is certainly likely.)

(2) is there something about the structure of the two melodies that makes the resemblence?

This is easier to answer more definitively, and of course the answer is yes.  Both have the basic structure sol-la-sol with the rhythm long-short-long and slightly different embellishment.  In both cases, the embellishment begins with an irregular rhythm and ends with an even rhythm, which is common in stately or ceremonial music of the baroque and classical periods.
In the case of Gaudeamus, the first sol takes three beats (with the first actually realized as mi-fa in a dotted rhythm).  In the Scarlatti, the sol is repeated five times over two beats.   The la is in both cases one beat divided evenly in two; Gaudeamus has la-fa while the Scarlatti has la-do.  Finally, the last sol is simply sol in both cases, two beats for Gaudeamus and three for the Scarlatti.  In the case of the Scarlatti, there is an echo of the same figure in the tenor octave at this point.
Answer: I'd say the similarity between these motives can be reduced to a motive falling from the fifth of the chord to the third, filling up the interval using a dotted note. Needlessly to say this is a very generic kind of motive and assuming any influence in any direction here would not be feasible. In fact while Scarlatti brings the motive on the tonic, Gaudeamus igitur has it on the subdominant and also progresses in a very different way.


Retorno da função main

Question: Estudando C/C++ aprendi que colocamos o return 0 no final da função main() para indicar que o programa funcionou corretamente, caso isso ocorra. Mas caso isso não ocorra, um valor diferente de 0 será retornado pela main(). O que esse valor indica especificamente? Acredito que não seja um número aleatório.
Answer: Assim como é possível passar argumentos para o código pela função main() através do parâmetro argv (com auxilio do argc) e estes dados vêm de quem chamou o executável, você também pode retornar um dado para quem chamou. Geralmente quem chamou é o sistema operacional (por ação de algum usuário ou script que cuida disto) e é ele que receberá esta informação para ser usada de alguma forma, por exemplo um script pode pegar isto e decidir o que fazer.
O número que vai retornar é definido por você mesmo para sua aplicação e deve documentar bem isto para quem for chamá-la possa usar este resultado para alguma coisa de acordo com a semântica que você quis dar e que faça algum sentido. Em geral cada número indica algum erro específico que deu, de acordo com sua documentação.
Mas é um engano que você precisa usar o return 0, se não fizer isto haverá o retorno de 0 de forma implícita, pelo menos isto vale para todos os compiladores mais conhecidos.
E tem um outro detalhe, quase todas as vezes que for retornar um erro o fará através, direta ou indiretamente, da função exit() ou algo semelhante, já que isto ocorrerá em outra parte do código que não a main() e deverá encerrar imediatamente.
Comment: É _standard_ em C11/C18 não precisar retornar valor em `main`?
Comment: Sim, até onde eu sei desde C99.
Comment: Achei em 188.8.131.52.3 do rascunho "_reaching the } that terminates the
main function returns a value of 0._"
Answer: O número retornado só faz sentido no contexto do programa que você criou. Se você estiver ciente de um possível erro, você pode colocar return 1 em um ponto, e return 2 em outro. Se o programa eventualmente falhar, fica mais fácil de traçar qual foi o motivo do erro pelo código retornado.
Comment: Mas fora de contexto, existe algum significado para ele?

Retorno da função main


Por que não preciso declarar o parâmetro na função?

Question: Na documentação do React ele traz um exemplo de form, quando o input recebe algum valor a propriedade onChange é chamada com a função handleSubmit(event) dessa maneira onChange={this.handleChange} porque eu não preciso definir o parâmetro nesse caso, já que a assinatura da função tem um parâmetro?
class NameForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {value: ''};

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange(event) {
    this.setState({value: event.target.value});
  }

  handleSubmit(event) {
    alert('A name was submitted: ' + this.state.value);
    event.preventDefault();
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>

          Name:
          <input type="text" value={this.state.value} onChange={this.handleChange} />

        <input type="submit" value="Submit" />
      </form>
    );
  }

Answer: Porque você não está chamando a função, está apenas dizendo qual função será usada pelo framework neste momento. Isto é o que se chama função anônima ou técnica de callback, você está parametrizando o que será executado em determinando momento, no caso específico o que será chamado quando ocorrer o evento onChange, então quem chamará a função de verdade é o React e ele é que passará um argumento para sua função. Portanto você está passando uma referência para a função e não chamando-a, os parênteses é justamente o que diferencia isto, com, chama, sem, passa referência.
Comment: Ele não sabe exatamente, isto não é característica do JS ou do React. Você tem que fazer certo o que ele espera, ele faz o que tem que fazer e espera que sua parte esteja ok, se não estiver vai dar erro. È um contrato que ele faz com você e espera que você cumpra. Mesmo em linguagens e tecnologias que garantem mais isso, a garantia vai até certo ponto, é como você fazer um `for` em todo um *array*, se você fizer errado vai dar erro de compilação, ou execução ou de lógica.
Comment: como ele sabe exatamente que o parâmetro está certo? tipo como ele sabe que tem que usar o event ou qualquer coisa?
Answer: Em linguagem JSX escreve-se onChange={this.handleChange} mas na verdade é o mesmo que .addEventListener('change', this.handleChange) ou seja uma callback. No momento em que essa callback é usada ela vai receber todos os argumentos que lhe forem passados.
Exemplo:

function handleChange(e){
    console.log(e.type, this.checked);
}

const checkbox = document.querySelector('input[type="checkbox"]');
checkbox.addEventListener('change', handleChange);
Clica aqui: <input type="checkbox" />

Nota que em classes React por vezes tens de usar o .bind(this) para garantir que essa callback vai ter o contexto de execução que esperas, ou seja o this é a instância da classe:
onChange={this.handleChange.bind(this)}


The resource cannot be found. after adding new page?

Question: I have created a new MVC4 Web application, and then i am adding new View in views called Login.aspx.
When i try to access it the way i am accessing About.aspx ( which is generated automatically with new project ) - i am receiving "The resource cannot be found." type of error.

What could cause this issue ?
Comment: Show the URL, the Controller and View codes. You shouldn't be accessing a `.aspx` anyway.
Comment: Create an action called "login" that returns "Login.aspx" as a view.
Comment: Have you defined `action`?
Answer: Sole view is not enough in ASP.NET MVC to add a new page to the application. You also have to:

Create controller with corresponding action, or add new action to one of existing controllers.
Implement this action to return necessary view (Login in your case).
Make sure that your action is covered by one of existing routes. If it is not - add a new route.

For details you can review this tutorial on MSDN.
Comment: O Lords!! .. Thank You VERY VERY Much Andrei ! :)


Aligning HTML Buttons Horizontally (Not Using CSS)

Question: I'm writing an email campaign in Ascendify and need to center 5 html linked buttons horizontally.I do not have access to the CSS, so I need to just do it with html code. I'm really struggling in figuring this out, any feedback would be appreciated. Here's the code:

Engineering

HR & Recruiting

Product & Design

Sales & Marketing

Women In Tech

Comment: How exactly do you want them aligned? The five of them in the center, in each line, or of the five of then in the center of its own line?
Comment: Five centered on one line.
Comment: *"Not Using CSS"* – But you're using CSS there? I don't get it.
Comment: @poke I believe he meant not using a CSS stylesheet file, even though he is using inline styling.
Answer: Add a style attribute
<button style='display: inline-block;'> </button>

Answer: Twop options for achiving expeccted result
<div style="text-align: center;float:left"

Other option using display:inline as mentioned by Blaze349
Codepen - https://codepen.io/nagasai/pen/pPWJVm
Comment: This worked almost perfectly. The only issue is that therewasnt enough space on a single line to fit them all.  So I put a break after the first three and now the two on the next line are left justified instead of centered. I've already asked a lot, but what would I do to center these?
Answer: You currently have 5 buttons stacked on top of each other because each anchor is wrapped in a div, which is display:block by default, meaning it fills the entire horizontal space for its line.
I would either remove the div tags wrapping the anchors altogether and just have 5 anchor tags next to each other, or change the div tags to span tags, which are inline by default.
You can also remove the extraneous div tags with non-breaking spaces and use style="margin-right: 10px;" (or whatever value looks good) on each anchor or wrapping span to give space between the anchors.
Also, you can move the "text-align: center" style to the outermost wrapping div and it will center all the buttons and their text for you without having to do that on each child element.

Engineering

HR & Recruiting

Product & Design

Sales & Marketing

  Women In Tech
Answer: You should add a display: inline-block; to your div's style inline. That way, for each of your divs, you just have to add this style tag, so it would be something like this:

You have to do it in all of your divs, otherwise it won't work.
In your code, it would be like this:

Engineering

HR & Recruiting

Product & Design

Sales & Marketing

Women In Tech

You can learn more about the display style in here: https://www.w3schools.com/cssref/pr_class_display.asp
Comment: Thank you, I appreciate you taking the time to respond. This worked almost perfectly. The only issue is that there wasnt enough space on a single line to fit them all. So I put a break after the first three and now the two on the next line are left justified instead of centered. I've already asked a lot, but what would I do to center these?
Comment: Try putting those inside another ``.
Comment: @G.Elliott It displayed something diferent from this? http://i.imgur.com/i59RUfH.png
Comment: It displayed like that...until I ran it.  The constraints of the email format template (probably the CSS I can't access) created weird spacing and wrapped the buttons.  So I put a break in after the first 3, and now the spacing is fine for the first three, centered on the top line.  And I'm working on centering the last two, centered on the second line.
Comment: @G.Elliott You want something like this, then? Just tell me so and i will edit my answer: http://imgur.com/FpTi5Fy
Comment: Yes, but with a space between the two rows, so that the'yre not touching.
Comment: Ok. Just a moment.
Comment: @G.Elliott Check my answer's snippet again. And if i helped you, please accept my answer as correct.


Event triggered backup systems -- what are my options?

Question: Background - I work in a corporate environment where files on network shares are constantly being modified. Created, deleted, overwritten. Of course with hundreds of users, you can imagine the odd time where people accidentally delete the wrong files or overwrite them at the wrong time.
What I am searching for essentially is an event-based backup system. Something that can monitor the entire filesystem for events and create snapshots of files when modified. There are libraries out there that make this possible like inotify (Linux), so I'm wondering if it has been put to use for a server backup system, whether it be Windows or Linux based (there are inotify ports for Windows as well as the Java platform). We are currently using Symantec backupexec which works wonders, the only problem is I cant be having backup after backup running constantly on the servers, especially during peak hours which is when I'd need it the most. I find an event based backup system would be much more efficient as it would only take action upon file modifications, as opposed to constantly snapshotting the entire disk at once. In our current environment, users can "accidentally" obliterate files only hours after they are created. Having our backups run once daily after hours doesn't help me restore these deleted files.
Essentially a system that can keep a desired amount of snapshots on a per-file basis would be ideal. Possibly the last 5 - 10 copies of a file.
Storage is not an issue, I have multiple servers available ranging from 2 - 10TB space. We've also recently purchased a SAN system with 60TB space which is itching to be utilized. We are only dealing with small word/excel/pdf documents as well.
Any help and insight is greatly appreciated.
Comment: The only thing I know for certain exists like this is Novell's Open Enterprise Server, running on Novell's proprietary NSS file-system. This is one of the features people migrating *away* from that platform miss the most. This probably doesn't help you, though.
Answer: I think what you want is a versioning filesystem, which is simply a filesystem that keeps multiple versions of old copies of the file.  I've not tried any of them, but a quick survey shows that NilFS could do what you want.
Answer: Windows kind of comes with something like this baked in. It's called Previous Versions in the GUI, and uses Microsoft's VSS to do the hard work. It's not exactly what you're after, but it has the nice side effect that you don't have to restore files from backup so often as the users can often do it themselves.
It's turned on per volume, and a scheduled task runs at intervals you define and takes snapshots of files that have changed since the last time the task ran.
This can help in the situation you describe where for example a user creates a file at 11AM (after last nights backup) and deletes it at 4PM. If for example the scheduled task ran at 1PM, the user can retrieve the file themselves by right clicking the folder it was in and selecting the Previous Versions tab.
This article talks about it in Windows Server 2003, but it's the same through to Windows Server 2008 R2.
Answer: If you have an inotify-enabled Linux kernel look into the incron/incrontab utility:
http://inotify.aiken.cz/?section=incron&page=about
It uses the inotify system to run commands that you configure.
Answer: For windows, you could look into Backup Exec's continuous protection services. It should allow you keep copies as they change, and stage them out over time. We have a VP assistant who keeps deleting files from our shares, and we have been able to recover everyone of them.
Answer: You could ask your Symantec salesdroid about NetBackup RealTime, which appears to do what you want by getting copies of all writes to the backed-up LUNs.
Warning: as with other NetBackup-family products, I expect an eye-watering price.


How to set Oracle to deal with object names case-sensitively?

Question: I know I can use double-quote to force case-sensitive object names, but I want to avoid using it. I wonder if there is a database option to set to make Oracle deal with object names in a case-sensitive manner without using double-quote. Thanks!
Answer: There is no such option.  If you want to force everything to be case-sensitive (and I would strongly question the wisdom of that), you would need to use double-quoted identifiers throughout your code.


Installing Error during ap Installation on other device

Question: My app is running successfully on my android device which is installed during build  but when I send this app to another device via bluetooth/whatsapp  from my device it does't run on this device show App not installed error....any body can help plz
Answer: The device does not support the function app needs like camera, wifi, or SDK version.
You might want to check the requirement of the app in there page.


Variable within double quotes

Question: Which is the correct syntax?
$current_renewal_date = $wpdb->get_results(
                    "
                    SELECT expiry_date
                    FROM bid_tag
                    WHERE id = $renewal_tag_id
                    LIMIT 1
                    "
                );

OR
$current_renewal_date = $wpdb->get_results(
                    "
                    SELECT expiry_date
                    FROM bid_tag
                    WHERE id = {$renewal_tag_id}
                    LIMIT 1
                    "
                );

Comment: The second one is easier to read and handier when you need to refer to, say, `$renewal_tag_id['some_index']`. However, in this context, you should consider `$wpdb->get_var( $wpdb->prepare("SELECT .. WHERE id = %s LIMIT 1", $renewal_tag_id))` to avoid SQL injection.
Comment: The first one. The second one might even work actually.
Comment: SQL injection with a `SELECT` statement?
Comment: @dcolumbus SQL injection does not mean 'inject data into the database' but 'inject commands into the SQL statement'.
Comment: I edited my answer with some extra information that might be useful to you. Please keep it mind when you work with interpolated variables.
Answer: They're both correct* and equivalent. When you're just interpolating a variable and not accessing an element in an array, the braces are optional.
* Use parametrized queries please
Answer: Both are correct. The latter is just used to avoid ambiguity like if you want to reference $foo and not $foobar:
"{$foo}bar"

Answer: I don't know if you could really say that there is a single correct form to put a variable within a string, but the most flexible and sure to work would be:
$current_renewal_date = $wpdb->get_results(
                    "
                    SELECT expiry_date
                    FROM bid_tag
                    WHERE id = ".$renewal_tag_id."
                    LIMIT 1
                    "
                );

There are at least 2 benefits of using this syntax instead of just putting the variable within the string.
Variable misinterpretation
1) When you put the variable within the string, you will probably experience problems if you need to mix the variable with other text.
Example:
$string = "My ID is AB$variableCD";

what is the variable? is it $variable? is it $variableC? or $variableCD? There are many interpretations for this on the syntax that you are using. This doesn't happen when you do
$string = "My ID is AB".$variable."CD";

Array usage
2) You can't easily use variables that have array indexes when you mix them within a string
Example:
$string = "The largest country is $options[countries in the world][$index]";

will get you *PHP Parse error:  syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting ']'*
while using the following will work perfectly:
$string = "The largest country is ".$options['countries in the world'][$index];

And a little extra that isn't really a matter of syntax...
3) And there is actually a performance benefit, and that is the possibility of using ' instead of " for your strings. Using ' makes the string literal, that is, it isn't parsed and this causes a performance improvement when handling large strings.
$string = 'hello';

instead of
$string = "hello";

Comment: why would that be any more correct than the ones in the question?
Comment: What do you mean, the most "sure to work"? They all work. String interpolation isn't some kind of random process.
Comment: Sorry, forgot to explain: This is  because you avoid 2 big problems: 1) you avoid cases of character escape. 2) you avoid problems with name concatenation. I will modify my answer to add some examples and you will see what I mean.
Comment: Edited my answer, that should answer your questions. Please comment.
Answer: They both work. The preferred way would be using prepared statements and bound parameters.

Variable within double quotes