Suspended (exception RuntimeException) When I click a button that opens a new class with a new layout

Question: My app recently started throwing a "Suspended (exception RuntimeException)" I think I might have accidentally messed with some code but I cant pinpoint the problem.
This is my log chat when I click on the breakfast button.

04-14 17:54:15.941: ERROR/AndroidRuntime(6099): FATAL EXCEPTION: main
  04-14 17:54:15.941: ERROR/AndroidRuntime(6099): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.merch.dine/com.merch.dine.myMenu}: java.lang.ClassCastException: android.widget.ImageButton
  04-14 17:54:15.941: ERROR/AndroidRuntime(6099):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2737)
  04-14 17:54:15.941: ERROR/AndroidRuntime(6099):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2753)
  04-14 17:54:15.941: ERROR/AndroidRuntime(6099):     at android.app.ActivityThread.access$2500(ActivityThread.java:129)
  04-14 17:54:15.941: ERROR/AndroidRuntime(6099):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2107)
  04-14 17:54:15.941: ERROR/AndroidRuntime(6099):     at android.os.Handler.dispatchMessage(Handler.java:99)
  04-14 17:54:15.941: ERROR/AndroidRuntime(6099):     at android.os.Looper.loop(Looper.java:143)
  04-14 17:54:15.941: ERROR/AndroidRuntime(6099):     at android.app.ActivityThread.main(ActivityThread.java:4701)
  04-14 17:54:15.941: ERROR/AndroidRuntime(6099):     at java.lang.reflect.Method.invokeNative(Native Method)
  04-14 17:54:15.941: ERROR/AndroidRuntime(6099):     at java.lang.reflect.Method.invoke(Method.java:521)
  04-14 17:54:15.941: ERROR/AndroidRuntime(6099):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
  04-14 17:54:15.941: ERROR/AndroidRuntime(6099):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
  04-14 17:54:15.941: ERROR/AndroidRuntime(6099):     at dalvik.system.NativeStart.main(Native Method)
  04-14 17:54:15.941: ERROR/AndroidRuntime(6099): Caused by: java.lang.ClassCastException: android.widget.ImageButton
  04-14 17:54:15.941: ERROR/AndroidRuntime(6099):     at com.merch.dine.myMenu.onCreate(myMenu.java:36)
  04-14 17:54:15.941: ERROR/AndroidRuntime(6099):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
  04-14 17:54:15.941: ERROR/AndroidRuntime(6099):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2701)

Here is the debug info on the thread

Thread [<1> main] (Suspended (exception RuntimeException))
      ActivityThread.performLaunchActivity(ActivityThread$ActivityRecord, Intent) line: 2659
      ActivityThread.handleLaunchActivity(ActivityThread$ActivityRecord, Intent) line: 2753
      ActivityThread.access$2500(ActivityThread, ActivityThread$ActivityRecord, Intent) line: 129
      ActivityThread$H.handleMessage(Message) line: 2107
      ActivityThread$H(Handler).dispatchMessage(Message) line: 99
      Looper.loop() line: 143
      ActivityThread.main(String[]) line: 4701
      Method.invokeNative(Object, Object[], Class, Class[], Class, int, boolean) line: not available [native method]
      Method.invoke(Object, Object...) line: 521
      ZygoteInit$MethodAndArgsCaller.run() line: 868
      ZygoteInit.main(String[]) line: 626
      NativeStart.main(String[]) line: not available [native method]

here is my java file with the button that causes the crash
public class EnglishOne extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //FIXED LANDSCAPE
        setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

        //FULLSCREEN
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setContentView(R.layout.english1);

        //button breakfast
        Button bBreakfast1 = (Button) findViewById(R.id.breakfast1);

        bBreakfast1.setOnClickListener(new View.OnClickListener() {
            public void onClick(View V) {
                startActivity(new Intent("com.merch.dine.BREAKFASTONE"));
            }
        });
    }
}

This is the activity that the button should start with a blank xml layout
public class breakfastone extends Activity {

    public void OnCreate(Bundle breakfastone) {
        super.onCreate(breakfastone);
        setContentView(R.layout.breakfast1);
    }
}

Answer: Never mind. I circumvented my problem by using XML to set the onClick function and then coded my java file to change the content view when the function is called.
Xml button specific code;
<ImageButton android:id="@+id/button1"
    android:layout_height="160dip"
    android:layout_width="285dip"
    android:onClick="switchLayer"
    android:src="@drawable/icon"
    android:layout_x="285dip"
    android:layout_y="481dip">
</ImageButton>

Java Button specific code;
public void switchLayer(View view) {
    // Button1 switches layout
    setContentView(R.layout.layer2);
}


Como alterna entre Lista e Galeria

Question: O que pretendo criar, é semelhante a Grid view utilizado em sistemas do tipo Mercado Livre. Seria uma função feito em javascript que alterna entre uma Lista ou Galeria, utilizando os mesmos dados em forma de tabela.

Expondo a dúvida - Suponho mostrar screenshot de jogos em flash com suas respectivas informações a frente, em modo Lista. Contudo se o usuário não deseja ver em modo Lista, após o clique no botão, como agrupa-los novamente dentro da página em modo Galeria?

Então, estou buscando num só código fazer as duas coisas distintas, algo como:
if(condição)
{
     ...
    Lista
     ...
   }else{
     ...
    Grade
     ...
}

A princípio, imagino que poderia ser divs retangulares que, ao clicar no botão elas redimensiona o tamanho para quadrados, pondo-se lado a lado.
Comment: Não faço ideia do que é um código ou função "Lista/Galeria"... podes explicar melhor?
Answer: Diego, defina os elementos que serão exibidos em cada grupo, no exemplo abaixo eu chamei o grupo de card e cada card possui uma imagem, titulo e desc.
então defina o espaço onde as card vão ser exibidas, no exemplo abaixo estou limitando o espaço delas pela div#container.
defina uma classe para cada tipo de exibição, novamente vamos utilizar apenas lista e grid, mas você pode definir quantos modelos desejar.
defina um tamanho para a card para cada disposição do container, no exemplo abaixo temos:
div#container.lista: .card{ width: calc(100% -10px); height: 128px; }
div#container.grid: .card { width: 192px; height: 192px; }

agora faça o mesmo para possicionar cada elemento (div.image, div.title, div.desc) da card na posição correta.
agora basta trocar a classe da div#container para mudar o layout.

var container = document.querySelector(".container");
var disposicao = document.querySelector("#disposicao");
var curClass = container.classList.contains("lista") ? "lista" : "grid";

disposicao.addEventListener("change", function (event) {
  container.classList.remove(curClass);
  curClass = disposicao.value;
  container.classList.add(curClass);
});
html, body {
  position: relative;
  width: 100%;
  height: 100%;
  margin: 0px;
  padding: 0px;
  background: whitesmoke;
}

.container {
  position: absolute;
  max-width: 1080px;
  padding: 5px;
  margin: auto;
  top: 0px;
  right: 0px;
  left: 0px;
  bottom: 0px;
  background: white;
  box-shadow: 0px 0px 10px black;
  box-sizing: border-box;
  overflow: auto;
}

#disposicao {
  width: 100%;
}

.card .imagem  {
  background-image: url('http://image005.flaticon.com/1/png/512/119/119706.png');
  background-size: calc(100% - 10px);
  background-repeat: no-repeat;
  background-position: center;
}

.lista .card {
  position: relative;
  margin: 5px;
  width: calc(100% - 10px);
  height: 128px;
  box-shadow: 0px 0px 5px black;
  border-radius: 3px;
}

.lista .card .imagem {
  position: absolute;
  top: 0px;
  left: 0px;
  width: 128px;
  height: 128px;
  border-right: 1px solid silver;
  background-color: whitesmoke;
}

.lista .card .title {
  position: absolute;
  top: 0px;
  right: 0px;
  left: 128px;
  height: 32px;
  line-height: 32px;
  padding-left: 5px;
  border-bottom: 1px solid silver;
}

.lista .card .desc {
  position: absolute;
  top: 32px;
  right: 0px;
  bottom: 0px;
  left: 128px;
  padding: 5px;
}

.grid .card {
  float: left;
  position: relative;
  margin: 5px;
  width: 192px;
  height: 320px;
  box-shadow: 0px 0px 5px black;
  border-radius: 3px;
}

.grid .card .imagem {
  position: absolute;
  top: 0px;
  left: 0px;
  width: 192px;
  height: 192px;
  border-bottom: 1px solid silver;
  background-color: whitesmoke;
}

.grid .card .title {
  position: absolute;
  top: 192px;
  height: 32px;
  width: 192px;
  line-height: 32px;
  padding-left: 5px;
  border-bottom: 1px solid silver;
}

.grid .card .desc {
  position: absolute;
  top: 222px;
  bottom: 0px;
  width: 192px;
  padding: 5px;
}

    <select id="disposicao">
      <option value="lista">Lista</option>
      <option value="grid">Grid</option>
    </select>

Title

Descrição

Title

Descrição

Title

Descrição

Title

Descrição

Title

Descrição

Title

Descrição

Answer: Em continuidade, a reposta de Tobias Mesquita que mostrou ser prático na forma como um List/Grid view se comporta, no que diz à respeito a elementos estilizados com CSS.
Não podia eu, ficar sem compartilhar a minha resposta como sempre faço. E quando o faço, é para deixar claro que alcancei o objetivo.
Neste caso, pondo o exemplo da resposta dada acima sobre teste em alguns navegadores obsoleto, houve algumas falhas(entre um caso e outro, estava o CSS ou Javascript a não funcionar conforme o esperado), já que alguns navegadores de internet não suporta tal semântica moderna.
Cheguei a conclusão de que seria viável escrever um novo código compativel com diversos Navegadores de Internet(antigos e atuais), reaproveitando particularidades do conceito dado na resposta de Tobias Mesquita.
Em função disto, utilizei o Firefox 2.0 como base. Vejamos o código abaixo:

    function changeSrc(id){

    var el=document.getElementsByTagName('div')[0]; var imagem=document.getElementById(id); if(imagem.alt == "Abrir"){ imagem.src = "http://sl.uploads.im/t/yx4Ig.png"; imagem.alt = "Fechar"; el.className = "grade"; } else { imagem.src = "http://sm.uploads.im/t/sRShv.png"; imagem.alt = "Abrir"; el.className = "lista"; } }

/* Aqui inicializa a estilização do layout "Lista" */ .item img { width:100px; height:100px; position:absolute; top:50%; left:50%; margin-top:-50px; margin-left:-50px; } .lista .item { position: relative; margin: 5px; width: 100%; height: 128px; box-shadow: 0px 0px 5px black; border-radius: 3px; } .lista .item .foto { position: absolute; top: 0px; left: 0px; width: 128px; height: 128px; border-right: 1px solid silver; background-color: whitesmoke; } .lista .item .nome { position: absolute; top: 0px; right: 0px; left: 128px; height: 32px; line-height: 32px; padding-left: 5px; border-bottom: 1px solid silver; font-weight: bold; display: block; font-size: 14pt; } .lista .item .desc { position: absolute; top: 40px; right: 0px; bottom: 0px; left: 128px; padding: 5px; display: block; font-size: 12pt; } /* A partir daqui, é a estilização do layout "Grade" */ .grade .item { float: left; position: relative; left: 90px; width: 192px; height: 320px; box-shadow: 0px 0px 5px black; border-radius: 3px; } .grade .item .foto { position: absolute; top: 0px; left: 0px; width: 192px; height: 192px; border-bottom: 1px solid silver; background-color: whitesmoke; } .grade .item .nome { position: absolute; top: 192px; height: 32px; width: 192px; left: 0px; line-height: 32px; padding-left: 5px; border-bottom: 1px solid silver; font-weight: bold; display: block; font-size: 14pt; } .grade .item .desc { position: absolute; top: 222px; bottom: 0px; width: 192px; left: 0px; padding: 5px; display: block; font-size: 12pt; }

