substr plugin not working

Question: I have been using Migrate API as a means to pull in RSS Data as nodes. Currently in Drupal 8 it doesn't seem there is any other reasonable way to do this.
One of my fields is a link that ends in a series of 6 numbers. I need those numbers as an id to go into the url. The substr plugin seems like it would be perfectly suited to accomplish this, but doesn't seem to work at all.
What I have in my YAML file :
grantid:
-
  plugin: substr
  source: guid
    start: 61
    length: 6

The error in my drush window when I attempt to even install the module that uses the plugin.
Unable to parse at line 61 (near "  start: 5").' in /var/beetbox/core/lib/Drupal/Core/Config/FileStorage.php:117

Currently I'm looking into using explode, but this is certainly not an ideal solution. Does anyone have some insight on why this plugin wouldn't work? It works fine without using this plugin.
Update : It does seem that was the problem. Thanks for the help.
Comment: I think the error is informing you that the YAML is not correct. The start and length should be on the same indentation as source because source is not a mapping or sequence.
Answer: Answered at https://www.drupal.org/node/2829462 - as mradcliffe says, this is a YAML syntax error.
Comment: Yes, That was the issue. Thanks for the help. Also, are you the same Mike Ryan that RUNS the Migrate API and PathAuto Modules??? Thank you for all of your great work!
Comment: Yep, I was the original author of the migrate and pathauto contrib modules.

substr plugin not working


In SEM, what is the difference between ADF and WLS estimation methods?

Question: In some books both WLS and ADF are considered different methods. In other books, they acknowledge that ADF = WLS, so they are used interchangeably throughout the book.
How solve this confusion?
Comment: @TyrelStokes ADF is a specific type of WLS so I can understand the confusion.
Comment: WLS = Weighted Least Squares and am I correct in assuming ADF = Asymptotic Distribution-Free Technique? Do you have a reference for where they are considered the same?
Answer: Weighted Least Squares (WLS) is a general class of estimators where squared differences between observed and estimated values are weighted by some critereon. When the weights are all 1, this is Ordinary Least Squares. When the weights are based on unequal variances, this is Generalised Least Squares (GLS). For a specific choice of weights, based on the covariance of the disturbance terms, and under conditions where the 4th and 8th moments around the mean of the observed variables exist, but without any other distributional assumptions, this estimator is called the arbitrary distribution function estimator (ADF). It is also sometimes know as the asymptotic distribution-free estimator due to the need for larger sample sizes than for other estimators.
Comment: @Hussain Does this answer your question ? If so, please consider marking it as the accepted answer. If not, please let us know why
Comment: Will you elaborate what it means that "the 4th and 8th moments... exist, but without any other distribution assumptions"? a) When is it not possible to calculate these moments? b) if these assumptions require other assumptions, what are they - that moments 1-3 can also be calculated? ... I will be happy to ask a new question should you prefer.


Intuition for Sobol Indices

Question: I have recently been learning about Sobol indices and have found them quite informative. However, as I have explored them I have encoutnered situations where I have found them counter intuitive and in fact more misleading than helpful.
I am lead to assume that this must be a misconception on my part, so perhaps somebody could shed some light on this for me?
For our considerations let $ X,Y \sim \mathcal N(0,1) $ be standard normally distribution and consider a model $ Z = f(X,Y) $.
Scenario (1): Let $ f(X,Y) = aX+bY $, then the Sobol indices are $ S_X = \frac{a^2}{a^2+b^2} $, $ S_Y = \frac{b^2}{a^2+b^2} $ and $ S_{XY} = 0 $, which makes a lot of sense each of them contributing a fraction of the variance proportional to their own variance.
Scenario (2): Let $ f(X,Y) = XY $, then the Sobol indices are $ S_X = S_Y = 0 $ and $ S_{XY} = 1 $, which again makes sense. All variation is contributed by their combination.
Scenario (3): Let $ f(X,Y) = X^2Y $. Now it gets counter-intuitive to me. Here the Sobol indices are $ S_X = 0 $, $ S_Y = \frac13 $ and $ S_{XY} = \frac23 $. I can compute the indices, no problem, but the way I see it $ X $ is much more significant to the variance than $ Y $ here, which is not clear from the indices at all. In fact, they kind of seem to tell the opposite story.
Of course, $ S_X = 0 $ in (3) is due to it being proportional to $ \mathbb E_Y[f(X,Y)] = 0 $, so $ f(X,Y) = X^kY $ for all $ k > 0 $ has $ S_X = 0 $.
What exactly am I supposed to take away from scenario (3)? And if this is kind of an artifact of the setup, how am I supposed to identify such an issue in another setting where the model $ f $ is way more obscure? or straight up black box?
Answer:
$$ is much more significant to the variance than $$

The Sobol indices belong to a specific category of Sensitivity Analysis called Global Sensitivity Analysis (GSA). GSA computes sensitivity indices by taking into account for the model $f(X,Y)$ and the probability distributions of the input random variables $X$ and $Y$. The above statement focuses solely on the model and does not account for the input distributions.
Example
Let us shift the mean of the distributions and compute the Sobol indices (numerically) once again for scenario (3).
Case 0: $X, Y \sim \mathcal{N}(0,1)$
As expected: $S_X \approx 0.00 , S_Y \approx 0.33 $ and $S_{XY} \approx 0.66$.
Case 1: $X, Y \sim \mathcal{N}(1,1)$
We obtain: $S_X \approx 0.37 , S_Y \approx 0.25 $ and $S_{XY} \approx 0.37$.
Case 2: $X, Y \sim \mathcal{N}(100,1)$
We obtain: $S_X \approx 0.79 , S_Y \approx 0.20 $ and $S_{XY} \approx 0$.
Intuition
For Case 0: $X, Y \sim \mathcal{N}(0,1)$, most of the probability mass ($\sim 68 \%$) of the random variables is between $[-1, 1]$. Therefore $X^2$ will be smaller than $Y$ "most" of the time. Since the values of $X$ are small, the effect of their variance is also small. As the probability mass shifts to higher values in Case 1 and Case 2, the values of $X$ increase and their variance naturally has a larger contribution to the overall variance of $f(X,Y)$ and we see that the first order index $S_X$ increases.

Intuition for Sobol Indices


resolve an non-homogeneous differential system

Question: Solve the given non-homogeneous system:
$$\dfrac{dx}{dt}=3x + 3 y - 2 z + e^t$$
$$\dfrac{dy}{dt} = x+y+ 2 z$$
$$\dfrac{dz}{dt}=x+3y+e^t$$
Can you help me understand a simple method to resolve the system?
Thanks for any help.
Comment: Hint: Can you write $X'(t) = AX(t) + F(t)$, solve for the eigenvalues of $A$ and then for $F(t)$? Also, were you given any initial conditions?
Comment: We haven't initial conditions. I know this method to compute the solution of homogeneous problem associate. But i don't understand the method to find the particular solution to write the formula of solution of the non-homogeneous problem.
Comment: @Amzoti does your method of solving this question (without initial conditions) work for any $F[t]$ or only for $F[t]$ in the form: $e^{t\alpha} \vec{w}$? because I only see the functions depending on t in this form. (I am using the notation you used in your answer).
Comment: It works for "any" $F(t)$.
Answer: We are given the nonhomogeneous system:
$$\dfrac{dx}{dt}=3x + 3 y - 2 z + e^t$$
$$\dfrac{dy}{dt} = x+y+ 2 z$$
$$\dfrac{dz}{dt}=x+3y+e^t$$
We can write this as $X'(t) = A x(t) + F[t]$, where:
$$A = \begin{bmatrix} 3& 3 & -2 \\ 1 & 1 & 2 \\ 1 & 3 & 0 \end{bmatrix}, ~~ F[t] = \begin{bmatrix} e^t \\ 0 \\ e^t \end{bmatrix}$$
We have the homogeneous solution (you said you know how to find this):
$$X_h(t) = \begin{bmatrix} x_h(t) \\ y_h(t) \\ z_h(t) \end{bmatrix} = c_1e^{4t} \begin{bmatrix} 1 \\ 1 \\ 1 \end{bmatrix} + c_2 e^{-2t} \begin{bmatrix}1 \\ -1 \\ 1 \end{bmatrix} + c_3e^{2t} \begin{bmatrix} -1 \\ 1 \\ 1 \end{bmatrix}$$
Now we need to find the particular solution using the Fundamental Matrix approach, by solving:
$$X(t) = e^{At}X_0 + \int_{t_0}^t e^{A(t-s)}F(s)~ds$$
So, we we use a linear combination from the components of the homogeneous solution to write:

Write $\phi(t) = [x_1(t)~ | ~x_2(t)~ | ~x_3(t)] = \begin{bmatrix} e^{4t} & e^{-2t} & -e^{2t} \\ e^{4t} & -e^{-2t} & e^{2t} \\ e^{4t} & e^{-2t} & e^{2t} \end{bmatrix}$
Find $\phi^{-1}(t) = \begin{bmatrix} e^{-4t}/2 & e^{-4t}/2 & 0 \\ 0 & -e^{2t}/2 & e^{2t}/2 \\ -e^{-2t}/2 & 0 & e^{-2t}/2 \end{bmatrix}$
Find $\phi^{-1}(t) \cdot F(t) = \begin{bmatrix} e^{-3t}/2 \\ e^{3t}/2 \\ 0 \end{bmatrix}$
Now we integrate the previous result and this gives us: $w = \begin{bmatrix} -\dfrac{1}{6}e^{-3t} \\ \dfrac{1}{6}e^{3t} \\ 0 \end{bmatrix}$
Next, we find $X_p(t) = \begin{bmatrix} x_p(t) \\ y_p(t) \\ z_p(t) \end{bmatrix} = \phi(t) \cdot w = \begin{bmatrix} 0 \\ -e^{t}/3 \\ 0 \end{bmatrix}$

