Visual Studio ASP.NET MVC Not Loading Local bootstrap.css

Question: I installed bootstrap using nuget package manager and the css files are now in my /Content/ folder. However, when trying to reference them using:
<link rel="stylesheet"  href="∼/Content/bootstrap.min.css" />

It doesn't work. But when referencing them using a CDN like:
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">

It does work. I can't seem to figure out what is wrong as I have never had this problem before. I'm using an Empty template with MVC.
EDIT: After some playing around, I found that it was failing to load /%E2%88%BC/Content/bootstrap.css but after removing the tilda (~) it works fine. Anybody got any ideas?
Comment: I FINALLY figured out what the problem was. I'm reading an e-book for ASP.NET MVC and as the examples are big, I have to copy and paste (my fault, I know) and it turns out that the because the font is different in the book, it doesn't pick it up. So I just typed the ~ myself instead of copying the ∼ from the book. Sorry to waste everyone's time.
Comment: Have you tried using fiddler or F12 dev tools to see if it is attempting to download the file and failing?
Comment: Yes it's failing to download bootstrap.css and bootstrap-theme.css. 404 not found.
Comment: Do any of the answers here help? http://stackoverflow.com/questions/10853316/tilde-slash-paths-not-working-in-mvc-4
Comment: I think it is necessary to add the bundle: https://stackoverflow.com/questions/20869907/adding-bootstrap-in-bundleconfig-doesnt-work-in-asp-net-mvc
Answer: This is not a correct path, it uses the tilda, which is used on the server when rendering links in server controls in asp.net.
Instead of this:
<link rel="stylesheet"  href="∼/Content/bootstrap.min.css" />

Try this:
<link rel="stylesheet"  href="@Url.Content("∼/Content/bootstrap.min.css")" />

Assuming that you are using Razor.

Alternatively, consider looking into style and script bundling that you get with new asp.net sites.  Can be very useful.
Comment: Hmm, that doesn't seem to be working. Breaks the application with "Compiler Error Message: CS1056: Unexpected character '∼'". My intellisense doesn't seem to like anything that I'm passing to the @Url.Content.
Comment: Doesn't work with passing the string in quotes either.
Comment: Sorry, missed the quotes.  Having the string passed in quotes works for me.
Answer: Adding "app.UseStaticFiles()" to Startup.cs worked for me:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseBrowserLink();
        app.UseStaticFiles();
        app.UseMvcWithDefaultRoute();
    }
}

