In AB test do the sample size calculations represent the minimum or maximum size required for measuring difference between the test and control

Question: A quick question on the frequentest approach of sample size calculation.
I recently came across this below note:
The sample size required should be strictly enforced; if the power analysis shows that each test variant requires 100,000 users, the test should only be evaluated based on the first 100,000 users that are bucketed.  If this is not strictly adhered to, we expose ourselves to uncertainty
I was under the assumption that the sample size calculation provides the minimum sample size that is required to measure the difference between the treatment and control and is related to the minimum detectable effect but having more data would not necessarily be a problem.
Comment: I'm having trouble squaring the idea of "stopping rules" with the setting of this question, which appears to concern *fixed* sample sizes.  Could you elaborate on this apparent inconsistency?  What stopping rules are you referring to?
Comment: @whuber: Hi, i removed that line about "stopping rules". Reading the question again, i realized that's actually not related to my doubt. Regards. My question is "is the sample size the absolute maximum" or will it have an impact on the measurement if i have more data points than the calculated sample size.
Answer: When you do a sample size calculation for a desired power level, the result is the number of observations required to achieve that power.  Any more than that and your power increases; any fewer and your power decreases.
What I think that passage is saying is that there should be no reason to interfere with assignment to variant (e.g. you should not prevent someone from getting some particular variant because of the behavior they display on your platform).  Doing so once isn't so bad, but if it is a systematic thing, you might mess up the causal interpretation of the test you perform.  It is basically saying to be honest and not fiddle with your experiment too much.


Matrix Multiplication Application

Question: I have a matrix representing the amount of different resources (columns) I would need to create (rows) different objects.
$\begin{bmatrix}
    1 & 1 & 0 & 0 & 0 \\
    1 & 1 & 1 & 1 & 0 \\
    0 & 0 & 2 & 0 & 3 \\
\end{bmatrix}$
My objective is to use matrix multiplication to find out how many resources it would take if we wanted to have i objects of row 1, j objects of row 2, and k objects of row 3.
I don't know an efficient way to go about this. A working solution  I have is to split each of the rows and multiply them by scalars i, j, k, but I don't feel as though this is the correct solution.
Is there a way to get the same result by multiplying two matrices? Thank you.
Answer: What you have described is matrix multiplication, and is the correct way to solve the problem.
Let $M$ stand for the $3 \times 5$ resource matrix in the question. Then the
$1 \times 5$ matrix
$$
[i,j,k]M
$$
tells you how many of each of the five kinds of resources you need to manufacture those objects.
The matrix product would look a little more traditional if you wrote the transpose $T$ of the resource consumption matrix instead, where each row corresponds to an ingredient and each column to a kind of object. Then the computation would be the $1 \times 5$ matrix
$$
T
\begin{bmatrix}
i \\ j \\ k
\end{bmatrix}
$$
Comment: I'm sorry, can you explain the [i,j,k]A notation?
Comment: Multiply the $1\times 3$ matrix $[i,j,k]$ bythe $3 \times 5$ matrix $A$.

Matrix Multiplication Application


The 'drupal' way to implement delete button UI