All that is left is to write the final solution as:
$$X(t) = X_h(t) + X_p(t)$$
Update
This is adding an example of using the VoP method for a $2x2$ matrix, so you can see the process. You can make up an initial condition for your $3x3$ and emulate this process as you can easily check the result by substituting it back into the system of ODEs.
$x' =  Ax(t) + f(t) = \begin{bmatrix} 6/7 & -15/14 \\ -5/7 & 37/14 \end{bmatrix}~x(t) + \begin{bmatrix} e^{2t} \\ e^{-t} \end{bmatrix}, x(0) = \begin{bmatrix} 4 \\ -1 \end{bmatrix}$
$e^{At} = \begin{bmatrix} \dfrac{6}{7}e^{t/2} + \dfrac{1}{7}e^{3t} & \dfrac{3}{7}e^{t/2}- \dfrac{3}{7}e^{3t} \\ \dfrac{2}{7}e^{t/2}- \dfrac{2}{7}e^{3t}  & \dfrac{1}{7}e^{t/2} + \dfrac{6}{7}e^{3t}  \end{bmatrix}$
$e^{At}x(0) = \begin{bmatrix} 3e^{t/2} + e^{3t} \\ e^{t/2}-2e^{3t} \end{bmatrix}$
$e^{A(t-s)} = \begin{bmatrix} \dfrac{6}{7}e^{(t-s)/2} + \dfrac{1}{7}e^{3(t-s)} & \dfrac{3}{7}e^{(t-s)/2}- \dfrac{3}{7}e^{3(t-s)} \\ \dfrac{2}{7}e^{(t-s)/2}- \dfrac{2}{7}e^{3(t-s)}  & \dfrac{1}{7}e^{(t-s)/2} + \dfrac{6}{7}e^{3(t-s)}  \end{bmatrix}$
$e^{A(t-s)} \cdot f(s) = \begin{bmatrix} \dfrac{6}{7}e^{(t-s)/2} + \dfrac{1}{7}e^{3(t-s)} & \dfrac{3}{7}e^{(t-s)/2}- \dfrac{3}{7}e^{3(t-s)} \\ \dfrac{2}{7}e^{(t-s)/2}- \dfrac{2}{7}e^{3(t-s)}  & \dfrac{1}{7}e^{(t-s)/2} + \dfrac{6}{7}e^{3(t-s)}  \end{bmatrix} \cdot \begin{bmatrix} e^{2s} \\ e^{-s} \end{bmatrix}$
$\displaystyle \int_0^t e^{A(t-s)} \cdot f(s)~ds = \begin{bmatrix} \dfrac{3}{7}e^{2t} -\dfrac{5}{28}e^{-t} -\dfrac{2}{7}e^{t/2} + \dfrac{1}{28}e^{3t} \\  \dfrac{10}{21}e^{2t} -\dfrac{13}{42}e^{-t} -\dfrac{2}{21}e^{t/2} - \dfrac{1}{14}e^{3t} \end{bmatrix}$
$\displaystyle x(t) = e^{At}x(0) + \int_0^t e^{A(t-s)} \cdot f(s)~ds = \begin{bmatrix} 3e^{t/2} + e^{3t} \\ e^{t/2}-2e^{3t} \end{bmatrix} + \begin{bmatrix} \dfrac{3}{7}e^{2t} -\dfrac{5}{28}e^{-t} -\dfrac{2}{7}e^{t/2} + \dfrac{1}{28}e^{3t} \\  \dfrac{10}{21}e^{2t} -\dfrac{13}{42}e^{-t} -\dfrac{2}{21}e^{t/2} - \dfrac{1}{14}e^{3t} \end{bmatrix} = \begin{bmatrix} \dfrac{3}{7}e^{2t} -\dfrac{5}{28}e^{-t} +\dfrac{19}{7}e^{t/2} + \dfrac{29}{28}e^{3t} \\  \dfrac{10}{21}e^{2t} -\dfrac{13}{42}e^{-t} +\dfrac{19}{21}e^{t/2} - \dfrac{29}{14}e^{3t} \end{bmatrix}$
Comment: We don't understand one point: how you use the formula $$X(t)=e^{At} X_0 + \int_{t_0}^t e^{A(t-s)} F(s) ds$$? you haven't compute $e^{Ax}$
Comment: I don't actually use $e^{A t}$, I am showing that this approach comes from Variation of Parameters (VoP). I assumed you would understand that given that you are learning to work with these sorts of systems. Search for VoP and Fundamental Matrix if you are not familiar with how those two work for the solution. The way I find $X_p$ is using the FM approach, but it is all based on VoP for the theory, mixed in with the FM for a solution. Regards
Comment: i think that there is an error on latex in yor message. So please can you redxplain me please?
Comment: See, , problem 9 for example as another example, but search for the above for the theory. http://www.math.ucsb.edu/~asdugas/5A_W09/5AfinrevSol.pdf, Regards
Comment: @jijii: Also note, this would be a lot with initial conditions as then we could easily use that VoP formula, but none were given here, so we have resort to these sorts of tricks. Regards
Comment: Si, we have two cases. case 1: if we have the initial data $X(t_0)=X_0$ then, we use the formula $$X(t)=e^{At}X_0+\int_{t0}^t e^{A(t-s)}F(s)ds$$, case 2: if we don't have the initial data, we must to compute the solution of homogeneous problem and find an particular solution. To find an particular solution:1-we compute $\Phi(t)$ and $Phi^{-1}(t)$,2- find $\Phi^{-1}(t).F(t)=V,$ 3-Integrate $V$ : $\int V = w,$ and finally $$X_p(t)=\Phi(t).w$$ it's okay?
Comment: Yes, very good! One point, if given an initial condition vector, it will be given as $X(0) = C$ and in this case $t_0 = 0$ for the integral. However, the IC may be given as $X(\pi)$, in which case $t_0 = \pi$. I suggest you take a problem with IC and use and don't use the IC and make sure you understand the difference! Regards
Comment: please, can you show me the detail of the method when we have the initial data $X(t_0)=C$ please.
Comment: @jijii: I will add it as an example, but have to do it after getting home from work, so several hours from now. Regards
Comment: I am waiting, and thank you so much.
Comment: @jijii: I added a detailed example for you to work out of a $2x2$, the $3x3$ is too much typing. You can use any initial condition with your $3x3$ and emulate the process. Regards
Comment: Thank you so much! I have an other question please. This two methods are applied when all eigenvalues of $A$ are distincts. But how we can find the solution of an non homogeneous system $X'(t)=A X(t) + F(t)$ when $A$ admits an unique multiple eigenvalue, or her eignevalues with different multiplicities?
Comment: That is no different than the methods used with constant coefficient matrices. Make up a $2x2$ with both eigenvalues the same and work it out. VoP does not change any of those rules.
Comment: But if the matrix $A$ admits for exemple one eigenvalue with multiplicity 2. How we can write the fundamental matrix??


Mudar fonte de texto de APP android

Question: Estou desenvolvendo um APP em Android no Android Developer Tools.
gostaria de saber como mudar a fonte de texto que é padrão do Android para a fonte Museo.otf, e como aplicar a todos os TextViews.
agradeço desde já
Answer: Existe uma série de passos a realizar para uma correcta implementação de tipos de letra não padrão numa aplicação, bem como algumas considerações a ter.
Segue em baixo uma explicação compreensiva sobre a implementação de tipos de letra numa aplicação Android:

Localização dos ficheiros
Para armazenar correctamente os ficheiros dos tipos de letra que vais utilizar, os mesmos deverão ficar dentro da seguinte localização no teu projecto:
/assets/fonts

Deverás já ter a /assets, faltando criar a sub-pasta /fonts.
Formatos dos ficheiros
Existem dois formatos suportados TTF e OTF, sendo o primeiro o mais recomendado por questões de compatibilidade, apesar de ambos funcionarem.
Nota:
O ficheiro e a sua extensão tem que estar com letras minúsculas:
minha_fonte.ttf (correcto)
minha_fonte.TTF (incorrecto)
minha_Fonte.ttf (incorrecto)
Museo.otf       (incorrecto) terá que ficar museo.otf

Criar XML para nomear propriedades personalizadas
O Android SDK permite que nomeies propriedades personalizadas para os teus widgets, mas para isso é preciso criar um XML na localização em baixo com o nome attrs.xml:
/res/values

O XML a criar terá o seguinte código:
<?xml version="1.0" encoding="utf-8"?>
<resources>
  <declare-styleable name="MyTextView">
    <attr name="minhaFonte" format="string" />
  </declare-styleable>
</resources>

Layout
Podemos agora elaborar o layout que deverá estar presente no ficheiro activity_main.xml no localização em baixo indicada:
/res/layout/activity_main.xml

Nesse ficheiro aplicamos o seguinte código:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:customfontdemo="http://schemas.android.com/apk/res-auto"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:orientation="vertical"
  android:gravity="center">

 <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textSize="24sp"
    android:padding="12dp"
    android:text="Fonte padrão do Android" />

  <com.authorwjf.customfontdemo.MyTextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textSize="32sp"
    android:padding="12dp"
    customfontdemo:minhaFonte="minha_fonte.ttf"
    android:text="A minha fonte no Android" />

</LinearLayout>

Como dá para ver, já estamos a fazer da propriedade personalizada fontName.
Classe
Falta agora criar uma classe em baixo com o nome MyTextView que vai estender a text view padrão, devendo o ficheiro ficar na seguinte localização:
/src

Com o nome da classe que estamos a criar:
/src/MyTextView.java

Contendo o seguinte código:
package com.authorwjf.customfontdemo;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.TextView;

public class MyTextView extends TextView {

  public MyTextView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    init(attrs);
  }

  public MyTextView(Context context, AttributeSet attrs) {
    super(context, attrs);
    init(attrs);
  }

  public MyTextView(Context context) {
    super(context);
    init(null);
  }

  private void init(AttributeSet attrs) {
    if (attrs!=null) {
      TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.MyTextView);
      String minhaFonte = a.getString(R.styleable.MyTextView_minhaFonte);

      if (minhaFonte!=null) {
        Typeface myTypeface = Typeface.createFromAsset(getContext().getAssets(), "fonts/"+minhaFonte);
        setTypeface(myTypeface);
      }

      a.recycle();
    }
  }
}

Aqui estamos a recolher o nome da fonte do atributo personalizado e a aplicar o typeface.
MainActivity.java
Dado que o text view está num ambiente independente, não precisamos de fazer modificações ao ficheiro MainActivity.java localizado na pasta em baixo indicada:
/src/MainActivity.java

Cujo mesmo terá o seguinte código:
package com.authorwjf.customfontdemo;

import android.os.Bundle;
import android.app.Activity;

public class MainActivity extends Activity {

  @Override
    protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
    }
}

Temos assim concluída uma aplicação em Android que faz uso dum tipo de letra que não o padrão do sistema.
Link para download dos ficheiros.

Créditos
Créditos deste tutorial passo a passo para o William J. Francis no site TechRepublic no seguinte tópico:
Pro tip: Extend Android's TextView to use custom fonts (Inglês)
Answer: Eis aqui uma ótima biblioteca para isso ok.
https://github.com/johnkil/Android-RobotoTextView
Answer: Utilizarei como exemplo a fonte orange_juice.
Primeiro de tudo: Crie a pasta assets em app/src/main/assets... Caso tenha dificuldade para localizar, mude a visualização do seu projeto:

Cole a fonte que deseja na pasta assets (arquivo .ttf ou .otf).
No método onCreate coloque o seguinte:

public class MainActivity extends AppCompatActivity {

    private TextView tv01;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tv01=(TextView)findViewById(R.id.tv01);
        Typeface font = Typeface.createFromAsset(getAssets(), "orange_juice.ttf");
        tv01.setTypeface(font);

    }
}

O código é bem simples na realidade.
Perceba que a classe TypeFace tem o método createFromAsset. Ele recebe como parâmetro a pasta default dos assets e o nome do arquivo de fonte a ser utilizado.
Vale ressaltar que quando se fala de fontes customizáveis, tenha sempre em mente que elas podem não funcionar corretamente, principalmente se ela não possuir todos os caracteres especiais que a aplicação pode vir a exigir.

FONTE => http://www.mobits.com.br/2011/5/20/personalizando-fontes-no-android
FIM!

Mudar fonte de texto de APP android


website panel installation error

Question: I am installing website panel by web Microsoft Web Platform Installer 4.0 but after installing website panel and going to website panel url it shows error that:-
Thanks Zinm3r you were right but now on opening the web site panel i got error:-Server Error in '/' Application.
Configuration Error
Description: An error occurred during the processing of a
configuration file required to service this request. Please review the
specific error details below and modify your configuration file
appropriately.
Parser Error Message: Unrecognized configuration section system.web.extensions.
Source Error:
Line 7:
Line 8:
Line 9:
Line 10:
Line 11:
Source File: C:\WebsitePanel\Portal\web.config    Line: 9
Version Information: Microsoft .NET Framework Version:2.0.50727.3053;
ASP.NET Version:2.0.50727.3053
Comment: Additional details needed
Answer: I had this issue before, I think WebsitePanel 1.2 is no longer supported. Try installing WebsitePanel using this installer which worked perfectly fine for me.
Edit: Choose Standalone mode in WebsitePanel installation process.
Comment: Ok i will try it jake and update you
Comment: I got an error in the final step that is got an error :- website panel enterprise server error the windows account is alr.    sorry i could read till here only coz the rest of error was hidden.
Comment: Alright, Go to server manager, under `Configuration` browse `Local Users and Groups` then open `User`. In right pane if you see any user related to WebsitePanel (WP*) remove it and Try again.
Comment: Thanks Zinm3r you were right but now on opening the web site panel i got error:-shown above in my edited question.
Comment: Cool, Run this: `aspnet_regiis -c`
Comment: I have to run in this powershell or somewhere else?
Comment: +1, You are quite welcome.

website panel installation error


stack profiling skipping cost centers in dependencies

Question: I am trying to profile my program the uses the hashables library and others. I don't want to profile the dependencies of my code, I just want to profile my code (and maybe the entry points of the dependencies). I am building with stack build --profile or with stack build --executable-profile and I am always getting noise like this in my profile (the following is from the profiterole output). How can I skip all this and only profile code from my package?
...