Answer: Now only Bootsrap 3 works with local links in .Net. Terrible. :(  For 4, you must use CDN :

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">


incompatible types: T#1 cannot be converted to T#2

Question: I am going to create one generic class, first i want to say my requirement. I have different classes e.g. A,B etc. I am going to create an instance of class based on the json object. This json object will be read from file. The file may contain equivalent json object.based on it i will create an instance of that class using GSON. Now i face one error i.e. incompatible types: T#1 cannot be converted to T#2
This is my code sample
public class JsonLoader<T> {

    private final  Gson gson = new Gson();

    private final T content;

    public <T> JsonLoader(Class<T> clazz, String filePath) throws IllegalFileException {
        if (filePath.isEmpty() || filePath == null) {
            throw new IllegalFileException("IllegalFileException: source file must required.");
        }
        try (Reader reader = new FileReader(filePath)) {
            T content= gson.fromJson(reader, clazz);
            this.content = content;

        } catch (IOException e) {
            throw new IllegalFileException(e.getMessage(),e);
        }

    }

    public <T> T getObject() {
        return this.content;
    }
}

Please help me.
Comment: Can you post more information about the error? Line number?
Comment: @Kevinrob `incompatible types: inference variable T#1 has incompatible bounds
    equality constraints: T#2
    upper bounds: T#3,Object
  where T#1,T#2,T#3 are type-variables:
    T#1 extends Object declared in method fromJson(Reader,Class)
    T#2 extends Object declared in constructor JsonLoader(Class,String)
    T#3 extends Object declared in class JsonLoader`
Answer: When you declare the type parameter T on the class, the entire class body has access to that type parameter, so you don't need to redeclare it. When you say public <T> JsonLoader and public <T> T getObject you are actually declaring new type parameters with the same name which shadow the type parameter on the class.
This is similar to how you can declare a variable which shadows a field:
class Example {
    int foo;
    // parameter foo shadows the field foo
    Example(int foo) {}
}

If you remove the type parameter declarations on the constructor and method it should just work.


How do I prove divisibility by 3 without induction?

Question: How do I prove that:

$3$ divides $4^n-1$, where $n$ is a natural number, and
$3$ divides $n^3-n$, where $n$ is a natural number?

All without induction?(only number theory)
Thanks !
Comment: If so, think about congruence mod $3$.
Comment: Hmm...did you mean "$3$ divides $4^n - 1$" and "$3$ divides $n^3 - n$"?
Comment: yup I made a mistake there
Answer: For the first one, use modulo arithmetic:
$$4^n - 1 \equiv 1- 1 \pmod 3\\
= 0 \pmod 3\\
\implies 3 | (4^n - 1)$$

For the second one, do a simple factorization:
$$n^3 - n = n (n^2 - 1) = (n-1)(n)(n+1)$$
and then notice that one  of $n-1, n, n+1$ must be divisible by $3$. This is a clever and very worthy trick : One and only one of $k$ consecutive positive integers must be divisible by $k$.
In fact, using similar arguments, we can deduce that $2$ divides $n^3 - n$ as well, and therefore since both $2$ and $3$ are divisors, then $6$ must also be a divisor of $n^3 - n$.

Just for completeness' sake:
$$\begin{align}4^n &= (1 + 3)^n \\
&= 1 + 3\binom{n}{1} + 3^2\binom{n}{2} +\cdots+3^n\binom{n}{n}\\
&= 1 + 3\left(\binom{n}{1} + 3\binom{n}{2} +\cdots+3^{n-1}\binom{n}{n}\right)\end{align}$$
So we've proved that for integers $n \ge 1$, $4^n$ gives a remainder of $1$ when divided by $3$, i.e. $4^n \equiv 1 \pmod 4$.
Answer: $4=1$ (mod 3) so the first reduces to $4^n-1=0$ (mod 3) and the second we have that $a^p=a$ (mod p) for any prime and any $a$ not divisible by $p$This is Fermat's Luttle Theorem. This $n^3-n=0$ (mod 3) if $3\not| n$ but if $3|n$ it should be clear that it still holds.


Antiderivative of $e^{x^2}$: Correct or fallacy?

Question: Please check where is the mistake in this following process. I could not make out.
$$e^x=\sum_\limits{n=0}^\infty \frac{x^n}{n!}$$
$$\implies e^{x^2}=\sum_\limits{n=0}^\infty \frac{{(x^2)}^n}{n!}=\sum_\limits{n=0}^\infty \frac{x^{2n}}{n!}$$
$$\implies \int e^{x^2} dx=\int \sum_\limits{n=0}^\infty \frac{x^{2n}}{n!} dx$$
$$\implies \int e^{x^2} dx=\sum_\limits{n=0}^\infty \frac{x^{2n+1}}{n!(2n+1)} + c$$
But $e^{x^2}$ has no antiderivative as such. How is then thus possible?
Is this correct or just a fallacy?
Comment: Where is the problem? The power series $\sum\limits_{n=0}^\infty \frac{x^{2n+1}}{n!(2n+1)}$ has radius of convergence $R=\infty$ and you differentiate it term by term. It is a very different matter to show that $e^{x^2}$ has no "elementary" antiderivative.
Comment: @PhilippeMalot Thanks but I cant read French.
Comment: e^x^2 doesnt have a closed form but i think it could have a seires
Comment: Congrats for figuring out the integral of $e^{x^2}$ !!!
Comment: you can evaluate first few terms and then reduce the rest as the error estimate.
Comment: If you can read french, here is a famous exam from the École Normale Supérieure on elementary functions and why $x\mapsto e^{x^2}$ has no elementary antiderivative. http://pomux.free.fr/corriges-1995/pdf/m95lm1ea.pdf
Answer:
But $e^{x^2}$ has no antiderivative as such.

This is false. $e^{x^2}$ certainly has an antiderivative, since all continuous functions have antiderivatives. It's just that the antiderivative cannot be written with our standard set of functions (i.e. polynomials, trigonometrics, and exponentials).
So yes, what you did is entirely correct (because all the sums are absolutely convergent, the operations are valid).
Answer: What you have done looks correct. $e^{x^2}$ does have an antiderivative, it is just not expressible as any combination of elementary functions.
Answer: You have found a series representation of the imaginary error function
\begin{equation}
\mathrm{erfi}(x) = \frac{2}{\sqrt{\pi}} \int\limits_{0}^{x} \mathrm{e}^{z^2} dz
= \frac{2}{\sqrt{\pi}} \sum_{n = 0}^{\infty} \frac{x^{2n+1}}{n!(2n+1)}
\end{equation}


installing ruby 2.0.0 through RVM

Question: I am on Macbook Air (v. 10.8.4) and am trying to install ruby 2.0.0. I did rvm get stable then rvm install ruby-2.0.0. I get this error...

Installing Ruby from source to: /usr/local/rvm/rubies/ruby-2.0.0-p247, this may take a while depending on your cpu(s)...
ruby-2.0.0-p247 - #downloading ruby-2.0.0-p247, this may take a while depending on your connection...
ruby-2.0.0-p247 - #extracted to /usr/local/rvm/src/ruby-2.0.0-p247 (already extracted)
ruby-2.0.0-p247 - #configuring - using Zsh, can not show progress, be patient...
ruby-2.0.0-p247 - #compiling - using Zsh, can not show progress, be patient...
Error running 'make -j4',
please read /usr/local/rvm/log/ruby-2.0.0-p247/1373658495_make.log
There has been an error while running make. Halting the installation.

I tried Can't install Ruby 2.0.0-p0 with RVM. Error running 'make -j8' but I am still getting the same error. As in, I tried
I copied and pasted the log file into a google doc because it was 400+ lines. Link here https://docs.google.com/document/d/1mwiL88KbWYfFge3XKQF2hOJjG_8PzYTdcRFxbZcpUeU/edit?usp=sharing
Comment: there should be `/usr/local/rvm/log/ruby-2.0.0-p247/137*_configure.log` can you show first 20-30 lines of it
Comment: which OS X version do you have?
Comment: There are multiple files that fit that requirement. Should I post all of them? And the version is 10.8.4.
EDIT: looks like they all say the same thing. Here you go, https://docs.google.com/document/d/1bItAf9TCNrq2gSao2rz6pymgDVu5Xj0df8K6sjtWdUE/edit?usp=sharing
Answer: try running these commands in given sequence: ---
brew update
brew tap homebrew/dupes
brew install apple-gcc42
rvm get stable
rvm install ruby-2.0.0

installing ruby 2.0.0 through RVM


Solving non linear ODE

Question: I've been trying to solve the following ODE
$$
4 x\left(y(x) \times \frac{\partial^{2} y(x)}{\partial x^{2}}+\left(\frac{\partial y(x)}{\partial x}\right)^{2}\right)+2 y(x) \times \frac{\partial y(x)}{\partial x}+y(x)^{2} x k \times \frac{\partial y(x)}{\partial x}=0,
$$
with $x = \psi^2/t, \ u(\psi,t)=y(x), \ u(\psi,0)=N_0 \delta(\psi)$,
but unfortunately I'm at a loss.
Any ideas?
Answer: 1. y = y(x) or y = y(x, t)?
The differential equation establishes that y is a function only of x, ie: y = y(x).
However, your boundary condition establishes that y is a function of something else, maybe time? y = y(x, t)?
2. What kind of answer?
Are you looking for analytical or numerical solutions?
3. Possible solution path
This kind of problem is usually solved by integral transform techniques or by finite elements. However, you would have to explain better the problem and what you are trying to achieve in order to decide which one would be the best.
Comment: Sorry. Thanks for the first point. I had made a mistake when formulating the question. Idealy I'm looking for an analytical solution, although even a numerical solution would be a good start
Comment: @FrancescoAzzollini > "x=ψ²/t, u(ψ,t)=y(x)" Ok, it looks like you are using some kind of self similarity. This is a well known technique.
Comment: @FrancescoAzzollini > "Idealy I'm looking for an analytical solution" Probably there are some analytical insights you can obtain. I have already seen nastier stuff with some interesting analytical approaches. However, my recommendation for you is the following:
Comment: @FrancescoAzzollini Instead of beginning with this tough problem, start with simple cases (ex: uni-dimensional heat transfer) and gradually increases the difficulty. There is a **plethora** of analytical approaches for such kind of equations in all sorts of engineering branches. After you've got familiar with that, then move forward to the tough problem you've posted.
Comment: @FrancescoAzzollini > "although even a numerical solution would be a good start" The same is true for numerical approaches. Start with easier stuff that has already been studied at deep.

Solving non linear ODE


How to validate expression on button click in asp.net C#

Question: I am making a website and I have made a form fields like email field and validation expressions associated with it. Validation is initiated on text change. But i want it t execute on "submit" button click event.
I have searched but could not locate the solution to my problem. Please tel me why is this happening and how can i make it right. I am new to this web development field, So need help from you guys.
Thanks in advance!!!
Hamad
Answer: You could disable showing errors in the validator itself and instead make a validation summary which will be shown only after you click submit.
Like this:
<asp:RequiredFieldValidator runat="server" ControlToValidate="txtEmail" ValidationGroup="vRegister" Display="None" ErrorMessage="Email field cannot be empty"></asp:RequiredFieldValidator>

and then declare a validation summary:
<asp:ValidationSummary runat="server" ID="vSummary" ValidationGroup="vRegister" DisplayMode="BulletList" />

Answer: What you should do is change the value of EnableClientScript to false. Then call the validation from your code behind (which should always be done since a user can disable their client side validation anyway. Security rule 1, never trust the client)
EnableClientScript: Gets or sets a value indicating whether client-side validation is enabled.
 <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
 <asp:RequiredFieldValidator ID="rfvName" runat="server" EnableClientScript="false"
 ErrorMessage="*" ControlToValidate="txtName" ></asp:RequiredFieldValidator>

Code Behind:
   protected void btnSave_Click(object sender, EventArgs e)
   {
          if (Page.IsValid)
             {
               //Do stuff
             }
             //No need for else, the validations should display accordingly
   }

Additional resources: http://weblogs.asp.net/rajbk/archive/2007/03/15/page-isvalid-and-validate.aspx
Comment: This is the real answer. Worked for me. Thanks
Answer: Are you simply looking for the validation type controls to validate input?
If so look at the property EnableValidation and set it to true.  Doing so will force the validation of the textbox even before the button_Click event can execute.
Answer: Try this:
 <asp:TextBox ID="txtName" runat="server" Height="23px"
 Width="252px"></asp:TextBox>
 <asp:RequiredFieldValidator ID="rfvName" runat="server"
 ErrorMessage="*" ControlToValidate="txtName"
 ValidationGroup="vadd"></asp:RequiredFieldValidator>

Comment: i don't think that's what he is asking,the validators do the validation when the text is changed, he is asking how to not do that, and to validate it on submit instead.
Answer: The "Causes Validation" property on the button itself will automatically force your page to meet you validation specifications before firing the rest of the code associated with the button press.
Answer: If i have understood your question, you need to create a same validation group for each of the validation control in your aspx page. You also need to have a validation summary with same validation group. And atlast in the submit button in aspx page you have to mention same validation group...


What is a simple way to make "null" not to render?

Question: I have created a simple polymer element with no js that has attributes in it. When the attribute is not called it shows "null".
http://jsbin.com/wakal/1/
How do I tell the element not to show null?.  If the attribute is left blank I do not want anything to show up?
Comment: `if (/*object*/ != null) { /* do stuff */ }`
Comment: the way to declare [*default values*](http://www.polymer-project.org/docs/polymer/polymer.html#default-property-values) is with the script
Answer: Normally to use default values you need to use the script and initialize the properties there.
See http://www.polymer-project.org/docs/polymer/polymer.html#default-property-values

Alternatives are to use

{{propname?propname:'default value'}} or
{{propname||'default'}}


connecting to an EC2 instance via ssh on a created user

Question: I can connect to my EC2 instance as root but if I create a user I get a Permission denied(public key) error. Here is the output from ssh -v
OpenSSH_5.3p1 Debian-3ubuntu3, OpenSSL 0.9.8k 25 Mar 2009
debug1: Reading configuration data /etc/ssh/ssh_config

debug1: Applying options for *

debug1: Connecting to 184.108.40.206 [126.96.36.199] port 22.

debug1: Connection established.

debug1: identity file /home/amaro/.ssh/identity type -1

debug1: identity file /home/amaro/.ssh/id_rsa type 1

debug1: Checking blacklist file /usr/share/ssh/blacklist.RSA-2048

debug1: Checking blacklist file /etc/ssh/blacklist.RSA-2048

debug1: identity file /home/amaro/.ssh/id_dsa type -1

debug1: Remote protocol version 2.0, remote software version OpenSSH_5.1p1 Debian-6ubuntu2

debug1: match: OpenSSH_5.1p1 Debian-6ubuntu2 pat OpenSSH*

debug1: Enabling compatibility mode for protocol 2.0

debug1: Local version string SSH-2.0-OpenSSH_5.3p1 Debian-3ubuntu3

debug1: SSH2_MSG_KEXINIT sent

debug1: SSH2_MSG_KEXINIT received

debug1: kex: server->client aes128-ctr hmac-md5 none

debug1: kex: client->server aes128-ctr hmac-md5 none

debug1: SSH2_MSG_KEX_DH_GEX_REQUEST(1024<1024<8192) sent

debug1: expecting SSH2_MSG_KEX_DH_GEX_GROUP

debug1: SSH2_MSG_KEX_DH_GEX_INIT sent

debug1: expecting SSH2_MSG_KEX_DH_GEX_REPLY

debug1: Host '184.108.40.206' is known and matches the RSA host key.

debug1: Found key in /home/amaro/.ssh/known_hosts:1

debug1: ssh_rsa_verify: signature correct

debug1: SSH2_MSG_NEWKEYS sent

debug1: expecting SSH2_MSG_NEWKEYS

debug1: SSH2_MSG_NEWKEYS received

debug1: SSH2_MSG_SERVICE_REQUEST sent

debug1: SSH2_MSG_SERVICE_ACCEPT received

debug1: Authentications that can continue: publickey

debug1: Next authentication method: publickey

debug1: Offering public key: /home/amaro/.ssh/id_rsa

debug1: Authentications that can continue: publickey

debug1: Offering public key: atkey.pem

debug1: Authentications that can continue: publickey

debug1: Trying private key: /home/amaro/.ssh/identity

debug1: Trying private key: /home/amaro/.ssh/id_dsa

debug1: No more authentication methods to try.

Permission denied (publickey).

Comment: Did you add the ssh key to the user, too? Depending on the image only key authentication is enabled.
Comment: hey which key are you referring to? Ive added the /.ssh/authorized_keys as well as the private and public key parts
Answer: found the solution had to set permissions to 700 on the .ssh keys thanks for the help


Convert 'intercept/drift' term to 'constant' term in arima/auto.arima functions, in case of higher orders - R

Question: suppose for a time series, the auto.arima output is:
ARIMA(1,0,1) with non-zero mean

Coefficients:
         ar1     ma1  intercept
      0.7456  0.2775   767.7463
s.e.  0.0804  0.1197     0.1072

It is specified in help file of arima function that definition used for this function is
X[t] = a[1]X[t-1] + … + a[p]X[t-p] + e[t] + b[1]e[t-1] + … + b[q]e[t-q]

and if we include mean(m),  this formula applies to X - m rather than X.
My questions are:
(1)  For the model considered above, what will be the arima equation?
  (a) X[t] =  767.7463 + 0.7456*X[t-1] + 0.2775*e[t-1]

or    (b) X[t] =  195.3258 + 0.7456*X[t-1] + 0.2775*e[t-1],
where constant term is achieved by 195.3258 = 767.7463*(1-0.7456).
(2) How to interpret this constant term if we have more than one AR coefficient?
e.g. ARIMA(2,0,2) with non-zero mean

Coefficients:
          ar1      ar2     ma1     ma2  intercept
      -0.0124  -0.6945  0.3629  0.9414    -0.1288
s.e.   0.1172   0.1132  0.0598  0.1270     0.0636

(3) What should be the ARIMA equation in presence of drift term?
e.g. ARIMA(1,1,0) with drift

Coefficients:
         ar1   drift
      0.3307  0.3981
s.e.  0.0946  0.1463

Answer: The model with no differencing:
$$\phi(B)(X_t -c) = \theta(B)e_t$$
where $\phi(B)=1-\phi_1B - \cdots - \phi_pB^p$,
$\theta(B)=1+\theta_1B + \cdots + \phi_pB^p$,
and $c$ is the "intercept".
The model with differencing:
$$\phi(B)(1-B)(X_t -ct) = \theta(B)e_t$$
where $c$ is the "drift" parameter.
Example 1:
$$(1-0.7456B)(X_t - 767.7463) = (1+0.2775B)e_t$$
So
\begin{align*}
X_t &= (1-0.7456)*(767.7463)  + 0.7456*X_{t-1}  + e_t + 0.2775 e_{t-1} \\
    &= 195.3147  + 0.7456*X_{t-1}  + e_t + 0.2775 e_{t-1}
\end{align*}
Example 2:
$$(1+0.0124B + 0.6945B^2)(X_t +0.1288) = (1+0.3629B + 0.9414B^2)e_t$$
So
\begin{align*}
X_t &= -(1+0.0124 + 0.6945)*(0.1288)  - 0.0124 X_{t-1} -0.6945 X_{t-2} + 0.3629 e_{t-1} + 0.9414 e_{t-2} + e_t\\
   &= -0.2198 - 0.0124 X_{t-1} -0.6945 X_{t-2} + 0.3629 e_{t-1} + 0.9414 e_{t-2} + e_t
\end{align*}
Example 3:
$$(1-0.3307B)(1-B)(X_t - 0.3981t) = e_t$$
So
\begin{align*}
X_t & = (1-0.3307)*0.3981 +  1.3307X_{t-1} - 0.3307 X_{t-2} + e_t \\
 & = 0.2664 +  0.3307X_{t-1} - 0.3307 X_{t-2} + e_t
\end{align*}
Comment: In the model with differencing, is the drift parameter ct multiplicative? That is, were I forecasting t + h periods in the future, would I get the appropriate drift value with c*(t + h)?
Answer: Regarding your question 1, what ARIMA calls the intercept is in reality the estimated mean of the time series. So the obtained constant term
195.3258 = 767.7463*(1-0.7456)
is the estimated intercept.
See issue 3 in http://www.stat.pitt.edu/stoffer/tsa4/Rissues.htm for an example:


É necessário especificar o MIME type na propriedade src ao renderizar uma imagem em base64?

Question: Estou fazendo alguns testes de renderização de imagem em base64 e me surgiu algumas dúvidas.
Percebi que mesmo passando a extensão da imagem errada no mime type, ainda é possível renderizar a imagem, no exemplo abaixo, uma imagem que tinha extensão .PNG, ao especificar
 a extensão como data:image/jpeg, ela ainda assim é renderizada. No segundo exemplo foi retirado a especificação da extensão e a imagem também é renderizada:

document.getElementById('imageBase64Png').src = 'data:image/jpeg;base64,iVBORw0KGgoAAAANSUhEUgAAAA8AAAAPCAIAAAC0tAIdAAABj2lDQ1BJQ0MgcHJvZmlsZQAAKJF9kbtLw1AUxr+mlRapiOggUiFCdRALoiAOLlaxCBVCrWDVwTz6EJI0JCkujoJrwUF08TXoHyC6OrgKgqAIIg7+Bb4WKfHcJNAirRcu55cv53zc+12AO1dlzQqNAppum5lUkl/OrfDhN4TQjy7wGBBly5gWhDRaru8HBFi9TzCv1n1NV4eSt2QgwBPPyYZpE5eIJzZtg/ERcY9cEhXiC+IRkw5I/Mp0yeNPxkWXuQhjM5uZIY4R88UGlhpYLpka8RRxXNF08ufWPVYYbzPW1Irsn5PdMJrXlxapDtOOIQUVG9BgwEKekpJQoW8VNhJUdVIsZKgrSdk29+lzfQSak1wvmWZmUSZP0XUAe4u/GVuF8THPKUrObS+O8zEIhHeBWtVxfo4dp3YCBJ+Ba70+X6YcJ79Ir9a1+CHQSfe8vKlr0h5wtQP0PhmiKbpSkDZXKADvZ/RcOaD7Dmhf9fLz/+P0EchuAelbYP8AGCqS91qLe0f8/OaxAOHfHj/BXyORdMhJPO7+AAAACXBIWXMAAC4jAAAuIwF4pT92AAAAB3RJTUUH5AQdESElzI3SVQAAABx0RVh0Q29tbWVudABDcmVhdGVkIHdpdGggR2xpbXBzZe5OGAcAAAAZSURBVCjPY9zg4MBANGBiIAWMqh5VTX3VAFy9AU4AdAftAAAAAElFTkSuQmCC';

document.getElementById('imageBase64WithoutType').src = ' data:image;base64, iVBORw0KGgoAAAANSUhEUgAAAA8AAAAPCAIAAAC0tAIdAAABj2lDQ1BJQ0MgcHJvZmlsZQAAKJF9kbtLw1AUxr+mlRapiOggUiFCdRALoiAOLlaxCBVCrWDVwTz6EJI0JCkujoJrwUF08TXoHyC6OrgKgqAIIg7+Bb4WKfHcJNAirRcu55cv53zc+12AO1dlzQqNAppum5lUkl/OrfDhN4TQjy7wGBBly5gWhDRaru8HBFi9TzCv1n1NV4eSt2QgwBPPyYZpE5eIJzZtg/ERcY9cEhXiC+IRkw5I/Mp0yeNPxkWXuQhjM5uZIY4R88UGlhpYLpka8RRxXNF08ufWPVYYbzPW1Irsn5PdMJrXlxapDtOOIQUVG9BgwEKekpJQoW8VNhJUdVIsZKgrSdk29+lzfQSak1wvmWZmUSZP0XUAe4u/GVuF8THPKUrObS+O8zEIhHeBWtVxfo4dp3YCBJ+Ba70+X6YcJ79Ir9a1+CHQSfe8vKlr0h5wtQP0PhmiKbpSkDZXKADvZ/RcOaD7Dmhf9fLz/+P0EchuAelbYP8AGCqS91qLe0f8/OaxAOHfHj/BXyORdMhJPO7+AAAACXBIWXMAAC4jAAAuIwF4pT92AAAAB3RJTUUH5AQdESElzI3SVQAAABx0RVh0Q29tbWVudABDcmVhdGVkIHdpdGggR2xpbXBzZe5OGAcAAAAZSURBVCjPY9zg4MBANGBiIAWMqh5VTX3VAFy9AU4AdAftAAAAAElFTkSuQmCC'
Imagem em base 64 com formato png utilizando mimetype image/jpeg:

Imagem em base64 com formato png sem especificar tipo:

Há alguma vantagem ou desvantagem de especificar ou não a extensão da imagem no MIME type visto que mesmo passando uma extensão que não é a correta, o navegador consegue interpretar e renderizar?
Comment: https://developer.mozilla.org/pt-BR/docs/Web/HTTP/Basico_sobre_HTTP/MIME_types e atenção na parte que fala sobre **MIME sniffing**
Comment: @hugocsl muito obrigado, este link tirou muito das minhas dúvidas :)
Answer: O mimetype é divido em tipo/subtipo
Nos 2 casos vc especificou um mimetype do tipo imagem, com a diferença em que no primeiro exemplo vc especificou o subtipo "jpeg"
Vc pode ver mais a fundo aqui https://developer.mozilla.org/pt-BR/docs/Web/HTTP/Basics_of_HTTP/MIME_types


Why do I get Access Denied error when changing my password?

Question: My company just purchased a new dedicated server from a hosting company, and the guy who handled the acquisition gave me an account and a temporary password. When I remote desktop to the server, it asks me to change my password... when I change it, and hit enter, it just says "Access Denied" and doesn't change the password.
What is causing this? How can we fix it?
Answer: As you have no access to the server without changing the password, you'll need to have the hosting company log into the server and correct any issues with it.
Answer: You will need to check (or get someone to check) the account is not set to not allow password changes.
For local accounts under computer management, it is one of the user account settings.


A question on Lyapunov exponents associated with a fixed point of a vector field.

Question: The Lyapunov exponent $\chi(x_{0}, e)$ in a direction $e \in \mathbb{R}^{n}$ along the trajectory $x(t,x_{0})$ of a vector field $\dot{x} = f(x)$ through a point $x_{0}$ is defined to be
$$\chi(x_{0},e) = \lim_{t \to \infty}\frac{1}{t} \log \frac{||X(t;x(t,x_{0}))e||}{||e||}$$ where $X(t;x(t,x_{0}))$ is the fundamental solution matrix of the linearisation of the vector field orbit about $x(t,x_{0})$. Here $x \in \mathbb{R}^{n}$.
Let us consider the case of the the orbit being a fixed point. It is known that then $\chi$ is just the real parts of the eigenvalues associated with the matrix of the vector field linearised about the fixed point. How does one prove this? Why do the imaginary parts of e-values do not contribute to $\chi$?
Comment: A short answer to your last question:  The only contribution of the imaginary part $\beta$ of an eigenvalue is the factor $e^{i \beta t}$, whose norm is constantly equal to $1$.
Answer: When $x_0$ is a critical point we have $X(t;x(t,x_{0}))=e^{At}$ with $A=d_{x_0}f$.

So what matters are the vectors in each generalized eigenspace.

For example, if $Av=\lambda v$ with $v\ne0$, then $e^{At}v=e^{\lambda t}v$ and so $\chi(x_{0},v)={\rm Re\,}\lambda$. This gives what you want (by taking sums of generalized eigenvectors).


how to change base url in drupal 8

Question: I had installed a drupal website inside a folder in web root on an amazon ec2 instance. I used to access it by calling http://xx.xx.xxx.xx/folder .Now that the site is finished i created virtual hosts in my http.conf file to point the domain name to folder. I edited trusted host patterns in settings.php. So far so good! http://mydomainname.com points to front page.
PROBLEM:
when i click on links it shows 404 because path is http://mydomainname.com/folder/link instaed of http://mydomainname.com/link The front page parameter in site settings in admin side is uneditable.
How can I change that..? Please Help.
Comment: Did you clear caches?
Comment: I tried clearing caches multiple times
Comment: I'm voting to close this question as off-topic because it is about setting up virtual hosts on the server, which is not influenced from the used CMS.
Comment: Does it work for you when you open the required URL directly, without clicking links?
Answer: sudo nano /etc/apache2/sites-enabled/000-default.conf

Make sure it looks like this:
<VirtualHost *:80>
        # The ServerName directive sets the request scheme, hostname and port that
        # the server uses to identify itself. This is used when creating
        # redirection URLs. In the context of virtual hosts, the ServerName
        # specifies what hostname must appear in the request's Host: header to
        # match this virtual host. For the default virtual host (this file) this
        # value is not decisive as it is used as a last resort host regardless.
        # However, you must set it for any further virtual host explicitly.
        #ServerName www.example.com

ServerAdmin webmaster@localhost
        ServerName mydomainname.com
        ServerAlias www.mydomainname.com
        DocumentRoot /var/www/html/drupal

<Directory /var/www/html/drupal/>
        Options +FollowSymLinks
        AllowOverride All
        order allow,deny
        allow from all
</Directory>

        # Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
        # error, crit, alert, emerg.
        # It is also possible to configure the loglevel for particular
        # modules, e.g.
        #LogLevel info ssl:warn

        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined

        # For most configuration files from conf-available/, which are
        # enabled or disabled at a global level, it is possible to
        # include a line for only one particular virtual host. For example the
        # following line enables the CGI configuration for this host only
        # after it has been globally disabled with "a2disconf".
        #Include conf-available/serve-cgi-bin.conf
</VirtualHost>

# vim: syntax=apache ts=4 sw=4 sts=4 sr noet

Comment: Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/74374/discussion-on-answer-by-no-sssweat-how-to-change-base-url-in-drupal-8).