A

Titulo

Descricao

B

Titulo

Descricao

C

Titulo

Descricao

D

Titulo

Descricao

E

Titulo

Descricao

F

Titulo

Descricao

G

Titulo

Descricao

H

Titulo

Descricao

Enfim, quando você projeta com CSS precisa ter a habilidade de analisar o layout e decidir como colocar as div.
Foi por causa desta minha dificuldade em racionar div que fiz à pergunta.
Este outro exemplo abaixo, é ainda menor e portátil se comparado ao anterior.
A única diferença entre um e outro, fica por conta da estrutura CSS e Javascript. Veja:

function ativar(tag) {
    var el = document.getElementsByTagName('div');

    for (var i=0; i < el.length; i++) {
        if (el[i].className == "menos") {
            document.getElementById("clic").innerHTML = "Grade";
            el[i].className = "mais";
        } else {
            document.getElementById("clic").innerHTML = "Lista";
            el[i].className = "menos";
        }
    }
}
    /* Ajusta para o modo Lista(Tabela) */

    .mais {
        width: auto;
    }

    /* Ajusta para o modo Grade(Galeria) */

    .menos {
        width: 128px;
    }

    /* Estiliza o Menu(botão) */

    a:link {
        text-decoration: underline;
    }

    a:visited {
        color: navy;
        text-decoration: none;
    }

    a:hover {
        color: dodgerblue;
        text-decoration: none;
    }

    a:active {
        color: azure;
        text-decoration: underline;
        background-color: dodgerblue;
    }

    /* Fim Estilização do Menu */

    /* Estilização do Corpo da Página */

    * {
        margin: 0;
        padding: 0;
    }

    /* Estiliza o Parágrafo da Descrição */

    p {
        line-height: 20px
    }

    /* Estiliza os bloco de conteudo */

    #bloco {
        margin-left: 5%;
        float: left;
        left: 65%;
    }

    /* Estiliza os blocos que mantém as figura */

    #figura {
        background: whitesmoke;
        text-align: center;
        padding: 20px;
        margin: 5px;
        float: left;
    }

    /* Estiliza os blocos que mantém as figura */

    #conteudo {
        text-align: left;
        padding: 0px;
        margin: 5px;
        left: 35%;
    }

    Lista

Titulo 1

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque sodales ultricies venenatis.

Titulo 2

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque sodales ultricies venenatis.

Titulo 3

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque sodales ultricies venenatis.

Titulo 4

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque sodales ultricies venenatis.

Titulo 5

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque sodales ultricies venenatis.

Titulo 6

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque sodales ultricies venenatis.

Titulo 7

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque sodales ultricies venenatis.

Titulo 8

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque sodales ultricies venenatis.

Titulo 9

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque sodales ultricies venenatis.

Titulo 0

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque sodales ultricies venenatis.

O código em si esta bem comentado e são auto-explicativo, não havendo qualquer dúvida, termino por aqui.

Como alterna entre Lista e Galeria


Why did the release statement here crashes the app?

Question: NSError *theError = nil;
NSArray *keys = [NSArray arrayWithObjects:@"password", @"userId", nil];
NSArray *objects = [NSArray arrayWithObjects:passwordTextField.text, userNameTextField.text, nil];
NSDictionary *requestDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];

NSString *JSONString =[requestDictionary JSONRepresentation];
NSData *JSONData =[JSONString dataUsingEncoding:NSUTF8StringEncoding];
NSLog(@"JSONString :%@", JSONString);
NSLog(@"JSONData :%@", JSONData);

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://184.108.40.206/11AprP306/passenger/jsonitem"]];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:JSONData];
[request setHTTPMethod:@"POST"];

NSURLResponse *theResponse =[[NSURLResponse alloc]init];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&theResponse error:&theError];
NSLog(@"response : %@", theResponse);
NSLog(@"error : %@", theError);
NSLog(@"data : %@", data);
NSMutableString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"string: %@", string);
[string release];
//[theResponse release]; // this statement crashes the app

Has it got something with to do with this statement :NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&theResponse error:&theError];
I see a & symbol used. What does it means?
Answer: I'll post this as a new answer as you edited your question.
You are doing it the wrong way.
It is the responsability of sendSynchronousRequest:returningResponse:error: to create the response for you (or the error if something went wrong)
This is why you need to pass a pointer to theResponse and a pointer to theError
When the call to sendSynchronousRequest:returningResponse:error: is done, theResponse will be created and most importantly autoreleased (by sendSynchronousRequest:returningResponse:error) !!
So in the end you are back to the autorelease/over release issue.
The correct code is:
NSURLResponse *theResponse = nil; // no need to init it will be done later on
NSError *theError = nil; // no need to init either
NSData *data = [NSURLConnection sendSynchronousRequest:request
                                     returningResponse:&theResponse
                                                 error:&theError];

if (aError != nil) { } // handle error
else {} // handle your response data

//no need to release theResponse

Answer: Well, you autorelease theResponse when you instantiate it, so releasing it twice is causing your problem.  Either don't make the autorelease call or don't make the release call.
Personally, I'd get rid of the autorelease.  release gives finer-grained control over the run of your program.
Oh, and the & there is nothing to worry about -- it just passes the address of the variable it proceeds.  In this case, you need to pas an NSURLResponse**.  Since you have an NSURLResponse*, you pass a reference to it.
Comment: sorry, the autorelease statement was not suppose to be there. I added in to solve the problem.
Answer: This is because theResponse has sent the message autorelease in:
NSURLResponse *theResponse =[[[NSURLResponse alloc]init] autorelease];

If you release an object that has been autoreleased you will cause your application to crash for the Garbage Collector will over release the object.
The & simply means "give me the address of theError and theResponse (basically you are passing a pointer of pointer which is required by the method sendSynchronousRequest:returningResponse:error:)
+ (NSData *)sendSynchronousRequest:(NSURLRequest *)request
                 returningResponse:(NSURLResponse **)response
                             error:(NSError **)error

The NSURLResponse ** and NSError ** means 'address of address' so give them only theError or theResponse (without the &) would simply give the method 'their address' when it is expecting something else.
Comment: Sorry, the autorelease statement was not suppose to be there. I added in to solve the problem
Comment: I just wanted to know why if I called release method manually instead, it will crashes.
Comment: ok i understand then you are doing it the wrong way i will post the correct answer but you should mention that you have edited your question in the question itself because now, someone getting into your problem will not understand our previous answers


Cholesky Shock - Interpretation of logs in IRF Models

Question: I came across a few articles here and there that conclude:
When the data (say variables X, Y) for an impulse response function are on log level, the y-axis depicts the % response of Y to a 1% shock by X.
Broadly speaking, I think the shocks in an IRF are one SD Choleski shocks, where the y-axis reflects responses in the units of the dependent variable.
However, can someone explain (mathematically or not) why using logs automatically implies the interpretation of % impulses and % shocks? And: Why do some source say that log value responses are "approximately equal to" the percent change?
Thank you!
Answer: If you logarithmize the dependent variable, you will get approximately % changes, see Why is it that natural log changes are percentage changes? What is about logs that makes this so?
We know that the vcv matrix $\Omega$ of the error term can be factorized into $\Omega = ADA'$ with $D$ being a diagonal matrix (and $D$ is the vcv matrix of the "structual innovations"). Alternatively, we can factorize $\Omega$ by the Choleski decomposition into $\Omega = PP'$ where $P$ is lower triangular. So, we have $\Omega = ADA' = PP'$ and moreover,
$$
ADA' = \underbrace{AD^{0.5}}_{=P}\underbrace{(D^{0.5})'A'}_{=P'}
$$
so $P$ has the standard deviations of the structual innovations on its principal diagonal. Without loss of generalization, one can set the standard deviations of the structural innovations to 1 (i.e. $D = I$). Triangular factorization and Choleski Decomposition are then equal. That is, the interpretation of the Choleski Decomposition changes to: "If $y_{jt}$ is increased by "standard deviation of the $j$th structural innovation" units (but we just set the standard deviation to one and the units are given by %, see the link above), $y_{t+s}$ changes by $\Psi_sp_j$ units (but again, since we use logs the units are %)" ($p_j$ denotes the $j$th column of $P$)


understanding a statement in Gill, Murray and Wright "Practical Optimization"

Question: Hi: I'm reading the book "Practical Optimization" and there's a part in Chapter 3 that
I can't prove to myself but I'm sure it's true. On page 64, they define the Taylor expansion of $F$ about $x^{*}$:
(3.3) $F(x^{*} + \epsilon p) = F(x^{*}) + \epsilon p^{T}g(x^{*}) + \frac{1}{2} \epsilon^2 p^{T} G(x^{*} + \epsilon \theta p)p$ where $g$ is the gradient of $F$ and $G$ is the Hessian of $F$.
They want to prove that a necessary condition for $x^{*}$ to be a local minimum of
$F$ is that $g(x^{*}) = 0 $. i.e: $x^{*}$ is a stationary point.
They proceed using a contradiction argument as follows. Assume that $x^{*}$ is a local minimum of $F$ and that it is not a stationary point. If $g(x^{*})$ is non-zero, then there must exist a vector $p$ for which (3.4) $p^{T}g(x^{*}) < 0$. Any vector that satisfies(3.4) is called a descent direction at $x^{*}$. This is fine so far.
It is the next statement that I don't see. The statement is "Given any descent direction $p$, there exists a positive scalar $\bar\epsilon$ such that for any positive $\epsilon$ satisfying $\epsilon \le \bar\epsilon$, it holds that
$\epsilon p^{T}g(x^{*}) + \frac{1}{2} \epsilon^2 p^{T} G(x^{*} + \epsilon \theta p)p < 0$.
I'm wondering how this statement can be proven. It's obvious to the authors and probably others but not to me. Thanks.
Answer: Divide the inequality by $\epsilon$. Then for $\epsilon\to0$ the left-hand side tends to $p^Tg(x^*)<0$. (Assuming that $G$ is continuous).
Thus, there is $\bar\epsilon$ such that the expression is negative for all $\epsilon\in(0,\bar\epsilon)$.
Comment: Very nice. Thank you daw. I checked the answer.


How to change the size of the browser window when running the FirefoxWebDriverProvider in JBehave Web

Question: We're using JBehave Web to drive our selenium test suite for a new project and really like the Etsy.com example available on JBehave, especially the Java/Spring maven archetype as this fits in with our architecture.
The biggest problem so far has been documentation, which is why I'm posting here in the hopes that I can get some help from others in a similar situation.
It looks like JBehave Web only provides a "FirefoxWebDriverProvider" class and no corresponding one for Chrome. Has anyone else run into this problem? Have you written your own ChromeDriverProvider?
Also, we need to change the size of the browser that comes up by default and I can't seem to find a way of doing that during the bootstrapping of the test run.
We're using the Maven archetype: jbehave-web-selenium-java-spring-archetype which uses the jbehave-maven-plugin and the "run-stories-with-annotated-embedder" goal so we're using the "Annotated" method of extending the InjectableEmbedder.
If anyone can provide some guidance, I'd really appreciate it, even if just pointers to more examples.
Comment: JBehave does provide Chrome but you have to load the Chrome binary somehow (or use SauceLabs).  I'm still trying to figure out how it works.  Hey, I started a local grid on 4444 and I am running JBehave-Web Jetty server but when I load a story from that spring Etsy example, it doesn't run.  How did you do it?
Answer: How To Resize Window
webDriverProvider.get().manage().window().setSize(new Dimension(width, height));