48.8  10.9   3.5  Data.Hashable.Generic ghashWithSalt (7601904)
45.3   7.5   4.6    Data.Hashable.Generic ghashWithSalt (6569085)
26.9    .3    .3      Data.Hashable.Generic hashSum (3165747)
 6.0   2.3   1.7      Data.Hashable.Generic ghashWithSalt (558817)
 1.6     -     -        Data.Hashable.Generic hashSum (432539)
 1.6    .2    .1        Data.Hashable.Class hashWithSalt (386021)
  .2    .1     -          Data.Hashable.Class hashWithSalt (0)
  .2    .1    .1            Data.Hashable.Class defaultHashWithSalt (186852)
  .1     -     -              Data.Hashable.Class combine (186852)
  .1     -     -          Data.Hashable.Class hashWithSalt1 (0)
  .1     -     -            Data.Hashable.Class liftHashWithSalt (7458)
  .6    .4    .2        Data.Hashable.Class liftHashWithSalt (61434)
  .4    .3    .1          Data.Hashable.Class liftHashWithSalt.step (614548)
  .3    .1    .1            Data.Hashable.Class hashWithSalt (0)
  .2     -     -              Data.Hashable.Class defaultHashWithSalt (614548)
  .1     -     -                Data.Hashable.Class hash (0)
   -     -     -                Data.Hashable.Class combine (614548)
   -     -     -          Data.Hashable.Class liftHashWithSalt.finalise (61434)
   -     -     -            Data.Hashable.Class hashWithSalt (0)
   -     -     -              Data.Hashable.Class defaultHashWithSalt (61434)
   -     -     -                Data.Hashable.Class combine (61434)
  .4     -     -        Data.Hashable.Generic ghashWithSalt (0)
  .4     -     -          Data.Hashable.Generic hashSum (206676)
  .1     -     -        Database.FluiDB.CnfQuery.Types hashWithSalt (70236)
 4.0    .1     -      Data.Hashable.Class hashWithSalt (128078)
  .2    .1    .1        Data.Hashable.Class defaultHashWithSalt (126035)
   -     -     -          Data.Hashable.Class combine (48982)
 3.5     -     -      Data.HashMap.Base hashWithSalt (116920)
  .2     -     -      Database.FluiDB.Cluster.Types.Clusters hashWithSalt (0)

28.7  10.0   2.7  Data.Hashable.Class liftHashWithSalt (539054)
 9.4   1.4    .4    Data.Hashable.Class defaultLiftHashWithSalt (105)
 6.1    .2    .2      Data.Hashable.Class hashWithSalt (90103)
 2.1     -     -        Data.Hashable.Generic ghashWithSalt (264200)
 2.3    .8    .6      Data.Hashable.Class liftHashWithSalt2 (506010)
 1.5    .2    .1        Data.Hashable.Class hashWithSalt (126670)
 1.3    .1     -          Data.Hashable.Generic ghashWithSalt (232657)
  .1    .1    .1            Data.Hashable.Generic hashSum (27468)
  .2     -     -        Data.Hashable.Class combine (195731)
  .6     -     -      Data.HashMap.Base hashWithSalt (846)
 8.8   5.3   2.3    Data.Hashable.Class liftHashWithSalt.step (10374784)
 6.1   3.0    .6      Data.Hashable.Class hashWithSalt (55681)
 5.0   2.4   2.1        Data.Hashable.Class defaultHashWithSalt (9979602)
 1.5     -     -          Data.Hashable.Class combine (8942838)
 1.5    .3    .3          Data.Hashable.Class hash (0)
  .4     -     -        Data.Hashable.Generic ghashWithSalt (164889)
  .4     -     -      Database.FluiDB.Cluster.Types.Clusters hashWithSalt (116428)
 7.2    .1    .1    Data.Hashable.Class hashWithSalt (211986)
 7.1     -     -      Data.Hashable.Generic ghashWithSalt (522861)
  .7    .5    .1    Data.Hashable.Class liftHashWithSalt.finalise (218121)
  .6    .3    .1      Data.Hashable.Class hashWithSalt (0)
  .5    .3    .3        Data.Hashable.Class defaultHashWithSalt (198539)
  .2     -     -          Data.Hashable.Class combine (98093)

...

Answer: Unfortunately, I think the best way of doing this currently is to use the per-package ghc-options feature of the project-specific stack.yaml file to explicitly disable automatic CAF generation for external dependencies.  In your stack.yaml file (not the package.yaml or .cabal file), you can add:
ghc-options:
  hashable: -fno-prof-auto

and then run:
stack build --profile
stack exec --profile -- myProgram +RTS -p

as usual.
As there doesn't seem to be a way to specify that this flag only applies to the profiled build, this means that hashable will need to be re-built especially for your project in both profiled and non-profiled versions, even though the non-profiled version should be equivalent to the "usual" non-profiled version.
Also, even though there are "$everything" and "$locals flags that can be used, so that the following might be supposed work:
ghc-options:
  "$everything": -fno-prof-auto
  "$locals": -fprof-auto

the Stack documentation is unclear on how these are resolved and includes multiple vague warnings that the "$everything" flag is dangerous.  I couldn't get it to work at any rate.
Comment: I am getting `The following packages specified by flags or options are not found: hashables`
Comment: Oh, looks like the package name is actually `hashable` without the "s".
Comment: Unfortunately that didn't work. I am still getting a lot of noise coming from `hashable` :(
Comment: Well, it worked fine for me using a test based on `primes`, but I don't have a good `hashable` example to test.  You can try running `stack clean` and then rebuilding with `stack build --profile`.  Maybe that will help?


Which country has the most international cricket grounds?

Question: Which country has the most international cricket grounds? How many cricket grounds do they have?
Comment: The list by @hims056 includes several that have not been used for a long time, such as the [Sardar Vallabhai Patel Stadium](http://www.espncricinfo.com/ci/content/ground/57852.html), which has not been used for international cricket since 1981. Do you mean all grounds that have ever been used for international cricket, or only ones that have been used recently?
Comment: I mean all grounds that have ever been used for international cricket.
Answer: India has the most international cricket grounds. It's 49! And that is more than double than the second highest(23)! Here is the list of numbers of international cricket grounds of Test playing country:
<code>| COUNTRY      | GROUNDS |
|--------------|---------|
| Australia    |      19 |
| Bangladesh   |       8 |
| England      |      23 |
| India        |      49 |
| New Zealand  |      16 |
| Pakistan     |      20 |
| South Africa |      16 |
| Sri Lanka    |      10 |
| West Indies  |      15 |
| Zimbabwe     |       4 |
</code>
Source: Cricinfo (I have counted manually.)
Comment: Nice effort....


Can glmmTMB be used without a random effect?

Question: I'm curious whether glmmTMB can be used without a random effect. Both glmer, lmer, and lme throw an error about lack of random effects, but glmmTMB runs fine. However, when I test a logistic regression using glmmTMB and regular glm, I get very different p values. Toy example below.
library(glmmTMB)
options(contrasts=c("contr.sum","contr.poly"))

data(mtcars)
mtcars$Bin <- as.numeric(mtcars$mpg > 20) # create a binary variable

m <- glm(Bin ~ as.factor(cyl) + wt, data= mtcars, family = "binomial")
m1 <- glmmTMB(Bin ~ as.factor(cyl) + wt, data= mtcars, family = "binomial")

car:::Anova(m)
car:::Anova(m1)

Comment: The coefficients and anova are different because the data is too sparse for logistic regression. If you look at the coefficients, some of them are huge, which indicates (likely) unreliable model fit.
Comment: This is just a toy example. I was seeing the same issue with my actual data. I'll update the example though to make it clearer, thank you!
Comment: I was wondering about the same thing. Did you reach an answer for this? Thanks.
Comment: I just don't think it's meant to do that. If, like me, you wanted to have access to the correlation structures as well as the full glm family list, try either looking into GAMs or into INLA...
Answer: Yes, glmmTMB happily fits models without random effects.
As pointed out in comments, the reason you're getting (apparently) very different answers from glm and glmmTMB is that you have complete separation in your example: all of the cars with 4 cylinders have Bin==1 and all of those with 8 cylinders have Bin==0 (There are questions on CrossValidated and Stack Overflow about how to diagnose and deal with complete separation, but a short version is that any coefficient value with $|\beta| \gt 10$ in a logistic regression with reasonably scaled inputs is a red flag.)
with(mtcars, table(Bin, cyl))
   cyl
Bin  4  6  8
  0  0  4 14
  1 11  3  0


Proxmox error on vmbr0

Question: I can't access to my pve due to networking error:
error: vmbr0: bridge port enp5s1 does not exist

interface file:

networking status:

Note: The second bridge work ok, the modem and external ip address are reached from pve, the problem is with LAN bridged. Network card led indicator is on.
Comment: show `ip addr` output. Copy-paste, please. it's text information and there is no reason to photograph the screen.
Comment: Sorry, i can´t access to pve by network (by ssh for example) to copy files content. is vmbr0 net connected to LAN.
Answer: Run ip link show to see known interfaces.
Is the interface there?  Perhaps it was renamed for some reason, or has a different name from the one you expect.
Running dmesg |grep enp5s1 should show kernel messages relating to that interface name.
If nothing is shown in the dmesg, perhaps you're missing an appropriate driver.
Comment: Ohhhhh, exactly!!!. enp5s1 doesn't exist any more, now is named enp5s0. Renamed in interface file and now all is working like a sharm. but, why it happen??
Comment: Did the card get moved to a different PCIe slot?  Was the hardware changed in some way?  Usually the "enpXsY" is defined as en (ethernet) in p (position) X s (slot)  Y.  Sometimes the method of identifying the ethernet ports isn't 100% exact... but it's usually pretty close.  In my own environments... I often rename my adapters to something more logical... but that's just a personal preference.
Comment: you can also see other ethernet interfaces that look like "enoX" or  "ensX"  eno usually is an "onboard" port... and an "ens" is in a card slot...  ... in the case of enpXSY ... it's usually a multi-port card in a slot.
Comment: Well, It seems like someone from the area tried to fix it yesterday and ended up complicating the situation. I installed this server in 2021 and had never had problems.

Proxmox error on vmbr0


tangent line to the graph

Question:
this is the problem, I reached pi/6 & -pi/6 each time yet the website is saying my answer is incorrect.
steps i took.
1) derivative of 4t-3tant/4t+3tant
2)yeilds 4+3sec^2(x) on bottom
3) set to 0
4) get +/-= sec = sort(-4/3)
5) cos = sqrt(3) /2 which => pi/6 or -pi/6
??? any ideas where I'm messing up? thank you!
Answer: We have $\frac{dx}{dt}=4+3\sec^2 t$. This is never $0$.
Remark: Note that $\frac{dy}{dx}=\dfrac{\frac{dy}{dt}}{\frac{dx}{dt}}$. You appear to be trying to find instead the derivative of $\frac{y}{x}$.
You do seem, however, to end up with $4+3\sec^2 t$, and set this equal to $0$.  Note there is no such thing (in the reals) as $\sqrt{-4/3}$. It is clear without calculation that $4+3\sec^2 x$ is always greater than $4$, indeed $\ge 7$.
Comment: If you really want to, set it equal to $0$. But then you have to solve the equation correctly. You did, sort of, getting a term $\sqrt{-4/3}$, which is not a real number. So there is no solution, just like the equation $4+t^2=0$ has no solution. I prefer to observe that $4+3\sec^2 t$ is obviously always positive, so is never equal to $0$.
Comment: so does that make it no values of t as it can't ever reach that value without imaginary numbers? Im not sure what to do instead of setting it to 0
Comment: ah ok that makes sense, thank you for the help!

tangent line to the graph


Understanding why a limit proof using another limit works

Question: Sorry for the title, hopefully I can explain it better. I think the title is about as good as I could get in terms of description.
I have a problem:

Let $x_n \ge 0$ for all $ N \in \mathbb{N}$
If $(x_n) \to x$, show that $(\sqrt{x_n}) \to \sqrt(x)$