how to change base url in drupal 8


How do I make pyCharm stop hiding (unfold) my Python imports?

Question: Every time I open a Python file PyCharm will hide all imports and shows:
import ...

within the editor.
I have to manually unfold it to see the imports. Where do I find the setting to undo auto-hiding of import statements?
Comment: http://www.jetbrains.com/idea/webhelp/configuring-autofolding-behavior.html
Comment: Thanks! And I kept searching for "hide imports", "unfold imports", did not know there was a general setting for "code folding" :-)
Comment: Thanks for asking this. I really don't like the defaults on this IDE. Fighting "features" like whack-a-mole is really not my cup of tea.
Answer: As this question may be useful for people who also are not looking for the term "code folding", I'll make my comment an answer.
As extracted from IntelliJ IDE Web Help, but also worked on PyCharm CE 3.4.1:

Open the IDE Settings (File > Settings, or Ctrl+Alt+S).
Under the "Editor" node, click "General" and then "Code Folding". The "Code Folding" page is displayed.
In the "Collapse by default list", select the check boxes to the left of the code constructs you want to be displayed collapsed. So here you can uncheck "Imports".
Apply changes.

The image below shows what it looks like:
Comment: This is now Editor > General > Code Folding, rather than just Editor > Code Folding
Comment: Thanks, that feature was super annoying
Comment: ... And "Collapse by default list" is now renamed to "Fold by default".
Answer:
Actually in pycharm 2016.1 it's Editor -> General -> Code Folding