You can easily find code like this by navigating through the code. If you are using Eclipse, Open Declaration and Quick Type Hierarchy options are everything you need.
How to Use Chrome Driver
You can use TypeWebDriverProvider or PropertyWebDriverProvider. For instance:
new TypeWebDriverProvider(ChromeDriver.class);

Comment: We ended up finding this Chrome Driver and it's been working great: http://code.google.com/p/chromedriver/wiki/GettingStarted.

It can take a parameter when it is bootstrapped to start in maximized mode and also exposes the capability to add extensions when it starts up.
Comment: @GinoFilicetti Chrome Driver downloads have been moved to http://chromedriver.storage.googleapis.com/index.html
Comment: The Code "Window resizing" works perfect for me. I do not understand why or when the part in "ChromeWebDriverProvideer" is needed.
Comment: @leo The question also mentions the use of Chrome instead of Firefox. I'll update the answer to make it clearer.
Answer: This should work:
driver.manage().window().setSize(new Dimension(800, 621));

Answer: What jokka said is correct, justr a side note: Before resizing window, I always put it to top left corner, so I know that WebDriver can "see" everything:
driver.get().manage().window().setPosition(new Point(0, 0));

Obviously, the driver above is assumed healthy instance of WebDriverProvider
Answer: We ended up finding this Chrome Driver and it's been working great. It can take a parameter when it is bootstrapped to start in maximized mode and also exposes the capability to add extensions when it starts up.
Comment: That's the Chrome driver that everyone uses.  http://chromedriver.storage.googleapis.com/index.html
Answer: driver.Manage().Window.Size = new Size(x, y);

This works fine for me. The x and y are in a feature file.
Answer: Try this:
This is working fine for me.
Capybara.current_session.driver.browser.manage.window.resize_to(1800, 1000)


Ocultar campo no HTML com Bootstrap

Question: Como posso fazer com que um campo de texto em meu HTML fique oculto quando o usuário estiver visualizando pelo celular e apareça quando ele estiver visualizando pelo PC?
Comment: Neste caso voce vai ter que suar javascript para alterar a classe do elemento.
Answer: Utilize as classes de responsividade do Bootstrap
http://getbootstrap.com/css/#responsive-utilities-classes
No seu caso, utilizar as classes hidden-xs para ocultar algo na resolução mobile e visible-xs para mostrar apenas em resolução mobile.

    Elemento oculto para mobile

    Elemento visível para mobile e oculto nas demais resoluções

Configuração das resoluções no Twiter Bootstrap

lg - Dispositivos grandes (desktops, >= 1200px)
md - Dispositivos médios (desktops, >= 992px && < 1200px)
sm - Dispositivos pequenos (tablets, >= 768px && < 992px)
xs - Dispositivos extra pequenos (smartphones, < 768px)

Poderá combinar os prefixos hidden- ou visible- com qualquer uma das tags de resolução acima.
Comment: Pedro, nesse caso eu tenho que definir a resolução que ele deve ocultar ou existem algum mecanismo que identifica a resolução como sendo de um celular?
Comment: @KleberNunes alterei a resposta explicando cada tag.
Comment: Cara, se não fosse as frameworks, fazer uma coisa dessa ia ser muuito chato
Comment: Também acho mas graças aos frameworks acabei aprendendo mais e ficando independente deles para esses tipos de coisas.

Ocultar campo no HTML com Bootstrap


Export to CSV, with wrap characters and skip headers

Question: Is there a way to export Excel to a csv file that wraps EVERY cell in " and skips the headers? Save-as .csv is not the answer I am looking for.
I am looking for a way to do this from within excel if it is possible. Not a coding solution. Thanks
Answer: Assuming you have your data in Sheet1, the best non-VBA solution I can think of is to add a second sheet and enter a formula in A1 like the following:
<code>=""""&Sheet1!A1&""","""&Sheet1!B1&""","""&Sheet1!C1&""""
</code>
Then copy that down for as many rows as you have in Sheet1.  You need to extend this formula for as many columns as you have as well.
This will give you a single column looking like the CSV file format you want.  You would then save that page as a text file.
Answer: Assuming your data starts in the activesheet at cell A1 with a first header row, the attached code should write it to a csv file to your specs.
<code>Sub WriteToCSV()

Const forReading = 1, forAppending = 3, fsoForWriting = 2
Dim fs, objTextStream, sText As String
Dim lLastRow As Long, lRowLoop As Long, lLastCol As Long, lColLoop As Long

Set fs = CreateObject("Scripting.FileSystemObject")
Set objTextStream = fs.opentextfile("c:\temp\myResult.csv", fsoForWriting, True)

lLastRow = Cells(Rows.Count, 1).End(xlUp).Row
lLastCol = Cells(1, Columns.Count).End(xlToLeft).Column

For lRowLoop = 2 To lLastRow
    sText = ""
    For lColLoop = 1 To lLastCol
        sText = sText & Chr(34) & Cells(lRowLoop, lColLoop) & Chr(34) & ","
    Next lColLoop

    objTextStream.writeline (Left(sText, Len(sText) - 1))
Next

objTextStream.Close
Set objTextStream = Nothing
Set fs = Nothing

End Sub
</code>
Comment: another option to loop through all used cells is

    `For Each cell In ActiveSheet.UsedRange.Cells`

then use `cell.row` to check if you need to add a EOL character
Comment: I am looking for a non-coding answer. Something you can do from within Excel if that is possible. I will edit my question for clarity.


Moment maps unitary group acting on matrices

Question: I am reading the fifth chapter of "An introduction to extremal Kaehler metrics" by Gabor Szekelyhidi. At the very beginning of that chapter, the author describes moment maps and Hamiltonian action. Here is a short description:
Suppose that a connected Lie group $G$ acts on a Kaehler manifold $M$ preserving the Kaehler form $\omega.$ The derivative of the action gives rise to a Lie algebra map
$$ \rho: \mathfrak{g} \rightarrow \mathfrak{X}(M)$$
Where $\mathfrak{g}$ is the Lie algebra of $G$ and $\mathfrak{X}$ is the algebra of vector fields on $M.$ Then the action of $G$ on $M$ is said to be Hamiltonian if there exists a $G-$equivariant map
$$ \mu: M \rightarrow \mathfrak{g}^{*} $$
such that for any $\xi \in \mathfrak{g}$ the function $\langle\mu, \xi\rangle$ is a hamiltonian function for the vector field $\rho(\xi):$
$$ d\langle\mu, \xi\rangle = -\iota_{\rho(\xi)} \omega. $$
I got stuck with the following exercise:
Let $M_n$ be the set of $n \times n$ complex matrices equipped with the Euclidean metric under the identification $M_n=\mathbb{C}^{n^2}.$ The unitary matrices $U(n)$ act on $M_n$ by conjugation, preserving this metric. I.e. $A \in U(n)$ acts by $M \mapsto A^{-1}MA.$ Find a moment map $\mu: M_n \rightarrow \mathfrak{u}(n)^{*}.$
So far, I've just noticed that if $n=1$ then the action of $U(1)$ by conjugation on complex number is the trivial action, what will be then the moment map? I am trying to see what happens also in dimension 2. I know that $\mathfrak{u}(2)$ is generated by skew-Hermitian matrices, so every skew-hermitian matrix can be diagonalized and the eigenvalues must be pure imaginary. How to find a moment map in this case?
Comment: A definition of the moment map would be useful for those not enough fluent with the subject.
Comment: Your moment map for the 1-dimensional case does not work. In fact, it does not even make any sense - do you know what the Lie algebra looks like?
Comment: the Lie algebra of U(1) is just the real line or the real line multiplied by the imaginary unit. Why it does not make sense?
Comment: Yes, the Lie algebra is a 1-dimensional real vector space, and so is its dual. How can $\mu(z)=z$ make any sense?
Comment: You are totally right, I will edit my post right now
Comment: So, regarding the 1-dimensional case: the action is trivial, and this means that the vector field corresponding to any element in the Lie algebra is the zero vector field. Hence, the zero map seems like a promising candidate.
Answer: Ok, so first, you should know what is the Kähler metric that you are defining on the space $M_n$. Since it is not specified, I will assume it is the induced by the standard hermitian product $$h(A,B)=Tr(AB^\dagger)$$, where $B^\dagger$ denotes the adjoint (that is the transpose conjugate) of $B$.
This of course has associated a scalar product
$$ g(A,B)=Re(Tr(AB^\dagger))$$
and a symplectic form
$$ \omega(A,B)=-Im(Tr(AB^\dagger))$$
(the minus sign here is just a convention).
As you noted, there $U(n)$ acts symplectically on $M_n$ via $A\mapsto U^\dagger A U$. Now, to see how the infinitesimal associated action $\mathfrak{u}(n)\rightarrow M_n$ is, just compute
$$
\rho_X(A)=\left.\frac{d}{dt}\right|_{t=0}(e^{-Xt}Ae^{Xt})=-XA+AX=[A,X].
$$
Now we want to find a moment map $\mu:M_n \rightarrow \mathfrak{u}(n)^{\ast}$ for this action. To do this we will identify $\mathfrak{u}(n)$ with its dual using the pairing given by the hermitian metric, that is
$$
\langle X,Y \rangle = Tr(XY^\dagger).
$$
Therefore, I claim that the momentum map is given by the mapping $\mu:M_n \rightarrow \mathfrak{u}$ such that $$\mu(A)=\tfrac{i}{2}[A,A^\dagger].$$
Now note that
$$
f_X(A)=\langle \mu(A),X \rangle =  \tfrac{i}{2} Tr([A,A^\dagger]X),
$$
so (check this out)
$$
df_{X,A}(Y)=\left.\frac{d}{dt}\right|_{t=0}f_X(A+tY)= \tfrac{i}{2}Tr([Y,A^\dagger]X+[A,Y^\dagger]X).
$$
Now, using the cyclic property of the trace ($Tr(ABC)=Tr(BCA)=Tr(CAB)$), is easy to check that this is indeed
$$
df_{X,A}(Y)=-Im(Tr([X,A]Y^\dagger))=\omega([X,A],Y)=-\omega(\rho_X(A),Y).
$$
So $\mu$ is indeed a moment map for this action.
This example is indeed very useful, for example, to find the moment map that gives Hitchin equations for Higgs Bundles, check out Section 4 on Hitchin's paper "The self-duality equations on a Riemann surface" if you want to read more about this.
Comment: Thanks for your very interesting answer. I noticed that during your carrying out the exercise, you claimed that the moment map has to have such a form (you write down the equation) and finally you checked that it satisfies the required condition. I was wondering if there is a way to understand the form of the moment map by using its definition property. It seems to me that in general it's not so obvious to give the exact form of the moment map and then check that it satisfies the properties. I hope that you get what I mean.
Comment: @John117 I understand that what you are asking is why one would know beforehand what the moment map should be. In this particular case I guess one can just deduce it easily as in the cited Hitchin's paper (page 78). I really do not think I can give a satisfying answer for the general case... However, at least in examples coming from classical mechanics, moment maps are obtained as the conserved quantities yielded by Noether's theorem.


Vue-i18n Integration by vee-validate not working as described in the documentation

Question: Hello I did a copy/paste from the vee-validate documentation into this codesandbox and I get no validation message - just the following error on the console:
[vue-i18n] Cannot translate the value of keypath 'validations.messages._default'. Use the value of keypath as default.