Assume that we have already proved the limit going to zero.
My proof was as follows:
Our goal is to find an $N$ that satisfies the inequality:
$|\sqrt{x_n|} - \sqrt{x}| \lt \epsilon$
with epsilon being arbitrary.
So:
$|\sqrt{x_n|} - \sqrt{x}| \lt \epsilon$
$|\sqrt{x_n|}| \lt \epsilon + \sqrt{x}$
$|\sqrt{x_n|}|^2 \lt (\epsilon + \sqrt{x})^2$
$|x_n| \lt (\epsilon + \sqrt{x})^2$
$|x_n| \lt \epsilon^2 + 2 \epsilon \sqrt{x} + x$
$|x_n - x| \lt \epsilon^2 + 2 \epsilon \sqrt{x}$
Since we already know $|x_n - x|$ can be made arbitrarily small we are ready to proceed.
Then allow $\epsilon > 0$ to be arbitrary and choose an $N \in \mathbb{N}$ satisfying:
$|x_n - x| \lt \epsilon^2 + 2 \epsilon \sqrt{x}$
For $n \ge N$ we find after some algebra (to save typing the above backwards)
$|\sqrt{x_n|} - \sqrt{x}| \lt \epsilon$
Which shows that given the limit we can choose an $N$ for any given $\epsilon$ and find that all $n \ge N$ will be inside the $\epsilon$-neighborhood of $\sqrt{x}$.
Where I am confused is how I am using the given limit $(x_n) \to x$. I am sort of following a template here from the author. Adding this extra limit has confused me.
How does reducing the inequality $|\sqrt{x_n|} - \sqrt{x}| \lt \epsilon$ to $|x_n - x| \lt \epsilon^2 + 2 \epsilon \sqrt{x}$ and then knowing "we can make it arbitrarily small" help us prove the given limit? What is the intuition?
Comment: Hmm unfortunately I don't think your proof works, because going backwards, I don't think you can justify every step. For example, I don't think you can deduce the first step from the second (counting from after the "so"). The place where you use that x_n goes to x is where you fix epsilon and you say that there exists an N s.t. after N, we have |x_n-x|< epsilon. If you didn't know that x_n goes to x, you couldn't say that. I am going to sleep now, but if no one answers this just ping me and I can give more details tomorrow.
Comment: @Ovi That would be wonderful, to be honest it has been a while since I had to remember all the ways to manipulate absolute values.
Answer: You're using the fact that $x_n \rightarrow x$ in the very first step:  that's how you know that you can make $|x_n - x|$ arbitrarily small.  And you need to be able to make that difference arbitrarily small for the rest of the proof to work.
Answer: I want to stress a point made by Ovi in his comments that can lead you to big problems in lots of other cases, when working with inequalities.
Your argument starts with (I'm removing a few superflous "|"):
$|\sqrt{x_n} - \sqrt{x}| \lt \epsilon$
$|\sqrt{x_n}| \lt \epsilon + \sqrt{x}$
This correct in the sense of
$$|\sqrt{x_n} - \sqrt{x}| \lt \epsilon \Rightarrow |\sqrt{x_n}| \lt \epsilon + \sqrt{x}$$
However, that is not the implication that you want, because you are working backwards: The part $|\sqrt{x_n} - \sqrt{x}| \lt \epsilon$ is what you want to prove in the end, and you are looking for ways to get there.
That means what you want is an implication of the sort
$$ ???\Rightarrow |\sqrt{x_n} - \sqrt{x}| \lt \epsilon.$$
The important thing to note is that if you substitute $|\sqrt{x_n}| \lt \epsilon + \sqrt{x}$ for the "???" part, you get something that is patently untrue:
$$|\sqrt{x_n}| \lt \epsilon + \sqrt{x} \Rightarrow |\sqrt{x_n} - \sqrt{x}| \lt \epsilon $$
With "patently untrue" I mean that you can find values for $x_n$ and $x$ that fulfill the assumption of the implication, but the difference $|\sqrt{x_n} - \sqrt{x}|$ is not just a little bit bigger than $\epsilon$, but vastly bigger:
Set $x_n=0$, $x=1,000,000$ and we of course have that the assumption is fullfilled, but $|\sqrt{x_n} - \sqrt{x}|$ is not smaller than $\epsilon$, but $1,000$.
When working backwards with inequalities, always use extreme care to either use only transformations that are equivalent for inequalities (like multiplication with a positive value on both sides), or make steps of the form "If I could prove this, what I want to prove in the end would follow".
Comment: Very insightful. Im sorry if this mistake seemed trivial. I am self teaching from a real analysis book after having been out of school for 3 years (I'm planning on starting my MSc in fall). Thank you for taking the time to write this. This chapter has been particular discouraging because its really testing me, haha. The author had made it seem you always just work to find something you can transform backwards into the required epsilon inequality. It seems thats the goal in general, I hadn't realized you can't just "add across inequalities" like I did. Thanks again.
Comment: I compare this to cooking recipes: In order to learn cooking, you follow recipes, so you get a feel for 'how things work'. But when you need to come up with your own recipes, you need to know more: Why do you even need (or want) to "cook" food, why do certain ingrefient always seem to go together, etc. With math it can be similar: Following a proof is one thing, but if you need to come up with one on your own, you need to know more, or at least apply things a bit differently. Just like cooking, not all ideas work out ;-)
Answer: If $x=0$, the proof is trivial.
If $x\neq 0$, $|\sqrt{x_n}-\sqrt{x}|=\frac{|x_n-x|}{|\sqrt{x_n}+\sqrt{x}|}$.
Then we can find a $N$, s.t. $|\sqrt{x_n}+\sqrt{x}|>a>0$ when $n>N$, where $a$ is a constant.
$|\sqrt{x_n}-\sqrt{x}|<\frac{|x_n-x|}{a}\rightarrow0$.
Comment: So I take it my squaring solution was too complicated? What was the idea that gave you the simpler fraction solution?


Explain chord progression

Question: I'm just starting learning musical theory and trying to grasp chord progression and modulation concept. I was watching youtube video about evanescence chord progression (C-Em-C-Em), and tried to come up with a continuation. I've got these two options:

C-Em-C-Em-F-G-G#-A#-C
C-Em-C-EM-F-G-D#-F

I think they feel good to me, but I do not understand what is happening in these. I was playing in C major, how come I got G# and A# in it? I don't think I've modulated, at least it does not sound to me like that.
And (2) sounds to me like I've modulated to F major, but why D# there? It does not belong to neither Cmaj nor Fmaj.
I assume here that because progression feels good, then there is a good explanation why, I just need somebody to explain that to me.
On a side note, I would also appreciate more material to read on the topic
Comment: that first progression is beautiful!
Comment: Big picture: Most tonal music simplifies to one big cadence, I - V - I. By that definition, the original Evanescence riff doesn't "go anywhere," but your extensions do. Your first one adds a straightforward "IV - V - I," but sticks in a flat VI and flat VII as a little elaboration of the cadence.
Comment: As others have mentioned, the latter portion of the first progression should be F–G–A♭–B♭–C instead of F–G–G♯–A♯–C, since G♯ and A♭ are not necessarily the same pitch.
Answer: Whenever you encounter a non-diatonic chord, it's worth checking if it's a modal interchange or a secondary chord. And perhaps also trying enharmonic spelling variations.
G# and A# could be rewritten as Ab and Bb, and these two chords are borrowed from the parallel key of C minor.
D# could be respelled as Eb, which is borrowed from C minor as well. Another way to interpret it is chromatic mediant.
Comment: Thanks. I have to google a few terms now :) I seriously need to read more theory, I am confused and probably lack some basics. Do you have any recommendations on literature/courses you could share? I know this is not the place to ask for recommendations, so I asked in the chat:  https://chat.stackexchange.com/rooms/440/the-practice-room
Answer: You'll probably find it easier to justify G#, A# and D# if you spell them as A♭, B♭ and E♭.
There are many reasons why a chord can 'fit'.   The most simple is when it's diatonic in the home key or in a closely-related key. (There's really no need to push the idea of 'borrowing' any further than that, unless perhaps a chord is being used as a pivot into a new key.) It may be part of a functional sequence, dominant function chords leading to temporary tonics.  Or it may have notes in common with the preceding chord - after a C major chord any triad containing any of the notes C, E or G won't sound TOO disconnected.  Or it might simply be 'one up' from the preceding chord - even better if it's the same shape, major, minor, m7 etc. - which might be the best excuse for your F-G-G#-A#-C progression.
If you stick to triads, it's actually quite hard to write a progression that sounds 'wrong'.   And harder still to find one that couldn't be validated by a label - 'diatonic', 'modal interchange', 'borrowing', 'planing' whatever. All chords are permissible.  We should be concerned with the different effects of different patterns, not  with whether one is more 'correct' than another.
Comment: Isn't it the exact role of music theory to explain and label different effects of different patterns, rather than to validate using them?
Comment: @user1079505 Fine!  So rather than simply saying "that chord 'fits' because it's borrowed from wherever' explain WHY it should be chosen.  You start.  In C major, why would we use, say, a F minor chord? 'Because it's borrowed from the parallel minor scale is NOT a reason.
Comment: A better question is the one you asked previously: what is the effect of a pattern. Let's look at the beginning of the verse of _Bungalow Bill_, chords C G C Fm C Fm G. I say that this section is in the key of C major. The chord Fm is borrowed from the key of C minor, by which I mean it brings the sound of the key of Cm, and creates a tension similar to what iv creates in Cm. I could accept that you hear it differently, in which case you could disagree with this interpretation, but I don't see why do you believe it doesn't describe what is happening.
Comment: Why can't it create a tension exactly like iv does in C major?   After all, that's the key we're in, there's been no modulation!  Why this reluctance to LET a chord be chromatic, rather than diatonic in some other key?
Comment: Why then even bother with giving it a roman numeral, suggesting some functional dependence, when you call it _chromatic_, which means it has no connection with the key? You demand explanation, but "chromatic" really means no explanation. Now, I can accept that _for you_, in some particular situation, Fm in the key of C sounds chromatic, unrelated to the key. But you seem to arbitrarily criticize the possibility for interpretation as borrowed chord, with no good arguments.
Comment: A chromatic chord may be used as a passing harmony, or as  just decoration.  It may be used as a gateway to another key.  In the latter case 'borrowing' makes some sense.  In the former it doesn't.
Answer: Another way to treat the C-Em-C-Em is to think of it as C/E-Em-C/E-Em. Slash notation doesn't really show what's happening. If you think of the notes, one has EGC-EGB-EGC-EGB; the EG interval stays the same and the "melody" or "soprano" voice oscillates between steps 5 and 6 (if in the key of Em) or 7 and 8 if in C. It's an ambiguous progression and may be continued in various ways.
It's not wrong to think of it as CEG-EGB-CEG-EGB (which could be considered the same pattern with the C being displaced an octave; either up or down depending on whether the CEG is the "main" chord or EGC is; it doesn't matter, only the sound does.)
All your proposed chords sound pretty good (but probably should be renamed as explained in other comments). Nearly any "functional" or "non-functional" or "whatever..." progress works well if the voice leading is good (and one can almost always make this work.) (The idea is mostly to avoid parallel and covered fifths and octaves so that the music doesn't sound like one instrument quit playing.)
Answer: We agree with other respondents here that G# makes more sense when named Ab (and so on) in this situation. We have found numerous uses of this flat 6 (Ab), flat 7 (Bb), 1 (C) chord progression in popular and classical music. You can explain it by whatever means you choose, but it is an harmonic progression that typically sounds good.
Answer: As Lawrence mentioned, if you stick to triads (and I would specify: of the same quality and mostly moving step-wise) it's hard to find a progression that sounds bad.  Moving from one major triad in root position to another is parallel motion, which is always rather strong.  Your underlying bass line F-G-Ab-Bb-C is a rather strong phrase leading back to C, probably because of step-wise motion and what could be thought of as simply an inverted interval sequence*.
*C-D-E-F  whole whole half
*G-Ab-Bb-C half whole whole
So basically, you have harmonies all moving in the same direction (parallel) based on a strong melodic line which goes back to the tonic.
Try comparing something like Fm-Gm-Abm-Bbm-C to your progression.  It's almost as strong.
If you change the sequence of your progression to F-Ab-Bb-G-C you can hear that it also sounds fairly coherent for similar reasons.
Then looking at the connection between the first part of the progression, where you established a foundation with C-Em-C-Em (a somewhat limited movement with low complexity), the second part provides contrast (it's more interesting) because there is more movement and some other notes (Ab and Bb) outside the key center.  The first part is just sitting there and then the second part takes off with some nice upward motion and resolves.  Resolution is key.  You can add another musical element to the progression with how much time you spend on each chord (the rhythm).  I'm hearing it one way with 2 beats each on C-Em-C-Em and then 1 beat each on F G Ab Bb, which makes a slightly unusual but cohesive 3-bar phrase.
Have fun exploring the possibilities!
Answer: In both of your extensions, the chords you highlighted are out of kilter with the key, but they are "out" in an interesting way.
It's odd that both belong to the C minor scale, and yet they feel somehow optimistic.  I wonder if this is because they do flip into C minor, creating a feeling of apprehension, but the return to resolution is via an ascending sequence, which is both inherently optimistic because of its upward trajectory, and also quite well known, as if we're climbing a familiar path towards a better place.

Explain chord progression


Android finishing previous activities for navigation

Question: I have 5 activities (let's say A,B,C,D and E).
Activities A to D are for setting some data, so user may be able to go back and forth changing whatever.
Activity E, on the other hand, is the summary, so the user is no longer allowed to go back.
My idea is to finish all previous activities when user gets to E
Currently my activities A to D have no flags attached to them.
Activty E is called like this:
Intent I = new Intent(this, SomeClass.class);
I.setFlags( Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(I);
I have read everywhere that those flags are supposed to achieve what I am trying to do, but they doesn't, when user gets to activity E and presses Back button, the application goes back to activity D.
Any ideas? I am missing something? Is this not the right way to solve this problem?
Thanks for your help
Answer: Use the method startActivityForResult in each of the activities A, B, C, D instead of startActivity. And when the user exits out of Activity E, handle the backbutton and set the result code in the intent. now in the onActivityResult method of each A, B, C and D classes handle it , close the activity and pass the result to previous activity.
You can also do it as soon as user finishes Activity D. When users go from D to E, you may use the above method to actually go all the way down to Activity A and then open activity E and finish Activity A.
Both the above cases produce the same result from users perspective and they do not see the intermediate activities A, B, C, D unless you are doing some long jobs in the onStart method of those activities.
Comment: It was an easy change to do and it worked, thank you very much!
Answer: Just in case someone needs the code that @achie suggested, here it is:
A,B,C,D activities should start the following activity like this:
Intent myIntent = new Intent(this, B.class); // Or C/D
startActivityForResult(myIntent, 1);

Also, A,B,C,D activities should override:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
   super.onActivityResult(requestCode, resultCode, data);
   if (resultCode == RESULT_OK && requestCode == 1) {
      setResult(RESULT_OK);
      finish();
   }
}

Then E activity should handle back button:
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
   if (keyCode == KeyEvent.KEYCODE_BACK) {
      setResult(RESULT_OK);
   }
   return super.onKeyDown(keyCode, event);
}

Comment: Did this work for you? I need the exact same thing you need, tried the code above, but my last activity keeps going back to the previous activity.
Comment: Yes, this is working for me. A navigates to B, which navigates to C, which navigates to D, which navigates to E, then you press back and you go to the Home screen because all activities are finished.
I have uploaded an Android project sample for you: https://anonfiles.com/file/e9a7c889a7b2f358f29c868b7fa1d755
Comment: Thanks for taking time to post it, but I've already managed to get it to work.
Answer: I suppose your're trying to write some sort of a Wizard :)
In order to use the FLAG_ACTIVITY_CLEAR_TOP flag you must have activity E already in current activities task.
Example: E->A->B->C->D --> if D will start E with CLEAR_TOP you will have only activity E in stack.
FLAG_ACTIVITY_CLEAR_TOP
Using flag CLEAR_TOP to launch an activity
If there is already an instance of the called activity type present in the stack, then this instance is brought to the foreground instead of creating a new instance. Also, all activities in the stack that reside on top of that instance are cleared from the stack. For example, assuming that the current activity stack is ABCDE, launching an activity of type C will clear activities D and E from the task and result in the stack ABC.
FLAG_ACTIVITY_SINGLE_TOP (not relevant in your scenario)
If an instance of the target activity is already at the top of the stack, no new instance is created.
Comment: Your explanation helped me a lot to understand the real use of those flags. In my case calling E before A was not viable right now, but I'll keep this in mind for future apps.

Thank you very much!
Answer: You need to override the onKeyDown() method in Activit E and intercept the key press event for KEYCODE_BACK(the Back key), and simply return true to indicate you handled the Back event. Now the user will not be allowed to navigate back to the previous activity.
Comment: That doesn't do it. That is actually creating a problem that the users do not have a chance to use back button any more which is against the best practices. Never block the back button unless you have a good reason to do so. And in this case the users are prevented even from exiting out when they click on back button.
Answer: when you start activity E, use this code:
Intent I = new Intent(this, SomeClass.class);
I.putExtra("finish_all", true);
I.setFlags( Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(I);

Comment: I tried it but seems to do nothing. It is some built-in flag or something?
Do I have to treat it in some way?


Sending number instead of string from Select in React component

Question: I have a "controlled" React component for a very simple drop down that looks like this:
const MyDropDown = ({field, handleChange}) => {

   return(

      <select name="myField" value={field} onChange={handleChange}>
         <option value="1">Apples</option>
         <option value="2">Oranges<option>
         <option value="3">Bananas</option>
      <select>
   );
}

MyDropDown.propTypes = {
   field: PropTypes.number.isRequired,
   handleChange: PropTypes.func.isRequired
}

export default MyDropDown;

Initially, I set the value of the field to 0 in my reducer. This is the right thing to do because the value will always be a number. The problem I'm having is this:
Initially, everything is fine but when I make a selection, I get a warning saying an invalid prop of type string is supplied and it was expecting a number.
How do I make sure the values in the options are numbers and not strings?
BTW, I tried not using quotes for option values but React doesn't seem to like it i.e. <option value=1>Apples</option>
Comment: Just a suggestion, does `value={1}` work?
Comment: I just thought of that myself and tried it but still getting the same warning. It's still treating it as a string and not a number.
Comment: okay i assume field is a state in a hierarchically higher component, which is set in the handleChange-function. Maybe you need to parse the value to a number before setting that state?
Comment: You're exactly right! @teaflavored just gave me the same answer. Thank you very much!
Answer: I assume your handleChange looks something like this
handleChange(e) {
    this.setState({ val: e.target.value});
}

The issue here is that html needs quotes around the attribute values, so in essence e.target.value resolves to a string. A simple fix would be to parse it into a number by using
parseInt(e.target.value, 10);

Comment: For those who don't know the second parameter of the parseInt function is radix. For decimal numbers, radix must be equal to 10.
Answer: if your handler looks like above you can use +e.target.value


Java8 using enum values in interface's default methods

Question: I'm exploring possibilities of static and default methods introduced in java 8.
I've an interface that has 2 default methods that do construct a command, that I run on server through ssh to do some simple tasks remotely. Moving mouse requires 2 arguments: x and y position of the mouse.
public interface Robot {

    default String moveMouse(int x, int y) {
        return constructCmd("java -jar move_mouse.jar " + x + " " + y);
    }

    default String clickLeft() {
        return  constructCmd("java -jar click_left.jar");
    }

    static String constructCmd(String cmd) {
        return "export DISPLAY=:1.0\n" +
                "cd Desktop\n" +
                cmd;
    }
}

I've multiple enums with values preset, I could potently combine all enums into one and not use interface what so ever, however that enum would contain hundreds or thousands of values and I want to keep it somewhat organised, so I've split evertying in multiple enums.
I want all enums to share same methods so I figured I'll give default methods in an interface a shot.
public enum Field implements Robot {

    AGE_FIELD(778, 232),

    NAME_FIELD(662, 280);

    public int x;
    public int y;

    Field(int x, int y) {
        this.x = x;
        this.y = y;
    }
}

So I can get String commands by:
Field.AGE_FIELD.clickLeft();
Field.AGE_FIELD.moveMouse(Field.AGE_FIELD.x, Field.AGE_FIELD.y);

However moveMouse looks really bad to me and I think it should be somehow possible to use enum's values by default.
Anyone has a a nice solution for such problem?
Comment: This seems to be a conceptual problem. What you want is an interface with methods `void moveMouse()`, `int getMouseTargetX()` and `int getMouseTargetY()`. Your current design asks for the specific x- and y-Coordinates. My proposal assumes that the object has some attributes, defininig the x- and y- Coordinates. My proposal is more like an extension to your already existing system than a replacement. Your interface would be used for the component to actually move the mouse, whereas my interface would be used by components, that call the component that actually moves the mouse.
Answer: The problem is your architecture. On the one hand, you have a layer that actually executes the mouse-movement (represented by your Robot interface). Now, you need a layer that produces mouse-movement and sends it to a Robot to execute this mouse-movement. Let's call the interface defining this layer MouseTarget (fits your example nicely):
public interface MouseTarget {
    int getTargetX();
    int getTargetY();

    default void moveMouseHere(Robot robot) {
        robot.moveMouse(this.getTargetX(), this.getTargetY());
    }
}

This interface represents one mouse-movement to one target. As you see the moveMouseHere(Robot robot) method expects a Robot to send the movement to (which does the actual work). Now, all what is left is to adapt your Fields enum:
public enum Fields implements MouseTarget {

    AGE_FIELD(778, 232), NAME_FIELD(662, 280);

    public int targetX;
    public int targetY;

    Fields(int targetX, int targetY) {
        this.targetX = targetX;
        this.targetY = targetY;
    }

    @Override
    public int getTargetX() {
        return targetX;
    }

    @Override
    public int getTargetY() {
        return targetY;
    }
}

Comment: Modifier 'public' is redundant for interface methods
Answer: As you may want to have several implementations of Robot, I would clearly not proceed as you do, I would rather provide a Robot instance to the methods of your enum instead of implementing the interface Robot, it would then be much more flexible and easier to test.
The enum Field
public enum Field {

    ...

    public String moveMouse(Robot robot) {
        return robot.moveMouse(x, y);
    }

    public String clickLeft(Robot robot) {
        return robot.clickLeft();
    }
}

Even if it is not strictly the Strategy pattern, it is globably the same approach.


Inverse of the $n$-by-$n$ matrix $(a_{jk})$ where $a_{jk} = \binom{j-1}{k-1}$

Question: I have an interesting problem which can be solved by Induction and Gaussian Elimination, but due to the nice structure of the matrix, I think there can be many more approaches.
Here's the problem :

Let $$ A = (a_{jk})_{n \times n} $$
where $\displaystyle a_{jk} = \dbinom{j-1}{k-1}$ (by convention, this is $0$ for $k>j$).
Prove that
$$ A^{-1} = ((-1)^{j+k} a_{jk})_{n \times n} $$

The small alphabets along with subscripts denote the element of the $j^{\text{th}}$ row and $k^{\text{th}}$ column of the matrix.

I think this problem might have deep links to theorems of linear algebra due to the nice structure of inverse. I'm specifically seeking an answer that makes such a connection.

Thanks in advance.
Comment: aren't those the matrices associated to the maps induced by $x \mapsto x \pm 1$ on the space of polynomials of degree less than $n$ ?
Comment: When asked to prove one matrix is the inverse of another, just check their product is the identity. In this case, you only need prove a combinatorial identity.
Comment: @Henry:  OK, had a brief look.  It seems the answer of Meow has it pretty well covered, but I'll give it some thought and if I can add anything else, I'll post.  Thanks again.  Cheers!
Comment: @J.G. That's not what I'm looking for. How would you derive it and what's the reason for this neat expression. I'm thinking it is related to some theorem of Linear Algebra.
Comment: How to understand $a_{jk}$ if $k>j$, for example $2 \choose 4$ ?
Comment: @Widawensen I'm using the usual convention that $\dbinom{n}{r} = 0$ if $r>n$.
Comment: @Henry ok, I see... so the matrix is lower triangular with 1's on diagonal.. determinant must be 1 ..
Comment: @Henry I think you'll want to combine the triangular nature of $A$ with a combinatorial simplification of the cofactors of $A$ to compute the inverse directly.
Comment: @mercio I don't know about that. Can you elaborate it as an answer?
Answer: Here are three methods (3 is a strictly worse proof than 1, but it's amusing):

Combinatorics: Rearrange
$$a_{ij}a_{jk}=(-1)^{j+k}\binom{i-1}{j-1}\binom{j-1}{k-1}=(-1)^{k+j}\frac{(i-1)!}{(i-j)!(j-k)!(k-1)!}$$
and to be clearer, set $\alpha=i-1,\beta=j-1,\gamma=k-1$. Then we want
$$\delta_{\alpha \gamma}=\sum_\beta (-1)^{\alpha+\gamma} \binom{\alpha}{\alpha-\beta, \beta-\gamma, \gamma}=\pm \binom{\alpha}{\alpha-\gamma, 0, \gamma}\pm \binom{\alpha}{\alpha-\gamma-1, 1, \gamma}\pm \cdots$$
But this is $(-1)^\gamma$ times the number of monomials in
$$(-x+y-z)^\alpha$$
with $z$-term $z^\gamma$. That is, it is the $z^\gamma$ coefficient of
$$(-1+1-z)^\alpha$$
i.e. it is $\delta_{\alpha \gamma}$.
mercio's observation: Consider the vector space of polynomials in $x$ with degree less than $n$. Then the linear map $x\to x+1$ sends
$$x^k\longrightarrow x^k+\binom{k}{1}x^{k-1}+\cdots+x^0$$
so with respect to basis $e_k=x^{k-1}$, it has matrix
$$\left(\binom{i-1}{j-1}\right)_{i,j}$$
Similarly, its inverse $x\to x-1$ has matrix
$$\left((-1)^{i+j}\binom{i-1}{j-1}\right)_{i,j}$$
Jacobi's formula: Recall that if $M$ is a matrix and $M(t)=M+tE_{\alpha \beta}$ (add $t$ to the $\alpha,\beta$ entry), then
$$\frac{d \det(M(t))}{d t}=\left( \text{adj}(M)\right)_{\beta, \alpha}$$
In this case, $\det (A)=1$, so in particular, $\text{adj}A=A^{-1}$. One can show that
$$\det(A+tE_{ij})=1+(-1)^{i+j}t\binom{j-1}{i-1}$$
which gives
$$(A^{-1})_{i,j}=(\text{adj}(A))_{i,j}=\frac{d \det (M+tE_{ji})}{dt}=(-1)^{i+j}\binom{i-1}{j-1}$$

To prove the determinant formula, look at the matrix $A+tE_{ij}$:

The green line are the $1$'s on the diagonal and the green dot has coefficient $t$. The white is zero and the grey is mess. Its determinant is the same as the determinant of the small red square's. The red square is zoomed in to on the left:

The term in the determinant sum not including the green dot is  $1$. The term involving it is $(-1)^{i+j} t \det T^{ij}$, where $T^{ij}$ is the matrix with the green column and row removed. Calculate $\det T^{ij}$ by considering which row of the last column (the pink dot) is summed over:
$$\det T^{i,j}=\pm \binom{j-1}{i-1} \pm \cdots \pm \binom{j-1}{i-1+n}\det (T^{i,n+i})\pm \cdots \pm \binom{j-1}{j-2}\det (T^{i,j-1})$$
since the lower blue box has determinant $1$, and the upper, $\det (T^{i,n+i})$. By induction,
$$\det T^{i,j}=\pm \binom{j-1}{i-1} \pm \cdots \pm \binom{j-1}{i-1+n}\binom{i-1+n}{i-1}\pm \cdots \pm \binom{j-1}{j-2}\binom{j-2}{i-1}$$
But (after following the signs) this is just a sum of the form as in $(1)$, with a $\binom{j-1}{i-1}$ term missing! Thus
$$\det T^{i,j}=\binom{j-1}{i-1}$$
Comment: your method 3 gives a result that is way too strong to be true. $\det(M+tE_{ij})$ has more then two terms.
Comment: @mercio I've corrected it, and it seems better now.


WLOG Assumption in Hoeffding's inequality proof: $||a||_2 = 1$

Question: I am reading a book where it proves Hoeffding's inequality for symmetric Bernoulli distribution (r.v $X$ takes values -1 or 1 with probabilities $\frac{1}{2}$ each.
The theorem says:
Let $X_1, X_2, \dots, X_N$ be independent symmetric Bernoulli random variables, and let $a = (a_1, \dots, a_N) \in \mathbb{R}^N$. Then for any $t \geq 0$ we have
$$ \mathbb{P} \left\{ \sum_{i=1}^{N} a_i X_i \geq t \right\}  \leq \exp\left(- \frac{t^2}{2||a ||^2_2}\right)$$
The proof begins with: "We can assume without loss of generality that $||a||_2 = 1$. I have some vague understanding of why we can assume this WLOG but struggling to communicate it in concrete way. For now, my thought process is following:
We can divide both side inside LHS by $||a||_2$ and write the above inequality as following:
$$\mathbb{P} \left\{ \sum_{i=1}^{N} \frac{a_i}{||a||_2} X_i \geq \frac{t}{||a||_2} \right\}  \leq \exp\left(- \frac{1}{2}\left(\frac{t}{||a||}\right)^2\right)$$
Substituting $\frac{a_i}{||a||_2} = b_i$ and $t' = \frac{t}{||a||}$, we get following:
$$ \mathbb{P} \left\{ \sum_{i=1}^{N} b_i X_i \geq t' \right\}  \leq \exp\left(- \frac{t'^2}{2}\right)$$
But verbally how should I explain why this WLOG is valid?hoe
Comment: If you're just asking what the underlying property is... note that the inequality is of the form $f(a,t) \leq g(a,t)$ where both $f,g$ are homogeneous of the same order (which is the property you used in your justification)
Comment: I would say either just "scale invariance" or "since both left and right hand sides are unchanged when  $t$ and the $a_i$s are rescaled..."
Answer: Suppose that the inequality
$$
\tag{*}\mathbb{P} \left\{ \sum_{i=1}^{N} a_i X_i \geq t \right\}  \leq \exp\left(- \frac{t^2}{2 }\right)
$$
holds for all $t\geq 0$ and all $a_1,\dots,a_N$ such that $\sum_{i=1}^Na_i^2=1$.
Now let $a_1,\dots,a_N\in\mathbb R$ and $t\gt 0$. We want to prove that
$$\tag{**}\mathbb{P} \left\{ \sum_{i=1}^{N} a_i X_i \geq t \right\}  \leq \exp\left(- \frac{t^2}{2||a ||^2_2}\right).$$
If $\sum_{i=1}^Na_i^2=0$, there is nothing to prove, since all the involved terms are zero.
If $\sum_{i=1}^Na_i^2\neq 0$, we can indeed (as said in the opening post) deduce (**) from (*) by applying the latter inequality to $\widetilde{a_i}=a_i/\sqrt{\sum_{j=1}^Na_j^2}$ and $ \widetilde{ t}=t/\sqrt{\sum_{j=1}^Na_j^2}$.


Does SVM suffer from curse of high dimensionality? If no, Why?

Question: While I know that some of the classification techniques such as k-nearest neighbour classifier suffer from the curse of high dimensionality, I wonder does the same apply to the support vector machines (SVM)?
I can imagine SVM would only have to take dot products of support vectors and a feature vector to classify a new data point, so it might not suffer from curse of dimensionality. But what about non-linear SVMs?
Answer: SVM also suffers the problems coming from high dimensionality, but under typical settings to a lesser degree compared to (say) LDA.

I can imagine SVM would only have to take dot products of support vectors and a feature vector to classify a new data point, so it might not suffer from curse of dimensionality.

This is not the reason for being affected by high dimensionality. High dimensional data affects the identification of support vectors themselves.
Under high dimensional + low sample-size contexts a lot of interesting things start happening. For SVM one such thing is that a lot of data points will become support-vectors at the same time. This most likely will not be the property of the data, hence SVM will be over-fitted.
One way to check for over-fitting in high dimensional data is to see how the points are distributed after the projection. If you find that the points from both classes accumulate right on the margin - then your classification rule is most likely affected.
For more in detail explanation and an example of affected SVM result, see figure 1 from this paper:
J. S Marron, Michael J Todd & Jeongyoun Ahn (2007) Distance-Weighted
Discrimination, Journal of the American Statistical Association, 102:480, 1267-1271, DOI: 10.1198/016214507000001120


Accept incoming traffic from loadbalancer as ingress, but send traffic originating from host to default gateway

Question: Setup
I have Linux virtual machines running on google cloud platform that are behind an external TCP forwarding loadbalancer.
The loadbalancer works by forwarding TCP traffic to healthy instances as-is (without modifying the IP addresses). To ensure traffic forwarded by the loadbalancer is accepted by the VMs, Googles guest-agent will by default add entries to the local routing table with the equivalent of this command:
ip route add to local LOADBALANCERIP/32 dev eth0 proto 66

Current behavior
While this accomplishes the main goal of accepting forwarded traffic, it has one disadvantage: TCP connections originating from the targeted instances to the loadbalancer IP never leave the instance as the IP is in the local routing table.
Wanted behavior
Is it possible (using routing, iptables or other means) to accept incoming TCP connections while also allowing outgoing traffic to go to the loadbalancer?
The reason I would want to do this is as follows:
Consider a service running on the targeted instances (kubernetes control plane in my case) that is targeted by the loadbalancer. There are also other programs running on the same instances which need to connect to a healthy instance of the service. For HA purposes, I would like to ensure that other programs running on the same instance can route traffic to healthy instances of the service. Using the current configuration, traffic for the main service will always be routed locally, even if the local service instance is unhealthy.
Solutions evaluated
One solution I considered is using a proxy loadbalancer instead. This has other disadvantages (only allowing a narrow set of ports being the main problem).
Comment: Why would you connect from the targeted instances to the load balancer? Why do you want outgoing traffic to go to the loadbalancer?
Comment: One instance where the instance needs to connect out to the loadbalancer is this: The kubernetes apiserver should be running on the instances. To deploy kubernetes, I use `kubeadm join` to add additional control plane nodes. During the join process, kubeadm will attempt to connect to the control plane while the local host is not yet a healthy kubernetes node.
Comment: @Malt3 your issue resolved?
Comment: @AbhijithChitrapu since a few days ago, Google allows using any port for proxy loadbalancers. So this is what I ended up using instead. The original issue still remains.
Answer: ip route add to main LOADBALANCERIP/32 dev eth0 proto 66

Comment: Please provide additional details and context on your answer.


Why do the Yankees and Mets usually have opposite home/away schedules?

Question: I never realized this until both teams played home series on 9-10 June 2015 (and continuing on 11 June 2015, for the Mets), but apparently when the Yankees play at home the Mets play away, and vice-versa. What's the reason for this? And has it always been this way? What about when the Dodgers and Giants were located here?
Comment: In football, teams from the same cities tend to have opposite home/away schedules as well. This has to do with spreading police deployment, separating away fan streams and safety issues regarding hooliganism.
Comment: TV schedule is also important.
Comment: @Braamstruik when you say football you mean what Americans would call soccer, right?
Comment: @Braamstruik That sounds like an answer to me :-)
Comment: I find that interesting.  In Chicago it is definitely not the case; Cubs and White Sox are very mixed in terms of their schedules (at least for the next month and a half, and in my past memory).
Comment: Yes, as is standard on this website. Americans are the only ones who play football with their hands ;)
Comment: Well, the only ones who do so legally...
Comment: @joe, doesn't look that way to me. Cubs and Sox only shared 8 home dates during the 2015 season.  Very similar to the other 2-team markets.
Answer: I can find little official as to why they play opposite.  Many possible reasons exist; the most logical seems simply to make it so the maximum total games can be attended by those who are fans of both teams (I'm sure there are a few), and in particular businesspeople who take out visitors or clients to games are most likely to have a game available to take their clients to.
I'm not sure that the other reasons givem by @Braamstruik in the comments really apply to baseball; Shea Stadium and Yankee Stadium are not particularly close, and police presence at baseball games is fairly minimal at most times (compared to the size of the total NYPD force, anyway), though perhaps it is a consideration.  Chicago does not have this concept of home and away alternation with its two teams; the Cubs and White Sox regularly play at home on the same day, though they do usually have home openers on different days than each other.
The only real discussion I've found online of this topic is articles about the 2013 Home Opener which was for the first time since the 1950s held on the same day for both teams.  Reasons for that occurence were that with the 15 team league and interleague play, it was more difficult to keep that aspect of scheduling.
As far as the other part of the question; during the period of 1903-1957, there were three teams in New York (the Yankees, the Dodgers, and the Giants), and so they certainly could not have had consistently played a similar schedule, though I imagine they didn't very often have all three playing home dates on the same day (just by coincidence if not by intent).
Comment: The major difference in Chicago vs NY is that the Cubs and White Sox have 100+ year history in the same town, occasionally with a third team.  Mets were a new team in the 1960s.  Perhaps there was some part of the agreement to form the Mets that they would not play at the same time, which didn't occur in the early eras?
Comment: Chicago appears to counter-schedule as much as any other city/region with multiple teams.  2015 shared only 8 home games (5th lowest of any pair of teams).  2016 shared only 8 home games (lowest of any pair of teams).
Comment: What you say about the police force makes sense to me. I didn't really think that had anything to do with it. Still, if it has to do with maximizing the availability of home games, it's strange that Chicago doesn't follow suit with New York. I wonder how much influence each city's leaders have over their teams' schedules (if any) -- you'd think that the same people who make the schedules for both cities' teams would use the same reasoning in both cities and be consistent!
Answer: I honestly believe it's to reduce heavy traffic. There would be a lot of congested traffic on the roads at the same time coming and going to the games. NYC isn't very big and all the roads eventually have some sort of connection.
Comment: "NYC isn't very big"??? Have you been there? The stadiums are not particularly close.


Drupal Coding D7 - Taxonomy - How do I establish the hierarchy and associated fields for taxonomy terms?

Question: Reviewing the code in Taxonomy.module I determined the array to define a taxonomy terms as:
 'taxonomy_term' => array(
      'label' => t('Taxonomy term'),
      'controller class' => 'TaxonomyTermController',
      'base table' => 'taxonomy_term_data',
      'uri callback' => 'taxonomy_term_uri',
      'fieldable' => TRUE,
      'entity keys' => array(
        'id' => 'tid',
        'bundle' => 'vocabulary_machine_name',
        'label' => 'name',
      ),
      'bundle keys' => array(
        'bundle' => 'machine_name',
      ),
      'bundles' => array(),
      'view modes' => array(
        // @todo View mode for display as a field (when attached to nodes etc).
        'full' => array(
          'label' => t('Taxonomy term page'),
          'custom settings' => FALSE,

Assigning the correct info in the array and calling taxonomy_save_term($term); creates the term, but I have not unearthed the method or array fields necessary to define the hierarchy and attach data fields.
Are there additional array key/values to identify the parent/children and fields?
Are the fields attached to a term in a separate operation after the term is created?
What array keys are required to create the term?
Answer: Here is an example:
// create the Foo vocabulary
$vocabulary = new stdClass();
$vocabulary->name = "Foo Name";
$vocabulary->machine_name = "foo_vocab";
$vocabulary->description = "Foo Description";
taxonomy_vocabulary_save($vocabulary);
// annoyingly taxonomy_vocabulary_save doesn't return any information about the vocabulary
$voc_vid = db_query("SELECT v.vid FROM {taxonomy_vocabulary} v WHERE v.machine_name = 'foo_vocab'")->fetchField();
$terms = array(
  'bar',
  'bat',
);
foreach ($terms as $term_name) {
  $term = new stdClass();
  $term->vid = $voc_vid;
  $term->name = $term_name;
  taxonomy_term_save($term);
}

Comment: Thanks, but this does not address the issue of term hierarchy or fields.
Answer: A taxonomy term is an entity in Drupal 7 so adding field data is exactly the same as adding it to a node, e.g.
$term = new stdClass;
$term->name = 'Term Name';
$term->vid = $vocab_id;
$term->field_some_field[LANGUAGE_NONE][0]['value'] = 'A value';
taxonomy_term_save($term);

The hierarchy is handled separately to this, in the taxonomy_term_save() function. All you need to do is add the parent term ID (tid) to the $term object before you save it, like so:
$term->parent = $parent_tid;

For multiple parents you would pass an array instead:
$term->parent = array($parent_tid_1, $parent_tid_2);


How to add a message to the "Preview" in Drupal?

Question: With a CCK form that any user is able to acccess at the bottom there is a "Preview" button that allows the user to preview the changes they make and scrolling down below the preview shows them the form/fields they can edit.
For large forms with input there is not a clear message that says that the original form they filled out is below the preview... how can I add a message at the top of the Preview that says "Scroll down below the preview to edit the form you submitted?"
Comment: for best result post it on drupal.stackexchange.com
Answer: I assume that the FORM which you are using is of either BLOCK or PAGE or CUSTOM CONTENT type.
All you need to do is check out the .tpl.php file. In there you can Easily modify and display any type of content you want.
Just check out for the function which prints the Form and echo your message above that.


How to store this list as individual data's in Django database?

Question: I have a subprocess code like this:
final_list = subprocess.Popen(['ls', destination], stdout=subprocess.PIPE).communicate()[0].splitlines()

This returns the directory as a list:
['genelaytics', '__init__.py', '__init__.pyc', 'settings.py', 'wsgi.pyc']

Now I want to calculate the size of each file and insert the file as individual elements in database along with size and other attributes. I tried using for loop:
for list in final_list:
        st = os.stat(list)
        size = st.st_size
        b = File(file_name=list, source=test_url, start_date=start_date, end_date=end_date, size=size)
        b.save()

I am getting this error while running the above code:
Traceback:
File "/usr/local/lib/python2.6/dist-packages/django/core/handlers/base.py" in get_response
  111.                         response = callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/contrib/auth/decorators.py" in _wrapped_view
  20.                 return view_func(request, *args, **kwargs)
File "/home/zurelsoft/workspace/genelaytics/fileupload/views.py" in sync
  94.         st = os.stat(list)

Exception Type: OSError at /sync/
Exception Value: [Errno 2] No such file or directory: '__init__.py'

Answer: You're passing just the filename (i.e.'__init__.py'), not the full path (i.e. '/module/__init__.py') to os.stat()
I suggest doing something like so:
>>> folder = '/Python27/Doc'
>>> files = os.listdir(folder)
>>> for filename in files:
    fullname = os.path.join(folder, filename)
    print fullname, os.path.getsize(fullname)

/Python27/Doc\python27.chm 5754439

Comment: Thanks for your answer. It helped. I have a problem with database insertion though. It inserts all the data many times.
Comment: My pleasure. Could you write up your problem in a new question?
Answer: you need to prepend the base directory location (os.dirname(__file__) ... (probably)) ,to the filename before you stat it ...


Calculating PDF from Autocorrelation

Question: I have a statement like this;

A zero mean Gaussian random process $X(t)$ is wide sense stationary with the auto-correlation function $R_x(\tau) = 4e^{-2|\tau|}$

And I want to find the probability density function of this $X(t)$...
So I started with the definition of auto-correlation function;
$$R_x(\tau) = E\left[X(t_1)X(t_2)\right]$$
$$R_x(\tau) = \int\limits_{-\infty}^{+\infty}\int\limits_{-\infty}^{+\infty}{X(t_1)X(t_2).f_{{X_1}{X_2}}(x_1, x_2;t_1, t_2)dx_1dx_2}$$
Since $X(t)$ is a WSS process, $X(t_1) = X(t_2)$
$\therefore$
$$4e^{-2|\tau|} = \int\limits_{-\infty}^{+\infty}\int\limits_{-\infty}^{+\infty}{X^2.f_{{X_1}{X_2}}(x_1, x_2;t_1, t_2)dxdx}$$
$$\frac{\dfrac{d^2}{dx^2}\left(4e^{-2|\tau|}\right)}{X^2} = f_{{X_1}{X_2}}(x_1, x_2;t_1, t_2)$$
But since the differentiation always produces a zero, the PDF is calculated as zero. I'm pretty sure there's a problem with my steps. Can anyone point me the right direction? :) Thanks in advance!!
EDIT::: I thought about trying multivariate Gaussian distribution;
Since this process is WSS, we can say the auto-correlation function is the same as covariance matrix for the Gaussian. (Am I right?)
And then we have, $$C_X = \begin{bmatrix}4 & 4e^{-2}\\4e^{-2} & 4\end{bmatrix}$$
We also need the inverse of this
$$C_X^{-1} =\frac{1}{16(1-e^{-4})}\begin{bmatrix}4 & -4e^{-2}\\-4e^{-2} & 4\end{bmatrix}$$
The two variable Gaussian PDF is given by;
$$f_{X_1X_2}(x_1, x_2)=\frac{1}{2\pi\sqrt{det(C_X)}}e^{-\left(\frac{1}{2}X^TC_X^{-1}X\right)}$$
by substituting;
$$f_{X_1X_2}(x_1, x_2;t_1, t_2)=\frac{1}{2\pi\sqrt{16(1-e^{-4})}}e^{-\left(2x_1^2 + 2x_2^2-4x_1x_2e^{-2}\right)}$$
Is this the correct approach?
Comment: Your expression of $R_x(\tau)$ does not depend on $x$. Maybe $x$ should be a boundary of the integral (instead of $\pm \infty $)?
Answer: Since the process is Gaussian and one-dimensional, its probability density function (PDF) must be
$$f_X(x)=\frac{1}{\sqrt{2\pi}\sigma}e^{-\frac{(x-\mu)^2}{2\sigma^2}}\tag{1}$$
where $\mu$ is the mean, and $\sigma^2$ is the variance. From the problem statement we know that $\mu=0$, so we only need to find $\sigma^2$.
From the definition of the auto-correlation function we know that
$$R_x(0)=E[X^2(t)]=\sigma^2+\mu^2=\sigma^2\tag{2}$$
where the last equality follows from the fact that $\mu=0$. From $(2)$ and the given auto-correlation function we know that $\sigma^2=R_x(0)=4$, so we finally get for the PDF
$$f_X(x)=\frac{1}{2\sqrt{2\pi}}e^{-\frac{x^2}{8}}\tag{3}$$
Comment: So in my approach I tried to solve it for a two dimensional Gaussian process right? But sir when a random process has so many sub functions in it, how can we figure out if it's a single variable or multiple variables? Even in this case can't we think of it as two dimensional?
Comment: @Blogger: Your process is $X(t)$, so for each value $t$ you get a single value $X$, that's why its PDF must be one-dimensional. If you had a vector for each value $t$, you would get a multi-dimensional distribution.

Calculating PDF from Autocorrelation


Is there a metric space structure on $\mathbb Z$ such that the open sets are the subsets $S\subset \mathbb Z$ such that $\mathbb Z-S$ is finite?

Question: I really don't know how to go about answering this question.
$S$ is open if $\mathbb Z - S$ is finite. If $S$ is open then this also means that $\mathbb Z -S$ is closed. So, the closed sets are the finite sets. I recognize this as the finite complement topology. The open sets look like $\mathbb Z - \{x_1, x_2, \dots, x_n\}$ and all finite sets are closed.
But how does one define a metric given what the open sets are?
Comment: Where did you find this question? This is a topological space for sure, but I doubt if this is a metric space!
Comment: This is a sample UPenn prelim question.
Answer: Since $\mathbb{Z}$ isn't finite, the finite complement topology on $\mathbb{Z}$ isn't Hausdorff, hence the space isn't metrisable.
Comment: @AlJebr It's not hard to show that all metric spaces are Hausdorff, and likewise that the finite complement topology on an infinite set is not Hausdorff. This is largely just looking at the definition.
Comment: Probably, you should definitely find the theorem which states that any metric space is Hausdorff in there, as for the finite complement topology on an infinite set not being Hausdorff, all you need to show is that any pair of open sets always have nonempty intersection.
Comment: Is this a theorem? Can I find it in Munkres?


How to prove $\limsup_{k \to \infty} \sqrt[k]{|a_k|} = \limsup_{k \to \infty} \sqrt[k]{ \left |(k+1)a_{k+1} \right|}$

Question: I'm doing Problem II.9.3 in textbook Analysis I by Amann.

My attempt:
To prove that both series have the same radius of convergence. I need to show $$\limsup_{k \to \infty} \sqrt[k]{|a_k|} = \limsup_{k \to \infty} \sqrt[k]{ \left |(k+1)a_{k+1} \right|}$$
Because $$\limsup_{k \to \infty} \sqrt[k]{ \left |(k+1)\right|} = 1$$ I have to show $$\limsup_{k \to \infty} \sqrt[k]{|a_k|} = \limsup_{k \to \infty} \sqrt[k]{ \left |a_{k+1} \right|}$$
I'm stuck from here.
Could you please give me some hints to finish the proof? Thank you so much!

Update: Thanks to Botond's answer, I added the most important part here. All credits go to Botond.
Let $c = \limsup \sqrt[k]{|a_k|}$ and $d = \limsup \sqrt[k]{|a_{k+1}|}$.
For all $\varepsilon > 0$, there exists $N$ such that $\sqrt[k]{|a_k|} \le c + \varepsilon$ and $\sqrt[k]{|a_{k+1}|} \le d +\varepsilon$ for all $k \ge N$.
We have $|a_k| \le (c+\varepsilon)^{k}$, consequently $|a_{k+1}| \le (c+\varepsilon)^{k+1}$, and consequently $|a_{k+1}|^{1/k} \le (c+\varepsilon)^{(k+1)/k}$ for all $k \ge N$. Take the limit $k \to \infty$, we get $$d = \limsup \sqrt[k]{|a_{k+1}|} \le \limsup (c+\varepsilon)^{(k+1)/k} = c+\varepsilon ,\quad \varepsilon >0$$
Take the limit $\varepsilon \to 0$, we get $d \le c$.
We have $|a_{k+1}| \le (d+\varepsilon)^{k}$ and consequently $|a_{k+1}|^{1/(k+1)} \le (d+\varepsilon)^{k/(k+1)}$ for all $k \ge N$. Take the limit $k \to \infty$, we get $$c =\limsup \sqrt[k]{|a_{k}|} = \limsup \sqrt[k+1]{|a_{k+1}|} \le \limsup (d+\varepsilon)^{k/(k+1)} = d+\varepsilon ,\quad \varepsilon >0$$
Take the limit $\varepsilon \to 0$, we get $c \le d$.
As such, $c = d$. This completes the proof.
Comment: Hint: $x^{1/(k+1)} = (x^{1/k})^{k/(k+1)}.$
Comment: Hi @zhw, your hint lead me to https://math.stackexchange.com/questions/3343260/let-lim-k-to-infty-x-k-a-and-lim-k-to-infty-y-k-b-does-lim?noredirect=1&lq=1, which is out of my capability. I'm only at convergence section in my textbook. Could you please elaborate more?
Comment: Couldn't you just take a monotone subsequence that "goes to the sup" and then multiply and divide by the $(a_{k+1})^{\frac{1}{k+1}}$?
Comment: @tommy1996q but how to prove $\left(\frac{a_{k+1}}{a_k}\right)^{\frac{1}{k+1}} \to 1$?
Comment: If the limit of the sequence is bounded, that is a Cauchy sequence and you should be able to do that. If it is not bounded, then the original problem is easier
Answer: Continuing your work:
Let $c:=\lim\sup |a_n|^{1/n}$. Let $\varepsilon >0$ be given. Then we have that (for big enough $n$):
$$|a_n|\leqslant (c+\varepsilon)^n$$
This means that
$$|a_{n+1}|\leqslant (c+\varepsilon)^{n+1}$$
$$|a_{n+1}|^{1/n}\leqslant (c+\varepsilon)^{1+1/n}$$
I think you can finish this direction, and work out the other direction as well.
Comment: @LeAnhDung You're welcome. You can use similar argument a lot of time when you are dealing with $\lim \sup$ and $\lim \inf$. For example, when you are proving the Stolz-Cesàro theorem.
Comment: I'm unable to understand your reasoning. Could you please more more specific? This question inspires me to ask a related one [here](https://math.stackexchange.com/questions/3343260/let-lim-k-to-infty-x-k-a-and-lim-k-to-infty-y-k-b-does-lim/3343301?noredirect=1#comment6881651_3343301). If you don't mind, please have a look at it.
Comment: @LeAnhDung With my work, you can show that $\lim \sup |a_{n+1}|^{1/n} \leqslant \lim \sup |a_n|^{1/n}$. And I think you can get a similar inequality, but the other way around, which will imply that they are equal.
Comment: @LeAnhDung With my work, you can show that $\lim \sup |a_{n+1}|^{1/n} \leqslant \lim \sup |a_n|^{1/n}$. And I think you can get a similar inequality, but the other way around, which will imply that they are equal.
Comment: For big enough $n$, we have $|a_{n}|^{1/n}\leqslant c+\varepsilon$ and $|a_{n+1}|^{1/n}\leqslant (c+\varepsilon)^{1+1/n}$. I'm unable to understand how your proceed to show $\lim \sup |a_{n+1}|^{1/n} \leqslant \lim \sup |a_n|^{1/n}$. Please elaborate more!
Comment: @LeAnhDung the RHS is $(c+\varepsilon)(c+\varepsilon)^{1/n}$. The second term goes to one, so taking th $\lim \sup$ of both sides, the RHS will be $c+\varepsilon$. Since it's true $\forall \varepsilon >0$, we will get that the LHS is $\leqslant c$.
Comment: Thank you so much :))))))) I got your ideas and update my proof to reflect your answer.
Answer: Hint:
Prove that, if $\{u_n\}$ is a bounded non-negative sequence and $\{v_n\}$ is a non-negative sequence such that $\lim_{n\to\infty} v_n=v$.Then,
$\limsup_{n\to\infty}(u_nv_n)=v(\limsup_{n\to\infty} u_n)$
Comment: I know the property you mentioned, but I don't know how to apply it in this problem. Could you please be more specific?
Comment: The sequence $\{n^{\frac{1}{n}}\}$ is a convergent sequence which converges to $1$.Can you proceed from here?
Comment: I already used that property in my proof.