html5boiler plate + jquery mobile = scripts loading twice

Question: I am working on an experimental jquery mobile based app using html5 boilerplate as a base for html and such.
Basically all I have done thus far is:

Download and extract html5 boilerplate, and view it in the browser. Make sure scripts/styles are loading properly. Good ready to go.
Add jquery mobile (cdn hosted full version 1.0 [released today? right on!])
Add $(document).ready(function () { console.log('ready'); });
Reload. 'ready' is output twice.. the second one after a slight delay..
wtf bbq and such inspect situation in chrome inspector.. notice all javascript files seem to be loading twice.
Restart from scratch, extract h5bp load in browser, note in particular that scripts load once. Add document ready handler, observe one output of 'ready'.
Add jquery mobile observe scripts loading once.
Move all scripts into the  tag. Scripts load once.

Anyone have any idea what is going on? It should be pretty easy to reproduce this, just extract h5bp and add jquery mobile to the scripts section at the bottom and suddenly the scripts all are loading twice. Move all those scripts into the head tag beneath (or before) modernizr and this no longer occurs.
Thanks
Comment: Dunno but I would just start deleting code. It could be some fakebody trick that JQM, JQ and Modernizr disagree on. Just reduce your test case more and more until you find the conflict
Comment: Interesting, I'll look into fake body.
Answer: Modernizr uses YepNope to load scripts. If you take a look at the issue here: https://github.com/SlexAxton/yepnope.js/issues/10
you'll see that scripts are intentionally loaded twice:

Yepnope does request every file you put into it twice. The first time
  it loads itself into your cache as some sort of non-executable entity
  (an object element, or an img element, or a script element with a fake
  type attribute, depending on your browser). The second time it's
  injected, we inject it as an executable script, and this time it's
  cached. So there is really only the millisecond or less that it takes
  to execute the callback function and reinject a script tag extra (and
  however long it takes to access the cache).

There's also mention of this on the http://yepnopejs.com home page. Just go there and scroll down to I'm seeing two requests in my dev tools, why is it loading everything twice?
Comment: Fair enough. But if you'll read the paragraph on the yepnope page that I referred you to, it says that if you are seeing double load times, then you need to make sure you're sending the correct cache headers. If yepnope can't cache the first load, then you would get double executes.
Comment: I think you need to read my post carefully. I am aware of the behavior of yepnope, the issue is that with jquerymobile added, event handlers and such are actually executing twice. The scripts are also loaded twice according to the Network pane of the inspector WITH jqM, but not without it.
Comment: Just re reading old comments - Did not intend to come off in the manner in which it sounds that I did. Belated thanks for the info.
Answer: Putting your  in  will fix this problem.
Answer: Are you using $(document).ready()??
Ran into this same issue and was frustrated to no end, noticed that if I moved all the JS to the head of the document it worked fine. When I switched everything to use pageinit started working properly with JS at bottom of page where it belongs.
example:

further details available at: http://jquerymobile.com/demos/1.0/docs/api/events.html
Comment: this did not helped me :(
Comment: might have changed -- this answer is over 2 years old =)
Comment: Oh too bad I tried almost all the possibilities still not able to figure it out
Answer: I tried adding jQuery and jQuery Mobile on a basic html page, it seems to happen like this as well. So don't think it's h5bp related. Could you try strip out the h5bp stuff and load again?
Comment: Interesting, I'll try adding only jquery and jqM to a simple html5 page.
Answer: Make sure your root div is like this...


Predict set of location points at a single time slot

Question: The sample dataset contains Location point of the user.
df.head()

   user           tslot         Location_point
0   0   2015-12-04 13:00:00     4356
1   0   2015-12-04 13:15:00     4356
2   0   2015-12-04 13:30:00     3659
3   0   2015-12-04 13:45:00     4356
4   0   2015-12-04 14:00:00     8563

df.shape

(576,3)

The location points are random and need to predict the next location point of the user for a given time. As the location points are random numbers I need to predict the set of location points at each time slot.
Example:

If I need to predict the location point at tslot 2015-12-04 14:00:00.
my predicted output should be [8563,4356,3659,5861,3486].

My code
time_steps=1
data_dim = X_train.shape[2]
model = Sequential()
model.add(LSTM(data_dim, input_shape=(time_steps,data_dim), activation='relu'))
model.add(Dense(data_dim))
model.compile(loss='categorical_crossentropy', optimizer='adam')
model.fit(X_train, y_train, epochs=20, batch_size=96)
model.summary()

which helps to to predict 1 location points for each time slot. I would like to know if this is possible and how?
Comment: I am confused. At each time t, are you trying to predict he location at t, t-1, t-2, ... or are you trying to make multiple predictions and like use the mean to be more accurate? Or sth else?
Comment: Hi, I am trying to make multiple predictions for each time slots.
Comment: Then, are you trying to obtain some notion of uncertainty around your predictions?
Answer: I assume that that this is for gaining some confidence about the predictions.
If this is the case, there are multiple ways to do this. For example, refer to this paper by Amazon on how to predict quantiles, and this paper on how to use a Bayesian framework to obtain uncertainty around the predictions.
If you have other intentions, please clarify.
Comment: Hello, Sorry for the late reply. I am new to neural networks. Can you help me with some sample code?


Centralizar conteúdo da div no AlertController

Question: Tenho o seguinte código abaixo
 let alert = this.alertCtrl.create({
  message: '

' +
  '
Cadastrado com sucesso!!!
' +
  '
',
   buttons: [{
    text: 'OK',
    handler: data => {
      console.log('Ok clicked');
    }
  }]
});
alert.present();

Onde estou usando importando o AlertController desta forma:
import { AlertController } from 'ionic-angular';

Veja a imagem como fica:

Gostaria de centralizar o conteúdo do AlertController, porém tentei de algumas formas mas não funciona, como por exemplo desta forma, mas não reconhece.
Existe alguma forma de centralizar conteúdo da div no AlertController?
Comment: Como exatamente gostaria que ficasse? Você tem 2 elementos divs 1 elemento img e um elemento p, não entendi qual exatamente quer alinhar no centro, é centro vertical horizontal ou ambos?
Comment: @MagicHat alinhar tudo. Aliás, menos o botão OK. Ou talvez também. huehe
Comment: Sei lá tenta : ' +
  'Cadastrado com sucesso!!!'...
Comment: @MagicHat já tinha tentando assim, mas não funciona.
Answer: Você precisa definir uma classe css pro seu AlertController:
Exemplo:
 let alert = this.alertCtrl.create({
      message: '

' +
      '
Cadastrado com sucesso!!!
' +
      '
',
      buttons: ['Dismiss'],
      cssClass: 'custom-alert',
    });
    alert.present();
 }

Repare que na criação do alerta eu tenho um atributo cssClass no qual passo uma classe css. O css ficaria dessa forma:
page-home {}

.custom-alert .alert-message{
    text-align: center;
    overflow: hidden;
}

OBS:. Note que o css não estão dentro da estilização da página, ou seja, ele tem que ser separado pois o componente alerta não é renderizado dentro da sua página:

Nesse exemplo usei um text-align: center para alinhar os componentes, mas nada lhe impede de customizar o css do jeito que você preferir.
Resultado:
Comment: hahaha... eu tava colocando a classe dentro da `page-home`! Por isso não estava funcionando. Você pode complementar sua resposta falando porque deve ficar fora da `page-home` no css? Deu certo aqui. =D
Comment: @acklay opa, posso sim.
Answer: Certamente cheguei tarde... mas encontrei esta resposta na documentação oficial: https://ionicframework.com/docs/api/alert:
"Observação
Se você estiver criando um aplicativo Ionic Angular, os estilos precisam ser adicionados a um arquivo de folha de estilo global.". Veja que isso se refere ao component alert.


Levy's 0-1 law and Martinagle

Question: This is from Durrett's probability: Theory and Examples Exercise 4.6.6.

Let $X_n \in [0,1]$ be adpated to $\mathcal{F}_n$. Let $\alpha,\beta>0$ with $\alpha+\beta=1$ and suppose
$$\mathbb  P(X_{n+1}=\alpha +\beta X_n \mid \mathcal{F}_n)=X_n,\quad \mathbb
 P(X_{n+1}=\beta X_n \mid \mathcal{F}_n)=1-X_n$$
Show $\mathbb P(\lim_n X_n= 0 \;\text{or}\; 1) =1.$

I know there is question Martingale convergence proof here but can't we prove this using levy's 0-1 law?
What can we say about levy's 0-1 law regarding Martingale Sequence?
Answer: $X_n$ is a martingale, and so converges (boundedly) to a random variable $X_\infty$. You'll be able to write a recursion for the second moments $\Bbb E[X_n^2]$, leading, after a passage to the limit as $n\to\infty$, to the conclusion that $\Bbb E[X_\infty^2] = \Bbb E[X_\infty]$.

Levy's 0-1 law and Martinagle


Do multi-parameter unitary subgroups exist?