Is it a bug within vue-validate , vue-i18n, vuejs ? Or should one configurate it somehow different?
Answer: you forgot to initialize i18n
After
const i18n = new VueI18n();

add this line
i18n.locale = "en";

this line tells i18n what the language it should look for, and merges all  your translations (that you can have in a json file) with the veevalidator translations of the given language
Comment: You are right about the line - it works! Thanks a lot!
But it is the documentation who forgot it not me :) - I did just copy and paste without knowledge of how it exactly works
Comment: @AlexanderMihailov .. o yes.. the veevalidator is really good, but it's documentation is very incomplete


Recriar os elementos HTML de uma Div para outra Div pela ClassName

Question: Bom, alguns vão me sugerir utilizar o cloneNode(true) do Javascript para fazer um appendChild(var) no DOM.
Mas para este caso, ja utilizei deste recurso nativo, mas não atendeu a minha necessidade. Por que, quando faço um clone fiel de seu filho no DOM, o CSS que deveria estilizar todo seus elementos perde-se, não define em nada.
Então acredito, que recuperando seus atributos com o laço for seja o ideal para replicar novamente os elementos. Veja o que tenho tentado:

var str = document.getElementById('nome').value;

if (document.getElementsByClassName(str)) {

        document.getElementById('B').innerHTML = '';

var figura = document.body.getElementsByTagName('img');

var evento = document.body.getElementsByTagName('a');

        for (var i in figura, evento) {

            var image = figura[i];
            var titulo = image.className;
            var endereco =  image.src;

            var clic = evento[i];
            var link = clic.href;

            if ((titulo == str) || (clic == this.link)) {
                var xerox = image.innerHTML;
                 var copia = endereco.innerHTML;

                 var clique = link.innerHTML;
             document.getElementById('B').innerHTML = '

';
             }
         }
}
#A {
    float : right;
    width : 115px;
    height : 400px;
    overflow: auto;
    padding  : 10px;
    border : thin solid silver;
}

#B {
    overflow-x: auto;
    overflow-y: hidden;
    width : 400px;
    height : 100px;
    padding  : 10px;
    border : thin solid silver;
}

#B p {
    padding : 10px;
    margin : 0 auto;
    cursor : pointer;
    display : inline-blinkk;
    display : inline;
    vertical-align : top;
}

<input type="hidden" id="nome" value="foto"/>

O detalhe fica por conta de replicar somente as className cujo o valor(foto) esta definido neste input type='hidden' id='nome' posto no exemplo.
A div id="A" esta na vertical, simboliza uma playlist no projeto real, e ja div id="B", esta na horizontal alinhado a esquerda onde simboliza elementos relacionados quando escolhido pelo clique na playlist. Ambas tem papel distintos, regras CSS diferentes.
Por isso da questão. Não posso reutilizar o CSS da div id="A" por div id="B".
Answer: Segue como resposta o snippet da Pergunta agora corrigido e em perfeito funcionamento. Veja:

var resultado = document.getElementById('B');

var str = document.getElementById('nome').value;

if (document.getElementsByClassName(str)) {

var figura = document.getElementsByTagName('img');

var evento = document.body.getElementsByTagName('a');

    for (var i in figura, evento) {

        var image = figura[i];
        var titulo = image.className;
        var endereco =  image.src;

        var clic = evento[i];
        var link = clic.href;

        if (titulo == str) {
         var xerox = image;
         var copia = endereco;

         var clique = link;
         resultado.innerHTML += '

'
            }
        }
}
#A {
        float : right;
        width : 115px;
        height : 400px;
        overflow: auto;
        padding  : 10px;
        border : thin solid silver;
}

#B {
        overflow-x: auto;
        overflow-y: hidden;
        width : 400px;
        height : 100px;
        padding  : 10px;
        border : thin solid silver;
}

#B p {
       padding : 10px;
       margin : 0 auto;
       cursor : pointer;
       display : inline-blinkk;
       display : inline;
       vertical-align : top;
}

<input type="hidden" id="nome" value="foto"/>


Show that $30$ divides $n^{5} - n$, where n is an integer