Prevent logged in users from seeing other registered users information

Question: I'm using Drupal 8 and I have a security requirement to prevent authenticated users from seeing other authenticated users' profiles.
I have a view which customizes the user profile page of each authenticated user. Each logged in user can see their own profile by accessing the path /user-profile/userId.
Now if the user decided to randomly change the userId in the URL, they cannot access other users' profiles, since, in the view I have set the 'Filter Criteria' to current user. Which works perfectly.
However, if a user decided to randomly change the userId in the path /user/userId they will have access to other users information. What I need to do is to prevent them from accessing /user/userId.
It's important to mention that the users are free to change their own information using the URL /user/userId/edit
Any suggestions?
Answer: You should change the permission for authenticated users.
Go to admin/people/permissions and under user permissions dissallow authenticated users to View user information
Comment: thank you, I hate how trivial that was, cheers


Let's get critical: Mar 2015 Site Self-Evaluation

Question: We all love Magento Stack Exchange, but there is a whole world of people out there who need answers to their questions and don't even know that this site exists. When they arrive from Google, what will their first impression be? Let's try to look at this site through the eyes of someone who's never seen it before, and see how we stack up against the rest of the 'Net.
The Site Self-Evaluation review queue is open and populated with 10 questions that were asked and answered in the last quarter.
Run a few Google searches to see how easy they are to find and compare the answers we have with the information available on other sites.
Rating the questions is only a part of the puzzle, though. Do you see a pattern of questions that should have been closed but are not? Questions or answers that could use an edit? Anything that's going really well? Post an answer below to share your thoughts and discuss these questions and the site's health with your fellow users!
Answer: Final Results