Question: I'm working with an $N$-dimensional quantum system that is defined by the following Hamiltonian
$$
H = H_{\text{drift}} + \sum_{j=1}^n a^j H_{\text{drive}}^j
$$
Where $n \ll N$ (in my case $n = 4$ and $N = 42$)
The unitary matrix in $SU(N)$ generated from $\text{span}\{H_{\text{drift}}, H^j_{\text{drive}}\}$ is presumably in an $(n + 1)$-parameter subgroup of $SU(N)$.  I know about one-parameter subgroups so I'm basically asking if multi-parameter subgroups are a thing? And also, if they are, if there are any known parameterizations of them?
Comment: You are asking about compact connected Lie groups of dimension $>1$. They definitely exist and a lot is known about them. Start by looking in Wikipedia.
Answer: Correct me if I'm wrong but your Hamiltonian looks a lot like the basic formulation of quantum control theory: there one extends the usual time-dependent Schrödinger equation $\dot\psi(t)=-\frac{i}\hbar H_{\sf drift}\psi(t)$ by control terms to arrive at a bilinear control system:
$$
\dot\psi(t)=-\frac{i}\hbar\Big(H_{\sf drift}+\sum_ju_j(t)H^j_{\sf drive}\Big)\psi(t)
$$
Here the $u_j(t)$ are control functions, i.e. locally integrable functions which an experimenter can choose freely.
If one works with general mixed states (and not just pure states) one analogously turns the Liouville-von Neumann equation $\dot\rho(t)=-\frac{i}\hbar[H_{\sf drift},\rho(t)]$ into a controlled version:
$$
\dot\rho(t)=-\frac{i}\hbar\Big[H_{\sf drift}+\sum_ju_j(t)H^j_{\sf drive},\rho(t)\Big]
$$
The most basic question one asks in this setting is the question of "reachability": given some initial state $\psi_0$ ($\rho_0$), which states $\psi_F$ ($\rho_F$) can one generate using the control Hamiltonians at hand? Shifting perspective one can also ask about gate reachability: the set of all solutions to
$$
\dot U(t)=-\frac{i}\hbar\Big(H_{\sf drift}+\sum_ju_j(t)H^j_{\sf drive}\Big)\quad \text{ with }\quad U(0)={\bf 1}\tag{1}
$$
is the set of all quantum gates (unitary operations) one can implement via the drift & controls at hand. While there are most relevant follow up questions like generating a reachable state or gate using controls which are optimal in some sense -- a central tool for which Pontryagin's maximum principle -- let us focus on reachability.
The reason for this is that Lie theory turns out to be of immense use here:
As long as one has access to at least all control functions $u_j(t)$ which are piecewise constant (NB: which is quite reasonable with modern digital equipment) then solutions to the above equation are products of operators of the simple form $e^{-\frac{i}\hbar t(H_{\sf drift}+\sum_ju_jH^j_{\sf drive})}$, that is, time-independent operators which are also featured in your question. In this case an essential tool for analyzing reachability is the system Lie algebra $\mathcal A:=\langle H_{\sf drift},H^j_{\sf drive}:j\rangle_{\sf Lie}$, i.e. $\mathcal A$ is the smallest Lie subalgebra of $\mathfrak u(n)$ (=the Lie algebra of the unitary group ${\bf U}(n)$) which contains $H_{\sf drift}$ as well as all $H^j_{\sf drive}$. Side note: this may sound a bit abstract at first but this object is quite simple to handle on a computer. Either way one has the following fundamental result:

Theorem. Let $G := \langle \exp(\mathcal A)\rangle$ denote the system group of control system (1), that is, $G$ is the smallest subgroup of ${\bf U}(n)$ that contains $\exp(\mathcal A)$). If $G$ is a closed subgroup of ${\bf U}(n)$, then then the set of all unitary matrices that can be generated via (1) (called "reachable set") coincides with the system group $G$.

A direct consequence of this is a very simple criterion for "controllability" (="one can generate all unitaries") via dimension counting:

Corollary. If all Hamiltonians are chosen traceless, then system (1) is controllable if and only if $\operatorname{dim}(\mathcal A)=\operatorname{dim}(\mathfrak{su}(n))=n^2-1$. Otherwise (1) is controllable iff $\operatorname{dim}(\mathcal A)=\operatorname{dim}(\mathfrak u(n))=n^2$.

I'll keep it at that for now, but I'll gladly add some more detail if this is what your question aimed at.
As for further literature:

G. Dirr and U. Helmke, "Lie Theory for Quantum Control", GAMM-Mitteilungen 31 (2008), pp. 59–93; the above theorem is Theorem 3.3 in said paper
D. D'Alessandro. Introduction to Quantum Control and Dynamics. Chapman & Hall/CRC, Boca Raton, 2008
or Chapter 3.3 in my PhD thesis "Reachability in Controlled Markovian Quantum Systems"
Comment: Frederik, thanks so much for the insight here, I ran a calculation on my hamiltonians and my system is indeed controllable -- interestingly certain subsets of the system hamiltonians do lead to a controllable system -- but the combination of the drive term with any of the other 4 is


this.navigate.url not working in promise

Question: I want to refresh a page (through this.navigate.url) when a promise is executed but I can't seem to make it work.
import {Router} from '@angular/router';

constructor(public router: Router) {
}

myPromise('/api/users').then((response) => {
    return response.json();
}).then(function (response) {
    this.router.navigate.url([url]);
});