Question: I started to think about this problem and then factored $n^5 - n$ to $(n^2 - 1)(n^2 + 1)(n)$, and later to $(n-1)(n)(n+1)(n^2 + 1)$. I know that $(n-1)(n)(n+1)$ is divisible by $6$, but it is not that case $5$ divides $n^2 + 1$ for any integer $n$, so i can´t use the multiplication property. Can anyone help me finish this proof?
Comment: Also: [How to prove $n^5 - n$ is divisible by 30 without reduction](https://math.stackexchange.com/questions/132210/how-to-prove-n5-n-is-divisible-by-30-without-reduction) – all found instantly with [Approach0](https://approach0.xyz/search/?q=%24n%5E5%20-%20n%24&p=1)
Comment: $5$ doesn't have to divide $n^2+1$.  $5$ could divide $n$, or $n-1$ or $n+1$.  Can you prove that $5$ must divide one of those $4$ values?  Hint: How can $5$ *not* divide any of the $n, n+1, n-1$?  If $5$ divides non of those three, what possible remainder is there if you divide $n$ by $5$?
Answer: Hint:
$$(n^2-1)(n^2+1)n=(n^2-1)(n^2-4+5)n=\underbrace{(n-2)(n-1)n(n+1)(n+2)}_{\text{product of } 5\text{ consecutive integers}}+5n(n^2-1)$$
Comment: Thanks, it wasn´t hard after all.
Comment: @MateusBuarque, Welcome! **See also**: https://math.stackexchange.com/questions/12065/the-product-of-n-consecutive-integers-is-divisible-by-n-factorial
Comment: Oops, i made a mistake, i wanted to prove if it for 30, but this strategy still works.
Comment: @MateusBuarque, That's also done here using the link I have just shared
Answer: One of the other answers requires that you know something - the other is very clever. A hint for a proof that doesn't require either non-trivial theorems or cleverness: $n=5k+j$, where $j\in\{0,1,2,3,4\}$.
Answer: This is a particular case of fermats little theorem


What is the distribution of $\min(r_1, r_2)$?

Question:
If I have 2 uniform random numbers $r_1$ and $r_2$ in $[0,1)$, what is the distribution of $\min(r_1, r_2)$?

I have a problem I'm trying to get my arms around, and getting some context on this will help.
(BTW, my next step is to look at the minimum of a set of uniform randoms, $r_1$ to $r_n$, but this is my starting point.)
Comment: $P(\min(r_1,r_2)\geq x)=P(r_1\geq x,r_2\geq x)=P(r_1\geq x)P(r_2\geq x)$ if we assume that $r_1$ and $r_2$ are independent.
Comment: I don't know if it helps, but $$\min(r_1,r_2)=\frac12\bigl(r_1+r_2-|r_1-r_2|\bigr).$$
Answer: If $r_1, r_2$ $-$ independent random variables with uniform distribution on $[0,1)$, then it is easy to use geometric interpretation of probability.
Universal sample space  $\Omega$ for pair $(r_1,r_2)$ is the square $[0,1) \times [0,1)$.
Cumulative distribution function for random variable $r = \min \{r_1,r_2\}$ is
$F(r_0) = P(r\leqslant r_0) = \displaystyle\frac{{\rm mes}\;A(r_0)}{{\rm mes}\;\Omega}$,
where $A(r_0)\subset \Omega$ is the subset of $\Omega$, where $\min\{r_1,r_2\}\leqslant r_0$;
other words, complement of $A(r_0)$ is  $\overline {A(r_0)} = \{(r_1,r_2)\in\Omega: r_1>r_0, r_2>r_0\}$ .
In fact, $\overline {A(r_0)}$ is the square: $(r_0,1)\times (r_0,1)$.
So, ${\rm mes}\:A(r_0) = {\rm mes}\:\Omega - {\rm mes}\:\overline {A(r_0)} = 1 - (1-r_0)^2 = 2r_0 - r_0^2$.
Hence $F(r_0) = \displaystyle\frac{2r_0-r_0^2}{1} = 2r_0 - r_0^2$, if $r_0 \in (0,1)$.
Finally, cumulative distribution function is
$F(r) = \;\;\;\begin{array}{lll}
0, \;\;{\rm if}\;  r<0; \\
2r-r^2, {\rm if}\; r\in [0,1); \\
1, \;\;{\rm if}\; r\geqslant 1. \end{array}$
Probability density function is $f(r) = F'(r)$:
$f(r)= 2-2r$, if $r\in [0,1)$; and is zero-function outside.

(In the case of $(r_1, \ldots, r_n)$ we'll consider $\Omega$ as $n$-dimensional cube.
${\rm mes} A(r_0) = 1 - (1-r_0)^n$. )
Comment: Wonderful! Thank you very much!
Comment: BTW I was going down the n-cube path last night, in a much less formal way, but tripped over the math at the end (been too long). But your solution completes what I couldn't! So that's nice. FYI the application is one of making selections from a huge set. I want to figure out what will be the first item to grab, so I'll treat the space as a 60-million-dimension cube and use this to pick the first value, and then continue that way until I've made the number of selections I need. (I think I mixed up the analogy, but you've given me the piece I need to make it work :) )
Comment: In case you're interested, here's the application of your work. Thank you again! http://looselyconnected.wordpress.com/2013/04/09/sampling-a-lage-datasource-with-one-pass/
Comment: @RobY: Wow! Great. Thank you too.


Caching - techniques? suggestions? best practices?

Question: I have a website that will be using three (3) views slideshows on the landing page/front page. What are the best ways to set this up site to be able to load efficiently?  Should I start with a Pressflow site? Install and enable specific modules to improve performance? Use Boost? Are most of the caching modules and techniques related only to logged in users? Do I have to own my own server to do this well?
I am assuming that because there are so many slideshow instances loading at the same time that this will be a severe performance hit at loading.
Answer: In general, I'd recommend using boost if you don't have access to the command line of a server.  Boost creates a static HTML copy of the file inside a cache directory within your Drupal file structure.  It updates cached pages only when content changes.  It is used in conjuntion with the performance enhancement features of Drupal such as CSS and JQuery compression found under <code>/admin/settings/performance</code>.
If you have command line access I'd reccomend APC and memcache/memcached.  This takes a little more effort to set up, but is well worth it IMO.  There are plenty or resources on Drupal.org to help you to set up memcached.
You can also set basic caching on individual views as shown here:

 You'll see the option for caching 7th from the bottom.  There is also a similar option in panels if you use them.
These caching options are designed for end-users really, not specifically logged in users.  Indeed you may want caching disabled for logged in users if they are administrators and/or are making changes to the site.
Answer: Picking a caching strategy before you have even built the site is really getting ahead of yourself.  Ideally, you should get your site running as well as possible without caching, and then use advanced caching strategies to get extra performance.
Build the site, then optimize Apache, PHP, and MySQL for the memory footprint you are seeing.  This will likely mean getting APC up and running, as well as interpreting mysqltuner results.
Getting a good baseline for Apache, PHP, and MySQL can do wonders for performance w/o even needing to play with caching.  This is really important, because no matter what you do, you will have cache misses / clears, and you want the site to be acceptable under these circumstances.
Then profile your site, and see what your performance problems are.  Then address them one by one so you can figure out if you are actually solving a problem, or just bandaiding it.
Don't underestimate the standard caching used by core Drupal and modules that utilize Drupal cache.  Go through all of the setting pages and learn what they can do.
Additional strategies could involve Boost, Varnish, Memcache, or other additional modules.  But, there is no solution that fits all scenarios.  You need to profile and be able to measure whether you are making forward or sideways progress.
To address specific questions.
Pressflow can make a difference.  But the changes to session handling can be problematic, and the the way it handles PHP error reporting can take a little getting used to.  I typically start with Pressflow, so I am not fixing quirks after the fact (though some of my clients don't have problems when I develop against standard Drupal and then they deploy Pressflow).
You don't necessarily need your own server, but you should really have a VPS with true root.  Preferable, you want one from a place where you can scale memory/CPU easily and on-demand.  If you have true root you can think about if PostgreSQL or Zend Server CE makes sense.
Most Drupal-based caching strategies only take effect with anonymous users.  This is why a properly tuned instance is so important.
Comment: To be honest, I don't really care about the downvote.  I would edit the answer if there was incorrect information, though (which is one of the three valid reasons to downvote).  In my mind, the answer addresses the questions about best practices as well as other specifics that the OP inquired about, and are based on my experience with the consequences of implementing similar optimizations too early in a site's design.  The answer also provides enough information for the OP to do more research, or ask more directed questions, as this one was rather open-ended.
Comment: MPD, thanks for taking the time to answer so thoroughly. I am not as seasoned as I would like to be so your experience and analysis is not falling on deaf ears. I am moving to VPS soon as I am coming up against more complex site development and shared hosting is not very performant in some cases.
Comment: There are some great suggestions above albeit quite advanced.  I don't however see any harm in installing boost straight-away, because you can easily see the performance difference on a standard installation.  If you are going to set up a VPS, it may also be practical to install APC an Memcache at the same time and get all of the configuration done at the same time.  You can then switch them on and off to see the performance differences should you wish.
Comment: Is there anything factually incorrect about this answer to warrant a downvote?
Comment: You suggest he profile the site, but don't say how.
Comment: In addition you are negative about the fact that he is thinking about caching (what's wrong with that?) without going through the very advanced and long process that you suggest. You don't say exactly how he should technically do all of the things you suggest.  Answers should be more succinct, and if you are willing to edit it a bit I'll gladly up-tick it, as you know the up and down marking is reflective of a relevancy scale, and is not personal.
Answer: Most of the other answers are about general caching strategies, not tailored to your situation.
3 slideshows loading on one page will probably cause a slow-to-load page, but not because of anything at the server end - generating the HTML and Javascript will take hardly any time at all, but it will take a long time for the user to download all the images used in three slideshows.
The problem  here is the users's internet connection.
You can improve the user experience by using a slideshow script that progressively loads up slideshow images just before they are needed rather than before the slideshow starts. So choose your javascript slideshow carefully.
BTW having 3 slideshows on one page will probably result in a pretty horrible design. Talk to your designer about that...


Postfix SASL allow SMTP Authentication and relay messages

Question: I am trying to set my SMTP server so it allows only SMTP authenticated users to send emails but the actual sending is done via Mailjet.
I am running on Ubuntu 14.04 LTS and Postfix version is mail_version = 2.9.6
If client authenticates with credentials - they are verified (if they are invalid the message is rejected). But clients can still send mails if they don't authenticate.
Please note that I am trying to send emails to all domains. Not just restricted list.
How can I deny all non-authorized users?
main.cf
# See /usr/share/postfix/main.cf.dist for a commented, more complete version

# Debian specific:  Specifying a file name will cause the first
# line of that file to be used as the name.  The Debian default
# is /etc/mailname.
#myorigin = /etc/mailname

smtpd_banner = $myhostname ESMTP $mail_name (Ubuntu)
biff = no

# appending .domain is the MUA's job.
append_dot_mydomain = no

# Uncomment the next line to generate "delayed mail" warnings
#delay_warning_time = 4h

readme_directory = no

# TLS parameters
smtpd_tls_cert_file=/etc/ssl/certs/ssl-cert-snakeoil.pem
smtpd_tls_key_file=/etc/ssl/private/ssl-cert-snakeoil.key
smtpd_use_tls=no
smtpd_tls_session_cache_database = btree:${data_directory}/smtpd_scache
smtp_tls_session_cache_database = btree:${data_directory}/smtp_scache

smtpd_sasl_auth_enable = yes
smtpd_sasl_security_options = noanonymous
smtpd_sasl_local_domain = mail2.xxx.cz
broken_sasl_auth_clients = yes
#smtpd_tls_auth_only = no

smtpd_delay_reject = yes
#smtpd_client_restrictions = permit_sasl_authenticated, reject

smtpd_recipient_restrictions = permit_sasl_authenticated, reject_unauth_destination, permit_mynetworks, check_r$

#permit_mynetworks, permit_sasl_authenticated, defer_unauth_destination
#permit_sasl_authenticated,
#   reject_unauth_destination,
#   permit_mynetworks,
#   check_relay_domains

# See /usr/share/doc/postfix/TLS_README.gz in the postfix-doc package for
# information on enabling SSL in the smtp client.

myhostname = sweetparadise.cz
virtual_alias_maps = hash:/etc/postfix/virtual
virtual_alias_domains = domain1.cz domain2.cz domain3.cz
alias_database = hash:/etc/aliases
myorigin = /etc/mailname

relayhost = [in-v3.mailjet.com]:587

mynetworks = 127.0.0.0/8 192.168.137.1 [::ffff:127.0.0.0]/104 [::1]/128
home_mailbox=Maildir/

smtp_tls_security_level = encrypt

Comment: *But clients can still send mails if they don't authenticate.* ---> show the proof (i.e. by posting maillog entry when client send email)
Answer: So the problem was that I was using port forwarding from a windows host machine to a VM running the postfix. Therefore all traffic went through 192.168.137.1. This resulted in emails originating within permit_mynetworks so all were accepted.


Ordenar listas sem o sort

Question: Estou tentando resolver um exercício porém estou sem resultado algum por enquanto.
Sou novato na linguagem.
'''Defina uma função merge que faz o seguinte:
Dadas duas listas ordenadas L1 e L2,
retorna uma lista ordenada com todos os números de L1 e L2.
A função NAO deve usar o método sort do python.
Em vez disso, faça o seguinte:
* Crie um indice i1 para a lista L1 e um i2 para L2
* Inicialize i1 e i2 com 0
* Compare L1[i1] com L2[i2] e coloque o menor dos dois
na lista de resposta. Se o menor era L1[i1], aumente i1.
Caso contrário, aumente i2
* Assim, L1[i1] e L2[i2] são sempre os menores elementos
de L1 e L2, e um deles é sempre o proximo que deve entrar
na resposta
* Continue fazendo isso até adicionar todos os elementos
de L1 e L2 na resposta'''
Tentei fazer algo do tipo abaixo
<code>def merge(lista1, lista2):
    i1 = 0
    i2 = 0
    resposta = []
    lista = lista1 + lista2
    for num in lista:
        if num < lista2[i2]:
            resposta.append(lista1[i1])
            i1 += 1
        else:
            resposta.append(lista2[i2])
            i2 += 1
    return resposta
</code>
Comment: https://pt.stackoverflow.com/questions/252400/python-ordenar-listas-sem-o-sort
Vê se isto ajuda...
Comment: O nome disso é balance line, juntar duas listas já ordenadas.
Answer: O nome desse algoritmo é 'Balance Line', era algo costumeiramente implementado nos tempos do COBOL, onde os dados vinham ordenados de fitas magnéticas, creio eu.
<code>#!/usr/bin/env python3

def merge(lista1, lista2):
        i1 = 0
        i2 = 0
        resposta = []
        while True:
                if i1 < len(lista1) and i2 < len(lista2):
                        if lista1[i1] <= lista2[i2]:
                                resposta.append(lista1[i1])
                                i1 += 1
                        else:
                                resposta.append(lista2[i2])
                                i2 += 1
                elif i1 < len(lista1):
                        # lista2 esgotada
                        resposta.append(lista1[i1])
                        i1 += 1
                elif i2 < len(lista2):
                        # lista1 esgotada
                        resposta.append(lista2[i2])
                        i2 += 1
                else:
                        # Ambas listas esgotadas
                        break
        return resposta

print(merge([1, 3, 5, 7, 9, 11], [1, 2, 3, 4, 6]))
</code>
Comment: Muito obrigado pela ajuda!

Ordenar listas sem o sort


$\inf\limits_{x \in [a,b]}|f^{\prime} (x)| \geq \frac{1}{b-a}$

Question: Let $f \in C^1([0,1])$ be a non-decrease function such that $f(0)=0, f(1)=1$.
Does there exist $[a,b] \subset [0,1]$ such that $\inf\limits_{x \in [a,b]}|f^{\prime} (x)| \geq \frac{1}{b-a}$?
Comment: Since function is non-decreasing then $f'(x)\geq0$ and if we assume such a segment $[a,b]$ exists, then from [MVT](https://en.wikipedia.org/wiki/Mean_value_theorem)
$$0\leq \inf\limits_{x\in [a,b]}f'(x) \leq f'(c)=\frac{f(b)-f(a)}{b-a}\leq \sup\limits_{x\in [a,b]}f'(x)$$
but
$$\inf\limits_{x\in [a,b]}f'(x) \leq f'(c)=\frac{f(b)-f(a)}{b-a}\leq\frac{1-0}{b-a}=\frac{1}{b-a}$$
Equality still may hold, though.
Comment: @rtybase why are you posting this as a comment and not as an answer?
Comment: @user190080 it may happen that OP committed a typo with the inequality. Just giving a chance to rectify ...
Comment: @rtybase I think you found the key! And I was typing my counter-example in the mean time. I incorporated a reference to your comment if you don't mind
Answer: Depends on $f$.
$f(x)=x^2$ is a counter example.
If $a>1/2$, the infimum is at most 2 and $b-a<1/2$ so the inequality is false.
If $a=0$, the infimum is zero so the inequality is definitely false.
If $0<a\le 1/2$, the infimum is at most 1 whereas $b-a<1$, so inequality is again false.
—
Edit: in the mean time rtybase found the key: this is true only if $f$ stays constant equal zero, then increases straight to one, and then remains constant at 1. In this case $[a,b]$ will be exactly the interval in which the function grows linearly from 0 to 1. I let you work the details from rtybase's comment until you prove this claim.


Invoke-Command Import-Certificate Access Denied

Question: Everyone in my network has read access to an SMB share containing a certificate which needs to be installed. I am also executing this code as domain admin.  What is necessary to overcome this error?
Access is denied. 0x80070005 (WIN32: 5 ERROR_ACCESS_DENIED)

This is the code where I want to install the certificate on each server.
$vms = "App1","App2","App3"

Invoke-Command -ComputerName $vms -ScriptBlock {
    Import-Certificate `
        -FilePath \\dc1\CertificateShare\17C37D0A655B89967398C9E7E8185F78541B1589.cer `
        -CertStoreLocation 'Cert:\LocalMachine\Root'

}

Comment: "*What is necessary to overcome this error?*" - fixing the the double-hop authentication issue; possible duplicate of [Powershell Server Network drive](https://stackoverflow.com/questions/24903878/powershell-server-network-drive)
Answer: You run into an issue known as the double hop issue. In essense you are asking the remote session to access another external resource using the same windows authentication.
Microsoft doesn't allow this by default for security reasons.

If you want to read more about it, please read the my entire post PowerShell remoting caveats
The solution is not easy and definetely not unique because it primarily has to do with Kerberos authentication and how the domain controller wants to control this. For example the domain controller could specify that a specific double hop is allowed between two servers, or you will have to allow the double hop per server.
The better solution is with domain configuration but you need to get in touch with your domain administrator and convince him.
I'll show by script references how to do this per server. For example from the above picture we must configure ServerA to allow credential delegation to ServerB.
I had to solve these issues for an automation repository I've build. The automation is named ISHBootstrap and I'll refer to scripts from this repository. Not everything fits here. Keep in mind that all scripts can executely locally or remotely and that's why you will notice the use of a wrapper cmdlet for Invoke-Command Invoke-CommandWrap. Just looks into the respected script blocks and extract the code.
First we need to install a couple of pre-requisites on ServerA.
I use this script Install-WinRMPrerequisites.ps1 but it is as easy as this command
Get-WindowsFeature |Where-Object -Property Name -EQ "WinRM-IIS-Ext"|Add-WindowsFeature

Then we need to enable and configure WSManCredSSP. This requires an secure remoting session and that's why we need to setup winrm over ssl. This script runs the entire process Enable-WSManCredSSP.ps1

Enable WSManCredSSP.
Install a self signed certificate and configure WSMan with a secure endpoint.
Restart WSMan.
Open firewall port.

Here is the code extracted from the script:
#region Enable WSManCredSSP
Enable-WSManCredSSP -Role Server -Force | Out-Null
#endregion

#region Configure a secure WinRMListener
$winRmListeners=& winrm enumerate winrm/config/listener
$httpsLine= $winRmListeners -match "HTTPS"
Write-Debug "httpsLine=$httpsLine"
if(-not $httpsLine)
{
    $certificate=Get-ChildItem -Path Cert:\LocalMachine\My |Where-Object -Property Thumbprint -EQ $Thumbprint
    $hostname=(($certificate.Subject -split ', ')[0] -split '=')[1]
    Write-Debug "Adding winrm https listener"
    & winrm create winrm/config/Listener?Address=*+Transport=HTTPS  "@{Hostname=""$hostname"";CertificateThumbprint=""$Thumbprint""}"
    Write-Verbose "Added winrm https listener"

    Write-Debug "Configuring ACL"
    # Specify the user, the permissions and the permission type
    $permission = "NETWORK SERVICE","Read,FullControl","Allow"
    $accessRule = New-Object -TypeName System.Security.AccessControl.FileSystemAccessRule -ArgumentList $permission;

    $keyPath = $env:ProgramData + "\Microsoft\Crypto\RSA\MachineKeys\";
    $keyName = $certificate.PrivateKey.CspKeyContainerInfo.UniqueKeyContainerName;
    $keyFullPath = Join-Path $keyPath $keyName;

    # Get the current acl of the private key
    # This is the line that fails!
    $acl = Get-Acl -Path $keyFullPath;

    # Add the new ace to the acl of the private key
    $acl.AddAccessRule($accessRule);

    # Write back the new acl
    Set-Acl -Path $keyFullPath -AclObject $acl;
    Write-Verbose "Configured ACL"
}
else
{
    Write-Warning "winrm https listener detected. Skipped"
}
#endregion

#region restart WinRm service
Write-Debug "Restarting winrm service"
Get-Service -Name WinRM |Restart-Service| Out-Null
while((Get-Service -Name WinRM).Status -ne "Running")
{
    Start-Sleep -Milliseconds 500
}
Write-Verbose "Restarted WINRM service"
#endregion

#region Configure windows firewall
$ruleName="WinRM-HTTPS"
$rulePort=5986
Write-Debug "Querying if firewall port for winrm https is open"
if(-not (Get-NetFirewallRule|Where-Object {($_.DisplayName -eq $ruleName) -and ($_.Direction -eq "Inbound")}))
{
    Write-Verbose "Adding firewall port for winrm https is open"
    New-NetFirewallRule -DisplayName $ruleName -Direction Inbound -Action Allow -Protocol "TCP" -LocalPort $rulePort|Out-Null
}
Write-Host "Winrm https firewall port is ok"
#endregion

At this point the ServerA is ready to delegate your authorization to another server but the client still needs to explicitly state that the remoting session must be capable of this. Create a session like this
$session=New-PSSession -ComputerName $Computer -Credential $Credential -UseSSL -Authentication Credssp

Notice two important things when using CredSSP authentication type:

-Credentials must be explicitly specified even if they are for the same user that is logged on.
Use -UseSSL to use winrm secure.

Now use the $session with your original code and it should work
Invoke-Command -ComputerName $vms -Session $session -ScriptBlock {
    Import-Certificate `
        -FilePath \\dc1\CertificateShare\17C37D0A655B89967398C9E7E8185F78541B1589.cer `
        -CertStoreLocation 'Cert:\LocalMachine\Root'

}


Group actions on the Fano-Mukai $4$-fold

Question: Do any of the Fano-Mukai $4$-fold from https://arxiv.org/pdf/1706.04926.pdf have a $\mathbb{C}^{*}$-action with  isolated fixed points? If so is it possible to compute the weights of the action?
Answer: One of these fourfolds has a $GL_2$-action. The corresponding group $GL_2$ is a subgroup in the group $G_2$ of automorphisms of the genus-10 fivefold. In particular, they have the same maximal torus $T$.
Now, the $T$-action on the genus-10 fivefold has isolated fixed points (this is true for the maximal torus action on any homogeneous space of a semisimple algebraic group). Moreover, these points can be explicitly described together with the $T$-action on the tangent spaces. Next, the fourfold is a hyperplane section of the fivefold, hence each $T$-fixed point of the formed is also fixed on the latter, and since their numbers agree, they just coincide. This allows to describe the points and compute the $T$-action on tangent spaces.
Finally, for a general $G_m$ inside $T$ the $G_m$-fixed points are the same as $T$-fixed points, and the $G_m$-action on tangent spaces is obtained by restriction.


Determine the range of $f(x) = \frac{1}{4}$arccot$(x^2 - 1 ) + \frac{\pi}{4}$

Question: I'm trying to determine the range of the function $f(x) = 1/4$ arccot$(x^2 - 1 ) + \frac{\pi}{4}$. I'm a little bit lost, because I thought that because the range of arccot$(x)$ is $]0,\pi[$, then the range of $f$ has to be $]\frac{\pi}{4},\frac{\pi}{2}[$. Unfortunately, it seems that the range is $]\frac{\pi}{4}, \frac{7\pi}{16}[$. What am I missing?
Comment: Is the $(x^2-1)$ part of the argument in the $arccot$ ?
Comment: Oh, typo, I'll edit!
Comment: The minimal value of $x^2 - 1$ is $-1$  So, the largest value of $\cot^{-1} (x^2 - 1)$ is $\frac {3\pi}{4}$
Comment: What is your background? Do you know calculus?
Answer: Note that the function is even, that is $f(-x) = f(x)$, so you can restrict yourself to the interval $x \geq 0$. Further, in this interval it is decreasing, because $\cot^{-1}$ is a decreasing function, and multiplication by a positive factor doesn't change this feature of $f$. Neither does addition of a positive number. Hence, the maximum is reached when $x = 0$, that is
$$f(0) = \frac{1}{4}\cot^{-1}(-1)+\frac{\pi}{4} = \frac{3\pi}{16}+\frac{\pi}{4} = \frac{7\pi}{16}.$$
There is no minimum instead, as $\cot^{-1}$ doesn't admit a minimum, but you can get $\inf(f(\mathbb{R}))$ computing the limit
$$\lim_{x \rightarrow +\infty} f(x) = 0+\frac{\pi}{4} = \frac{\pi}{4}.$$


What is the correct format of Json string

Question: I'am trying to display a Json string and I have some douts if my string is correct...
This is what i've done so far:

//defining tehe string
var test = "{\"data\":[[100.50, 170.00, \"13/04/2022\", \"Vigente\", 14, 15]]}";

//return my string
return Json(test);

//NOTE -- I'am using C# controler to make this work

and this is what I have to follow ---
Image that i trying to display like
I'am doing this right, if not whats is the right sintaxe to display that?
Comment: Why do you have a double [[ character? What error or behavior are you experiencing (you posted the question for a reason, what caused it)?
Comment: Have you tried using an online validator? If not, there are more than a few that you can just paste your string and determine if it's valid json. [JsonLint](https://jsonlint.com/) | [JsonFormatter](https://jsonformatter.org/)
Comment: I want display the json like the image does, they are datas from a table, and if is not the same as the image, they are not going to work....
Answer: DO NOT ATTEMPT TO MANUALLY CREATE JSON
You should never attempt to generate JSON yourself like this as it is prone to errors. Anyway, Json() takes an object to serialize and will do it for you.
What you should do is:
var test = new {
    data = new List<List<object>>{
        new List<object>{ 100.50, 170.00, "13/04/2022", "Vigente", 14, 15 }
    }
};

return Json(test);

Even better would be to create a ViewModel object that you can populate  instead of using an anonymous type.
Comment: It is that what i've been looking for @phuzi, super worked for me!! Thanks a lot dude


Is $\forall A \in \mathcal R: P(A)$ equivalent to $\{A \in \mathcal R: P(A)\} = \mathcal R$?

Question: Suppose I want to  prove the $ \forall A \in \mathcal{R}, $statement
$ P(A)  $ holds. Now consider the set
$$ \mathcal{K} = \{ A \in \mathcal{R} : P(A) \; \text{holds}\}$$
my question is: is it enough to show that $\mathcal{R} = \mathcal{K}$ to solve the problem above? If so, why?
thanks
Comment: Please, try to make the title of your questions more informative. E.g., *Why does $a\le b$ imply $a+c\le b+c$?* is much more useful for other users than *A question about inequality.* For more information on choosing a good title, see [this post](http://meta.math.stackexchange.com/a/10144).
Answer: Yes, it is enough.
Sets in Set theory are equal if they have the same elements. Now imagine you have this K == R. It means that every A in R belongs to K, that is, satisfies P.
(And I have to learn to use this beautiful notation that you use.)
Comment: By the way, it is not necessary to use the axiom of extensionality (which says that if two sets have the same elements, then they are equal.)  All we need here is the converse statement "if two sets are equal, then they have the same elements", which is a logical tautology because if two things are equal then _everything_ about them is the same.
Comment: For some basic information about writing maths on this site see e.g. [here](http://meta.math.stackexchange.com/questions/5020/), [here](http://meta.stackexchange.com/a/70559/155238), [here](http://meta.math.stackexchange.com/questions/1773/) and [here](http://math.stackexchange.com/editing-help#latexhelp/notation).
Answer: $\forall x; (x \in\mathcal{K} \implies x \in \mathcal{R} \land P(x)) \\  \forall x;(x\in \mathcal{K} \implies P(x)) \text{ (1)}\\
\mathcal{R}=\mathcal{K} \implies \forall x; (x\in\mathcal{R}\implies x\in\mathcal{K})\text{ (2)}  \\ \mathcal{R}=\mathcal{K} \implies \forall x; (x\in\mathcal{R}\implies P(x)) \text{ using (1) and (2)}$
Comment: I'm afraid I can't make sense of this.  What does "$\forall x \in \mathcal{K} \implies ...$" mean?  The antecedent is not even a formula.
Comment: @TrevorWilson I hope it is fixed now.
Comment: Yes, it looks good now.
Answer: You have $K$ being the subset of $R$ on which $P$ holds. If $R=K$, then $P$ must hold on all of $R$, as required.
For a formal proof, just make the substitution $R$ for $K$. No need to invoke extensionality. Something along the lines of:
Suppose $\forall a (a\in K \iff a\in R \land P(a))$ and $R=K$.
Substituting, $\forall a (a\in R \iff a\in R \land P(a))$.
Suppose $x\in R$. Then $P(x)$.
Generalizing, we have $\forall a (a\in R \implies P(a))$ as required.


How do I prevent webpack from rewriting import() so that I can use the buildIn one?

Question: I am writing a kind of meta application. It is written in React and bundled by webpack. The meta application loads a .js file based on the user input etc. The .js file may not exist at the bundling time. My loading function should just make an HTTP(S) request, try to load the file, and take a function with a known name in the file.
If I just have import(aConstructedPath}) in my loading function, webpack treats it as its directive and generates something like __webpack_require__("./ lazy recursive ^.*$").... How can just just say that this import() should use the built-in one?
Answer: I am not sure if you have defined import already. But you can give it a try if you have
const anyName = eval(`import(${aConstructedPath})`);

Where anyName is imported package.
This will make webpack not to rename the code inside ``
Comment: Yes. wrapping it in eval() does the trick, and it probably is the easiest. Thanks!  I could fetch the file itself and eval it but this probably is more reasonable.
Comment: You can upvote and accept it as answer if you like. Thanks
Comment: I want to do so... but I don't have enough reputation yet to upvote.
Comment: You can accept it as answer, i think that is possible


Finding roots of Equation involving trig. functions.

Question: In a problem of classical mechanics, I encounter the following equation:
$$\mu \sin^4 \theta + \cos \theta = 0 \qquad \mu > 0 \qquad \frac{\pi}{2} < \theta < \pi,$$
where $\mu$ is some constant containing things like mass $m$ and angular momentum $L$. I would like to find the roots in $\theta$ for it being in the interval $\left(\frac{\pi}{2},\pi \right)$, which is a condition I know for sure to be true. Mathematica gives me an extremely blown up solution for this equation. Is there any (nice) way to find the roots of this equation by hand?
Answer: Let $x=-\cos(\theta)$ so that
$$\mu(1-x^2)^2-x=0$$
This polynomial indeed has a single root in the range $[0,1]$ for all positive $\mu$.
We can rewrite the above equation as
$$\mu=\frac x{(1-x^2)^2}.$$
For small $x$, $x\approx\mu$.
For $x$ close to $1$, let $1-\epsilon$, we have
$$\mu=\frac{1-\epsilon}{(1-(1-\epsilon)^2)^2}\approx\frac1{4\epsilon^2}.$$
This gives us the approximation
$$x=1-\frac1{2\sqrt\mu}.$$
You can refine the root numerically in the range
$$[\mu,1-\frac1{2\sqrt\mu}].$$
For a "manual" method, you can plot the relation $\mu=f(x)$ as accurately as possible. Then for a given value of $\mu$, find the corresponding $x$ on the plot and use it for a starting value of Newton's iterations.

Update:
The $\mu$ curve has a vertical asymptote at $x=1$, which makes it more difficult to handle. We can discard it by considering the function
$$\frac\mu{\mu+1}=\frac x{(1-x^2)^2\left(\frac x{(1-x^2)^2}+1\right)}=\frac x{(1-x^2)^2+x}.$$

It turns out that the function is fairly well approximated by $x$ in the range of interest, so that a good initial approximation is simply
$$x=\frac\mu{\mu+1} !$$
Comment: For $\mu>1$ the given range for numerical refinement becomes useless, right?
Comment: @MattL.You are right.
Answer: You can avoid ugly analytical formulas but you'll need to use a numerical method to solve for the roots of a polynomial.
Rewrite your equation as
$$\mu\sin^4\theta-\sqrt{1-\sin^2\theta}=0$$
(because $\pi/2<\theta<\pi$), from which you get
$$\mu^2\sin^8\theta+\sin^2\theta - 1=0$$
With $x=\sin\theta$ this is equivalent to
$$x^8+\frac{1}{\mu^2}x^2-\frac{1}{\mu^2}=0\tag{1}$$
Solve for the roots of $(1)$, choose the one which is real-valued and positive, and compute the desired angle as
$$\theta_0=\pi-\arcsin x_0$$
(again, because $\pi/2<\theta<\pi$).
Comment: @K.Rmth: No, because $\cos\theta <0$ for the given interval of $\theta$.
Comment: Shouldn't your first equation read $\mu\sin^4\theta+\sqrt{1-\sin^2\theta}=0$ instead of $\mu\sin^4\theta-\sqrt{1-\sin^2\theta}=0$ ?
Comment: Understood. :-)


Practical handling of Dynamic Time Warping for time-series with unequal sampling frequency (irregular time series)

Question: Hi all and thank you for taking time to read this.
When I read the general literature about dynamical time warping (and the vignette for the $\texttt{R}$ package $\texttt{dtw}$), the time series seem to be given at the same time index. They are not of the same length, and I do know you can do a warping that does not require the beginning and ending of the series to match, but it seems to me, that the time distance between measurements is always the same. I might be reading it all wrong, but as I see it I need two time series complying to the following in order to compare them:
$$X = (X_t)_{t \in \{1,\dots n\}}$$
and
$$Y = (Y_t)_{t \in \{1,\dots m\}}$$
where the time between observations $X_t$ and $X_{t+1}$ is the same as between $Y_h$ and $Y_{h+1}$ $\forall (t,h) \in \{1,\dots n\}\times\{1,\dots m\}$ (namely index 1).
However I have two time series looking like this:
$$X = (X_{t_i})_{t_i \in \{t_1,\dots t_n\}}$$
and
$$Y = (Y_{h_j})_{h_j\in \{h_1,\dots h_m\}}$$
where $d(t_i,t_{i+1})\neq d(h_j,h_{j+i})$ (just plain euclidean distance $d$). You could think of them both as independently randomly sampled in time. Now it seems to me that what I should do is to do some kind of interpolation of each time series separately, extract series $X'_t$ and $Y'_t$ and warp these? I can of cause (if I do not care about calculation time) make the smallest set of equidistantly sampled time points which include all my actually sampled time points - but that could be somewhat cumbersome. I guess my question is - what do you usually do? Just low key practical handling of the issue?
Answer: So you are right that the sampling frequency needs to be constant and the same for both signals, according to the literature, https://ieeexplore.ieee.org/document/1163055. You're also right that the signals do not need to be the same length, and the ends do not need to match.
I also agree that resampling / interpolating to a smaller sampling frequency could be combersome. I have previously suggested to someone that you could convert these signals to a cumulative sum which would then be easier to interpolate to some common sampling frequency, but I don't know the result of this, and might perhaps be worth trying.

Edit: full reference for the paper added after comment request - H. Sakoe, and S. Chiba, IEEE Transactions on Acoustics, Speech, and Signal Processing, Volume 6, Issue 1, 1978
Comment: Thanks for the comment @Antoine, added in the main text
Comment: please provide full reference of the paper you cite in case your link dies


Recovering Ubuntu after apt-get upgrade failed

Question: I was trying to install Firefox 5 using these commands -
sudo add-apt-repository ppa:mozillateam/firefox-stable
sudo apt-get update
sudo apt-get upgrade
The upgrade was happening, but I accidently killed the process, and Firefox 5 was up, so I didn't bother then. But the next time I restarted the system, I was stuck at the login screen. How can I recover it ?
Answer: You might have some broken packages. To check, press CTRL-ALT-F1 to go into TTY1 (note: CTRL-ALT-F7 gets you back to the GUI) and login using your credentials.
Now, run:
sudo apt-get install -f

It should give you more info about what's wrong.
Because you didn't provide any error logs or anything, we can't help you much...


tag is not being parsed

Question: This is the RSS I want to import. I want to write mapping to fetch the  tag within the <description> tag. When I import I get this.
 xpathparser:3 :
   <description><img
   src="http://www.moneycontrol.com/news_image_files/2013/a/acquisitions_yahoo_tumblr.jpg"
   alt="Tumblr had $16.6 mn in cash when Yahoo acquired it" title="Tumblr had $16.6 mn in
   cash when Yahoo acquired it" border="0" width="75" height="75" align=" left"
   hspace="5"/> The deal for Tumblr was the largest since Yahoo Chief Executive Marissa
   Mayer took the role in July with a focus on reversing a long decline in Yahoo's
   business and web traffic. The deal also made Tumblr founder and CEO David Karp, 27, a
   multimillionaire.</description>

What should be the xpath to get the  source?
I've tried Feeds Tamper to convert < to < and > to >and the following xpaths, but nothing works.
   //img/@src
   description[1]
   description/img
   description/img/@src

I am using Drupal 7.
Answer: This cannot be done the way you are trying. HTML embedded in XML is no different than regular text in XML. XPath has no way to look inside the HTML to query it.
There is some work being done, essentially adding another parsing step, https://drupal.org/node/1459870.

tag is not being parsed


Regarding Gibbs sampling and HMC in fitting Bayesian model, their differences and advantages

Question: I have a question regarding the two MCMC algorithms, Gibbs sampling and Hamiltonian Monte Carlo (HMC) for performing the Bayesian analysis.
If using Gibbs sampling, my understanding is that we need to derive the exact formulas for different conditional distributions corresponding to interested latent variables.  The Gibbs sampling scheme has to rely on these formulas. If we are handling complex models in practice, deriving the exact formula might be infeasible.
If using HMC, we do not need to derive these exact formulas and rely on gradient information, (like probabilistic programming) to fit the model. This makes modeling a complex Bayesian model feasible in practice.  Is this understanding correct?
Comment: If anything, HMC constrains you a little but in my opinion, it's worth it. Gradient info cannot be obtained from discrete priors. For example, the Bernoulli PMF doesn't have a gradient and so your choices are limited. In practice, you'd just use a Beta PDF instead. https://proceedings.neurips.cc/paper/2020/file/c6a01432c8138d46ba39957a8250e027-Paper.pdf
Comment: There are more than two MCMC algorithms.
Answer: It is incorrect to state that a Gibbs sampler requires the exact densities of the full conditionals. A Gibbs sampling algorithm requires a collection of conditional distributions that

correspond to a partition of the vector to be simulated (or a completion of said vector by auxiliary variables) into blocks
and such that the conditional distributions of these blocks are generative models, ie are associated with simulation algorithms of a moderate enough complexity.

In the event the simulation from the conditionals is not readily available, it can be replaced with a Metropolis-within-Gibbs version, which requires further that the joint density associated with these conditionals is available up to a normalising constant. The pseudo-marginal generalisation demonstrates that using an unbiased estimate of the density is also valid.
An HMC algorithm similarly requires the (joint) target density to be available up to a multiplicative  constant so that the gradient be computed (or again estimated in an unbiased manner)]. There is therefore no complexity gain in using HMC.
Comment: thanks for your reply. While using modern probabilistic programming language, like Stan and PyMC3, it seems that we only need to setup prior and model specifications (likehood function), and it is not necessary to derive/write down the target posterior density, which is required by classical Bayesian analysis using Gibbs/MH.  And it seems that they all use HMC to fit the distribution. which confuses me on how they achieve it.
Comment: If you input a prior $\pi(\theta)$ and a likelihood function $\ell(\theta|x)$, you equivalently input the posterior:$$\pi(\theta|x)\propto\pi(\theta)\ell(\theta|x)$$Check this [earlier question](https://stats.stackexchange.com/q/307882/7224)


Turning UILabel to NSString with same size and alignment

Question: Is there any way to make a NSString out of a UILabel while keeping the size and alignment? I need this for a section header in a UITableView.
Comment: Also, I am not sure I understand you correctly. Do you want to copy a string from an existing UILabel?
Answer: An NSString has neither font size nor alignment, it's just a series of characters.
You can however use a UILabel as part of a section header view.
Comment: Implement `tableView:viewForHeaderInSection:` instead of `tableView:titleForHeaderInSection:` (which you are probably using now).


Updating Commerce Kickstart's Contrib Modules

Question: What is the recommended way to update outdated Drupal contrib modules? The Commerce Guys doing a great job to keep Commerce secure and updated. However there's always a Contrib Module update around. For the most part this isn't an issue. Most of the Contrib Module updates are maintenance fixes. However what about security fixes for Contrib Modules? Usually I don't touch the /profiles/commerce_kickstart/modules/crontrib folder and I am waiting until a new Commerce Kickstart release is published.
Does Commerce Kickstart uses special Contrib modules? Can I update ctools, Webform myself?
Answer: First, you need to understand that Commerce Kickstart is a Distribution. So your goal is to learn how to update a Drupal distribution before their official release.
For the most part you would need to understand how Drupal Make works. Where is a great article ( Maintaining your installed Drupal distro.) that would explain you how to maintain Drupal distributions.
If you successfully was able to update your Drupal distribution (commerce_kickstart) using Drupal Make. You should created a patch and provide that patch to the commerce_kickstart issue queue.
Comment: Thank you for your reply. Yes, I am already using Drush, however I am new to Drush Make. Frankly I was looking for a more comfortable solution without creating own patches, that is why I've choosen Kickstarter.

Anyway, thanks for pointing me in the right direction.

Updating Commerce Kickstart’s Contrib Modules


Proof on Functions /Set Theory

Question: Let $S$ be the set of all numbers of the form $a + b\sqrt 2$ where $a$ and $b$ are rational. Let $f : S \to R$ be a function such that $f(x+y)=f(x)+f(y)$ for all $x$ and $y$ in $S$. Then $f(x)=f(1)x$ for all $x$ in $S$.
How to prove disprove this? And can you go really slow with explaining?
Here are some steps done in the book (tho I don't understand the steps at all):
On trying to prove the statement, you may succeed in proving that $f(a) =
f(1)a$ for all rational $a$ ("I didn't succeed"), and perhaps go
on to prove that $f(a+b \sqrt 2) = f(1)a+f( \sqrt 2)b$ for all rational $a$ and $b$ ("Nah, didn't manage to do that either"). At this
point, you may notice that it would suffice to prove that $f( \sqrt 2) = f(1) \sqrt 2$ ("WHY?").
Comment: Let $f(a+b\sqrt{2})=a-b\sqrt{2}$.  There are other examples.
Answer: Not true.
Let $a,b$ arbitrary real numbers. Set
$$
f(p+q\sqrt{2})=pa+qb.
$$
Then $f$ satisfies $f(x+y)=f(x)+f(y)$, and $f(x)\ne xf(0)$, in general, unless
$b=a\sqrt{2}$.
Answer: Let's go step by step, and see exactly where the proof fails.
You may notice that the set S forms a vector space with basis $(1,\sqrt 2)$. If this does not meant anything to you, do not worry.
The point is that every element of S can be expressed in terms of the base, so it would be natural to assume that the image of every such element is somehow determined by the images of the basis.
Let's try showing first that the simplest members of S, the natural numbers, satisfy the property. Notice that every natural number n is the sum of n 1's. Thus:
$$
f(n)=f(1+\dots+1)=f(1)+\dots+f(1)=f(1)n
$$
With this accomplished, we want to proceed to show the property for the rational numbers. As before, a rational number $\frac{a}{b}$ can be expressed as the sum of a numbers of the form $\frac{1}{b}$. So we need to show that the numbers of this form have the property. This is easy:
$$
f(1)=f(\frac{b}{b})=bf(\frac{1}{b})\implies f(\frac{1}{b})=\frac{1}{b}f(1)
$$
Therefore:
$$
f(\frac{a}{b})=f(\frac{1}{b}+\dots+\frac{1}{b})=f(\frac{1}{b})+\dots+f(\frac{1}{b})=a\cdot f(\frac{1}{b})=\frac{a}{b} f(1)
$$
So we only have to deal with the numbers with $\sqrt 2$ present; that is, of the form $\frac{a}{b}+\frac{c}{d}\sqrt 2$. Trying a similar analysis:
$$
f(\frac{c}{d}\sqrt 2)=f(\frac{1}{d}\sqrt 2+\dots+\frac{1}{d}\sqrt 2)=
f(\frac{1}{d}\sqrt 2)+\dots+f(\frac{1}{d}\sqrt 2)=c\dot f(\frac{1}{d}\sqrt 2)=\frac{c}{d}(f(\frac{1}{d}\sqrt 2)+\dots+f(\frac{1}{d}\sqrt 2))=\frac{c}{d}f(\frac{d}{d}\sqrt 2)=\frac{c}{d}f(\sqrt 2)
$$
So:
$$
f(\frac{a}{b}+\frac{c}{d}\sqrt 2)=f(\frac{a}{b})+f(\frac{c}{d}\sqrt 2)=
\frac{a}{b}f(1)+\frac{c}{d}f(\sqrt 2)
$$
And here we ran into a roadblock, since the property cannot be shown to be satisfied by $\sqrt 2$.
A valid counterexample is conjugation: $f(p+q\sqrt 2)=p-q\sqrt 2)$. Then $f(\sqrt 2) = -\sqrt 2\ne \sqrt 2 f(1) = \sqrt 2$.

Proof on Functions /Set Theory


How to compute minimum required VC dimension for a classifer to classify a specific data

Question: Suppose we're given an N dimensional data to classify. To cope with this task we may choose a classifier that suits our desires more. However obviously not every classifier is capable of classifying every data for many reasons including its VCD. Now I want to know is there a way to compute the minimum required VC-dimension for a classifier(Hypothesis) to classify a specific data?
As an example to make my question more clear, a classifier having VC-dimension of 2 is not capable of shattering this data set:
<code>+++    ---    +++
</code>
Answer: In general I don't think this is going to be possible (let alone useful). Recall that VC-dimension is an existence property, i.e., for some hypothesis class $H$,  $\text{VCdim}(H) = d$ if there exists some set $X \subseteq \mathcal{X}$ such that $|X| = d$ and $H$ shatters $X$ and there does not exist a set of size $> d$ which is shattered by $H$. Importantly, this does not mean every set of size $d$ is shattered, just at least one.
To understand the difference let's take the canonical example where $H$ is the set of lines in 2d space. Then we know $\text{VCdim}(H) = 3$. To show this we first appeal to Radon's theorem to show $\text{VCdim}(h) < 4$. Next we observe that 3 points arranged in a triangle can be shatter by lines. Notice how this doesn't mean every set of three points in shattered. Indeed, no set of three collinear points can be shattered by lines.
I think to actually know if some hypothesis class shatters a specific set of points you would just need to try (unless you can make some special assumptions about the points).
Lastly, and most importantly, the process you are considering is seriously flawed. If you observe a set of points and then pick a hypothesis class that ensures this set of points is shattered, you throw away any VC style bounds you might get. For those type of bounds to hold you need to pick your hypothesis class before observing the data. What you propose actually results in a hypothesis class with infinite VC-dimension, since you just keep considering more and more complex hypothesis classes until you shatter the observed data. At this point you might as well be using a 1 nearest neighbor classifier.


how can I export table content to excel or csv

Question: I am using drupal 6, I have created a table using
$tableHeader = array (
  array('data' => 'Ebooks','field' => 'etitle'),
  array('data' => 'Volumes','field' => 'Volume' ),
  array('data' => 'Chapter','field' => 'ctitle'),
  array('data' => 'Total Sale'),
);

$TableRows[] = array (
  l($row->etitle,$ebookinfo),
  $row->name,
  str_replace("&", "&" ,$row->ctitle ),
  round($row->totalsale,2).' $',
);

$output .= theme('table', $tableHeader, $TableRows);// get the pager
$output .= theme('pager', NULL, 5, 0);

How can I export it to MS Excel or CSV?
Answer: Maybe the following code can help you.
$filename= 'export.csv';
drupal_set_header('Content-Type: text/csv');
drupal_set_header('Content-Disposition: attachment; filename=' . $filename);

You can add a function to send the row values, filename, and column title.
function export_to_excel_page($row_array, $filename, $column_titles) {
  drupal_set_header('Content-Type: text/csv');
  drupal_set_header('Content-Disposition: attachment; filename=' . $filename);

  foreach ($column_titles as $key => $value) {
    $keys[] = $value;
  }

  if ($keys) {
    print implode(',', $keys) ."\r\n";
    unset($keys);
  }

  foreach ($row_array as $key => $value) {
    $values[] =$value;
  }

  print implode(',', $values) ."\r\n";
  unset($values);

  drupal_exit();
}

Answer: Here's an updated function that should work for D7.
<?php
/**
 * Exports a CSV.
 *
 * @param array $variables
 *   An associative array of data containing "header" and "rows" keys.
 *   This is ready to be passed to theme_table(). See api.drupal.org/node/22950.
 *   Also contains the key "filename" specifying the filename.
 */
function _epc_standards_statistics_export_csv($variables) {
  drupal_add_http_header('Content-Type', 'text/csv; utf-8');
  drupal_add_http_header('Content-Disposition', 'attachment; filename=' . $variables['filename']);

  $output = '';
  $keys = array();
  foreach ($variables['header'] as $key => $value) {
    $keys[] = $value['data'];
  }
  if ($keys) {
    $output .= implode("\t", $keys) . "\n";
  }
  foreach ($variables['rows'] as $value) {
    $output .= implode("\t", $value) . "\n";
  }
  print $output;
  exit;
}
?>

Comment: Wouldn't it be better to use drupal_exit() https://api.drupal.org/api/drupal/includes!common.inc/function/drupal_exit/7 ?
Comment: Separating values with tabs would make it a TSV (Tab Separated Values) file instead of a CSV.
Answer: If you are trying to export Nodes content, then you can able to use views_data_export module and export content using views !

This module is designed to provide a way to export large amounts of
  data from views. It provides a display plugin that can rendered
  progressively in a batch. Style plugins are included that support
  exporting in the following types:
CSV, Microsoft XLS, Microsoft DOC, Basic, TXT, XML.

If you want to export database tables data then you can consider data module.

Data module helps you model, manage and query related sets of tables.
  It offers an administration interface and a low level API for
  manipulating tables and accessing their contents. Data module provides
  Views integration for displaying table data and Drupal search
  integration for searching table content.
Comment: Dear Anil Sagar, thanks for suggestion, but i need to export data from custom tables. as i generated table from that data i want to export those tables, and i am not using views.
Comment: You can use phpmyadmin that works with mysql to export tables or query results to CSV format easily ! Try data module too as it tells it can export tables date to CSV!
Comment: I have to provide a UI to user that shows data and if they need then they can export data  in csv or excel. i have completed the UI but i have to give export functionality to users to export the table content.


How to shuffle matrix data in R?

Question: I have a matrix M of float values, how to shuffle M line-wise?
Comment: This sort of question is probably more suited for [Stack overflow](http://stackoverflow.com), as there is no statistics involved. I answered two of them because the answers were short, but please send more of these type of questions over there. Better yet: read the introduction to R, which holds the answer to at least your previous question...
Comment: Gorodetski you'd be surprised at the number of R pros on stack overflow-- I often get more responses to programming oriented R questions there than here.
Comment: Thank you! I thought R questions fit here, there must many more R pros here than at StackOverflow.com
Answer: something like:
nr<-dim(M)[1]
M[sample.int(nr),]

Comment: A bit shorter version: `M[sample.int(nrow(M)),]`

How to shuffle matrix data in R?