Question: I think I'm missing something fundamental here. What's the 'right' way to implement a delete button on the UI-end?
My app has a classic list-type data model: User has wishlist(s) -> wishlist has item(s) -> item has properties. (These are represented in several tables, of course).
The several views are loaded via tpl files using hook_theme(). When the app has a view loaded for any step of the way (looking at an item in a list, for instance) I want to have edit/delete buttons that act on the item.
The CRUD methods are in place, they just need to be wired to the button.
In some places in the app, I've exposed methods via hook_menu(), and that works fine by passing the target to l() - I'm using this for many of my "View Item" UIs. Is there another way, though? This seems to be exposing a ton of core logic to the address bar if I keep going that route.
In a nutshell: How do I have a button action similar to pseudocode button.click=$this->bluenose_app_remove_available_property($property->id);? Preferrably without routing through hook_menu()
Answer: What you listed is what we normally do.
A menu router item (what you define in hook_menu actually serves a lot more than just pointing logical actions to functions/methods. It also makes sure than the items exist, they are accessible, and delivered correctly.
In hook_menu, you can definite how the access should be granted (with permission system or anything else). You can use wildcard loaders to load items, so you don't have to throw 'page not found' errors yourself.
You don't have to put your logic in the URLs. If you deal with entities, have your entity build the operation URLs, so they become part of your entity class, and not part of the template (the "View" of traditional MVC).
When the entity gets complicated, I often end up writing a single menu router to handle them all. The operation argument of a menu path (edit, delete, clone, disable, etc) can be a wildcard loader as well, and you can easily validate it using a method_exists() call.


metodo reconstrutor classe javascript?

Question: Eu estou planejando uma classe carta:
class Carta {
    constructor (el) {
        // propriedades imutaveis
        this.el = el;
    }
    // metodos
    reconstrutor () {
        // propriedades mutaveis
    }
    isManilha () {

    }
    desenhar () {

    }
    apagar () {

    }
    jogar () {

    }
}

Dentro do construtor eu guardo el que e um elemento html. E um jogo de cartas entao a cada rodada eu poderia apagar os objetos antigos e instanciar novos com novas propriedades, mas o el teria que ser passado novamente. Entao seria mais correto usar um metodo reconstrutor para apenas alterar as propriedades necessarias ou isso seria uma gambiarra?
Comment: Nem sei o que deseja, mas imagino ser pelo menos invencionice.
Comment: era exatamente o que eu queria saber, saber se estou no caminho certo ou nao e ja vi que nao, isso que da ter php como primeira linguagem.
Comment: Se o objeto carta será "reinstânciado" - uma nova carta, penso que poderia utilizar somente o construtor. A não ser que somente propriedades da mesma carta será alterado, por exemplo, ela ser manilha num certo momento e não ser mais em outro momento.
Answer: A ideia de herança em classes faz o que procuras. Em vês de teres esse "reconstrutor" tens duas alternativas:
#1- Se fôr só el que muda, ou outros parâmetros que podem ser passados em variáveis então usa a mesma classe mas passa-lhe somente novos argumentos:
var A = new Carta('A', 'Joker', etc...);

#2- Se queres ter funcionalidade diferente, mas usando grande parte do código de outra classe podes usar extends, que no fundo é uma cópia da outra classe onde podes sobre-escrever métodos:
classe Joker extends Carta {
    constructor(el){
        super(el); // <- aqui chamas o construtor de Carta passando `el`.
    }

    desenhar () {
        // aqui podes escrever lógica que é só do Joker
        // os outros métodos serão os mesmos, mas este vai substituir
        // o método desenhar da classe Carta
    }

}

metodo reconstrutor classe javascript?


Does Kernel Function Only Apply To Support Vector In SVM?

Question: We know that the if $α=0$ in below equation it is not a support vector; support vectors have $α \ne 0$.
$$
L(w, b, α) =
\sum_{i=1}^m α_i − \frac12 \sum_{i,j=1}^m y^{(i)} y^{(j)} α_i α_j (x^{(i)})^T x^{(j)}.
$$
However, the kernel function i calculated for all pairs of vectors even if $α=0$.
Can we say that kernel is calculated for all vectors, but only support vector contribute to the final decision boundary?
Or actually is the kernel only calculated for support vectors?
It confuse me that because only support vector decide the boundary, why is the kernel need to calculate all pair of vectors in sample?
Answer: You don't know in advance which inputs are going to be support vectors; you need to do the optimization to figure that out.
One way to do that is to pre-compute the kernel matrix for all pairs of inputs, then run the solver on that.
Some more efficient SVM solvers will actually only compute the kernel function when it's needed, and can (using various techniques based on only a few kernel evaluations) figure out that a point isn't going to be a support vector, then not compute the kernel between those points and the rest of the dataset. But how those work exactly is complicated.
Comment: +1 Can you provide some key references or papers about the "more efficient SVM solvers"? This sounds very interesting and I would like to know more!
Comment: @Sycorax The old-school classic [SMO solvers](https://en.wikipedia.org/wiki/Sequential_minimal_optimization) do this, and I think more modern fancy SVM solvers do as well, though I don't know those very well.


Erro ao tentar exibir as mensagens de erro/sucesso e pagina continua a recarregar com ajax

Question: Olá, estou desenvolvendo uma pagina de "em breve", onde possuí a funcionalidade de cadastrar e-mail.
Fiz esta funcionalidade com ajax e php, utilizando o banco de dados mysql, e estou enfrentando 2 problemas.

Ao digitar o e-mail e clicar no botão a pagina recarrega, mas não deveria por que estou a utilizar o ajax.
Todas as vezes em que eu tento fazer o registro, ele é bem sucedido, porém a mensagem de registrado com sucesso não é exibida, e ao fazer vários registro, em sequencia, para testar a página, todos funcionaram, mas às vezes exibe a mensagem de erro que criei.

Ex:

O código da minha pagina index.php

<form id="SignupForm" method="POST">

                    <input type="text" id="email" class="form-control-input" placeholder="E-mail..." required>

                        <button type="submit" class="form-control-submit-button" id="submit" onclick="inserir_registo()">Enviar</button>

                </form>

e por fim da pagina insert.php
<?php
    //Conexão à base de dados
    mysql_connect("localhost", "root", "") or die(mysql_error());
    mysql_select_db("birdleco_site") or die(mysql_error());

    //recebe os parâmetros

    $email = $_REQUEST['email'];

    try
    {
        //insere na BD
        $sql = "INSERT INTO captura (Email_Captura) VALUES('".trim($email)."')";
        $result = mysql_query($sql) or die(mysql_error());

        //retorna 1 para no sucesso do ajax saber que foi com inserido sucesso
        echo "1";
    }
    catch (Exception $ex)
    {
        //retorna 0 para no sucesso do ajax saber que foi um erro
        echo "0";
    }
?>

NOTA: estou usando este jquery: "jquery-1.10.2.min.js".
Me deem um luz por favor!
Answer: Tente alterar o type do botão para "button".
O type "submit" faz com que o navegador execute o form, que por sua vez deve cancelar a request feita no Ajax.
https://www.w3schools.com/tags/att_input_type_submit.asp
Comment: Nossa não imaginei que fosse algo tão simples, isso nem passou pela minha cabeça, obrigado, só preciso resolver o erro das mensagens agora uashhsuas obrigado
Answer: $('#SignupForm').on('submit', function(e){
   e.preventDefault();
    var dadosajax = {'email':$("#email").val()};
    pageurl = 'grava.php';
$.ajax({

    //url da pagina
    url: 'insert.php',
    //parametros a passar
    data: dadosajax,
    //tipo: POST ou GET
    method: 'POST',
    //cache
    cache: false,
    //se ocorrer um erro na chamada ajax, retorna este alerta
    //possiveis erros: pagina nao existe, erro de codigo na pagina, falha de comunicacao/internet, etc etc etc
    error: function(){
        alert('Erro: Inserir Registo!!');
    },
    //retorna o resultado da pagina para onde enviamos os dados
    success: function(result)
    {
        //se foi inserido com sucesso
        if($.trim(result) == '1')
        {
            alert("O seu registo foi inserido com sucesso!");
        }
        //se foi um erro
        else
        {
            alert("Ocorreu um erro ao inserir o seu registo!");
        }
    }

});
Remova a função OnClick do botão submit e pronto.


How to transpose from guitar scores to clarinet?

Question:
Guitar in standard tuning
B♭ clarinet

I have the chords for a song in guitar. I need to join the guitar on clarinet, but I cannot find the partiture to play.
How can I join the guitar (rhythmic guitar) on clarinet using the chords he is playing?
I mean what is the analogue of it in clarinet?
By the way the song is Volare by gypsy kings. So if you know the partitures that would be awesome.
Comment: Are you the clarinettist? Do you need the _clarinet_ part?
Comment: Does this answer your question? [I find composing for transposing instruments hard](https://music.stackexchange.com/questions/74774/i-find-composing-for-transposing-instruments-hard)
Comment: @OldBrixtonian yes
Comment: @CarlWitthoft - there's a tenuous link, that's all.
Answer: The clarinet most used is a transposing instrument, in B♭. That means when the music shows a note C, and the player blows what he perceives as that note, the pitch comes out as a B♭. So everything he plays off the partitions will be a whole tone lower than you need on guitar. See a C chord - play a B♭, see a G chord - play an F, and so on.
There are other clarinets, but B♭ is the most commonly used, and written for.
You could capo the guitar, but at the 10th fret, it's not particularly practical.
What we don't do on this site is provide music, or routes to that music, sorry.
EDIT  - just in case I read the question the wrong way round. You'll have to play the clarinet part a whole tone higher. So: see a C, play a D, see a G, play an A, etc. Or, re-write it all in a key that's a tone higher.
When I was learning trumpet, (also B♭) a long time ago, I realised the same problem, and learned to read 'properly', but also 'wrongly' - playing a tone above what was written. That put my playing into the same key as everyone else, rather than have everyone else change to match my key.
RE-EDIT- playing only one note at a time on clarinet (usual!) you could even play the melody - which would be, as I say, a tone higher than that if it was written for a concert - tuned instrument. If you could find the partition written for clarinet, then you'd play verbatim.Or- if you wanted to extemporise around the tune, just need to be aware that the key you'd do that in is the guitarist's key - a tone above.
RE-RE-EDIT - there are plenty of arrangements available for not a lot, most if not all can be transposed before buying. All you need do is ascertain what key the singer or guitarist wants to do the song in, and order the same but in a key a tone higher. That way, you'll be able to read off as the others play, and all be in the same key!
Comment: When I read the OP's question I got the impression he himself was the clarinettist. I could be wrong.
Comment: @OldBrixtonian yes your are right. I need to play a tone higher that what is written for guitar
Comment: @OldBrixtonian - thanks, answer edited accordingly. But OP seems to have the gist anyway - except trying to play chords on clarinet..!
Comment: Got it. What about the chord like Em B7
Comment: Like I say, drop every chord a whole tone. So Em>Dm, and B7>A7. It seems a little strange that any chords written for guitar wouldn't be in *concert pitch*, though.
Comment: I got it. One tone higher for clarinet. I dont get how to play E minor, I mean it is a chord, in clarinet I just play singles notes, so which note should I play when the guitar plays E minor. should I play D in clarinet? The chord of Dm is formed by three singles notes, which note(s) should I play on clarinet. I am so sorry I just learnt how to read notes like two weeks ago, but I am very motivated. thanks for your explanations
Comment: When the guitar plays an Em chord, you play any notes of the F#m chord: F#, A, C#. When it plays B7, you play notes of the C#7 chord: C#, E#, G#, B. Get it? :-)
Comment: @Tim: Sorry to galumph in. I was worried he might set off for the gig :-)
Comment: @OldBrixtonian - you mean leaving the clarinet at home and picking up a guitar instead..?
Comment: No! Taking his clarinet, and sounding TWO tones lower than the guitar!


How is it simplified?

Question: 1 ) I have this equation and don't know how $(1 + 2e^y)$ and $(1 + 2e^x)$ from each side of equation cancelled each other out and get the final answer $x = y$.
$$\frac{e^x}{1+2e^x}=\frac{e^y}{1+2e^y}$$
$$e^x(1 + 2e^y) = e^y(1 + 2e^x)$$
$$e^x = e^y$$
$$x = y$$
Question 2 - I don't know how the equation turned into fraction in the last step. Appreciate much for fast reply :)
$$y =\frac{e^x}{1+2e^x}$$
$$e^x = y + 2ye^x$$
$$e^x =\frac{y}{1-2y}$$  (How does $y + 2ye^x$ turned into this?)
Comment: Check the concept of "one-to-one functions". If f(x)=f(y) leads to x=y then the function f is one-to-one. One way to check whether f is one -to-one is through its derivative.
Answer: If you need I can add in the missing steps.  For question 1, you have
$e^x(1+2e^y)=e^y(1+2e^x)$
Clear the parentheses to obtain
$e^x+2e^{x+y}=e^y+2e^{x+y}$
Then just subtract $2e^{x+y}$.  Now for problem 2, you have
$e^x=y+2ye^x$
$e^x-2ye^x=y$
$e^x(1-2y)=y$
Now just divide and you have your last line.
Comment: Got it. Thank you so much!

How is it simplified?


Jquery .live issue

Question: I have the following snippet of code.
HTML (simplified):

Invoegen

On which a JS function is running (simplified) to retrieve the data from the form, add it to the database and then update the form/table with the correct class & ID's:
    $(".insert").click(function() {
        // current field, is the id: insert_24
        // layer is retrieved in the function: 24
        // Full table has the id 'canvas'

        // do something
        // Insert into database

        console.log('insert-'+layer);
        $("#"+ current_field).removeClass("insert").addClass("delete").html('delete').attr('id', 'delete_'+layer);
        $("table#canvas tr:last").attr('id', 'row_'+layer);
    });

Directly after this code I also have the code to delete a line (simplified):
    $(".delete").live("click", function() {
        // do something
        // Insert into database

        console.log('delete-'+layer);
        $("#row_"+ layer).remove();
    });

The insert works perfectly, but when I look at the console log functions, on 'insert', also the 'delete' function is being triggered directly after the insert, which doesn't make sense. I only clicked the
 once.
Which step/setting am I missing to have this function work in the correct way?
Comment: jsfiddle please? -> http://jsfiddle.net/
Comment: FYI, you can replace `$("#"+ current_field)` with `$(this)`.
Answer: Update your click() handler to return false;, or:
$(".insert").click(function(e) {
    e.stopPropagation();
    // your code here
});

.live() works by attaching a handler at the document level and waiting for events to bubble up - at which time it checks if the original target element matches the selector you used. So when a click occurs it first triggers the (non-live) click handler and then bubbles up to trigger the live handler.
Note also that removing the "insert" class from the element will not stop your click handler from firing on that element. You'd need to either unbind the click handler (from within the handler) or change that one to a live handler too.
Note that .live() is way out of date. You should update to use the delegated syntax of the .on() method instead..
Comment: Just to be clear, `.on()` uses a similar approach as `.live()`, so it suffers from the same original problem.
Comment: Good catch on that last part. A better solution would probably be to have one handler that just checks `$(this).hasClass("insert")`.
Comment: Thanks @Barmar. +1 to you too - you answered first. And yes, switching to `.on()` wouldn't make any difference on this problem, but I recommend it in a general sense since it is slightly more efficient and because `.live()` was deprecated in version 1.7 and removed in 1.9.
Comment: Excellent solution. Sometimes they are so simple. This works and I will definitely will look into the .on() function to replace the live to keep on with the newest solution.
Comment: If you take a look at the `.live()` doco page it tells you how to update. (Note that `.on()` can be called with several different types of parameters, so make sure you get the right combination for delegated event handling.)
Answer: Try this:
$(".insert").click(function(e) {
    e.stopPropagation();
    // current field, is the id: insert_24
    // layer is retrieved in the function: 24
    // Full table has the id 'canvas'

    // do something
    // Insert into database

    console.log('insert-'+layer);
    $("#"+ current_field).removeClass("insert").addClass("delete").html('delete').attr('id', 'delete_'+layer);
    $("table#canvas tr:last").attr('id', 'row_'+layer);
});

What's happening is that the click event is bubbling up to the document. .live() has a handler on the document that checks whether the target of the event matches the selector. After the click handler completes, the class of the DIV has changed to delete, so this check succeeds, and it runs the handler.

Jquery .live issue


Form field will not validate with onSubmit

Question: I am trying to get a script that validates a form field to work in Chrome, IE and Firefox. The script works fine in Safari.
The problem is when I click "submit", the form does not return false with a statement stating one of the form fields is required. This happens in every browser except Safari.
Here is a link to the page that I would like help on:
www.3elementsreview.com/submit
Comment:
Answer: Can you post a bit of your JS code so we know what you're dealing with?  The two most likely problems are that you have a syntax error in your validation function or you didn't assign an id to one of the form inputs you are trying to reference in the function.
EDIT: Next time post your code in the actual question, but on first glance it looks like you're using == instead of === to check conditions.  Also you need to say document.myForm.myAttribute.value if you want to check the values of each attribute.
Comment: //E-Mail Address

  if (document.getElementById("email").value.indexOf("@",".") == -1) {
   document.getElementById("invalid-3").innerHTML = "**Please enter a valid e-mail address**";
   invalid += 1;
  }
  else {
  document.getElementById("invalid-3").innerHTML = "";
  }

  //Comments

  if (document.getElementById("message").value == "") {
   document.getElementById("invalid-4").innerHTML = "What would you like to say?";
   invalid += 1;
  }
  else {
  document.getElementById("invalid-4").innerHTML = "";
  }
Comment: if (invalid != 0) {
    return false;
   }
   else {
    return true;
   }
  }


Kotlin + Mockito + Spring-boot

Question: I am studying Kotlin with Spring Boot, and I am trying to use Serenity just for report.
But I have some problem with Mockito because I cannot mock the last part of my code.
That's my case:
@RestController
@RequestMapping("/person")
class PersonController {

    @Autowired
    private lateinit var personUseCase : PersonUseCase

    @GetMapping("/all")
    fun findAllPeople(): DataModelResponse<List<PersonDataModelResponse>> {
        return DataModelResponse(
                PersonDataModelResponseMapper.transform(personUseCase.findAll()))
    }

}

@Component
class PersonUseCase {

    fun findAll(): List<PersonEntity> {
        val personImpl : Person = PersonImplementation()
        return personImpl.findAll()
    }
}

class PersonImplementation : Person {

    private val personDaoResponse :  PersonDaoResponse = PersonDaoResponse()

    override fun findAll(): List<PersonEntity> {

        val listPeopleDao = personDaoResponse.findAll()

        return PersonDaoMapper.transform(listPeopleDao)
    }

}

internal class PersonDaoResponse (
        val identification: Long = 0,
        val personName: String = "") {

    fun findAll(): List<PersonDaoResponse> {
        return listOf(PersonDaoResponse(1, "José"))
    }
}

And I am trying to mock my Dao in an integration test:
@RunWith(SerenityRunner::class)
@WithTag("Integration")
@AutoConfigureMockMvc
@WebMvcTest
class PersonControllerTest {

    @InjectMocks
    private lateinit var personController : PersonController

    @InjectMocks
    private lateinit var personImplementation : PersonImplementation

    @SpyBean
    private lateinit var personUseCase : PersonUseCase

    @Spy
    private val personDaoResponse = PersonDaoResponse()

    @Autowired
    private lateinit var webApplicationContext: WebApplicationContext

    @Autowired
    private lateinit var mockMvc: MockMvc

    @Rule @JvmField
    var springMethodIntegration = SpringIntegrationMethodRule()

    @Before
    fun init() {
        MockitoAnnotations.initMocks(this)
        reset(personDaoResponse)

        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.webApplicationContext).build()
        this.mockMvc = MockMvcBuilders.standaloneSetup(personController).setMessageConverters(MappingJackson2HttpMessageConverter()).build()
    }

    @Test
    fun `integration success`() {
        doReturn(listOf(PersonDaoResponse(999L, "Zé")))
                .`when`(this.personDaoResponse).findAll()
        val result = this.personController.findAllPeople()
        assertNotNull(result)
        assertEquals(999L, result.data[0].personId)
        assertEquals("Zé", result.data[0].name)
    }

}

I know this mock is working if I do something I try call the mock method:
assertEquals(999L, this.personDaoResponse.findAll()[0].identification)
How can I Mock this Dao in an integration test like this?
Answer: Unfortunately, I don't have an answer for the Mockito problem because I've been off Mockito for way to long.
If Mockito is not a must, I recommend using MockK (https://github.com/mockk/mockk) from my Spring Boot + Kotlin experience. If you need injectable mocked Beans as well, you can add SpringMockK (https://github.com/Ninja-Squad/springmockk) as well.
As your "PersonDaoResponse" is constructed within the PersonImplementation class, you could use something like this with MockK:
every { anyConstructed<PersonDaoResponse>().findAll() } returns listOf(PersonDaoResponse(999L, "Zé"))

Kotlin + Mockito + Spring-boot


How can this error be? 'Invalid WebP header detected' using Imazen.WebP.SimpleDecoder

Question: I have the following code:
SimpleDecoder decoder = new SimpleDecoder();
byte[] fileBytes = File.ReadAllBytes(filename);
Bitmap image = decoder.DecodeFromBytes(fileBytes, fileBytes.Length);

PictureBox pb = new PictureBox
    {
    Size = new Size(100, 100),
    Image = image,
    SizeMode = PictureBoxSizeMode.Zoom,
    Tag = filename
    };

FlpThumbnails.Controls.Add(pb);
pb.Refresh();
Application.DoEvents();

at the Bitmap image = decoder.DecodeFromBytes(fileBytes, fileBytes.Length); I get the exception thrown System.Exception: 'Invalid WebP header detected'. However, in my Windows Explorer I can see the image perfectly well.
I am using Imazen.WebP.SimpleDecoder to decode the image.
Does anyone have any ideas on how to fix this error?
Thanks.
Answer: Ok I created a solution.
In his code I did the following:
public static Bitmap DecodeFromPointer(IntPtr data, long length)
    {
        int w = 0, h = 0;
        //Validate header and determine size
        if (NativeMethods.WebPGetInfo(data, (UIntPtr)length, ref w, ref h) == 0)
        {
            w = 100;
            h = 100;
            NativeMethods.WebPGetInfo(data, (UIntPtr)length, ref w, ref h);
            //  throw new Exception("Invalid WebP header detected");
        }

I commented out the throw new exception, and added the default thumbnail size I am using of 100,100. It still does not show the image but it continues until...
It gets a little further down the file and finds this:
//  if (bd.Scan0 != result) throw new Exception("Failed to decode WebP image with error " + (long)result);

As you can see I simply commented that line out as well.
And that was all I had to do to get Imazen.WebP.SimpleDecoder to not crash on images that I can see in Explorer but not see in my .Net Application. It is true I can still not see the images but the application does not crash anymore.


Ajax button in admin

Question: So I figured I'd create a configuration for my module. I created a normal form with some fields to let the users configure the module with variables. I also added a button which would do an ajax-call to a service. Problem is, this button is within the form, meaning it submits the form aswell.
<code>$form['products']['update'] = array(
            '#type' => 'button',
            '#ajax' => array(
                'path' => '/products/update',
                'event' => 'click'
                ),
            '#value' => t('Update Products')
);
</code>
I just want the button to actually call this service (/products/update) and not act like a submit button. This worked in beta3 but is not an annoying feature in beta4, preventing the actual service call. How do I fix this?
Comment: Not an answer to the question, but converting the button to a styled link might be an easy solution
Comment: `button` types are not supposed to call the submit handlers. You will get the form values, but it shouldn't execute submit handlers.
Answer: ajax path is not supported anymore I think. It would need to be a route.
Why do you need a path? The common way to do this is to have a #submit callback on that form element, then just that will be called.
Comment: Well according to most tutorials out there setting up an AJAX-service in Drupal 8 is by using the path as a main-route and then the callback is there as a.. callback. That's the main reason why I used path this early. I will have to adapt, I suppose.
Comment: I'm not sure where you've seen those tutorials, but many D8 tutorials are out of date anyway, so careful with those. You can see the properties for #ajax for example on RenderElement::preRenderAjaxForm(), and it has 'url', which is a Url object. But almost nothing in core uses that, the common case is to use the standard url, which is system/ajax, which takes care of processing your form, submitting it as defined and then calling the callback.
Comment: https://api.drupal.org/api/drupal/core!modules!system!core.api.php/group/ajax/8 I suppose this is outdated, but it can be confusing when path actually states being used for requests. Also since I am very used to setting up routes for services from other frameworks I thought this approach was the easiest.
Comment: Is there any workaround my initial solution to just have a button use the route 'products/update' through an AJAX request?
Comment: Yes, you could create a Url object with Url::fromRoute() or Url::fromUri() and assign that to 'url'.
Comment: Anyway you could help me out a little bit more with the code? :) Am trying to find information about the scenario but the help I find seems a tad outdated.
Comment: I did follow Berdirs suggestion and rewrote the code to use a callback instead. Calling the function immeditately instead of creating a route proved more useful.

Ajax button in admin


What is the correct way to implement Jensen-Shannon Distance?

Question: I'm trying to use this code to compute the Jensen-Shannon distance:
def js_dist(P, Q):
    """Compute the Jensen-Shannon distance between two probability distributions.

    Input
    -----
    P, Q : array-like
        Probability distributions of equal length that sum to 1
    """

    def _kldiv(A, B):
        # Calculate Kullback-Leibler divergence

        return np.sum([v for v in A * np.log2(A/B) if not np.isnan(v)])

    P = np.array(P)
    Q = np.array(Q)

    M = 0.5 * (P + Q)

    # Get the JS DIVERGENCE
    result = 0.5 * (_kldiv(P, M) +_kldiv(Q, M))
    # Take sqrt to get the JS DISTANCE
    return np.sqrt(result)

but when comparing it to Scipy's implementation:
from scipy.spatial.distance import jensenshannon

#See here for the Scipy source code:
https://github.com/scipy/scipy/blob/v1.5.2/scipy/spatial/distance.py#L1230-L1287

I get different results:
a = [0.2, 0.4, 0.4]
b = [0.3, 0.2, 0.5]

[In]: js_dist(a,b)
[Out]: 0.18918

[In]: jensenshannon(a,b)
[Out]: 0.15750

Where am I going wrong??
Comment: The two vectors (a and b) are in the box that shows the two differing results.
Comment: You ought to give the data, the two vectors, as an example in the question.
Answer: You are using logarithm base 2 by default.
scipy.spatial.distance.jensenshannon uses the default base of scipy.stats.entropy.
https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.jensenshannon.html
If you set the optional base parameter in jensenshannon(a,b, base=2.0), function will use log2 too, and you will obtain the same result as in your function 0.18918.
Your functions is well implemented.
Answer: If you want calculate "jensen shannon divergence", you could use following code:
from scipy.stats import entropy
from numpy.linalg import norm
import numpy as np

def JSD(P, Q):
    _P = P / norm(P, ord=1)
    _Q = Q / norm(Q, ord=1)
    _M = 0.5 * (_P + _Q)
    return 0.5 * (entropy(_P, _M) + entropy(_Q, _M))

but if you want " jensen-shanon distance", you can take square root of JSD or use scipy.spatial.distance.jensenshannon
Answer: Here is a minimal example based on two normal distributions (built based on the answers already exist in this thread):

import scipy.stats
import scipy.spatial
import numpy as np

# Start with two normally distributed samples
# with identical standard deviations;
# The two means are 2 standard deviations away from each other
x1 = scipy.stats.norm.rvs(loc=0, scale=1, size=1000)
x2 = scipy.stats.norm.rvs(loc=2, scale=1, size=1000)

# Construct empirical PDF with these two samples
hist1 = np.histogram(x1, bins=10)
hist1_dist = scipy.stats.rv_histogram(hist1)
hist2 = np.histogram(x2, bins=10)
hist2_dist = scipy.stats.rv_histogram(hist2)

X = np.linspace(-4, 6, 10)
Y1 = hist1_dist.pdf(X)
Y2 = hist2_dist.pdf(X)

# Obtain point-wise mean of the two PDFs Y1 and Y2, denote it as M
M = (Y1 + Y2) / 2

# Compute Kullback-Leibler divergence between Y1 and M
d1 = scipy.stats.entropy(Y1, M, base=2)
# d1 = 0.406
# Compute Kullback-Leibler divergence between Y2 and M
d2 = scipy.stats.entropy(Y2, M, base=2)
# d2 = 0.300

# Take the average of d1 and d2
# we get the symmetric Jensen-Shanon divergence
js_dv = (d1 + d2) / 2
# js_dv = 0.353
# Jensen-Shanon distance is the square root of the JS divergence
js_distance = np.sqrt(js_dv)
# js_distance = 0.594

# Check it against scipy's calculation
js_distance_scipy = scipy.spatial.distance.jensenshannon(Y1, Y2)
# js_distance_scipy = 0.493

The difference between the KL-divergence-derived JS distance and scipy's JS distance may have been caused by the very coarse binning used to construct the empirical PDF.


While loop add class to first result

Question: I have the following
while ( $query->have_posts() )
{
$query->the_post();
if ( $keys = get_post_custom_keys() )
{
    echo "

";
    echo the_title();
    echo "";

// Network query
    $network_value = get_post_custom_values('srchnetwork');
    foreach ( $network_value as $key => $value ) {
    echo ''. $value . ''; }

// Pricing Query
    $pricing_value = get_post_custom_values('srchpricing');
    foreach ( $pricing_value as $key => $value ) {
    echo ''. $value . ''; }

// Setup Query
    $setup_value = get_post_custom_values('srchsetupfee');
    foreach ( $setup_value as $key => $value ) {
    echo ''. $value . ''; }

// Services Query
    $services_value = get_post_custom_values('srchservices');
    foreach ( $services_value as $key => $value ) {
    echo ''. $value . '
'; }

// Big Card Query
    $bigcard_value = get_post_custom_values('bigcard');
    foreach ( $bigcard_value as $key => $value ) {
    echo ''; }

//      echo '';

    echo the_excerpt()."
";   }};
}

Im wondering if its possible that I can wrap the first returned result within a span tag? if so how would I go about doing this? thanks
Answer: As a general approach, any time you need behavior to only execute on the first time through a loop, you can simply use a flag variable to check whether to execute that behavior.
$firstLoop = true;
while( $query->have_posts() ){

    //do some things

    if( $firstLoop ){
        //do things on only the first loop
    }

    //do other things

    $firstLoop = false;
}

Or, for a foreach loop:
$firstLoop = true;
foreach( $network_value as $key => $value ){

    if( $firstLoop ){
        //do things on only the first loop
    }

    //do other things

    $firstLoop = false;
}

This avoids needing to count loops, and it works for any loop structure. Just remember to always set your flag variable to false at the end of the loop.
Answer: $i = -1;
while ( $query->have_posts() )
{
$i++;
$query->the_post();
if ( $keys = get_post_custom_keys() )
{
echo "

";
echo the_title();
echo "";
...

Check this line ( $i ? 'first' : '').
Comment: When using the code on a FOR loop the 'first' gets placed on the second item, easy fix ( $i ? '' : 'first'). That worked for me.
Answer: You can take help from a counter :
$count  = 0;
while(){
  <div class="<?php $count++; if($count == 1) { echo ' active'; } ?>">hello

}

Answer: My assumption on that basis would then result in something like this around each loop...
// Network query
$neti = 1;
$network_value = get_post_custom_values ( 'srchnetwork' );
foreach ( $network_value as $key => $value ) {
  if($neti == 1){
      echo '' . $value . '';
  }else{
      echo $value;
  }
  $neti++;
}

Comment: @scottevans93, if you have questions for the original poster, it's better to ask them as comments on the question itself, rather than entering them as a possible answer.
Comment: @Jazz It would not let me for some strange reason.
Comment: @scottevans93 Do you have enough reputation to post comments (in places other than on your own answers) yet?

While loop add class to first result


Smallest positive integer such at $2^n$ contains 2018 as a substring?(Give approximation)

Question: This is what the solution says:
Since each string of 4 digits are independent, having 2018 in a string has probability of $(1/10)^4$
By geometric distribution, expected value of digits to obtain 2018 in a string would be $10^4$
So we need to see how many powers do we need to write before we reach $10^4$ units.
Since $2^{10} \approx 1000 $, we can say $2^n$ has $0.4$ digits.
So the number of digits is:
$\sum_{r=1}^{n}0.3r  = 0.2n^2$
Thus $0.2n^2 = 10^4$ where $n \approx 231$
For the last part I don't get why the solution put summation of $0.3r$. According to the explanation above, isn't it correct just to solve the equation
$0.4n = 10^4$ because we need to see whether $2^n$ has $10^4$ digits?
summation implies the summation of the digits, but that means writing all numbers $2^n$ side by side, which the problem did not intended.
Hope anyone would shed some light with this one.
Comment: Not sure what the goal is here.  Are you just looking for a heuristic argument?  Vague probabilistic arguments aren't going to prove that a given string occurs in $2^n$.  And you seem to drop the $n$ a lot..."we can say that $2^n$ has $.4$ digits"  ought to refer to $.4n$, for instance (though $2^{100}$ has $31$ digits, so this is a very poor approximation).
Comment: $2^n$ has about $n\log2\approx0.3n$ digits
Comment: To stress: this is in no sense an "approximation" as it relies on a serious, and entirely unjustified, assumption.
Comment: But even by the standards of heuristic arguments, this is awfully vague.  If you really want to assume that all the strings are independent (even when they overlap) then the point would be to find $n$ such that there are $10^4$ strings of length $4$ amongst all of $2, 2^2, \cdots, 2^n$.
Comment: @lulu Thank you for the comment.  I guess you are right about what this problem wants. An approximation of the number, not the exact one. And you are right about the approximation of n digits.
Comment: See [this post](https://stackoverflow.com/questions/18942546/finding-digits-in-powers-of-2-fast) for using the computer for it.
Comment: $2^{212}\approx6.58\color{green}{2018}229\times10^{63}$ The fact that this is close to the estimate is either by coincidence or, more likely, by choice. Half of all 4-digit strings occur within the first $223$ powers of $2$, so this 'approximation' may be close to the expected value of $n$ for a random 4-digit string.
Comment: What is the merit of the approximation if a simple brute force search reveals the result ? Even if we assume random distribution of the digits (which is not quite correct, since the last digits are not at all random and the first follow Benfords law) , the approximation based on such an assumption would be quite poor.
Answer: The digits of 2^n are pseudo-random (hard to predict, behaving like random except they are of course deterministic) except for the first and last few digits. So if you calculate values 2^n until you produced 10,000 digits, there is a good chance that four consecutive digits equal 2018, or any other four digit sequence. Of course it may happen a bit earlier or later.
2^n has roughly 0.3n digits. The powers 2^k for k <= n have a total of 0.15n^2 digits. You can reasonably expect a solution for some k <= sqrt(10,000 / 0.15) or k <= 260, which would have about 78 digits.
A much smaller solution (say k <= 100) or having to calculate many more powers (say first k >= 1000) is possible, but unlikely.
And as said elsewhere, there is an infinite number of k such that 2^k even starts with 2018.
Comment: The last digits are far from being random.
Answer: Since $log_{10}2$ is irrational $\{n*log_{10}2\}$, $n \in N$ is uniform distributed on $[0,1]$. In particular it is dense on $[0,1]$. Thus, there is a $n \in N$ such that $n*log_{10}2 \in [log_{10}2.018,log_{10}2.019]$. It means that some $k\in N$ we have $$log_{10}2.018 + k <= n*log_{10}2 < log_{10}2.019 + k+1$$ or $$log_{10}2018 + k-3 <= nlog_{10}2 < log_{10}2019 +k-2$$ that is $$log_{10}2018*10^{k-3} <= log_{10}2^n <log_{10}2019*10^{k-2}$$ which is $$2018*10^{k-3} <= 2^n < 2019*10^{k-2}$$ In words, power of 2 starts with 2018. So, there are infinite many powers of 2 which start with 2018. If you want to find the first one ... good luck with that.
Comment: The question is not concerned with powers of 2 that start with 2018. The question is asking about the smallest power of 2 with 2018 as a substring, which happens to be $2^{212}$
Comment: You have completely missed the point.
Comment: If it starts with 2018 it means it contains it. That $2^{212}$ contains 2018 is an accident.


Observer in magnetic and electric fields

Question: respect an inertial observer O, I have an object of weight m and charge $q$. It is in a electric field $E=(E,0,0)$ constant and a magnetic field $B=(0,0,B)$ constant. I have another observer o' that moves along the y axis with speed $(0,-E/B,0)$ I have to rewrite the dynamics equation respected o' observer and show that it is a cicular uniform motion.
I think the dynamics equation of the observer o' is the same than the other because his movement has acceleration zero but I can't prove is circular.
Comment: Hello! If you want a physical argument, you should consider asking this at physics.stackexchange.com. On the other hand, if you want strictly mathematical help with the change of coordinates, you should provide the dynamical equation you want to transform, any work you've done so far on it, and where you've gotten stuck.
Comment: Should this be moved to physics.SE?
Comment: yes, i have that the dinamic equation of the observer O is $a(t)=q/m(v_2 B+E,-v_1 B,0)$I prefer mathematical solution because Im studying maths XD thanks. Myy problem is that I dont know how to get the velocity or what I need to see is circular because we havent done very much about diferential equations, we have a basic level.
Comment: I think by inertial u mean at rest because otherwise the second observer is also in inertial frame.
Comment: yes, at rest, sorry if my translation is bad, in spanish, is inertial
Comment: @robjohn Yes. it should be. there is not much maths in it.
Comment: @Verod: please add the dynamic equation to the question. Questions should be self-contained and comments should be treated as removable.
Answer: Okay , then.In o' frame $$\vec v=-E/B \hat j $$
$$\vec B= B_0  \hat k $$
$$\vec E=E_0   \hat i$$
$$\vec F_B=q(\vec v \hat j \times \vec B \hat k)=qvB \hat i=-qE  \hat i$$
$$\vec F_E=qE  \hat i$$
So, $$\sum\vec F=0$$
So, its same as in frame of observer O as no extra force comes into scene due to relative speed.
Now, if we observe the scenario in O frame ,
$$\vec F_E=qE \hat i$$
So, $$\vec v=qEt \hat i$$
$$\vec F_B=q(\vec v\times \vec B)=q(qEtB)\ \perp \hat v\ in\ X-Y \ plane$$
Now as $V$ and $F_b$
 are $\perp$ then the motion is a circular due to $F_B$ but the drag due to $\vec E$ will distrott the circular motion and particle will move in a complicated path.
A very-very$\times \infty$ rough diagram of path:
The radius goes on increasing due to increasing speed and particle is dragged to +ve direction of X-axis.


Is k-means clustering supposed to behave like this?

Question: First of all, data I'm using can be found here.
My code is:
library(readxl)
prouni <- read_excel("C:/Users/e270860661/Downloads/prouni.xlsx",
                 sheet = "Formatados_para_rodar")
View(prouni)
str(prouni)

coercivo <- data.frame(prouni$mensalidade, prouni$Medicina,
prouni$nota_integral_ampla)
summary(coercivo)
coercivo$dropador <- complete.cases(coercivo)
summary(coercivo$dropador)
final <- coercivo[coercivo$dropador == TRUE,]
final$dropador <- NULL

set.seed(100)
analise <- kmeans(final, centers = 4)
str(analise)

plot(final, col = analise$cluster)

The plot I get is:
For context, "mensalidade" means "tuition", "medicina" is a dummy variable (1 for a given program being Medicine and 0 for not being Medicine) and "nota_integral_ampla" is equivalent to required SAT score to be approved in the program.
My problem is that clustering doesn't seem to be working "multivariably". The algorithm seems to have chosen tuition thresholds and classified observations considering only these thresholds. Is my intutition right or is kmeans supposed to do this? Is there a coding error?
I'm an economist by training so this is all very new to me, sorry if it's a poorly elaborated question.
Answer: I think what is seen is an artefact of having data in different scales, using somewhat inappropriate $k$ and potentially employing an inappropriate clustering algorithm.
As the data in the sample's dimensions are on substantially different scales, it is problematic to use the raw data directly. That is because simple Euclidean distances between data-points are potentially irrelevant if the differences in scale do not translate to difference in importance. If we think that all features are equally important the easiest way to achieve that is by using normalised data in the sense of : newfinal <- apply( final, 2, scale) where the values of the features contained on the columns of newfinal are set to have mean $0$ and variance $1$. That said, I do not think that using $k=4$ is a good choice, even with standardised data. I say that based on how the data look as well as what standard metrics for choosing $k$ like the GAP-statistics (available in cluster::clusGap) suggest. Running something like: clusGap( newfinal, kmeans, K.max = 6, B = 100) strongly suggests that $k=4$ is overkill and potentially $k=2$ is a much more reliable options. You can use other metrics too (e.g. fitting a Gaussian Mixture Model and examining the relevant AIC, BIC values) but I suspect these will also suggest $k<4$.
Check out MATLAB's tutorial on Cluster Using Gaussian Mixture Models and its relevant links. It is well written and easy to follow.  $k$-means is a special case of a GMM so this can help your understanding a lot.
Aside using $k$-means I would suggest look into a density-based approach like DBSCAN. This algorithm can be easily used by using the function dbscan::dscan. The DBSAN results suggest having two major clusters and 2-3 smaller/outlier clusters. The relevant command will be something like : analise2 <- dbscan( newfinal, eps = 1). Notice DBSCAN requires to define a smallest relevant "neighbourhood size, the parameter eps, there is very good thread here explain the role of the parameter eps in more detail.
Comment: Late by 20 sec. Oh well.
Comment: I'm almost ashamed of the half-assed answer I gave comparing to yours.  XD
Comment: We good, no worries. Practice makes perfect. (+1)
Comment: Damn, that's a great answer. I have a question now, which I hope you (and Marcelo <3) can answer too.

Is changing mensalidade to standard-deviations from mean mensalidade something to consider as far as clustering _tecniqués_ go?  I mean, it does make sense to the economist in me. I'm more interested in relative tuition costs (thus, prices), not on the exact amount of brazilian reais someone spends on a given program.

Anyway, I'll check dbscan out. Thanks for the tips!
Comment: _Let me know if this should be in a different question_

I've run this code:

    analise2 <- dbscan(final, eps = 100)
    summary(analise2)
    summary(final)
    hullplot(final, cl = analise2$cluster)

And [this is the plot](https://i.imgur.com/v0NhqdO.png). I know some topology and $\epsilon$-radius neighborhoods are not new to me, but interpreting this plot surely is. Also, what are PC1 and PC2?
Comment: @PedroCavalcanteOliveira: 0. I am happy I could help! 1. Yes, using relative costs would be very reasonable. It will also make your findings potentially more transferable too 2. You seem to be using the Principal Component scores as surrogate data. That is not a bad idea! (Actually I would say it is a rather good one!) I am a bit confused as what dbscan function you are using. I think this is more suitable for a separate question.
Comment: As a principal: When clustering the measurement of similarity between our points is as important if not more important to the actual algorithm we are using.

That's why we opt to normalise our sample almost by convention; the most common distance (i.e. Euclidean) usually gives coherent similarity scores for points coming from a normalised sample, that is not always the case and that's why we have many different distance metrics. See for example the "Gower distance" (Gower 1971, *Biometrika*) that works both with categorical and continuous data natively.
Comment: Hey, I made a question specifically about PCA. Here it is, if you guys don't mind helping me out a bit more: https://stats.stackexchange.com/questions/362349/how-do-i-interpret-principal-components-in-k-means-analysis
Answer: Welcome to Cross Validated!
Notice that your two quantitative variables are on different scales, with mensalidade ranging from zero to ten thousand and nota_integrada ranging from 450 to 800 (say).  Since the k-means minimizes a sum of squares involving the three variables, mensalidade's variability is swallowing the variability of the other two.
Standardize both variables and give it another try. (Notice that medicina will range between 0 and 1, there is no need to standardize it too).
Comment: (+1 for spotting the scale issue) Notice that normalising the indicator variable `medicina` is not a bad idea. If we ultimately use a technique that uses the covariance matrix of our data, it sensible to have variance $1$ across all our features. Just because a feature's values are `0/1` do not guarantee unit variance.
Comment: Indeed, it will not guarantee unit variance but that is not even the point.  The difference of scale is so grossly wide, that magnitide of the variance will be immaterial.  Once the two other variables get padronized (and get to the same univary scale), the variance of the dummy will be roughly on the same order of magnitude of the two quantitatives, so rescaling it will make only a marginal effect.
Comment: Marcelo, I wish I could accept your answer too, but the other one certainly took more time to be written, so I'll give user11852 the points, sorry.

I'm very thankful for your answer, tho!
Comment: @PedroCavalcanteOliveira I could not agree more. His answer is way more complete than mine. **I** would vote his.
Comment: Cross Validated will not allow me to greet Pedro with a hello. I'm trying to include that polited piece of starters, but Cross Validated is being ruthless with my attempts.


Responsive images with high performance

Question: I'm making a new webiste and I want to configure it to load different image in mobile version.
I saw some solutions that can fit my needs.
My question is what is the best solution for high performance.
What is the solution that will prevent the explorer to load unnecessary contents.
One method is using html5's  element:
<picture>
 <source srcset="img_smallflower.jpg" media="(max-width: 400px)">
 <source srcset="img_flowers.jpg">

</picture>

Another method is using css display property:
.img-responsive.mobile {
  display: none;
}

@media only screen and (max-device-width: 480px) {
  .img-responsive {
    display: none;
  }
  .img-responsive.mobile {
    display: block;
 }
}

I don't know any other methods.
I would like to know what is the best option for high performance
thank you
Comment: I recommend using the `` element for most cases.
Answer: All you need to do is to set a few CSS attributes to the img-responsive class, for example:
.img-responsive {
  width: 100%;
  max-width: 400px;
  height: auto;
}

Comment: I want to load completely different image in mobile version.

Responsive images with high performance


Show there is no isomorphism between a subgroup of $ \mathbb{Q}$ and $\mathbb{Z} \times \mathbb{Z}$

Question: I am currently working on a problem trying to prove that there is no subgroup  $ H $ of $\mathbb{Q}$ such that $H \cong \mathbb{Z} \times \mathbb{Z}$.
I was able to show that $\mathbb{Q}$ cannot be isomorphic to $ \mathbb{Z} \times \mathbb{Z}$, since $ \mathbb{Z} \times \mathbb{Z} $ can be generated by two elements, where as $\mathbb{Q}$ cannot be finitely generated. Also the subgroup $\mathbb{Z}$ of $\mathbb{Q}$ can also not be isomorphic since it can be generated by a single element.
However, I am somewhat stuck showing, that there cannot exist any subgroup of $\mathbb{Q}$ isomorphic to $ \mathbb{Z} \times \mathbb{Z} $. Some help would be very much appreciated.
I am also wondering, if it is also true that $\mathbb{R}$ and $\mathbb{C}$ have no subgroup isomorphic to $ \mathbb{Z} \times \mathbb{Z} $. I would guess that they do not have one since $\mathbb{Q}$ has none.
Comment: [here](https://math.stackexchange.com/questions/173049/any-finitely-generated-subgroup-of-mathbbq-is-cyclic) is a general version of the question that was actually being asked.
Comment: Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer.
Comment: I don't know how $ \mathbb{Q} $ being divisible helps. But I have a different idea. Can I say that any subgroup that is finitely generated in $ \mathbb{Q} $ has to be cyclic. Since $ \mathbb{Z} \times \mathbb{Z} $ can be generated by at least two elements we would need a subgroup that can also be generated by at least two elements. But this subgroup of $ \mathbb{Q} $ would be cyclic. Since $ \mathbb{Z} \times \mathbb{Z} $ is not cyclic we are done with the proof?
Comment: @MathMaestro sure, but how would you show that every finitely generated subgroup of $\mathbb{Q}$ is cyclic?
Comment: Yes. And to comment on $G=\mathbb{R}$ or $G=\mathbb{C}$. For each $n$ our $G$ has a subgroup isomorphic to $\mathbb{Z}^n$. That's because $G$ is a vector space over $\mathbb{Q}$ of infinite dimension (by the cardinality argument). And so a choice of $n$ linearly independent numbers will generate such subgroup.
Answer: Hint: Suppose that $f:\Bbb Z\times \Bbb Z \to H$ is an isomorphism. Take $\frac{a}{b}=f(1,0)$ and $\frac{c}{d}=f(0,1)$. Then $\langle \frac{a}{b},\frac{c}{d}\rangle = \{n \frac{a}{b}+m\frac{c}{d}:n,m\in\Bbb Z\}$ would be isomorphic to $\Bbb Z \times \Bbb Z$, but $\langle \frac{a}{b},\frac{c}{d}\rangle$ is cyclic.
Comment: Is it correct, that $ \frac{1}{bd} $ would generate the same group?
Comment: No, but it's obviously a subgroup of $\langle \frac{1}{bd}\rangle$, which is enough to prove it's cyclic. Take for example $\langle \frac{2}{3},\frac{2}{5}\rangle$. It's evident that $\frac{1}{3\cdot 5}$ is not in the group.
Comment: Thank you very much


Using C++ templates or macros for compile time function generation

Question: I have a code that runs on an embedded system and it has to run really fast. I know C and macros, and this particular project is coded mostly in C but it also uses C++ templates [increasingly more]. There is an inline function:
inline my_t read_memory(uint32 addr) {
  #if (CURRENT_STATE & OPTIMIZE_BITMAP)
    return readOptimized(addr);
  #else
    return MEMORY[addr];
  #endif
}

This function reads from memory in an optimized fashion or conventional fashion based on the current state and a bitmap that tells whether to use optimization in a specific state or not.
#define STATE_A 0x0001
#define STATE_B 0x0010
#define STATE_C 0x0100
#define STATE_D 0x1000

#define OPTIMIZE_BITMAP 0x1010 // optimize states d and b

and during the course of execution (ok, compilation), I tried to redefine CURRENT_STATE like so:
int main(){
  #define CURRENT_STATE STATE_A
  do_a();
  #undef CURRENT_STATE
  #define CURRENT_STATE STATE_B
  do_b();
  ....
}

All do_X() functions make read_memory() calls. I could not make this approach work. The value of current state is always STATE_A as I can see when I use #warning statements. This is not my question, although if you can help me with this I'll be double happy. So, my question is, is there a way to do this kind of thing using templates instead of macros?
Some more info: I have to use an inline function because I cannot export MEMORY[] and this is a library function. I really prefer not to modify the function prototype (like read_memory()...) but it will do. Also, pardon my obscurity.
many thanks,
Comment: Why do you want to use templates to do this?
Comment: OK, what makes you think that a run-time decision would be too slow? Have you profiled such  a thing? We all want our code to run "really fast" and 99.99% of the time that's exactly what it does, without exotic use of macros or templates.
Comment: That's what I could think of for compile time decisions as I don't want to decide in run-time. But I'm open.
Comment: This is cuda code and I was told to minimize if statements, but maybe I have to profile it first, thanks
Comment: As it turned out in comments below, perreal is writing a library and the `do_X()` functions are actually user-supplied code.
Answer: The inline function will be parsed once, at the point in the translation unit where it is declared, and the state of the macros at that point will be used. Calling the function multiple times with the macros defined differently will not change the definition of the function.
You can do this with a template though --- if you pass the "current state" as a template parameter then you can use a different instantiation at each call point:
template<unsigned state>
inline my_t read_memory(uint32 addr) {
  if(state & OPTIMIZE_BITMAP)
    return readOptimized(addr);
  else
    return MEMORY[addr];
}

int main(){
    read_memory<STATE_A>(some_addr);
    read_memory<STATE_B>(some_addr);
    ....
}

The compiler will realise that state & OPTIMIZE_BITMAP is a constant and optimize out one or other branch of the if for each template instantiation.
Comment: And since `state` and `OPTIMIZE_BITMAP` are constants, it's very probably the compiler will eliminate the test and the deadcode altogether, thus achieving the same effect.
Answer: I think you may be misunderstanding what the compiler (or rather, the preprocessor) does with #defines.
Your example (quoted below) is not useful, because CURRENT_STATE is not used between the #define and the #undef. The preprocessor isn't 'executing' your code, or expanding do_a() inline at this point. #defines and macro expansion can only occur EXACTLY IN THE ORDER OF THE LINES IN YOUR SOURCE.
  #define CURRENT_STATE STATE_A
  do_a();
  #undef CURRENT_STATE

Here's a preprocessor-based solution, if templates fill you with horror. Let's assume that do_a() should use the optimised version.
inline my_t read_memory(uint32 addr)
{
  return MEMORY[addr];
}

inline my_t read_memory_optimized(uint32 addr)
{
  return readOptimized(addr);
}

Now, create DO_CONFIG.H
#if defined(DO_A) || (defined(DO_C) || ...)
  #define READ_MEMORY read_memory_optimized
#else
  #define READ_MEMORY read_memory

In DO_A.C, add this at the top
#define DO_A
#include DO_CONFIG.H

...and use x=READ_MEMORY(addr) instead of x=read_memory(addr). To switch from optimised to non-optimised, just change DO_CONFIG.H
Comment: @perreal. You're asking questions here. That's SMART!
Comment: so, maybe something like

#define CURRENT_STATE STATE_A
#include "usr_do_a.c"
do_a();
#undef CURRENT_STATE
...

will work? lot's of files...
Comment: @per: Please don't, that will get quite ugly. Can't the `do_X()` functions be templated instead? That would be much cleaner.
Comment: @perreal - that still won't work unless read_memory() is defined as static in each of your do_x.c files
Comment: @Roddy, @Georg: I see your point, my point being if user knows that he has to call different versions according to his needs then he might as well explicitly call a different version. My intension is to make it totally transparent (yes the bitmap is there but it's different).


On "creating" a Lipschitz continuous derivative from a strictly convex function.

Question: I believe the following statement to be true:
Let $f: \mathbb{R} \rightarrow \mathbb{R}$ be a strictly convex twice differentiable function, call it's unique global minimum $x^*$ .
Take any differentiable function $S(x) : \mathbb{R} \rightarrow \mathbb{R}$ such that $$ 0<\ell < \frac{ d(S(x) f'(x))}{dx} < L  $$
for all $x$, where $\ell, L \in \mathbb{R}$.
Then $g(x):= S(x) f'(x) $ is Lipschitz continuous and the derivative of a strongly convex function with global minimum $x^*$ .
To apply this reasoning one only needs the derivative of the function $f$ and the knowledge of strict convexity.
Is this true or is something incorrect?  Is strict convexity necessary or would convexity suffice? I have the impression that if there where multiple critical points we would need to know the minimum a priori.
Comment: "Choose $S(x)$" seems ambiguous here. Does it mean that there exists an $S$ satisfying the inequality below and making $g$ satisfying the mentioned conditions, or that for any $S$ satisfying the inequality, $g$ satisfies the conditions?
Comment: Anyway, the proposition is correct for any such $S$, and $\dfrac{\mathrm d}{\mathrm dx}(S(x)f'(x))>0$ already implies that $f$ is strictly convex.
Comment: @Saad That for any $S$ satisfying the inequality $g$ satisfies the condition.  Thanks you, maybe I should be clearer, will edit. If $f$ had multiple critical points would the statement still hold?
Answer:
Why $f$ has a global minimum? Take $f(x)=e^x$ on $\mathbb R$, you should add it to your hypothesis.

So suppose $f$ has a minimum point $x^*$ in $\mathbb R$, in general this result holds:
Theorem Let $f:\mathbb R\rightarrow\mathbb R$ a differentiable function and let $M>0$ such that $\lvert f'(x)\rvert \leq M$ for every $x\in\mathbb R$, then $f$ is a Lipschitz continuous function on $\mathbb R$.
Proof For every $x, y\in\mathbb R$ with $x\leq y$ by mean value formula we get
$$
\lvert f(x)-f(y)\rvert =\lvert f'(\xi)(x-y)\rvert\leq M\lvert x-y\rvert
$$
for some $\xi\in [x, y]$.
$\square$
Then $g(x)=S(x)f'(x)$ is clearly a Lipcschitz function. Remember that $f$ is strictly convex if and only if $f''(t)>0$ up to countable many $t\in\mathbb R$, then set
$$
F(x)=\int^x_0S(t)f'(t)\ dt
$$
you have $F''(x)=\frac{d}{dx}[S(x)f'(x)]> l>0$ so $F$ is strictly convex.
Finally because $f$ is convex we have $x^*$ is a minimum $\Leftrightarrow f'(x^*)=0$ so
$$
F'(x^*)=S(x^*)f'(x^*)=0
$$
and $x^*$ is the unique global minimum of $F$.
If $f$ is only convex we have
$$
F''(x)=S(x)f''(x)+S'(x)f'(x)=\frac{d}{dx}[S(x)f'(x)]
$$
so if $f$ has multiple minimums then doesn't exists any function $S$ that satisfies your inequality, because $f''(y)=f'(y)=0$ for all these minimums. If $f$ has only one minimum then your assertion is true and $F$ is strictly convex.
Comment: Not all strictly convex functions on $\mathbb R$ have a global minimum, in fact the exponential is strictly convex and lower bounded on $\mathbb R$ but haven't any minimum.
Comment: " Why $f$ has a global minimum? Take $f(x)=e^x$ on $\mathbb R$   " I'm not sure what you mean by this.
Comment: Ok, I see thank you. Another question:  you say there does not exist a function $S$ that satisfies the inequality in the case of multiple critical points because $f''(y) = f'(y) = 0$ but by the same logic before we had that $ f''(x^*) = f'(x^*) = 0 $ no?
Comment: Take for example $f(x)=x^2$, it is strictly convex and has only one critical point at $x^*=0$, but $f''(x^*)=2>0$.
Comment: In general if a $C^1$ convex function $f$ has multiple critical points then all these points are (global) minimum points for $f$ and the set $I$ of critical points for $f$ is an interval in $\mathbb R$. Then $f$ is constant on $I$.
Comment: So could I relax the assumptions by requiring that the additional minimum $y$ was such that $f''(y)>0$ ?
Comment: I don't understand how you would relax your assumption. If you require only that $f''(x^*)>0$ then $F=\int Sf$ could not be convex nor Lipschitz and $x^*$ may not be the minimum for $F$.
Comment: No I meant to say, that we assume there are multiple minima $y_1, y_2$ but we impose that $ f''(y_1) > 0, f''(y_2) > 0 $, to allow for the possibility of multiple minima. I hope I am clear now.
Comment: You need at least that $M\geq \frac d{dx}[S(x)f'(x)]\geq 0$ on $\mathbb R$ and it's strictly positive when $x=x^*$.


python import not working

Question: I have three files in total in python 2.7:

A module file in some directory (e.g. module1.py)
A different module in the same directory, which imports this module (e.g. worker.py)
A main script in the top-level directory importing worker.py

When the file worker.py looks as the following
import module1 as mod

everything works as expected (i.e. I can use worker.mod.XXX in my main code). But when I replace the content of worker.py as follows (which I expected to do the same):
mod = __import__('module1')

I get an error: ImportError: No module named module1. I need the latter way to handle things to automate importing modules from a list.
What am I missing here?
To be more precise: I am just looking for a way to replace the statement
    import module1 as mod
by an expression in which module1 is a string. I have e.g. modulname='module1', and want to import the module with the name of the module given in the string modulname. How to do that?
Comment: I believe there should be another factor, because `__import__()` is directly invoked by the `import` statement.
Comment: What factor do you mean?
Comment: Well, for example does this error appears ONLY when you change this particular line of code (and absolutely everything else, including how the program is launched is the same)?
Comment: Yes. I only try to import the same module in a different way, everything else is the same.
Answer: __import__(name, globals={}, locals={}, fromlist=[], level=-1) -> module
Import a module. Because this function is meant for use by the Python
interpreter and not for general use it is better to use
importlib.import_module() to programmatically import a module.
The globals argument is only used to determine the context;
they are not modified.  The locals argument is unused.  The fromlist
should be a list of names to emulate from name import ..., or an
empty list to emulate import name.
When importing a module from a package, note that __import__('A.B', ...)
returns package A when fromlist is empty, but its submodule B when
fromlist is not empty.  Level is used to determine whether to perform
absolute or relative imports.  -1 is the original strategy of attempting
both absolute and relative imports, 0 is absolute, a positive number
is the number of parent directories to search relative to the current module.
Comment: Man, this is helpful, if you do not understand the basics nobody can't help you.
Comment: I tried to use `importlib`, but `importlib.import_module('module1')` gives the same error.
Comment: OK, how to place module which you want to import against place where you do import?
Comment: First, I do not understand your comment. Secondly, I am just looking for a way to replace `import module1 as mod` by an expression in which `module1` is used as string. I have e.g. `modulname='module1'`, and now I want to import the module with the name as defined in the string `modulname`. How to do that?
Comment: At first try to understand how MRO working in Python. This is a really ordinary theme which discussed here many times. Read this http://stackoverflow.com/questions/10287054/how-to-import-the-src-from-the-tests-module-in-python
Comment: This is not helpful. This does not answer my question
Comment: @Alex: I don't think you'll get much more help here if you continue making comments like that :)
Comment: I really do not understand your comments. Denis explanation is not helpful. What does it mean that `globals` is not modified? What does it mean that `locals` is unused? I do not understand. And the link provided by Denis does not seem to be related to my problem at all.
Comment: This document neither mentions `__module__` not `globals` nor `locals`. It seem to be an interesting historical document in the development of python imports, but unrelated to my problem. Also no person so far has mentioned the basic problem with my approach.
Answer: try this:
mod = __import__('module1', globals=globals())

Comment: Thank you so much!! This solves my problems with a concrete example.

python import not working


Chrome apps: Will Chrome apps work on older versions of Chrome after December 2022?

Question: Google has decided to end the ability to open the Chrome apps on Windows and MacOS after December 2022. My question is if they will work on older versions of Chrome?
Comment: As long as you don't update your old Chrome and the old app/extension it will all work for you. Google doesn't even consider the older versions of their browser as existing, they only support the most recent stable version and a few recent versions in their extended LTS for enterprises.
Comment: Thank you @wOxxOm! :) Do you know what is good for Chrome App migration? PWA doesn't work for me, because i need webviews in each opened tab in app.
Answer: June 2022: Chrome Web Store will stop offering Chrome App installations for Windows, Mac, and Linux users.
July 2022: End support for Chrome Apps on Windows, Mac, and Linux.
March 2023: Chrome Apps will no longer be launchable on Windows, Mac, and Linux.
January 2025: End support for Chrome Apps on ChromeOS.
For more Info please visit below link
https://support.google.com/chrome/thread/174381169?visit_id=638222337887590606-870330188&p=chrome_app_deprecation&rd=1


$\operatorname{Rank}(ABC) = 1$ true or false

Question: Suppose $A, B, C$ are $3 × 3$ real matrices with $\operatorname{Rank}( A )= 2, \operatorname{Rank} (B) = 1,\operatorname{Rank} (C) = 2$.
Then $\operatorname{Rank}(ABC) = 1$.
We have to find out whether the statement is true or false.
Now $\operatorname{Rank}(ABC)\leq \min\bigl\{\operatorname{Rank}(A),\operatorname{Rank}(B), \operatorname{Rank}(C)\bigr\}=1$. So it should be true!
Comment: Are you sure that the rank can't be zero?
Answer: Consider A with all zero entries except $a_{11}$ and $a_{22}$ ($rank(A)=2$). $B$ is all zeros except $b_{33}$ ($rank(B)=1$). $AB= 0$, thus $ABC=0$ and has rank $0$.


how to display an image from mysql database on a jsp page?

Question: I want to display an image that is stored in a MySQL database. To retrieve the image, I am using a servlet. Please tell me how to display it in a jsp page. This is the flow:
login.html ---> dologin.jsp

login.html and the servlet are nearly ready. Please tell me how to finish dologin.jsp.
login.html

<title>Login Page</title>

    <form id="f1" name="f1" action="doDelete.jsp" method="get" onsubmit="return ccheck()">

Welcome to DiaEmr

                        Welcome to all at the "Workshop on Ileal Interposition".

                        Brazil to inaugurate & launch this very important Data Registry

                        Key features of the solution-

        image

Portal Login

                            User ID
                        <input name="uid" type="text" />

                            Password
                        <input name="cpass" type="password" />

                            <input type="submit" class="button button-submit" value="Submit" />
                            <input type="reset" class="button button-submit" value="Reset" />

New UserRegister

</form>

servlet
import java.sql.*;
import DB.DataBaseConnection;

import java.io.IOException;
import java.io.InputStream;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class imagetestServlet
 */
@WebServlet("/imagetestServlet")
public class imagetestServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public imagetestServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
              throws IOException,ServletException {

                 Blob image = null;
                  Connection con = null;
                  Statement stmt = null;
                  ResultSet rs = null;
                  DataBaseConnection db= new DataBaseConnection();
                  ServletOutputStream out = response.getOutputStream();
                  try {
                  Class.forName("com.mysql.jdbc.Driver");
                  con=db.connet();
                  stmt = con.createStatement();
                  rs = stmt.executeQuery("select img from one where  id = '4'");
                  if (rs.next()) {
                  image = rs.getBlob(1);
                  } else {
                  response.setContentType("text/html");

                  out.println("image not found for given id");

                  return;
                  }
                  response.setContentType("image/gif");
             InputStream in = image.getBinaryStream();
              int length = (int) image.length();
              int bufferSize = 1024;
              byte[] buffer = new byte[bufferSize];
              while ((length = in.read(buffer)) != -1) {
              out.write(buffer, 0, length);
              }
              in.close();
              out.flush();

            } catch (Exception e) {
              response.setContentType("text/html");
              out.println("<title>Unable To Display image</title>");
              out.println("
Image Display Error=" + e.getMessage() +
               "
");
              return;
              }
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
    }

}

Comment: Did you try to implement something yourself?
Comment: @Funtik i tried this way
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

Insert title here
Comment: @Funtik i tried this way also
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

Insert title here
Comment: Refer 4th answer in that page it may help you to find solution to your answer [Click this URL](http://forum.springsource.org/showthread.php?59811-Jpeg-image-as-blob-in-mysql-database-how-to-show-it-on-jsp-page).
Answer: why dont you try like this:

i have a getImageDetails.jsp to retrive the image data from the database based on user_id or name or some other constraint as follows (put the code in jsp/servlet page)
int img_id = Integer.parseInt(request.getParameter("your_id"));
Connection con = //get your connection object here ;
ResultSet rs = null;
PreparedStatement pstmt = null;
OutputStream oImage;
try {
pstmt = con.prepareStatement("your sql statement for retriving the image column data");
pstmt.setInt(1, img_id);
rs = pstmt.executeQuery();
    if(rs.next()) {
        byte barray[] = rs.getBytes(1);
        response.setContentType("image/gif");
        oImage=response.getOutputStream();
        oImage.write(barray);
        oImage.flush();
        oImage.close();
    }
}
catch(Exception ex){
    //ex.printStackTrace();
}finally {
    try{
    if(con!=null)
       con.close();
    }catch(Exception ex){
       // ex.printStackTrace();
    }
}

then i am calling this page from html or any another jsp page as follows

please try like this you will get answer
let me know the status
happy coding
Comment: its throwing java.nullpointer exception. well i am checking it
Comment: can you post total error msg to me so that i will let you know where is the problem and one more thing have you updated the code with your database details check it once
Comment: your  helped me because i have developed using servlet.thanks
Comment: thats not a big issue whether it is jsp or servlet. you may copy the code to servlet. i think you know this concept right. try to change that to servlet. let me know if you get any problem
Comment: i have a form having fields like name,age etc and one field to get image. i have 2 tables one for storing details and another for storing image. the form action calls a servlet that stores details except image. i have designeda  servlet that stores images into the DB. Please tell me how to call this servlet. Can one submit call 2 servlets.


Crash in react-native-Uuid-generator when using library in expo app

Question: I want to generate a uuid in ReactNative app built with expo cli.. when I install UUIDGenerator from React-native-uuid-generator, I get undefined is not an object(evaluating 'RNUUIDGenerator.getRandomUUID'..)
Tried two dif libraries, react-native-uuid, and React-native-uuid-generator, same problem, think it might have to do with expo not liking the link command.
UUIDGenerator.getRandomUUID().then(uuid => console.log(uuid));

Expecting new uuid to be printed, actually getting error message.
Answer: react-native-uuid works with expo.
npm install react-native-uuid --save

import uuid from 'react-native-uuid';

then generatte uuid like
const uuid = uuid.v1();

Comment: Does not work with ejected expo due to missing `stream` dependency
Comment: We recently released an updated version using TypeScript – https://github.com/eugenehp/react-native-uuid


Find lines that contains a specific string and randomly pick one in c#

Question: So, I have a text file that looks like this:
[hello]Hi
[hello]welcome back
[hello]Hello sir
[goodbye]goodbye sir
[goodbye]until next time
...

And here is a part of the code:
string[] responseLines = File.ReadAllLines(@"responses.txt");
Random rand = new Random();
string response;

case "hello":
    chatBox.Items.Add(Me);
    response = responseLines[rand.Next(responseLines.Length)];
    JARVIS.SpeakAsync(response);
    chatBox.Items.Add("Jarvis: " + response);
    break;

The problem is that I want to find ONLY the lines that contains [hello] and then randomly pick one of them.
Answer: Instead of
string[] responseLines = File.ReadAllLines(@"responses.txt");

use
string[] responseLines = File.ReadAllLines(@"responses.txt").Where(s => s.Contains("[hello]")).ToArray();

Answer: After reading all string in file, split them in two different list:
string[] responseLines = System.IO.File.ReadAllLines(@"responses.txt");
List<string> helloStrings = responseLines.Where<string>(str => str.StartsWith("[hello]")).Select(str => str.Replace("[hello]", "")).ToList<string>();
List<string> goodByeStrings = responseLines.Where<string>(str => str.StartsWith("[goodbye]")).Select(str => str.Replace("[goodbye]", "")).ToList<string>();

now pick up a random element from the list you need
Comment: I tried but i cant? Im new to this site. I think i need atleast 15 reputation?
Comment: Works too! exactly what i was looking for :)
Comment: Maybe, I'm new to this site too. I upvoted your comment, I think this gave you some reputation point. anyway, not really important.


Interpreting simple linear regression

Question: Good day,
I will am currently doing some self-study on Simple Linear Regression. I understand the formula:
$$\hat{Y}_i=\beta_0+\beta_1 X_i$$
But what does it mean when the value of $\beta_1$ is 0? Does it mean that $X$ and $Y$ have no relationship?
Appreciate some advice and explanations please
Comment: Since you have $\hat y_i$ on the left, your right hand side should have $\hat \beta$'s. While you're editing, please remove the "e" from the end of the word 'formula'; you have only one formula so you should not use the plural.
Answer: If $X$ and $Y$ have no linear relationship, i.e. $\beta_1=0$, then no matter what value $X$ is, the predicted value for $Y$, $\hat{Y}$, is $\beta_0$.  If you draw the regression line, it would be a flat line with the y-intercept at $\beta_0$.  It might help to also think about the interpretation of the slope $\beta_1$ as the change in $\hat{Y}$ for a 1-unit change in $X$.  Notice that if the slope is 0, then the value of $\hat{Y}$ does not change with $X$ (no linear relationship).
Comment: +1, though in respect of your last sentence, it's possible for the slope coefficient of a linear model to be 0 while there is nevertheless a relationship (for example if we fit a linear relationship, but the relationship is nonlinear in a way that's orthogonal to the linear term). I'd have said "no *linear* relationship"
Answer: @jsk 's answer is mostly correct, but perhaps needs more emphasis on the last sentence: No linear relationship. For example, if y = sin(x) and x goes from 0 to pi, then a linear regression of y on x will have a parameter estimate very very close to 0. In the real world, this might be approximated by the relationship between month of year (1 to 12) and average temperature.
There are also some U and inverse U shaped relationships. For example, the relationship between exam score and anxiety is inverse U shaped. $\beta_1$ isn't 0 in this case, but it doesn't reflect the relationship.

Interpreting simple linear regression


Formatting string in python

Question: I want to write to a file in tabular format and following is code I have written till now.
file_out=open("testing_string","w")
file_out.write("{0:<12} {1:<20} {2:<30}\n".format("TUPLE","LOGFILE STATUS","FSDB STATUS"))
file_out.write("{0:12}".format("Check"))
file_out.write("{0:12}".format("_5"))
file_out.close()

Testing_string looks like this.
TUPLE        LOGFILE STATUS       FSDB STATUS
Check       _5

Problem is I want _5 to be with check. Please see that I cannot concatenate check with _5 as check is printed first in file then depeding on some logic I fill LOGFILE STATUS FSDB STATUS. If I am unable to fill status then I check if I have to append _5 or not. so due to this I cannot concatenate string.
How to then print _5 right next to Check?
Comment: Do the calculation before you write it out. You can't write out `'Check       '` and then backspace to write out `_5`.
Comment: @AChampion Not true.  One can use the `'\b'` character, which is the [ASCII](http://www.asciitable.com/) character code 8, literally called "backspace". It's not elegant, but it's possible.
Comment: This will depend... the file will contain `Check   \b\b\b_5` which may more or may not work. Displaying that file may show the right thing but the file still contains the extra characters, e.g. if you were to read it back in with python, you would have to explicitly deal with `\b\b\b`.
Answer: In a perfect world, you wouldn't do what is given in the below answer. It is hacky and error-prone and really weird. In a perfect world you would figure out how to write out what you want before you actually write to disk.  I assume the only reason you are even considering this is that you are maintaining some old and crusty legacy code and cannot do things "the right way".

This is not the most elegant answer, but you can use the backspace character to overwrite something previously written.
with open('test.txt', 'w') as file_out:
    file_out.write("{0:<12} {1:<20} {2:<30}\n".format("TUPLE","LOGFILE STATUS","FSDB STATUS"))
    file_out.write("{0:12}".format("Check"))
    backup_amount = 12 - len("Check")
    file_out.write("\b" * backup_amount)
    file_out.write("{0:12}".format("_5"))

Output:
TUPLE        LOGFILE STATUS       FSDB STATUS
Check_5

This only works in this specific case because we are completely overwriting the previously written characters with new characters - the backspace nearly backs up the cursor but does not actually overwrite the previously written data.  Observe:
with open('test.txt', 'w') as f:
    f.write('hello')
    f.write('\b\b')
    f.write('p')

Output:
helpo

Since we backspaced two characters but only wrote one, the original second character still exists.  You would have to manually write ' ' characters to overwrite these.
Because of this caveat, you will probably have to start messing with the length of the format codes (i.e. '{0:12}' might need to become '{0:5}' or something else) when you add '_5'. It's going to become messy.
Comment: Just to be clear the file contains `Check   \b\b\b_5` not `Check_5`, this may or may not be sufficient. Personally, I would find some other way to do this.
Comment: @AChampion Agreed, which is why I have a paragraph at the top stating that this is a bad idea and the OP should try to do it the right way in the first place.
Answer: The problem is that you are specifying 12 characters for Check. Try this:
file_out=open("testing_string","w")
file_out.write("{0:<12} {1:<20} {2:<30}\n".format("TUPLE","LOGFILE STATUS","FSDB STATUS"))
file_out.write("{0:5}".format("Check"))
file_out.write("{0:7}".format("_5"))
file_out.close()

Formatting string in python


Django model FilterSet - choose database and update filter fields from view

Question: I have a Django application working with multiple databases of the same structure. Database name is a part of the url so it comes as an argument into the view (self.kwargs['db']). I use django-tables2 along with django-filter to show  table data (SingleTableMixin, FilterView). I need to set which database has to be used to populate the filter's fields. The filter uses the default one at the moment.
filters.py
class FooFilter(django_filters.FilterSet):
    class Meta:
        model = Foo
        fields = ['project', 'fooclass']

views.py
class FilteredFooView(SingleTableMixin, FilterView):
    template_name = "metadata/metadata-filtered-table.html"
    table_pagination = False
    table_class = FooTable
    model = Foo
    filterset_class = FooFilter

    def get_queryset(self):
        return Foo.objects.using(self.kwargs['db']).all() # sets db for the table

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        template_input = {'item': 'FooItem', 'name': getName(self.kwargs['db'])}
        context = {**template_input, **context, **self.kwargs}
        return context

Answer: You should be able to pass the db name in the kwargs,
and then use it during the init of the FilterSet
some helpful info here; https://django-filter.readthedocs.io/en/stable/guide/usage.html#request-based-filtering
class FilteredFooView(SingleTableMixin, FilterView):
    template_name = "metadata/metadata-filtered-table.html"
    table_pagination = False
    table_class = FooTable
    model = Foo
    filterset_class = FooFilter

    # pass the db name to the FooFilter
    def get_filterset_kwargs(self, filterset_class)
        kwargs = super(FooFilter, self).get_filterset_kwargs(filterset_class)
        kwargs['db'] = self.kwargs['db']
        return kwargs

class FooFilter(django_filters.FilterSet):

def __init__(self, **kwargs):
    # capture the db name
    self.db_ = kwargs.pop['db']
    super(FooFilter, self).__init__(**kwargs)
    # override the base queryset
    self.queryset = Foo.objects.using(db_).all()

    class Meta:
        model = Foo
        fields = ['project', 'fooclass']


Qt 4.8 compiling from ubuntu to windows

Question: I have a simple app that I can compile on the desktop for Ubuntu 12.04, but not for Windows. I installed the MinGW toolchain, both from synaptic, and the QT 64-bit package from here.
I went to Tools-->Options-->Build, and manually added both the /usr/bin/i686-w64-mingw32-g++, as well as the g++.exe from the link above (in the bin folder) as MANUAL_1 and MANUAL_2.
When I go to create a custom target however I am unable to select either Manual toolchain and it reverts back the standard GCC x86_64 linux.
What am I doing wrong?
I doubted the g++.exe file would work since that is a windows binary, but why does it not select the system mingw binaries?
Comment: Added Qt Creator tag, as this seems to be issue with that. What version of Qt Creator? You shoild probably try with latest, the whole thing got a re-design in a recent version.
Answer: Few things you should check

Your gcc version number
Is your gcc path added to environmental variable?

I too found it very difficult to compile my MINGW Qt application in Windows, and after lot of research on net I found that qt4 works with gcc 4.4.0 MINGW. I downloaded qtcreator 2.1 from qt website and copy MINGW folder from qtcreator directory, copy that folder into my windows root directory then installed latest qt creator and qt4 sdk,
Add path of gcc
and finally qt creator compiles my code.

Qt 4.8 compiling from ubuntu to windows


A summation identity which is for me hard to verify

Question: I found a summation identity when I try to figure out the proof of an exercise in Apostol's Mathematical Analysis (Page 27, Exercise 1.26):
$\ ~~~~$ If $a_1\geq a_2\geq \dots\geq a_n$ and $b_1\geq b_2\geq \dots\geq b_n,$ prove that
$$\sum_{k=1}^n a_k\cdot\sum_{k=1}^n b_k\leq n\sum_{k=1}^n a_kb_k.$$
I have at last proved this reslut based on the summation identity. That summation identity is
\begin{gather*}
\sum_{1\leq i<j\leq n} (\alpha_i+\beta_j)=\sum_{i=1}^{n-1} (n-i)\alpha_i+\sum_{i=1}^{n-1}i\beta_{i+1},~\forall \alpha_i,\beta_j\in\mathbb{C}, 1\leq i<j\leq n.
\end{gather*}
And I want to verify this identity, for I have never seen it. I have tried using induction on index $n,$ but was stuck. Although this identity is obvious, so is the proof, I have trouble in verifying it.  Can anyone give me some clues?
Comment: I think you have written the inequality in the wrong direction.
Comment: @EinarRødland, can you explain in some detail?  Actually I have checked this identity for $n=5,6,\cdots,20$ via Maple.
Comment: If you set $a_1=b_1=1, a_2=b_2=0$, the left-hand size becomes $1$ and the right-hand side becomes 2. The inequality should be $\le$.
Comment: @EinarRødland: If $a_1=b_1=1, a_2=b_2=0,$ and we just take $n=2,$  then the left side of the identity is just $\sum_{1\leq i<j=n=2} (\alpha_i+\beta_j)=\alpha_1+\beta_2=1,$ in this case the right side is $(2-1)\alpha_1+\beta_2=1+0=1,$ which implies the identity is valid.
Comment: In the top inequality, the left side becomes $(a_1+a_2)\cdot(b_1+b_2)=1$, while the right side becomes $n\cdot(a_1b_1+a_2b_2)=2$. It is not true that $1\ge2$.
Comment: Sorry, I've mistyped. Now it is right.
Comment: Can't you just use rearrangement inequality to prove the first guy?
Answer: I have two different proofs of the initial inequality, not based on the equality you cite. The first one is the simpler one, while the second one is perhaps more "analytical".
First, we can notice that for any $i,j$, we have
$$
(a_i-a_j)(b_i-b_j)\ge0 \implies a_ib_i+a_jb_j\ge a_ib_j+a_jb_i.
$$
E.g. if $i<j$, both $a_i-a_j\ge0$ and $b_i-b_j\ge0$, and the product is non-negative; if $i>j$, both factors are $\le0$, and the product is again non-negative.
Now, we have
$$
\sum_{i=1}^n a_i\cdot\sum_{j=1}^n b_j
=\sum_{i,j}a_ib_j=\frac12 \sum_{i,j}a_ib_j+a_jb_i
\le\frac12 \sum_{i,j} a_ib_i+a_jb_j
=n\sum_{i=1}^n a_ib_i.
$$

The second proof starts of with the interpretation of this inequality that is used in statistics.
First, if we let $\bar a=\frac{1}{n}\sum_{i=1}^n a_i$ and $\bar b=\frac{1}{n}\sum_{i=1}^n b_i$, we can rewrite the inequality as
$$
\text{cov}[A,B]=
\frac{1}{n}\sum_{i=1}^n(a_i-\bar a)(b_i-\bar b)
=\left(\frac{1}{n}\sum_{i=1}^n a_ib_i\right)-\bar a \bar b
\ge0
$$
which is simply the expression for the covariance of the two series, with $A=(a_1,\ldots,a_n)$ and $B=(b_1,\ldots,b_n)$ representing the series.
In particular, we see from this that adding a constant to either of the series, i.e. $a'_i=a_i+\alpha$ and $b'_i=b_i+\beta$, does not change this covariance: $\text{cov}[A+\alpha,B+\beta]=\text{cov}[A,B]$.
Now, pick $\alpha=-a_n$ and $\beta=-b_n$, so we get $a'_1\ge \cdots\ge a'_n=0$ and $b'_1\ge \cdots\ge b'_n=0$. So proving the inequality for the original series is equivalent to proving it for $A'=(a'_i)$ and $B'=(b'_i)$: i.e. we need to prove that
$$
\sum_{i=1}^{n}a'_i\cdot\sum_{i=1}^{n}b'_i\le n\cdot\sum_{i=1}^n a'_ib'_i.
$$
However, since $a'_n=b'_n=0$, we can drop the $n$th term and only sum for $i=1$ to $n-1$, which reduces the problem to a shorter series. Now, we can use induction. The inequality certainly holds for $n=1$. If we assume it holds for sequences of length $n-1$, we know that
$$
\sum_{i=1}^{n-1}a'_i\cdot\sum_{i=1}^{n-1}b'_i\le (n-1)\cdot\sum_{i=1}^{n-1} a'_ib'_i
$$
by the induction hypothesis. And since the $a'_i$ and $b'_i$ are all non-negative, this makes
$$
\sum_{i=1}^{n} a'_i\cdot\sum_{i=1}^{n}b'_i
=\sum_{i=1}^{n-1}a'_i\cdot\sum_{i=1}^{n-1}b'_i
\le (n-1)\cdot\sum_{i=1}^{n-1} a'_ib'_i
\le n\cdot\sum_{i=1}^{n} a'_ib'_i.
$$
Answer: This is just counting.
Among the integer pairs $(i,j)$ with $1\leq i < j \leq n$, for every fixed value of $j$, there are $j-1$ possible values for $i$, therefore there are $j-1$ pairs with a given $j$.
Consequently, the sum on the left-hand side adds $\beta_j$ precisely $j-1$ times.
Likewise, if we instead fix $i$ and look for pairs $(i,j)$ with $1\leq i < j \leq n$, we find $(n-i)$ valid values for $j$, hence there are precisely $(n-i)$ pairs $(i,j)$ for given $i$.
Which means that the left hand side adds $\alpha_i$ precisely $(n-i)$ times.
Your summation identity combines those two facts, that's all.
Comment: thanks a lot. I will try again based on your suggestion.


Select union only if @variable is emply, using SQL stored procedure

Question: I have a stored procedure with the following UNION SELECT. I want the second select to run only if @name is empty.
CREATE PROCEDURE [dbo].[spNames]
@name NVARCHAR(20)
AS
SET NOCOUNT ON;
SELECT names FROM namesTbl1
UNION SELECT names FROM namesTbl2 //This should run only if @name = ''

Any help is appreciated
Answer: You can use if.  But if you want a single query:
SELECT names FROM namesTbl1
UNION
SELECT names FROM namesTbl2 WHERE @name = '';

Note:  because you are using UNION, this will remove duplicates (if any) from the first table.  So, if is more efficient:
if (@name = '')
begin
    SELECT names FROM namesTbl1;
end;
else
begin
    SELECT names FROM namesTbl1
    UNION
    SELECT names FROM namesTbl2;
end;


Drupal field that get db content

Question: How can I make a drupal field that gets a value from a specific database/table, it should be a select list. What I need is to have a drop down select where I can see all entries from a specific content on the drupal system. So I have content type A, and content type B. When I want to create a new content of type B I want a select box where all entries from content A are listed.
Answer: This sounds like something you can handle pretty easily with a couple of contrib modules:

If you don't already have them install Views and Entity Reference.
Add a View of type "Content", filtered by content type B. Call it something like "All type B content".
Add an "Entity Reference" display to the new View.
Add any sorting/filtering options and change the display field if required.
Repeat steps 2-4 for a new view called "All type A content", and filter by content type A instead.
Add a new field to content type A of type "Entity Reference".
On the field settings page under "Entity Selection" choose Views: filter by an entity reference view for the mode, choose the "All type B content" View, and save the rest of the field config as normal.
Repeat steps 6-8 for content type B, choosing the "All type A content" View instead.

That should get you exactly what you're looking for, with the added benefit of being able to customise the results easily with Views.

Drupal field that get db content