I even tried window.location.reload and it doesn't work either.
Comment: What is `this` here? What does `this.navigate` do? Where does `url` come from? What does the console show?
Comment: I went through that particular question before creating mine. My URL isn't changing and nor do I want it to. I just need to perform a page reload after my promise is executed.
Comment: Do you want to navigate inside your app with the help of the Angular router och to an external site?
If external, try `window.location.replace("http://something.com");`
Comment: @torazaburo I edited my question to elaborate further. router is an instance of Router class, url is current page URL. What I want is to refresh my current page after a promise is executed.
Comment: @FredrikLundin I want to refresh my page once a promise is successfully executed.
Comment: @torazaburo is there a refer to correct this answer for typescript/angular? Like: https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-context-inside-a-callback
Comment: Possible duplicate of [Navigating to the same route not refreshing the component?](https://stackoverflow.com/questions/38127308/navigating-to-the-same-route-not-refreshing-the-component)
Answer: constructor(private zone:NgZone) {}

this.zone.run(() => this.router.navigate(['main']));

//import NgZone from angular core, use zone.run inside the promise

Comment: Welcome to StackOverflow. Some explanation would greatly improve the quality of the answer and help other users who may encounter similar problems in the future
Please take some time to read the help page https://stackoverflow.com/help/how-to-answer
Answer: Angular 6.0 Router link is always disabled in child component.
Router link is always disabled in child component, if our navigation code is inside promise. To solve this issue we can use NgZone inside promise.
Let me show you the file contents:

login.component.ts

import { NgZone } from '@angular/core'; //import ngZone from angular core

constructor(private zone:NgZone) {}

authorize(): Promise<any> {
return new Promise((resolve, reject) => {
  let promise = this.auth2.signIn();
  promise.then(() => {
    let self = this;
    let profile = this.auth2.currentUser.get().getBasicProfile();
    this.authenticationService.login(profile);
    this.zone.run(() => this.router.navigate(['/contacts']));
  });
});
}


Unicity of a projective transformation determined by 5 points in $CP^3$?

Question: Consider an ordered set of five points $\{p_1, p_2, \dots, p_5\}$ in linear general position in $\mathbb{CP}^3$ and another ordered set of five points $\{q_1, q_2, \dots, q_5\}$, also in linear general position in $\mathbb{CP}^3$. These two sets are of course projectively equivalent, but is there a unique projective transformation that will map $p_i$ to $q_i$?
I seem to have an argument for it by translating the problem to mapping ordered sets of 1-dimensional subspaces in $\mathbb{C}^4$. However, I wish to confirm the result, just in case I may be making some mistake.
Thank you.
Comment: I think the correct word is "uniqueness"?
Answer: Indeed there is a theorem which say:

Let $V,W$ be $(n+1)$-dimensional vector spaces further on let $P(V),P(W)$ be two $n$-dimensional projective spaces and assume that
  $$
A_1, \dots,A_{n+2} \in P(V) \quad \text{and} \quad B_1, \dots,B_{n+2} \in P(W)
$$
  are in general position. Then there exists a unique projective transformation $f \colon P(V) \to P(W)$ with $f(A_i) = B_i$ for $i = 1, \dots, n+2$.

So for $p_1, \dots, p_5 \in \mathbb{CP}^3$ and $q_1, \dots, q_5 \in \mathbb{CP}^3$ which are in general positions, resp. There exists a unique projective transformation $f \colon  \mathbb{CP}^3 \to  \mathbb{CP}^3$ such that $f(p_i) = q_i$ for $i= 1,\dots,5$.


python regex: replacing st, nd, th etc in a adress with a single sub

Question: I have many adresses like "East 19th Street" or "West 141st Street" and I would like to remove the "th" and the "st" in a single call to re.sub.
re.sub("(\d+)st|(\d+)nd|(\d+)rd|(\d+)th", "g<1>", "East 19th Street")

doesn't work because it is not always the first gorup which is caught
I could chain the subs but it is dirty.
Help appreciated
Answer: Let's try this:
re.sub(r"(\d+)(st|nd|rd|th)\b", r"\1", str)

or better
re.sub(r"(?<=\d)(st|nd|rd|th)\b", '', str)

\b prevents things like 21strange from being replaced.
To replace only grammatically correct constructs, you can also try:
re.sub(r"(?<=1\d)th\b|(?<=1)st\b|(?<=2)nd\b|(?<=3)rd\b|(?<=[04-9])th\b", r'', str)

This replaces 23rd and 44th but leaves invalid things like 23st intact. Don't know if this is worth the trouble though.
Comment: What about `12th` and `13th`?
Comment: *"Don't know if this is worth the trouble though"* -- Yes, it's edge cases like this that make it not worth the trouble. I'd just stick to the simplest solution that works for you.


How to add custom properties to Paperjs objects?

Question: I found some discussions about doing this using the inject method, like this one https://groups.google.com/forum/#!topic/paperjs/16ToDJquig8
But I cannot find this method in the official doc.  So what is the officially recommended way to add custom properties to Paperjs objects?
Answer: If you just want to add properties to an Item, you can use Item.data.
From paper.js documentation:

Item.data: A plain javascript object which can be used to store arbitrary data on the item.

Example:
var path = new Path();
path.data.remember = 'milk';


How to convert DateTime to Date

Question: How can I convert Date to DateTime and vice versa?
E.g.
Date dt = new Date();

Now I want to covert this to DateTime.
Also
DateTime dtim = new DateTime();

Now I want to convert it to Date.
Answer: Is this Joda Time's DateTime you're talking about? If so, it will be
dateTime.toDate()

Answer: As skaffman said above
dateTime.toDate()

should do the trick. But keep in mind that if the dateTime object had a different timezone than the user's current timezone, dateTime.toDate() will return the date object in user's timezone.
ie
DateTime newDate = new DateTime().toDateTime(DateTimeZone.forID("America/Los_Angeles"));
System.out.println(newDate);
System.out.println(newDate.toDate());

This will print
2017-07-05T14:19:23.294-07:00
Wed Jul 05 15:19:23 MDT 2017
as my system time is in MDT
Answer: I guess you convert it to UTC via Date.getTime(). And after that, use a constructor/setter on the other object.
Answer: Transform to date:
dateTime.toDate()

Transform to DateTime:
new DateTime(new Date())

Answer: If you want to convert a DateTime to Date without losing the timezone, convert DateTime to Joda LocalDateTime first.
DateTime dateTimeUtc = new DateTime(); //because my default timezone is UTC
DateTime dateTimeBerlin = dateTimeUtc.withZone(DateTimeZone.forID("Europe/Berlin"));
Date convertedDate = dateTimeBerlin.toLocalDateTime().toDate();

Answer: Easiest way, would be to use the built-in toDate() method, like:
Date dt = new Date();
DateTime datetime = New DateTime(dt);

Date result = dateTime.toDate();

Answer: You can easily use the toDate() function which gets the date time as a java.util.Date:
Date date = MydateTime.toDate();

How to convert DateTime to Date


Statistical prediction model with copula

Question: Copula models are used widely to present the dependency structures among variables. Assume that I have a disease dataset. Assume further that I need to diagnose patients. Suppose that 0 refers to positive and 1 negative sign of the disease. That is, 0 means the patients are healthy. Assume that I would like to build a statistical prediction model based on the dependency structure among variables. As I understand, the linear regression model is a commonly used predictive model. I just wonder, is this model capable of copula models. In other words, can I use the linear regression model based on dependency structures from copula models?
If not, could you please advice me with some statistical predictive model for copula-based models?
Answer: There are huge prediction copula models in the literature. Yes, you can use a copula prediction model for your case. Note, you should use copula, for discrete data, with caution. I tried to write a comment, however, I cannot.


Convert Apache VirtualHost to nginx Server Block for Dynamic Subdomains

Question: I have a web app running on Apache where the virtual hosts file is configured to route requests to subdomains to specific folders.  Rather than having to modify the host file every time a subdomain is created, this allows me to dynamically route URLs to the relevant folder (with a catchall if the folder doesn't exist) -
<VirtualHost *:8080>
    ServerName localhost.com
    ServerAlias *.localhost.com
    VirtualDocumentRoot "/var/www/clients/%1"
    ErrorLog "logs\errors.log"
    <directory "/var/www/clients/%1">
        Options Indexes FollowSymLinks
        AllowOverride all
        Order Deny,Allow
        Deny from all
        Allow from all
    </directory>
</VirtualHost>

I am trying to convert the above to nginx but cannot find the right logic to extract the subdomain from the URL and then set the root variable in the config file.
Can anyone help me to write the server {} block for nginx, together with a catch-all block if the root path doesn't exist?
Comment: `server {
  server_name ~^(.*)\.localhost\.com$ ;
  root var/www/clients/$1;
}`
Answer: Use a named regex capture in the server_name that you can refer to later.
server {
    listen 8080;
    server_name ~^(?<subdir>.*)\.localhost\.com$ ;

    set $rootdir "/var/www/clients";
    if ( -d "/var/www/clients/${subdir}" ) { set $rootdir "/var/www/clients/${subdir}"; }
    root $rootdir;
}

What your are doing is setting your default root directory to a variable $rootdir and then overwriting it if the subdirectory set by $subdir exists.
Comment: Many thanks for this.  Unfortunately it is not working as expected.  under the `/var/www/clients` directory I have a directory `client1` with an index.html.  I also have an index.html under the catch-all directory.  If I navigate to `http://client1.localhost.com` nginx is returning the catch-all page (i.e. going directly to `$rootdir` instead of `$rootdir/client1`.
Comment: I have switched the order of setting the default. It should work now.
Comment: I have changed the `server` block  to `server {
 listen 8080;
 server_name *.localhost.com;
 if ( -d "/var/ww/clients/$subdir" ) { set $rootdir "/var/www/clients/$subdir"; }
 if ( $rootdir == "" ) { set $rootdir '/var/www/clients'; }
 root $rootdir;
}
` but when I try to restart nginx with `sudo service nginx restart` it fails.
Comment: Thanks. I went ahead and tested and found the error. I also simplified by taking from your example of what you tried.


How to extend protocols / delegates in Objective-C?

Question: If i want to extend a class like AVAudioPlayer, whats the best way to also add another method to AVAudioPlayerDelegate?
Should I make a category for it, do I extend it?
If I extend it do I then also have to make sure to overwrite the actual delegate getter/setter?  How would I extend the protocol?
The following gives me errors
@protocol AudioTrackDelegate : AVAudioPlayerDelegate {
    - (void)foo;
}
@end

@interface AudioTrack : AVAudioPlayer {
}
@end

Answer: The syntax for creating a protocol that implements another protocol is as such:
@protocol NewProtocol <OldProtocol>
- (void)foo;
@end

If you want to call a method in NewProtocol on a pointer typed as OldProtocol you can either call respondsToSelector:
if ([object respondsToSelector:@selector(foo)])
    [(id)object foo];

Or define stub methods as a category on NSObject:
@interface NSObject (NewProtocol)
- (void)foo;
@end
@implementation NSObject (NewProtocol)
- (void)foo
{
}
@end

Comment: A protocols doesn't have methods, it has method definitions; that is, it describes the name, arguments and return types that a class must have to be deemed "conforming" to said protocol.  By your comment/question I'm betting you are forgetting to call [super setDelegate:value] in your -setDelegate:
Comment: If I create a protocol that implements another protocol... Is there anything else I need to do to make sure the 'OldProtocol' methods get fired ?    because for me i'm getting the new protocol firing but all the existing ones aren't any longer
Comment: using this approach you doesn't exposes the new protocol's methods, take a look on my reply for a cleanest way
Comment: @simonthumper: In what way is it horrible?
Comment: You're adding methods via a category that are nothing to do with NSObject to a system class which is used everywhere.

It's not going to break your code of course, but it is hacky, also every single object you access you will be able to call those methods on, which is going to make code completion fun times!
Comment: @simonthumper: It's a common pattern known as an informal protocol. See, for example Apple's CALayerDelegate and UIAccessibility categories on NSObject.
Answer: Remember a protocol adds no code to the compiled app -- it only enforces the fact that your class must implement the methods to be considered "conforming" to the protocol. A good use of this would be to generate a group of classes with all the same way of operating: <printable> or <serialized>, etc. So you could create a <plays> protocol for instance:
@protocol plays
    - (void) play;
    - (NSString *) type;
@end

And then a class that conforms to <plays> MUST implement the play and type methods. If it doesn't, the compiler issues a warning but compiles the class anyway. In your code you check if an object does conform to a protocol with the following code:
if ([obj conformsTo: @protocol(plays)]) {
    [obj play];
}

A category actually adds new methods dynamically to your class. These methods are globally accessible to the runtime as selectors and can be called by name as in @selector(foo) and [object foo:bar];
The purpose of a category is to add special new code to a class even if you don't have the source code for that class. There may be security problems and you could create memory leaks in classes, etc.
In your case maybe, in a separate file AVAudioPlayerDelegate_TrackOps.m
#import "AVAudioPlayerDelegate.h"
@implementation AVAudioPlayerDelegate (TrackOps)

- (NSObject *) foo {
    // do foo stuff;
    return bar;
}

@end

Putting it as a category of NSObject makes all classes respond to foo. Foo can be a stand alone method  Objc_perform_selector(@selector(foo)) as well.
Bottom Line: use a category to add a quick method to a class, protocols for enforcing
method implementations, and subclasses to specialize existing classes (things like adding member variables or major new functionality). Categories can also be used to override a method or two when a subclass is not needed and wanted, but usually if you want to add functionality to a class you make a subclass. For more examples, ideas, other general information on this topic, there's always the Apple introduction to Objective-C
Comment: Can you please elaborate on how to add a category to a protocol ?  I think somethings wrong with the syntax of what you wrote.  thanks


How to show fixed amount of rows in asp.net gridview

Question: So here I have few gridviews in a row in asp.net. The problem now is it is inconsistent where some gridview would have 5 data and some would have 10. It looks ugly and since I needed to print. It's crucial.
I wanted to show max 15 rows. It is databound from the database which the user would fill up the subjects taken form(up to 15 rows). And if any of the rows doesn't have any of the data. It would leave it blank instead(note that the database didn't fills up to 15 rows.. only what is entered by the user). I've done some research but only found a few that might be related but using javascipt/changing current SQL given. I'm not allowed to use any javascript in the site (supports later would be a problem). And since I'm an intern. The sql code is given to me. I just need to implement it. What can I do to show fixed amount of rows in gridview? Is there any attribute that I can use in gridview to fill up the empty space to 15 rows?
aspx file
<asp:GridView ID="GridViewResult" runat="server" AutoGenerateColumns="False" EmptyDataText="NO RECORD" Font-Size="Small"
                        GridLines="Both" CellPadding="1" Height="101px" Width="100%" ShowFooter="True">
                        <Columns>
                            <asp:TemplateField HeaderText="Subjects">
                                <ItemTemplate>
                                    <asp:Label ID="lbl" runat="server" Text='<%# Eval("Subjects") %>'></asp:Label>
                                </ItemTemplate>
                                <ItemStyle HorizontalAlign="Center"  Width="25px"  />
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="Grade">
                                <ItemTemplate>
                                    <asp:Label ID="lbl1" runat="server" Text='<%# Eval("Grade") %>'></asp:Label>
                                </ItemTemplate>
                                <ItemStyle HorizontalAlign="Center"  Width="25px"  />
                            </asp:TemplateField>
                        </Columns>
                        <HeaderStyle Font-Bold="True"  HorizontalAlign="Center" Height="40px"/>
                        <PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
                        <FooterStyle HorizontalAlign="Center" />
                    </asp:GridView>

And the back code
Protected void LoadgvResult1()
{
    SqlCommand cmdgvKep1 = new SqlCommand();
    cmdgvKep1.Connection = conn;
    cmdgvKep1.CommandType = CommandType.Text;
        cmdgvKep1.CommandText = " SELECT ROW_NUMBER() OVER(ORDER BY Grade ASC) AS Numb, Subjects, Grade ";
        cmdgvKep1.CommandText += " FROM Result_SMU ";
        cmdgvKep1.CommandText += " WHERE siri = '" + siri + "' ";
    conn.Open();

    SqlDataAdapter adaptergvKep1 = new SqlDataAdapter(cmdgvKep1);
    DataSet dsgvKep1 = new DataSet();

    adaptergvKep1.Fill(dsgvKep1, "Result_SMU");

    GridViewResult1.DataSource = dsgvKep1;
    GridViewResult1.DataBind();

    conn.Close();
}

Comment: Are you looking for pagination? You can set `AllowPaging="True"` if that is the case.
Comment: Nope I'm not looking for paging. I needed it to show all in one page since it is used for printing. Like 15 rows of boxes/data and fills up the empty rows with blank if there's no data in it.
Comment: Try filtering datasource, `dsgvKep1.Tables[0].Rows.Cast().Take(15);`
Comment: this can be simplified to `GridViewResult1.DataSource = dsgvKep1.Tables[0].dt.AsEnumerable().Take(15).CopyToDataTable();`
Comment: Tried the first one. But the code is for limiting it to take only 15 am I right? The gridview still shows only 5 rows. The rest of the remaining rows still didnt show
Comment: Is it showing only 5 rows? Are you sure `AllowPaging` is not set on the grid?
Comment: Yes still showing 5 rows since there's only 5 rows of data in the database. Tried AllowPaging set to true and false. Still unable to get it to work
Comment: I guess I read your comment wrong. You can always do this to add some empty rows to your `DataTable` with this `for(int i = 0; i < 15 - dsgvKep1.Tables[0].Rows.Count; i++)    dsgvKep1.Tables[0].Rows.Add();`. I suggest re-think your design.
Comment: Have you tried including the property PageSize to your GridView control? (e.g. )
Answer: There was a lot of problems with your code.

1)Your data access layer should not be on the same place when you are
  DataBind the Grid
2)You should not use global SqlConnection. Connection pool is your
  friend. Also if exception occurs your connection will never be closed.