Can't Add Child Block to product_list

Net Score: 20 (Excellent: 20, Satisfactory: 7, Needs Improvement: 0)

Making a purchase without Shipping or Payment. Follow up Invoice with actual shipping costs

Net Score: 11 (Excellent: 13, Satisfactory: 10, Needs Improvement: 2)

Proper use of <slow_backend> for local.xml implementation

Net Score: 8 (Excellent: 11, Satisfactory: 10, Needs Improvement: 3)

Doubt Regarding Magento Subdomain Creation

Net Score: 2 (Excellent: 6, Satisfactory: 15, Needs Improvement: 4)

Pass session and location between two sub-domains?

Net Score: 1 (Excellent: 6, Satisfactory: 14, Needs Improvement: 5)

Magento 2 backend errors

Net Score: 1 (Excellent: 6, Satisfactory: 12, Needs Improvement: 5)

Cannot update page template for <review_product_list />

Net Score: -2 (Excellent: 5, Satisfactory: 12, Needs Improvement: 7)

How to create an admin grid with non auto increment field?

Net Score: -2 (Excellent: 4, Satisfactory: 14, Needs Improvement: 6)

recently viewed products not showing for guest users

Net Score: -13 (Excellent: 2, Satisfactory: 8, Needs Improvement: 15)

Create a custom index with product information

Net Score: -19 (Excellent: 1, Satisfactory: 3, Needs Improvement: 20)
Answer: recently viewed products not showing for guest users => Close. Typical case of not checking google. Answer contains a link to here even, that should've come up when posting the question.


Motivated by Level Sets, how can I show that minimizing this functional is equivalent to this PDE?

Question: I would like to show, that minimizing the functional
$$F(g)=\alpha\int_\Omega |\nabla g(x)|^2dx+\mu \int_\Omega (g(x)-f(x))^2dx $$
is equivalent to solving the differential euqation
$$-\alpha\nabla g(x)+\mu g(x)=\mu f(x),\qquad x\in\Omega$$
$$\frac{\partial}{\partial \nu}g(x)=0,\qquad x\in\partial\Omega$$
wheren $\Omega=[0,1]^2$ and $\frac{\partial}{\partial \nu}g(x)$ is the normal derivative of $g$. I started by computing the first variation of $F$ and found
$$\frac{d}{d \varepsilon}F(g+\varepsilon\bar{g})|_{\varepsilon=0}=\int_\Omega 2\alpha \nabla g\nabla \bar{g}+2\mu g\bar{g}\ dx-2\mu\int_{\Omega}f\bar{g}\ dx \overset{!}{=}0$$
Is this correct so far? How can I apply Green's identities here to find the differetnial equation?
Answer: There must be a typo in the equation, since $\nabla g\in \Bbb R^n$, and $f,g\in\Bbb R$, so dimensionally the equation does not make sense. It should be
$$-\alpha\Delta g+\mu g=\mu f.$$ The boundary condition depends on which space you want to minimize the functional over, lets assume it is $V=\{v\in H^1(\Omega):\frac{\partial v}{\partial\nu}=0\}$, this space is affine, so the problem makes sense (Mazur's lemma states that a closed and convex set is weakly closed). You have found that for all $\overline{g}\in V$,
$$\int_\Omega 2\alpha\nabla g\cdot\nabla\overline{g}+2\mu g\overline{g}-2\mu f\overline{g}\,dx=0.$$
Noting that $\overline{g}\in V$, the divergence theorem tells us that $$\int_\Omega 2\alpha\nabla g\cdot\nabla\overline{g}\,dx=-2\alpha\int_\Omega\overline{g}\Delta g\,dx,$$
so we have
$$\int_\Omega (-2\alpha\Delta g+2\mu g-2\mu f)\overline{g}\,dx=0\quad\forall\overline{g}\in V.$$
The fundamental lemma of the calculus of variations tells us that the integrand must be zero (at least in a distributional sense) and so we have the PDE.
Comment: yes! sorry for the typo. This is exactly the step I was missing, thanks!


Is there a kind of "reference manual" for Z3

Question: I played around with Z3 after reading the excellent tutorial at https://www.rise4fun.com/Z3/tutorial. But now I would like to get an overview over all commands available in Z3's dialect of SMTLIB2.
Unfortunately I only found reference manuals for the different languages bindings, but not for SMTLIB2 itself.
Answer: You can read all about SMTLib in http://smtlib.cs.uiowa.edu/
In particular, the document http://smtlib.cs.uiowa.edu/papers/smt-lib-reference-v2.6-r2017-07-18.pdf is the "official" document on all SMTLib commands.
For logics, you want to browse: http://smtlib.cs.uiowa.edu/logics.shtml
Now, this document is not Z3 specific. But to a large extent, it captures all the SMT commands/logics supported by Z3, and Z3 is one of the most "compliant" solvers out there in terms of implementing the specs. There are a few differences of course: For instance, the spec never talks about optimization and Z3 does support that, likewise for set operations and a few other "extras." As Malte pointed out the documentation for these are available, but maybe not easy to navigate. My favorite links are:

https://ericpony.github.io/z3py-tutorial/guide-examples.htm (Python specific, but also tons of info on Z3 features.)

Programming in Z3: https://theory.stanford.edu/~nikolaj/programmingz3.html This is a wonderful document detailing how z3 works internally with most of its features demonstrated. Again, it uses Python, but for the most part you can find the corresponding commands in SMTLib more or less directly.

API documentation in various languages: https://z3prover.github.io/api/html/index.html Eventually you'll need these as you get to program z3; but you can keep this as a "reference" only for later use.

If there is a specific piece of info you're looking for that's not covered in one of these documents, then that's what this forum is for! Best of luck..
Comment: Not exactly what I hoped to get but nevertheless very useful...
Answer: I'm not aware of any such reference manual, browsing the source code is probably your best option currently.
I might of course be wrong regarding the existence of such a manual, but the fact that questions regarding Z3's SMT-LIB dialect are often asked via the Z3 issue tracker (e.g.#4549, #4536, #4460), suggests that there is no reference manual. The developers' responses also do not hint at any such manual.