3)Your query should use sql parameters to prevent from Sql Injection.
4) You should wrap SqlDataAdapter in using statement, so it will be disposed
  after Fill.

If I understood you correctly you want to fill the grid with dummy records for some reason in the C# when the number of the records are under 15, you can add dummy rows to the fetch dataset like this.
        int countRows = dsgvKep1 .Tables[0].Rows.Count;
        int dummyRecords = 0;

        if(countRows < 15)
        {
            dummyRecords = 15 - countRows;
        }

        for (int i = 0; i < dummyRecords; i++)
        {
            DataTable tbl = dsgvKep1.Tables[0];
            DataRow row = tbl.NewRow();

            //add dummy values if you want
            //row["ColumnName"] = value;
            tbl.Rows.Add(row);
        }

I advise you to fix the 4 pointers which I gave you. From what I see you are intern and this will be good for you in long term.
I wrote how to create a simple data access layer in this question: checking user name or user email already exists , here you can see data layer, disposing sqlDataAdapter, preventing of not close sql connection when exception occur and also preventing sql injection using SqlComand.Parameters.
Comment: First of all. Thanks for the advise. I might fix it when I have extra time. For the current problem. It is still showing 5 rows of data. What am I doing wrong here? I added the code you gave after the databind and before closing the connection
Comment: Check in debug if the data set have 15 records, when you put it in DataSource.


Continuity of a peculiar function

Question: I came across the question: Evaluate$f(x)=\lim_{m \to \infty}\lim_{n \to \infty}[\cos(n!\pi x)]^{2m}$.
I simplified this to: $$f(x)= \begin{cases} 1 & \text{if $x \in Q$} \\ 0 & \text{if $x\notin Q$} \end{cases}$$
Is this function continuous?
As far as I know, if the limit of the function at a point $x=a$ equals $f(a)$, then the function is continuous at $x=a$. In this case however, how does one decide whether the limit is 1, 0, or does not exist?
Comment: @GDumphart: If $x$ is rational, then for $n$ sufficiently large, $n!$ will contain all prime factors of the denominator of $x$, and hence $n! x \in \mathbb N_0$.
Comment: @GDumphart Well for rational $x$'s eventually the denominator is canceled out by the $n!$. So I think the OP is right there. The issue is irrational $x$'s where very probably the inner limit does not exist.
Comment: Your distinction should focus on whether $x$ is integer or not, not on it being rational/irrational. In the case of an integer $x$, this is just $1$, yes. In the case of almost all irrational $x$, the inner limit $n\rightarrow\infty$ does not exist I am pretty sure. Are you sure about the order of the limits? Things would be different if $m \rightarrow\infty$ was on the inside. Your last paragraph is very fishy too.
Comment: @cfh Oh, you guys are correct of course.
Comment: I think @DRF is right that the inner limit doesn't exist for irrational $x$; it basically looks like some pseudo-random generator. With the limits in $m$ and $n$ swapped, things would be different.
Comment: @cfh Actually I think for some irrationals you might still get a limit. Suppose you define an irrational number in such a way that it is 1.01001000100001 etc. with increasingly long stretches of 0's which are smartly positioned so that from some point onward the n! always gives us a number increasingly closer to an even integer. Not sure it can be done but certainly not sure it can't.
Comment: @cfh Actually you might be able to define such a number in terms of some smart sum of factorial reciprocals?
Comment: I posted a new question: http://math.stackexchange.com/questions/1244778/closeness-of-n-x-to-integers-for-irrational-x
Answer: In the comments to your question, we have discussed that your first $f$ cannot be your second $f$. However, if we just look at
$$
f(x)= \begin{cases} 1 & \text{if $x \in Q$} \\ 0 & \text{if $x\notin Q$} \end{cases},
$$
this is a well-defined function and we can think about whether it's continuous in some point $x$ or not.
First, assume that $x \in \mathbb Q$, so $f(x) = 1$. Then, for any $\epsilon>0$, you can find an irrational number $y$ with $|x-y| < \epsilon$ (for instance by choosing $y = x + \frac1n \sqrt2$ with a large enough natural number $n$). But then $|f(x) - f(y)| = 1$ even though $|x-y|$ can be arbitrarily small.
On the other hand, if $x \notin \mathbb Q$, we can use that the rational numbers are dense in the real numbers to find a $y \in \mathbb Q$ with $|x-y| < \epsilon$ for any small $\epsilon$ we like. Again, $|f(x) - f(y)| = 1$.
In both cases, if you refer to the $\epsilon$-$\delta$ definition of continuity, this shows that $f$ is not continuous in $x$. Thus, $f$ is a function which is continuous nowhere.
Comment: I'd like to add that this is known as the Dirichlet function (usually shown as an intuitive example for a non-Riemann-integrable function, but Lebesque integration gives $0$). http://en.wikipedia.org/wiki/Nowhere_continuous_function#Dirichlet_function
Comment: Oh look, my Wiki link even contains the problem of the question and, like I suggested, the limits are taken the other way around.

Continuity of a peculiar function


Converting large web applications from mysql_connect to PDO usage

Question: I got an assignment to create a new server environment. My boss decided to switch to a new version of PHP, what I encouraged. I just installed PhpMyAdmin on the new server and got a warning that the mqsql_connect function is deprecated. I understand this an old method and we should start using PDO but we have so many query's which should be changed too when we step over to PDO right? It will take a very long time too change all these query's and it will take even longer to test them all.. Is there a way to make this easier?
Thanks in advance.
Answer: The only way to make it easier at this point would be to create a PDOproxy class that remaps/mimick mysql_xxx calls. Then you can do a search replace over your project providing your "proxy" is "perfect".
Comment: I'm afraid this will only work with the connection methods. But because of the way PDO handles update/insert/delete etc. query's will prevent us from using this method..


Determinant of $[A,X]$

Question: Question: Let $A$ be any $2\times 2$ matrix in $\mathbb{C}^2$ and let
$$X=\begin{pmatrix}
\cos(\theta) & -e^{i\lambda}\sin(\theta)\\
e^{i\phi}\sin(\theta) & e^{i(\lambda+\phi)}\cos(\theta)
\end{pmatrix}$$
(the most general $2\times 2$ unitary matrix). Are there angles $(\theta,\lambda,\phi)$ (where each of these angles live in the interval $[0,2\pi)$) such that
$$\text{det}([A,X])=\left|A X-XA\right|=0$$
other than the trivial case $(0,\lambda,2\pi-\lambda)$.
Previous Work: First, the trivial case is ignored because otherwise $X=I$ would always force a zero determinant. I have also proved (by exhaustion) this conjecture for the cases when two or more elements of $A$ are zero and it always works. Additionally, I have done numerical tests and can always find non-trivial angles which give a zero determinant. Of important note: it is possible that for some matrices $A$ the resulting matrix $[A,X]=AX-XA\neq \mathbf{0}$ (for any angles other than the trivial angles). However, in all these cases (at least that I have found) there are still angles which give a zero determinant corresponding to a zero eigenvalue with multiplicity one (as opposed to $\mathbf{0}$ which has a zero eigenvalue of multiplicity two).
Motivation: This is a continuation of my question here and the motivation remains the same. Basically, I have simplified that question down (and slightly generalized it) to the question presented in this post.
I feel that there should be a simple way to prove this, but for the life of me I cannot show it in generality.
Answer: Choose a nonzero eigenvector $v$ of $A$; this is guaranteed to exist. Pick also a second vector $v'$ orthogonal to $v$. We have $Av=\lambda v$ with some complex $\lambda$, by definition. Define $X$ by $Xv=z v$, $X v'=z' v'$, where $z,z'$ are complex numbers of unit modulus. This $X$ is then unitary and $[A,X]v=0$, so $[A,X]$ has zero determinant. If we assume that $ A $ is hermitian or more generally normal, we can even choose an orthonormal basis of $A$ and construct unitary $X$ such that $[A,X]=0$.

Determinant of $[A,X]$


How to delete all translations when deleting a node using default language?

Question: I'm trying to delete all translations when deleting a node using default language?
For that purpose, I am using the hook_node_delete, but I am not able to invoke node_delete() from it. It cause a fatal error and the process can't terminate. Even the first node I am deleting isn't deleted preoperly.
 function hook_node_delete($node){
        $translation_list = translation_node_get_translations($node->tnid);
        $default_language = language_default()->language;

        if($translation_list!=""){
           foreach($translation_list as $translation_list_item){
              if ($translation_list_item->language!=$default_language){
                  node_delete($translation_list_item->nid);
              }
           };
        };
    }

So I am forced to simply unpublish the translations by doing something like that:
 function hook_node_delete($node){
                $translation_list = translation_node_get_translations($node->tnid);
                $default_language = language_default()->language;

                if($translation_list!=""){
                   foreach($translation_list as $translation_list_item){
                      if ($translation_list_item->language!=$default_language){
                          $node_translated = node_load($translation_list_item->nid);
                          $node_translated->status = 0;
                          node_save($node_translated);
                      }
                   };
                };
            }

Why can I not invoke node_delete() from hook_node_delete()??
Answer: you first have to remove the nodes from the translation set before you can delete them. So do something like this:
function hook_node_delete($node){
    $all = translation_node_get_translations($node->tnid);

    foreach($all as $del){
        if($node->nid != $del->nid){
            translation_remove_from_set(node_load($del->nid));
            node_delete($del->nid);
        }
    }
}

Answer: The answer provided by 118218 doesn't work for me because if you are deleting the source node (first node created of the translation set) the function translation_node_get_translations will return null, since the tnid of the other nodes of this translation set will be updated before the execution of hook_node_delete.
The solution for me was to overwrite the node/%node/delete menu item like this:
/**
 * Implements hook_menu_alter().
 */
function my_module_menu_alter(&$items)
{
    $items['node/%node/delete']['page arguments'] = array('my_module_custom_node_delete', 1);
    $items['node/%node/delete']['file path'] = drupal_get_path('module', 'my_module');
    $items['node/%node/delete']['file'] = 'my_module.module';
}

and then implement the delete confirmation form and submit function creating a callback before the node deletion like this:
function my_module_custom_node_delete($form, &$form_state, $node) {
    $form['#node'] = $node;
    // Always provide entity id in the same form key as in the entity edit form.
    $form['nid'] = array('#type' => 'value', '#value' => $node->nid);
    return confirm_form($form,
        t('Are you sure you want to delete %title?', array('%title' => $node->title)),
        'node/' . $node->nid,
        t('This action cannot be undone.'),
        t('Delete'),
        t('Cancel')
    );
}

function my_module_custom_node_delete_submit($form, &$form_state) {
    if ($form_state['values']['confirm']) {
        $node = node_load($form_state['values']['nid']);
        drupal_alter('before_node_delete', clone $node);
        node_delete($form_state['values']['nid']);
        watchdog('content', '@type: deleted %title.', array('@type' => $node->type, '%title' => $node->title));
        drupal_set_message(t('@type %title has been deleted.', array('@type' => node_type_get_name($node), '%title' => $node->title)));
    }
    $form_state['redirect'] = '<front>';
}

implement the deletion of the other nodes:
function my_module_delete_child_nodes($node) {
    if($node->language == SOURCE_NODE_LANGUAGE) {
        $all = translation_node_get_translations($node->tnid);
        if(isset($all[SOURCE_NODE_LANGUAGE]))
            unset($all[SOURCE_NODE_LANGUAGE]);
        if(count($all) > 0) {
            $nids = array();
            foreach($all as $t) {
                $nids[] = $t->nid;
            }
            node_delete_multiple($nids);
        }
    }
}

and finally, you can call the deletion function from any module you want just implementing the hook MODULE_NAME_before_node_delete_alter($node)
/**
 * Implements hook_before_node_delete_alter().
 */
function MODULE_NAME_before_node_delete_alter($node)
{
        my_module_delete_child_nodes($node);
}

Answer: As "filipedelmonte" answer says, if the source node of the translation set is deleted, then the function translation_node_get_translations will return null since the tnid of the other nodes of the translation set will be updated before the execution of hook_node_delete. However, his approach is too complicated. So I improved "Gert van den buijs" answer to work in all cases. The idea is to preload the translation set in all nodes:
/**
 * Implements hook_node_load().
 */
function hook_node_load($nodes, $types) {
  if (!is_array($nodes)) {
    return;
  }
  foreach ($nodes as $node) {
    $node->translation_set = translation_node_get_translations($node->tnid);
  }
}

/**
 * Implements hook_node_delete().
 */
function hook_node_delete($node) {
  if (is_array($node->translation_set)) {
    foreach ($node->translation_set as $del) {
      if ($node->nid != $del->nid) {
        translation_remove_from_set(node_load($del->nid));
        node_delete($del->nid);
      }
    }
  }
}

Answer: The "Gert van den buijs" answer doesn't work for me. So I managed to do it by deleting the content directly with db_delete. I'm not sure it's the best way to do it but at least it works.
Like that, hook_node_delete isn't called recursively and the function can terminate properly.
function hook_node_delete($node){
   $all = translation_node_get_translations($node->tnid);
     unset($all[$node->language]);
     if(isset($all)){
            foreach($all as $del){
                    if($node->nid != $del->nid){
                        $nids[] = $del->nid;
                            db_delete('node')
                                ->condition('nid', $nids, 'IN')
                                ->execute();
                            db_delete('node_revision')
                                ->condition('nid', $nids, 'IN')
                                ->execute();
                            db_delete('history')
                                ->condition('nid', $nids, 'IN')
                                ->execute();
                            db_delete('node_access')
                             ->condition('nid', $nids, 'IN')
                             ->execute();
                    }
            }
     }
}


javascript inherit from a class

Question: Im learning inheritance. In the code below
1)penguin inherits from Animal
2)when I call penguin.sayName();  why does it output "Hi my name is undefined";
function Animal(name,numLegs){
    this.name = name;
    this.numLegs = numLegs;

}
Animal.prototype.sayName = function(){
  console.log("Hi my name is " + this.name);
};

function Penguin(){}

Penguin.prototype = new Animal();

var penguin = new Penguin("Captain Cook", 2);
penguin.sayName();

Answer: You need to add the name and numLegs properties to the penguin object via the function constructor.  These two properties are specific to the Animal object and will not be assigned simply by calling the Penguin constructor.
function Penguin(name,numLegs){
  this.name = name;
  this.numLegs = numLegs.
}

Working Example: http://jsfiddle.net/5A7hH/
You could also use the constructor on the prototype chain, which is similar to calls of the super() constructor in Java.
function Penguin(name,numLegs){
   this.constructor(name,numLegs);
}

Comment: @Hello-World It doesn't get used because the Animal constructor is never called unless explicitly stated, as illustrated in the second example.  In your example, the name and numLegs properties never get assigned since the Parents constructor is not called.  This is pretty standard in OO languages.  Are you familiar with Java?  Think about how the call to super is required for every class that extends another.
Comment: Please note that `this.constructor(name,numLegs);` *only* works because the `constructor` property is overridden to point to `Animal` in `Penguin.prototype = new Animal();`. *Usually* the `constructor` function points to the constructor function itself, i.e. to `Penguin`, so it does *not* behave like `super`. A better approach would be `Animal.apply(this, arguments)`.
Comment: thanks - but I still a little unsure, if its inheriting from Animal why don't those automatically get used?
Comment: Not sure why but typically constructor will not get inherited by child object. This apply to C#, Java and etc.
Comment: Kevin Bowersox  - wow - thank you - I'm still new to all of this. which is the best way - Is your first example the most correct?
Comment: @FelixKling  What if I added a function to Penguins prototype and call `this.constructor` from within said function, which constructor would I get?  I guess my question is when would I receive the child classes constructor when calling `this.constructor`?
Comment: @Kevin: As I said, *usually* `Constr.prototype.constructor` refers to `Constr` itself. And `this.constructor` would always point to `Constr` if the prototype wasn't overwritten completely, no matter *where* it is accessed. Often you will find the statement `Child.prototype.constructor = Child;` to "set things right again". Using `this.constructor` in *your* example is perfectly fine, however it might be confusing because of the already mentioned reasons... does this answer your question?
Comment: @FelixKling Yes it does. I appreciate the time you took to answer it.

javascript inherit from a class


Expected value with recursive probability

Question: First of all, I'm aware of an existing question with a similar title, but my problem is fundamentally different.
I'm trying to solve this: in the first try, there is a 5% probability of obtaining a success. In the second try, if the first one was a success, the probability resets to 5%, but if the first one was a failure, now there is 5% more probability (10%). This goes on an on for an arbitrary number of trials, what I'm trying to calculate is the expected number of trials to obtain a single success.
What I got is the probability of obtaining a success in try number $n$, which obviously depends on the probability of the previous try:
$$p(n) = p(n-1)\times 0.05 + (1-p(n-1))\times(p(n-1)+0.05),$$
with $p(1)=0.05$. Is it possible to calculate what I want?
In a more general way, what I'm asking is how to calculate the expected number of trials when the probability of success in a single trial depends on the probability of the previous trial, $p(n)=f(p(n-1))$.
Comment: Model this with a Markov model. The rest is straightforward.
Comment: The probability on try $n$ does not depend only on the probability on the previous try. It really depends on the actual outcome! Perhaps you should make a tree of the first few steps.
Comment: Also note that $n$ can't be arbitrarily large. $20$ at most.
Comment: You are right, so in my case I can just calculate the probabilities of the first 20 steps and from that get the expected value that I want. I guess I was thinking in the general case in which $E(n)$ could be arbitrarily large. Thank you.
Answer: Let $p(n)$ be the probability of having a success within the first $n$ trials, and let $q(n)$ be the probability of having the FIRST success in trial $n$. Then it holds that $p(1)=q(1)=0.05$,
$$q(n)=0.05n[1-p(n-1)],$$
and
$$p(n)=p(n-1)+q(n).$$
Generate the sequences $p(n)$ and $q(n)$ for as long as they satisfy $0\leq p(n)\leq1$ and $0\leq q(n)\leq1$. It turns out that $p(21)=1$ and this is where you can stop. Then calculate
$$\sum_{n=1}^{21}q(n)n.$$
Answer: Not a complete answer. Let the probability of success on the first try be $1/m$, where $m$ is a positive integer. If the first try fails, the probability of success on the second try is $2/m$, and so on, as explained by the OP for $m = 20$. Success requires at most $m$ tries, since the probability of success on the $m$th try is $1$. The probability of success on the $r$th try and not before is $p(r)$ where
$$p(r) = {{m-1}\over{m}} \times {{m-2}\over{m}} \times \cdots \times {{m-r+1}\over{m}} \times {{r}\over{m}}.$$
The expected number of tries is
$$p(1) + 2p(2) + 3p(3) + \cdots + mp(m).$$
The values for $m = 1, \dots\ 6$ work out to
$$1,\quad3/2^1,\quad17/3^2,\quad142/4^3,\quad1569/5^4,\quad21576/6^5.$$
The numerators can be found in the OEIS at
https://oeis.org/search?q=1%2C3%2C17%2C142%2C1569&language=english&go=Search
Unfortunately the table doesn't go as far as $m = 20$ but the references may help.


Admob - anuncios em videos

Question: Gente, to pensando em criar um app cuja forma de monetização seja aqueles anuncios em videos que o usuario assiste pra ganhar algo no app, sabe os rewards videos tipo o Angry Birds, na verdade, eu to pensando em alguns itens em que pra o usuario ganhar ele tem que assistir 1 ou 2 videos, ok.
Minha duvida é: 1º como faço pra saber se o usuario assistiu realmente o video? o admob tem algum metodo de retorno pra informar isso? Alguem conhece algum exemplo implementado, algum link ou video que explique?
E minha maior duvida é: sera que compensa? A gente não consegue encontrar nada a respeito de valores do admob!!! Tipo quanto eles pagam por cada click nos banners, por cada anuncio intersticial que é exibido, ou por cada anuncio nativo (igual aqueles do CM Lite), e principalmente quanto eles nos pagam por cada video que o usuario assiste??????? Alguem pelo amor de Deus pode me informar esses valores... onde tem essa tabela, porque eu não achei nada a respeito, inclusive o admob nem tem email de suporte >:[
Sei que bem relativo, mas to perguntando em media mesmo... porque preciso decidir se uso essa forma de monetização ou vendo cada item no inApp Billings, mas os videos é bem mas facil do usuario aceitar, comprar q é bom ninguem quer...
Por favor se alguem souber eu agradeço.
Answer: Eu te  aconselho a usar o Appodeal, Appodeal é um mediador que trabalha com varias networks e escolhe os anúncios que pagam mais, você pode escolher com quais network trabalhar ou simplesmente trabalhar com todas.
https://www.appodeal.com/sdk/documentation?framework=1&full=1&platform=1
A documentação explica sobres as recomeças, acho que vale a pena dar uma lida.
Aqui fala um pouco sobre os Rewards
https://blog.appodeal.com/blog/2016/09/15/rewarded-videos-irresistible-format/
Comment: ei @Wallace Roberto, esse Appodeal tem de instalar uma extenção do chrome, voce saberia me informar como eu faço pra configurar no braço? porque eu só uso o firefox.
Comment: então você tem que ter conta no admob.
Comment: Faz outra pergunta aqui no stack que detalho pra você como usar o appodeal
Comment: Oi, valeu pela dica. Fiz a pergunta aqui (https://pt.stackoverflow.com/questions/188000/usar-o-mediador-appodeal) se vc puder me ajudar, sou nova nisso e trabalho sozinha, como o @Armando Marques Sobrinho tb só uso firefox porem ja tenho a conta do admob. Esse mediador é usado junto com o admob? Como? Como eu disse sou nova nisso, é meu 1º app. :)

Admob - anuncios em videos