Find $\min\big\{ \lfloor xy + \frac{1}{xy} \rfloor \,\Big|\, (x+1)(y+1)=2 ,\, 0<x,y \in \mathbb{R} \big\}$

Question: I am invited to calculate the minimum of the following set:
$\big\{ \lfloor xy + \frac{1}{xy} \rfloor \,\Big|\, (x+1)(y+1)=2 ,\, 0<x,y \in \mathbb{R} \big\}$.
Is there any idea?
(The question changed because there is no maximum for the set (as proved in the following answers) and I assume that the source makes mistake)
Answer: There is a minimum of $6$ achieved at $x=y=\sqrt{2}-1$
to prove this, start with the identity
$\left(x-\frac{1}{x}\right)\left(y-\frac{1}{y}\right)+\left(\frac{y}{x}+\frac{x}{y}\right)=\left(x y+\frac{1}{x y}\right)$
a simple verification shows that $\left(x-\frac{1}{x}\right)\left(y-\frac{1}{y}\right)=4$
on the other hand $\frac{y}{x}+\frac{x}{y}\geq 2$
it follows that $x y+\frac{1}{x y}\geq 6$
Comment: Could you corroborate your "simple verification"?
Comment: @ Christian Blatter $(x+1)(y+1)=xy+y+x+1=2$
Comment: i am sorry but i am not able to continue with my previous comment (5 minute warning or something like that) so please solve for y and replace and a few algebra steps later you get that the expression = 4
Comment: (ok work offline to prepare the comment and then sign in and copy and paste)

$y=\frac{1-x}{1+x}$

$\left(x-\frac{1}{x}\right)\left(\frac{1-x}{1+x}-\frac{1+x}{1-x}\right)=\frac{x^2-1}{x}\left(\frac{-4x}{1-x^2}\right)=4$
Answer: This needs further verification.
I believe that the maximum does not exist since the set is not bounded above.
Suppose $x, y \gt 0$ satisfies $ (x + 1)(y + 1) = 2 $. Then we can conclude that

$ xy + x+ y = 1 $
$ 1 + \dfrac{1}{x} + \dfrac{1}{y} = \dfrac{1}{xy}  $ (dividing by $xy$)

Subtracting equation $2$ from $1$ we can rearrange this to $$ xy + \dfrac{1}{xy} = 2 + \left({\dfrac{1}{x} - x}\right  ) +  \left({\dfrac{1}{y} - y}\right  ) $$
Now notice that the expression $\left({\dfrac{1}{t} - t}\right  )$ can be made arbitrarily large by making $t$ arbitrarily small. Hence the floor function  $ \lfloor xy + \frac{1}{xy} \rfloor  $ is also not bounded above and so the maximum of the given set cannot exist.
Comment: @user221158: Does not matter. We can take both $x$ and $y$ to be very small and make the expression on the right very large. Hence the one on the left will also be very large.
Comment: Thanks. I edited the question.
Answer: Solve for one variable using the equation $(x+1)(y+1)=2$.  Solving for $x$ we get $x=\frac{1-y}{1+y}$.  Then rewrite the floor function as $\lfloor{xy+\frac{1}{xy}}\rfloor=\lfloor{\frac{y^2(1-y)^2+(1+y)^2}{y(1-y^2)}}\rfloor$, so there is no max, taking $y \rightarrow 1$
Comment: @user221158 When $y \to 1$, $x \to 0 $
Comment: Thanks. I edited the question.
Answer: From $xy+x+y=1$ and $x>0$, $y>0$ it follows that $xy<1$. Since $t\mapsto t+{1\over t}$ is decreasing when $t<1$ we conclude that we have to make
 $xy$ is as large as possible. Let $x+y=:s$. Then
$$1-s=xy\leq{s^2\over4}\ .$$
The largest possible $xy$ goes with the smallest admissible $s>0$, and the latter satisfies $1-s={\displaystyle{s^2\over4}}$. This leads then to $$x=y={s\over2}=\sqrt{2}-1\ ,$$ and finally to
$$xy+{1\over xy}=6\ ,$$
which is already an integer.


Variáveis estourando

Question: As variaveis cont_setosa, cont_versicolor, cont_virginica estao estourando no final do código, por que?? Como arrumar isso?
Antes dos IFs as variáveis estão normais, porem depois deles, ha essa alteração...

#include <stdio.h>
#include <string.h>

typedef struct element{
    int index;
    long double dist;
}Element;

int main(int argc, char const *argv[])
{
    char *classe_aux, classe_main;
    classe_aux = &classe_main;

    int k = 3;
    int i = 0;
    Element el[3] = {{1},
                     {1},
                     {1}};

    int cont_setosa = 0;
    int cont_versicolor = 0;
    int cont_virginica = 0;

    for (i = 0; i < k; i++)
    {
        if (el[i].index == 0)
        {
            cont_setosa++;
        }
        else
        {
            if (el[i].index == 1)
            {
                cont_versicolor++;
            }
            else
            {
                if ( el[i].index == 2)
                {
                    cont_virginica++;
                }
            }
        }
    }

    printf("%i %i %i\n", cont_setosa, cont_versicolor, cont_virginica);

    if ( cont_setosa > cont_versicolor && cont_setosa > cont_virginica)
    {
        strcpy(classe_aux, "Iris-setosa");
    }
    else
    {
        if ( cont_versicolor > cont_setosa && cont_versicolor > cont_virginica)
        {
            strcpy(classe_aux, "Iris-versicolor");
        }
        if ( cont_virginica > cont_setosa && cont_virginica > cont_versicolor)
        {
            strcpy(classe_aux,"Iris-virginica");
        }
    }

    printf("%i %i %i\n", cont_setosa, cont_versicolor, cont_virginica);
    return 0;
}

Saida:
0 3 0
1936876918 1819239273 29295

Comment: Não consegui reproduzir essa situação com o seu código de exemplo, precisa efetuar alguma modificação?
Comment: Não, é so rodar normalmente, não tem nem entrada o codigo, testei ele em dois compiladores no computador e um online e sempre se mantem estourando as variáveis...
Answer: Me parece que você está corrompendo a memória da pilha/stack.
A variável classe_aux é um ponteiro que aponta para classe_main.
classe_main por sua vez é uma variável do tipo char, ela armazena apenas um caractere, então quando você faz strcpy(classe_aux, "Iris-setosa") por exemplo, você está alocando o primeiro caractere 'I' no classe_main, e os outros caracteres são alocados logo em seguida, na região do stack, em posições que outras variáveis estão utilizando, corrompendo sua memória.
Se você declarar a variável classe_aux como um array de tamanho 16 por exemplo, isso já resolveria o problema de memória nesse caso.
Link com o código funcionando.

Variáveis estourando


How to make a Button direct to a link on click

Question: I've been writing some HTML code to develop a website. I want to have some buttons link to other parts of the page. The button is in a "Meet the Team" style. Here is the code:

 Lorem Ipsum

Lorem ipsum dolor sit amet, consectetur adipiscing
    elit.

<button class="button">Button</button>

I've tried to get it to link to a page but I can't find anything (I'm new to HTML). Maybe one of you can help? Thanks!
Comment: Possible duplicate of [How to create an HTML button that acts like a link?](https://stackoverflow.com/questions/2906582/how-to-create-an-html-button-that-acts-like-a-link)
Comment: The `button` element is not really the right tool for the job here. Use `a` and style it like a button. See the linked duplicate for suggestions on how you can do this. By using `button` you break expected behaviors e.g : right click giving contextual menus and middle (scroll wheel) click opening in new window.
Answer: This is the best way to link other pages style a tag looks like button:
Click me

Alternatives:
<button onclick="location.href='http://www.example.com'" type="button">
    www.example.com
</button>

Or
<form action="http://google.com">
    <input type="submit" value="Google" />
</form>

Comment: Thanks that worked, but Is there any way I can still keep the style and look of the original button?
Comment: Note that nesting a `button` in an `a` tag is [invalid html](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a)
Comment: So how would I still keep the style of the button but not nest the  in a  tag, and still make it link to a .html file on click?
Comment: 'Button'``
Answer: Your button tag is not properly formatted, the  will break your html code.
All you have to do is just pass href attribute to button.

<button type="button" class="button" href="team-page.html">Button</button>

http://www.tizag.com/htmlT/ is a very good starting point.
Comment: Thanks for pointing that out, I will go for anchor tag instead then give it a button style.


Unable to parse Json Data from json file in Android using Gson

Question: I am facing below error, I don't know why this error occurs. I spent 48 hrs and try to solve with different-different technique.

java.lang.IllegalStateException: Expected a string but was BEGIN_ARRAY at line 71 column 15 path $[11].scName.

Here is a snapshot of data, where issue is occurring:
Click to see json data.
Check below code to parse Json String,
Gson gson = new Gson();
JsonReader reader = new JsonReader(new StringReader(builder.toString()));
reader.setLenient(true);
list = gson.fromJson(reader, new TypeToken<List<SubCategory>>(){}.getType());

Answer: You could create a class
public class SubCategories extends List<SubCategory> {}

Then parse using this class directly
gson.fromJson(reader, SubCategories.class)

Comment: line 71 you don't have an array in the file you provided, are you sure that you're reading this file ?


Why my springboot application ended up like this?

Question: Here is the screenshot for the running result, the program ends immediately after running
enter image description here
And below is my pom.xml
<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.0</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>Meituan</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>Meituan</name>
    <description>Meituan</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <scope>compile</scope>
        </dependency>

        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.2</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.20</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.76</version>
        </dependency>

        <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
            <version>2.6</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.23</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
</code>
Can somebody help?
Comment: And what is the code that is running?
Comment: Please share how you're running this application (command line? maven goal? be specific) and the code that you expect to be executed (not everything if it's large, but a minimal description + configuration/code example).
Answer: In common the JVM will ends when Main Thred finished the work and no non-daemon threads. It hard to say what you have now in your code. But I can see that there are no web-server (like embedded tomcat) and guess there are no tasks (for Main thread or any non-daemon thread). It is expected behavior for current project.
There are 2 ways (depend what you want to get)

Start web server
Create task which will do anything.
Comment: Thank you, it is successfully started today and I didn't do anything to my code, it is weird.


irtouchServer on openSUSE 11.4 (i586) - (irtouchServer) did not claim interface 0 before use

Question: I'm trying to install IR Touch from IRTOUCHSYSTEMS. I download the drivers and install them but on dmsg I see:
usb 2-1.3: usbfs: process 8179 (irtouchServer) did not claim interface 0 before use

This message is repeated and touch does not work. I can not understand what is the meaning of this message. Can anyone help me to understand what is wrong and how to fix it.

# cat /etc/SuSE-release
openSUSE 11.4 (i586)
VERSION = 11.4
CODENAME = Celadon
# uname -a
Linux grkiosk3 188.8.131.52-1.2-default #1 SMP 2011-02-21 10:34:10 +0100 i686 i686 i386 GNU/Linux

http://all.bg/~tdenev/irtouch_log_configs.zip
Answer: I contact the producer of the product to help me. First the producer send me other driver (not published on the site). With this driver message is missing from dmesg, but the touch still does not work. I sow that if I run irtouchServer manually I receive:
ret=-16 :Device or resource busy

This message is repeated.
I contact the producer again and it send me some convert tool that change the product number.
Before convert the lsusb output was:

Bus 002 Device 005: ID 6615:0081 IRTOUCHSYSTEMS Co. Ltd.

After I run convert tool and re plug the touchscreen the output of lsusb is:

Bus 002 Device 005: ID 6615:0080 IRTOUCHSYSTEMS Co. Ltd.
Comment: I have exactly the same problem. Have you got a link to the flashing tool? I contacted the company some days ago but no answer yet :-(
Thank you. Eric
Comment: They send it to me by email. If you need it I will search for it and will upload it. (IF YOU USE IT IT'S ON YOUR RESPONSIBILITY, I AM NOT RESPONSIBLE FOR ANY DAMAGE ON THE DEVICE.)
Comment: Do you still have that file? I have the exact same problem...
Comment: Yes, you will find it here:
http://kontrax.bg/~tdenev/irtouch/linux_convertor.tar.gz - change ID on linux OS
http://kontrax.bg/~tdenev/irtouch/windows_convertor.zip - change ID on windows OS

If links does not work please write me.


Test hypothses in small populations

Question: I have 2 independent populations, each with N=50 people. I took n=20 samples from each population. For each person, I asked a question with an answer from 1 to 5. I want to know if there is a significant difference between the distributions of the answers of the 2 populations (e.g., mean). I can assume that the variance is the same in the 2 populations.
Which statistical test fits this scenario, and how do I use it in SPSS?
Answer: I will assume your variables are likert and ordinal from your wording in your question. Mann–Whitney U test is a common statistical test for your scenario.
It's also possible to use t-test, but that requires normality assumption. Read the following blog post to decide yourself wherther you like t-test or Mann-Whitney (I prefer Mann-Whitney):
http://blog.minitab.com/blog/adventures-in-statistics-2/best-way-to-analyze-likert-item-data:-two-sample-t-test-versus-mann-whitney
Comment: What are the implications of using a Mann-Whitney test when we have small populations and relatively large sample sizes (as a proportion of the population size)?
Comment: Yes shouldn't there be a finite population correction for each population that shoulld be used? It adds information about the mean and reduces sample variance.
Comment: Yes, and our sampling also affects the composition of the remaining unsampled population so that observations are not independent of one another.
Comment: Personally, I would start thinking about a simulation based approach using the 40 observations as a best guess at a single parent population. But the question asks for something suitable to use in SPSS. I did start to think of Chi-square/G-test approaches (with exact probabilities from multivariate hypergeometric distribution) but Tomer seems to want to explicitly test for differences in central location.

Test hypothses in small populations


How do I add prompt entry to object and have it called back in another prompt?

Question: I'm making a color guessing game. I'm trying to have a prompt ask for the players name, and then have the players first and last name pop up on the next prompt before the game starts.
function user() {
    let player = {
        firstName: '',
        lastName: ''
    }

    player = prompt("To play enter your first and last name:");
    if (player === null) {
        alert("This game is cancelled.");
        return;
    } else {
        player.name = prompt("Thank you, let get started " + player.name + "!");
        runGame();
    }
}

Answer: It seems that you're confusing variable names. You are assigning the result of the name to player variable, not player.name.
function user() {
    let player = {
      // if we're reading the full name at once we should get rid of redundancy
      name: null
    }

    // here we assign the result of the prompt to name attribute of player object
    player.name = prompt("To play enter your first and last name:");
    // honestly I don't know what empty prompt returns so I would fall back to rejecting all falsey values
    if (!player.name) {
        alert("This game is cancelled.");
        return;
    } else {
        // Alert is definitely a better choice here as the player doesn't input any information
        alert("Thank you, let get started " + player.name + "!");
        runGame();
    }
}

Answer: The prompt will return a string that must be parsed into a user's first and last names. split can do that.
The final prompt will block on user input. Presumably, this is the first move the player will make. I'd suggest moving that first input to the runGame() function, keeping the concerns of getting the player name and playing the game separated.
// just get a player object. (don't start the game)
function getUser() {
  let string = prompt("To play enter your first and last name:");
  if (!string) {
    alert("This game is cancelled.");
    return;
  }

  let names = string.split(' ');
  if (names.length < 2) {
    // handle a single name
  }

  let player = { firstName: names[0], lastName: names[1] };
  return player;
}

// start the game, given a player
function runGame(player) {
  let firstMove = prompt("Thank you, let get started " + player.firstName + "!");
  // run the game
}

let player = getUser();
if (player) runGame(player);


Which library should I use in hadoop 2.0?

Question: guys. I'm new to hadoop, and my hadoop version is 2.0.0-cdh4.0.1. But I'm confused about which library should I use. mapred or mapreduce or mapreduce.lib, jobconf or job, and so on.
I tried the examples of the 3rd education of Hadoop: The Definitive Guide, I got lots of warning. But when I tried the examples of 2ed education, it's much better. It totally confused me.
And when I tried to find some guide about hadoop, I can't finger out which version. It seems that the 2.0 version has some relationship about 0.2X? Is there some guide about hadoop 2.0?
Thanks.
Answer: 2.0.1-alpha is the current version as per the API docs (Sept 2012) - http://hadoop.apache.org/docs/current/api/
From "Hadoop: The Definitive Guide" (3rd Ed.) - page 27 "Analyzing the Data with Hadoop"
"The new API is in the org.apache.hadoop.mapreduce package (and subpackages). The old API can still be found in org.apache.hadoop.mapred."
"Job control is performed through the Job class in the new API, rather than the old JobClient, which no longer exists in the new API."


carregar metodos async antes do atribuir campo/input

Question: Olá, estou com uma dúvida referente a chamadas assincronas no javascript.
Em meu projeto, possuo um metodo que carrega os valores de resposta de uma api no formulario da tela.
No entanto, dois desses campos eu faço um novo GET para um outro endpoint para popular as options de um campo tag select.
O que ocorre e que esse campo(tag select) está carregando antes da minha chamada de requisição terminar.
Exempo no código abaixo:
            $.ajax({
            type: "GET",
            url: `$edpoint/${id}/${sku}`,
            success: function (response) {

                    buildWarrantyType(response.categoryMl);

                    //Tipo de garantia
                    document.getElementById('warrantyType').value = response.warrantyType;
                  }
                });

No trecho acima, tenho uma requisição GET que retorna a response para ser preenchida no campo tipo de garantia, porém, antes desse campo ser carregado, eu chamo a função
buildWarrantyType para realizar o carregamento das opções disponiveis para o campo 'warrantyType' e eu preciso que esse metodo buildWarrantyType seja executado e so então, o trecho com o campo warrantyType seria preenchido, somente a após a requisição terminar.
Segue abaixo o conteudo do metodo buildWarrantyType:
async function buildWarrantyType(CategoryMl) {
let response = await fetch(`endpointUrl/${CategoryMl}/sale_terms`);
let data = await response.json();

await responseWarrantyType(data);

}
async function responseWarrantyType(data) {
for (var i = 0; i < data.length; i++) {

    if (data[i].id == "WARRANTY_TYPE") {
        $('#warrantyType').empty();

        for (var x = 0; x < data[i].values.length; x++) {

            switch (data[i].values[x].name) {
                case "Garantia do vendedor":
                    $('#warrantyType').append($('<option>', {
                        value: 0,
                        text: data[i].values[x].name
                    }));
                    break;

                case "Garantia de fábrica":
                    $('#warrantyType').append($('<option>', {
                        value: 1,
                        text: data[i].values[x].name
                    }));
                    break;

                case "Sem garantia":
                    $('#warrantyType').append($('<option>', {
                        value: 2,
                        text: data[i].values[x].name
                    }));

                    document.getElementById('warranty').value = 0;
                    break;
            }
        }
    }
}

}
Como podem ver, nos metodos acima, já estão declarados com async e await, porém, não está dando certo.
Pois os campo warrantyType continuam carregando o dado sem esperar que a requisição do metodo buildWarrantyType, seja concluído.
Gostaria de saber qual a melhor forma de resolver esse problema?
Answer: Tens que usar o await na função buildWarrantyType().
     success: async function (response) {

             await buildWarrantyType(response.categoryMl);

             //Tipo de garantia
             document.getElementById('warrantyType').value = response.warrantyType;
     }


What's the relationship between Borel set and set whose boundary is measure zero?

Question: Is a set whose boundary is measure zero a Borel set?
Does any given Borel set has a measure zero boundary?
I want to give my ideas first:
If $E \subseteq  R^n $ is some set whose boundary has Lebesgue measure zero, then we can safely do the Riemann integral $\int _E1dx$, which means we can calculate the "volumn" of $E$. Hence I think $E$ is a Borel set.
But how about the inverse arguement?
Answer: To your first question:
Take the example of a non borel set from this page: http://en.m.wikipedia.org/wiki/Borel_set
Then use sterograpic representation to wrap it around the open unit disc. That set (this weird boundary union disc interior) has a measure zero boundary (closure minus interior) but is not borel, otherwise the original set would be.
Your second question:
http://en.wikipedia.org/wiki/Smith–Volterra–Cantor_set is a borel set with positive measure boundary.
So the answer to both your questions is "no".
My first example satisfies the theorem, but is not Borel. So what you would like to prove is false.
Comment: For a non-constructive answer to the first question, note that there are $2^c$ many subsets of the boundary of the unit disk in the plane, all of which have (planar) measure zero, and only $c$ many of these can be Borel sets, so *most* subsets of the boundary of the unit disk have the property that its union with the open unit disk is not a Borel set (non-Borel union Borel is non-Borel), and all the boundaries of these non-Borel sets have measure zero.
Comment: the cantor set is measure zero. and the cantor set is it's own boundary.


Significance test based on precision/recall/F1

Question: Is it possible to do a significance test based solely on precision/recall/F1 scores?
For example, if you come across 2 systems in a paper for which only P/R/F1 are reported (on the same dataset, etc.), can you then perform a statistical significance test? If yes, how is that done?
Answer: Intuitively, getting a high P/R/F1 on a small data set, or on a very uniform/predictable dataset is probably easier than getting a high P/R/F1 on larger or more chaotic datasets. Therefore, an improvement in P/R/F1 on a larger and more chaotic dataset is more significant.
Following this intuition, you would probably need access to the output of the "black-box" methods in order to measure the difference in the distribution of results, while taking into account the size and variety in that set. The P/R/F1 alone are probably too little information.
Significance testing in this setting is usually done by forming a null hypothesis (the two algorithms produce always the same output) and then calculating the probability of observing the difference in output that you are observing if the algorithms were indeed the same. If the probability is less than .05 for example, you reject the null hypothesis and conclude that the improvement is significant.
This paper has relevant discussions:
http://www.aclweb.org/anthology/C00-2137


A question on Projective modules

Question: If M is a finitely generated projective R-module then $M \bigotimes -$ is exact.
I need some help to prove this. So please give some hints.
Answer: Proceed as follows:

$M=R$ satisfies this property (which is, by the way, known as flatness).
If $M,M'$ satisfy this property, then so does $M \oplus M'$.
If $M \oplus M'$ satisfies this property, then so does $M$.
Conclude that every finitely generated projective module satisfies this property (actually every projective module, since 2. also holds for infinitely many summands).

Alternatively, finitely generated projective modules are dualizable, and dualizable objects are flat since $M \otimes -$ is right adjoint to $M^* \otimes -$.

A question on Projective modules


How to get the selected value of a dropdown inside panel?

Question: I have an exposed filter inside the panel.
I want to filter the taxonomy term. For that I add "Content: Has taxonomy term (exposed)" field.
I need to get the selected value in js.
Drupal.behaviors.mymodule = {
  attach: function (context, settings) {
    var tid = $('#edit-tid').val();
    alert(tid);

  }
};

In alert I am getting "All" rather than the selected tid, as shown in this image:
Comment: Check `onchange` event inside `attach`
Answer: Apply little trick and my issue solved. Used default taxonomy search and hide it.
(function($) {

Drupal.behaviors.tushar_1 = {
  attach: function (context, settings) {
    $('#edit-shs-term-node-tid-depth').change(function(){
      var eid = $('#edit-shs-term-node-tid-depth').val();
      $('#edit-tid ').val(eid);
    });
  }
};

})(jQuery);

Solved my issue.
Comment: I "think" that you found this solution thanks to the hint in the comment from "Sibiraj PR" (below your question). If that's the case, then I "recommend" (not more then that ...) to also add something like "**Credits to [Sibaraj PR](http://drupal.stackexchange.com/users/6508/sibiraj-pr)**".


Why is this deterministic variant of Miller-Rabin not working?

Question: I am using this paper as a reference.
The Miller-Rabin test, as classically formulated, is non-deterministic -- you pick a base $b$, check if your number $n$ is a $b$-strong probable prime ($b$-SPRP), and if it is, your number is probably prime (repeat until "confident.")
A deterministic variant, assuming your number $n$ is below some bound (say $n<2^{64}$), is to pick a small number of bases $b$, and check if $n$ is a $b$-SPRB relative to each of those bases. There seems to be a bit of a sport to finding very small sets of bases, so as to make this process as fast as possible.
In particular, the cited reference declares a theorem of Jaeschke and Sinclair, that

If $n < 2^{64}$ is a $b$-SPRP for $b\in\{2, 325, 9375, 28178, 450775,
9780504, 1795265022\}$, then $n$ is a prime.

It doesn't state any extra hypotheses on $n$, or on what it means to be a $b$-SPRP. However, the classical formulation of Miller-Rabin only talks about $n$ being a $b$-SPRP when $b\leq n-2$, whereas the theorem above seems to allow $n<b$.
In particular, I have found (purely by accident) that $n=13$ does not satisfy the above criterion, meaning that as stated it gives wrong answers, and I don't know why (so I can't predict more of them).
So the question: Is this a shortened form of a proper theorem, where I should only be checking the values of $b$ where $b\leq n-2$? Is this an error in the paper? Am I just crazy?
For sake of completeness, the definition of $b$-SPRB I am using is the one given in the paper:
Factor $n$ as $2^sd$, where $s$ and $d$ are nonnegative integers and $d$ is odd. Then $n$ is a $b$-SPRB iff $b^d\equiv 1\ (mod\ n)$ or, for some $r$ with $0\leq r < s$, $\left(b^d\right)^{2^r}\equiv -1\ (mod\ n)$.

Not a duplicate of: Bases required for prime-testing with Miller-Rabin up to $2^{63}-1$ seems to lead to the same questions (they don't address the issue of when $n<b$; it's just irrelevant there) and uses bases so small it doesn't matter.
Answer: As stated the theorem is fine, because it only says if $n$ is a $b$-SPRB for all these $b$ then it is prime; it does not say "if and only if".
A prime $p$ will be a $b$-SPRB for any base $b$ which is not a multiple of $p$. So every prime will pass the test except for primes dividing one of the bases listed. Those primes are $2, 3, 5, 13, 19, 73, 193, 407521$ and $299210837$.
Comment: Thank you for the clarification.
Answer: If you look at Best known SPRP base sets, you can see the remark "Depending on your Miller-Rabin implementation, you may need to take a ← a mod n." and "When the witness a equals 0, the test should return that n is prime."  The latter is saying we skip that test when n divides the base.
This is especially critical for making sense of the smaller base sets which generally have very large bases.
Answer: Sometimes the definition of SPRB includes the condition  $\gcd(b,n)=1$.
Anyway, if $b$ is a multiple of $n$ you have $b^d\equiv 0 \pmod n$ and $n$ cannot be a b-SPRB. So your implementation of the test is not correct, because $325 = 25\times13.$
And you should always do the simple test $\gcd(n,b)=1,$ if it fails you know $n$ is composite.
Comment: Yes, n & b should be coprime. But the problem is that some witness sets contain composites, so you need to deal with that before doing the SPRB calculation, and a simple gcd calculation may not do what you want. Eg, if 15 is in the witness set, your gcd test will detect 3 & 5 as composite.
Answer: The deterministic version requires a modification as to how base values are handled. The base b is reduced mod n, and the test skipped (e.g., 'passed') in the event that b mod n = 0. More details here.
I have a working implementation here.


Pandas DataFrame count row length for specific entry

Question: I have a data frame that looks like this.
     item   color
0   apple     red
1  orange  orange
2  banana  yellow

is there a way to count the row length of a specific entry such as "orange"? Not count the entire row length but the len of the particular "item" column. Like I want to write some type of code that would state "orange" is in the second row or second in the index.
Comment: Would you mind clarifying? Do you mean how many observations are in the item column, or do you mean the number of characters in the item column for a particular observation?
Comment: I reedited my post since it was confusing
Answer: If you are simply looking for the location of an item in the Series, you could convert it to a list and then call .index():
list(df['item']).index('orange')

You just have to keep in mind that Python is 0-indexed and so the index '1' means it is the second item.


Frontend developer screening - abstract coding

Question: I received some kind of theoretical assessment after applying for a Junior HTML/CSS developer offer.
I totally have no idea what the abstract programing language is. Is anyone able to solve this task?
Below you can find block of abstract coding. What should be instead of suspension points "..."?
$ul .= wrap(wrap($name, wrap($url, '') . '|'), '
...');
What is this function for and how it actually works?
Answer: I would replace the ... by |
.
It seems that the wrap() function takes the first parameter and puts it instead of the | char of the second parameter.
If $url contains https://www.google.com and $name contains Google then the result stored in the $ul variable will be
Google
.
Comment: Ok, so it means my answer was good. I took similar way of thinking during this assessment. Thanks for your time and help ;)
Answer: The point of it being abstract is that it's not a specific language, it's trying to test your logical thinking skills.
That being said, it looks like the wrap function accepts two strings, the second should contain a | character which will be replaced with the first argument.
The answer should be |
.
Comment: Ok, my final answer during this assessment was the same. Thanks for your time and help.


Correct or most common term for altering a loss function to ignore unlabelled pixels?

Question: In my experience it is quite commonplace to alter the loss function used when training a neural network for segmentation to ignore the contribution to the loss of unlabelled pixels. There are a few ways to implement it, but the one I have used prior is to alter network predictions to always predict truly unlabelled pixels correctly. In psuedo-code
<code>predicted[where(labels == unlabelled)] = unlabelled
</code>
Is there a common, or most common, term for this?
I am attempting to add the technique itself as part of a literature review, though I can't find any examples which "directly" reference the technique. I can really only find articles that use the technique, but really make no mention of it.
Answer: You could do almost anything to implement this -- you could set the predictions to 0, or 1, or any value for the unlabelled predictions, and the training would still work, because the autodiff engine of whatever neural network library you're using would see that those predictions are not a function of your paramters $\theta$, and therefore the update wouldn't depend on them.
In particular, setting the predicted values to the ground truth is convenient, because the resulting loss is "average cross-entropy (or other loss) of the labelled pixels", rather than "average cross-entropy of labelled pixels, plus some arbitrary constant".
A common term for this is "masking". The loss of those pixels is "masked out", because they are set to 0 / ignored.


Conjugacy in SO(1,2)

Question: I have one question:
Is there an element $g \in SO(1,2)$ such that
$$
g^{-1}\begin{pmatrix}
\cosh\psi & \sinh\psi & 0\\
-\sinh\psi & -\cosh\psi & 0 \\
0 & 0 & -1
\end{pmatrix}g = \begin{pmatrix}
\cosh\psi & \sinh\psi & 0\\
\sinh\psi & \cosh\psi & 0 \\
0 & 0 & 1
\end{pmatrix}?
$$
If $\psi \not= 0$, of course not. Just look at the spectrum.
Comment: What do $ch$ and $sh$ mean?
Comment: It is hyperbolic sine and cosine.
Answer: There is no $g \in SO(1, 2)$ (or even $g \in GL(3)$) satisfying the desired property.
Recall that $\operatorname{trace}(AB) = \operatorname{trace}(BA)$ so $\operatorname{trace}(g^{-1}Ag) = \operatorname{trace}(g^{-1}gA) = \operatorname{trace}(A)$. The trace of the left hand side is $-1$ while the trace of the right hand side is $2\cosh\psi + 1 \geq 2 + 1 = 3$; in particular, they are not equal.

Conjugacy in SO(1,2)


CouchDB in Production

Question: I have been using CouchDB on some prototype applications and it has been brilliant, very easy to use and extremely quick. I was wondering if anyone has been using it in production and have any views on it's reliability, performance suitability for operational management etc ?? I am considering using it to support a service layer and would make use of its replication functionality.
Any comments/experiences would be most welcome.
Answer: I've used CouchDB for a few small in-house applications - it's been very stable and I've had no serious complaints. Setting that aside, a few small gripes -
1) Databases can be synchronized, but not nodes. That is, if you have four servers and twenty databases, you have to specify each server, and each database to synchronize. A minor gripe, but I prefer less management to more.
2) Since databases are append only, a database with a bunch of activity gets really big really quickly. Compacting fixes this, but isn't exactly fast, especially on big (e.g. 20 gigabytes) database. Scheduling compact for the weekends solved this, but doing that is probably less of an option for high availability applications.
3) Javascript is the de facto view language. What is not well advertised is that since CouchDB is written in Erlang, it also supports Erlang views, which are faster as they are "native". For applications doing a lot of operations in views, Erlang probably makes more sense.
Setting those minor issues aside, I'd wholeheartedly recommend it.
Comment: I should clarify that compacting a database doesn't make it unavailable, but it does greatly impact performance. In fact, if writes occur faster than the compact, compact might never finish. See: http://wiki.apache.org/couchdb/Compaction
Comment: Brilliant thanks, for the advice. Especially the ip on erlang views and synchs...
Answer: CouchDB ships in Ubuntu and is a fundamental component of the Ubuntu One service.

CouchDB in Production


how to show number of cell in table view using label

Question: i have one table view which contains more that many results which will dipslay in each cell. Totally i have 50 data in table view. I did some array and display that in table view.Like this :
var tableData = ["thomas", "Alva", "Edition", "sathish", "mallko", "techno park" ..... till 50 data]

What i need is, i have one label called countlabel. Now i need to display how much data in my tableview is there? in my lbel countLabel. i need to dipslay in my label is  50 datas.... Because i am having 50 data in my table view. PLease help me how to do that ?
Thanks
Comment: do you mean you want a simple count displayed somewhere on the view - like @DarthVader has provided, or do you need something within the tableView, perhaps with each row containing a label like "row 1 of 50" ?
Comment: Doug you have any idea about UITalbeView?
Comment: What you return in `tableview(...numberOfRowsInSection)` is the count of your table view.
Answer: countLabel.text = "\(tableData.count) data"


How to change the uri error message in codeigneiter

Question: I was able to solve the problem of uri error in codeigniter as shown below:
<code> $config['permitted_uri_chars'] = 'a-z 0-9~%.:&_\-';
</code>
And now, I am looking where I could modify the error message
"The URI you submitted has disallowed characters" if it appears because I dont know where it comes from or how to do it. Also, I'd like to know how to display my own error 404
page when a uri contains disallowed characters. thanks
Answer: please find the files under the errors folder and change the html content
error_404.php
error_db.php
error_general.phpetc
Comment: Thanks I got this in error_general.php . But, i could not modify the message caption without change the echo $message; . I need to modify the caption without deleting the $message.


Explanation of confidence interval in example in Gelman and Hill

Question: Gelman and Hill have an example in their text where they analyze this birth related dataset.  I understand the idea behind the analysis, but I can't verify the actual confidence interval  that they get:
Total proportion girls:                                              .4857
Observed standard deviation of proportion girls:                     .0064
Expected s.d. of proportion girls:  sqrt((.486)(1-.486)/3903) =      .0080
95% conf. interval for observed s.d. (based on chi^2 with 23 d.f.): (.006, .010)

I'm familiar with the approach to generate the confidence interval outlined here , but they seem to be using a different method.  Can anyone point me to the technique they use?
Comment: With 3903 girls the estimate of the binomial proportion is approximately normal.  Then its estimate of variance should be proportional to a chi-square.  But the degrees of freedom should be close to the sample size if 3903 (I would think) in which case a normal approximation to the chi square should be warranted (note the estimate is close to 0.5 so these normal approximations should be very accurate.  A confidence interval centered at (0.008)$^2$ using + or - 1.96 time the standard deviation from the normal approximation would give the 95% confidence interval for the variance.
Comment: The corresponding CI for the standard deviation would be obtained by taking the square root of the lower and upper endpoints for its lower and upper endpoints.  The interval for the variance would be symmetric around the estimate.  The interval for the standard deviation would not.  But it could be nearly symmetric since the estimates are so small. This may be how to get their estimate but the use of chi-square 23 df is a mystery.
Comment: I agree that the estimate of variance for the total population is what you said.  But we're trying to estimate variance for the 24 samples.
Comment: I am confused as to why the analysis of the 24 separate months is better than analysis of the 3903 points that are pretty much independent. I know that the gender of an alligator is determined by the temperature at hatching (http://www.nature.com/nature/journal/v296/n5860/abs/296850a0.html), so fluctuations of the environment have a legitimate effect on gender. However, I am failing to see why the standard deviation has to come from 24 observations rather than 3903 observations and the binomial model. (TBC)
Comment: In many other situations, I would object to an indiscriminate application of models that may give poor approximation to reality, and would be especially suspicious to the CIs based on the standard errors that assume independence when in fact the data come in chunks. If we were talking about precipitation, say, then of course I would yell out loud that we should treat these observations as clustered in months or seasons, at least. But the gender of a newborn?... I am lost.
Answer: Now that I looked at the observed birth data, I see that there are 24 months of data.  For each month you have a sample proportion of girl births.  If we assume that births are independent of month then each estimate is approximately normal with mean the true p and variance p(1-p)/n$_i$ where n$_i$ is the actual number of girl births in month i.  So you have 24 independent estimates of  p.  Each one normally distributed.  The variances differ slightly becuase of the differences in the n$_i$s.  But since the ns are all close to 3900 we can ignore that difference.
Now 0.4857 is the overall average of these 24 estimates.  Take the sample variance of these 24 estimates.  If each estimate were exactly normal and independent the variance would be proportional to a chi square random variable with 23 degrees of freedom (1 less than the number of months).  Since the normal approximations are all very good that chi square distribution can be used to get a confidence interval for the variance and then the square root of the end points can be used for the approximate 95% confidence interval for the standard deviation.
I think that what is very interesting about this is the upper endpoint of 0.010.  We see that if we add 0.01 to the estimate of 0.4857 for girls we still get 0.4957 <0.5.  This indicates that we would reject the null hypothesis that p=0.5.  So we have evidence that slightly more girls are born than boys.  The actual hypothesis test though would be gotten by inverting say the 95% confidence interval for p which is [0.4742, 0.4972] (barely excluding 0.5).  I got the CI by subtracting 1.96 (0.0064) from 0.4857 for the lower endpoint and adding that quantity to 0.4857 for the upper endpoint.
Comment: Hi Michael,  Your method of bounding the CI for the variance does not give the numbers in the example as near as I can tell.  Did you compute this?
Comment: Also, if our estimate is for standard deviation is .01, then we would not reject the null hypothesis at the 95% level because we would have to add two (1.96) standard deviations, right?
Comment: Strictly speaking, you can talk about $\chi^2$ only if the underlying normal variables have identically the same variance. In this example, they have different sample sizes $n_i$, and hence different variances. The overall mean (proportion) would be normal, but its variance will be complicated, and the Satterthwaite approximation to the degrees of freedom would give something a bit smaller than 23 d.f.s.
Answer: 10 years late...
However, to calculate the 95% confidence interval, the following R code is what you need:
expected_std = 0.0080
df = 24 - 1

q95 = sqrt(
  (df*expected_std^2) / qchisq(c(0.025, 0.975), df, lower.tail = FALSE))

Essentially, one scales the expected variance (expected_std^2) by $\frac{df}{\chi^2}$ where $\chi^2$ are the values given by the $\chi^2$ distribution at the quantiles of interest: (0.025, 0.975). We then take the square root to convert from variance to standard deviation.
A useful resource.


How to find the angle formed by an interior bisector and a suplementary from another bisector?

Question: The problem is as follows:
$AD$ bisect angle $\angle BAC$. Point $E$ which lies on $BC$ is generated by the $DE$ which is a bisector of $\angle ADC$. Using this information and the figure from below, find the angle which is made by $DE$ and $BC$.

The alternatives given in my book are as follows:
$\begin{array}{ll}
1.&100^{\circ}\\
2.&90^{\circ}\\
3.&110^{\circ}\\
4.&120^{\circ}\\
\end{array}$
I'm totally lost in this problem. What exactly should be the way to approach this?.
The problem not only lies in solving but how can it be solved relying only in euclidean geometry postulates?. The thing here from what I can spot is that there might come into play notable angle in triangles. Such as the angle formed by an exterior bisector or an interior bisector.
Can someone help me in a way that I can understand without much fuss?. Please include a drawing in the answer because I'm lost here.
Suspiciously $\angle ABC = 2 \angle BCA$. Is this an implicit hint which makes us to conclude to draw a segment and build an isosceles there?. I don't know. Does it needs congruence or what?. Please guide me, I need help step by step.
Comment: You can find $\angle A$, so you know its bisection.
Answer: Hint:

The internal angles of any triangle sum to $180^\circ$.
The angles on a straight line sum to $180^\circ$.

That's all you need.
Answer: You can just chase angles.
Find $\angle ECD$ (and $\angle ACD$)
Find $\angle BAC$ from $\triangle ABC$
$AD$ is a bisector, so half this for $\angle CAD$
Find $\angle ADC = 2\alpha$ from $\triangle ACD$
Calculate $\alpha$
Find $x$ from $\triangle ECD$


changing text of custom navigation bar item

Question: I am creating a custom UINavigationBar BarButtonItem as follows:
 // Set up bar button items
    UIButton *backButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 35.0f, 35.0f)];
    [backButton setImage:[UIImage imageNamed:@"myimg.png"] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(myselector) forControlEvents:UIControlEventTouchUpInside];

    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];

This is working perfectly, but when I go to set the title of the UIButton or BarButtonItem, it won't show up. Any suggestions?
Tried...
    [backButton setTitle:@"Edit" forState:UIControlStateNormal];
    [backButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];

And...
     self.navigationItem.leftBarButtonItem.title = @"Edit";

without luck.
Comment: Try this to set image : [backButton setBackgroundImage:[UIImage imageNamed:@"myimg.png"] forState:UIControlStateNormal];
Comment: @Auser Your problem solved?
Comment: It might have to do with you setting the image and trying to overwrite the image with your own text.
Comment: Why not just have the text "Edit" on your button image?
Comment: @CRDave that was it. The image and text were fighting for space so I was only seeing the image while the text was kicked off to the side, outside of the barbutton view.
Comment: @CRDave answer the question so @A user can accept it
Answer: The problem is that image and title use same viewspace for display.
So when we use image with title first it show image and than title (right side of image).
If size of UIButton is same as image than we can't see Title.
A simple solution is set image in background. So try this:
[backButton setBackgroundImage:[UIImage imageNamed:@"myimg.png"] forState:UIControlStateNormal];

Answer: UIImage *image = [UIImage imageNamed:@"myimg.png"];
UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
[backButton setBackgroundImage:image forState:UIControlStateNormal];
[backButton setTitle:@"Edit" forState:UIControlStateNormal];
 [backButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal]
backButton.frame=CGRectMake(0, 0, 35.0f, 35.0f);

UIBarButtonItem *barButton= [[[UIBarButtonItem alloc] initWithCustomView:backButton] autorelease];
self.toolbar.items = [NSArray arrayWithObject:barButton];


Webform data tables name change d7 to d8 tables to delete records from

Question: I have converted my d7 webforms to d8 with custom modules ... looks great
Previously I pulled data down from the database daily and deleted records from the webform_submissions and webform_submitted_data tables. (worked flawlessly for years)
With d8 the names are webform_submission and webform_submission_data.
Does anyone know if deleting the records from these two tables affects any other tables?  I intend to do as before... read daily, delete daily.
Thank you
Comment: No, in D8 webform submissions are entities and you should use the [Entity API](https://www.drupal.org/docs/8/api/entity-api/working-with-the-entity-api) to delete records.
Answer: I agree that you should use the 'Entity API' but if you are deleting 1000's of records I understand why you would want to do it using SQL.
Below are all the tables that are used to store webform submission related data.

webform_scheduled_email
webform_submission
webform_submission_data
webform_submission_log


Does $u|x \sim N(0,\sigma^2)$ implies independence?

Question: I'm a bit confused by the following statement found in "Introductory Econometrics, A Modern Approach" (Wooldridge, 2019):

The phrase seems to imply the assumption is about independence and Normality. But as far as I can tell, $u \sim N(0,\sigma^2)$ already implies complete independence between $u$ and the explanatory variables. Maybe he is just being explicit about the implications of Normality without going onto the details of what implies what, details that might confuse a novice reader (this might be supported by the title of the assumption, which is "Normality" rather than "Independence and Normality").
Still, my point is: $u \sim N(0,\sigma^2)$ implies independence not only for the first two moments of $u$ but for the whole distribution. Is this the case? Am I misunderstanding Wooldridge's point?
Answer: Stating the distribution of $u$ does not imply independence.
Consider $v = 2u$. Thus, $v \sim \mathcal N (0, 4\sigma^2)$, yet $v$ is not independent of $u$.
Answer: $u\sim\mathcal N(0,\sigma^2)$ does not imply independence, as @Firebug stated. But I would add that $u|x_1,x_2,\cdots,x_k\sim\mathcal N(0,\sigma^2)$ does imply independence, since it means that the conditional distribution of $u$ is always the same, regardless of the values of the covariates.


OpenGL ES 2: GLSurface View Showing Black Screen When SetContentView is set to an XML File

Question: I'm fairly new to OpenGL and my problem is when I do SetContentView("R.layout.main") nothing happens, however when I do SetContentView("mGLView")the game is displayed fine. My main.xml file contains an surface view and therefore I would of thought that it would be displayed, since main.xml has an surface view.
I suspect a way to fix this, will be done with addview or findviewbyid, however my implication of this have failed.
Relevent MainActivity Code:
public class OpenGLES20Activity extends Activity {
private GLSurfaceView mGLView;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mGLView = new MyGLSurfaceView(this);
    setContentView(R.layout.main);

main.xml code:
    <FrameLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <RelativeLayout android:id="@+id/linearLayout1" android:layout_width="wrap_content"
android:layout_height="wrap_content">

            <SurfaceView
android:id="@+id/SurfaceView"
android:layout_width="500dp"
android:layout_height="478dp">
</SurfaceView>

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/Timer"
                android:id="@+id/Timer"/>
        </RelativeLayout>

    </FrameLayout>

Any help is appreciated.
Answer: You need to set your extended GLSurfaceView instead of just SurfaceView in the xml file so just change SurfaceView to com.example.yourapp.MyGLSurfaceView:
<com.example.yourapp.MyGLSurfaceView
    android:id="@+id/SurfaceView"
    android:layout_width="500dp"
    android:layout_height="478dp"/>

Comment: I have made the change in my code and now I have the following error Error:(31, 19) error: constructor MyGLSurfaceView in class MyGLSurfaceView cannot be applied to given types;
required: Context,AttributeSet
found: no arguments
reason: actual and formal argument lists differ in length
Comment: Your constructor needs to be `MyGLSurfaceView(Context context, AttributeSet attrs)` like shown in the documentation I have linked you.
Comment: My constructor is set to that and I still get the error.
If this helps my IDE has indicated this to be an problem: mGLView = new MyGLSurfaceView(this);
Comment: Yeah you should remove that line
Comment: I have mGLView.onResume() and mGLView.onResume() what should I set them to? as MyGLSurfaceView.onResume() does not work.
Comment: Extend them from inside of the MyGLSurfaceView class


Why $\int_0^1\left|f_n(x)-f_m(x)\right|^2dx <\int_{\frac{1}{2}}^{\frac{1}{2}+\frac{1}{n+1}}[(n+1))\left(x-\frac{1}{2}\right)]^2 \mathrm{~d} x $?

Question: In these notes we read, at page 22, the following argument.
Let $\left(f_n\right)$ be the sequence of functions defined by,
$$
f_n(x)=\left\{\begin{array}{cl}
1 & \text { if } 0 \leq x<\frac{1}{2} \\
1-(n+1)\left(x-\frac{1}{2}\right) & \text { if } \frac{1}{2} \leq x<\frac{1}{2}+\frac{1}{n+1} \\
0 & \text { if } \frac{1}{2}+\frac{1}{n+1} \leq x \leq 1
\end{array}\right.
$$
(...) Observe that, without loss of generality taking $m>n$, we have
$$
\begin{aligned}
\left\|f_n-f_m\right\|^2 & =\int_0^1\left|f_n(x)-f_m(x)\right|^2 \mathrm{~d} x \\
& <\int_{\frac{1}{2}}^{\frac{1}{2}+\frac{1}{n+1}}[(n+1))\left(x-\frac{1}{2}\right)]^2 \mathrm{~d} x \\
& =\frac{1}{3(n+1)} \\
& \rightarrow 0 \text { as } \mathrm{n} \text { (and hence } \mathrm{m}) \rightarrow \infty
\end{aligned}
$$
Can someone explain to me why $\int_0^1\left|f_n(x)-f_m(x)\right|^2 \mathrm{~d} x
<\int_{\frac{1}{2}}^{\frac{1}{2}+\frac{1}{n+1}}[(n+1))\left(x-\frac{1}{2}\right)]^2 \mathrm{~d} x $? This inequality is given simply without adding explanations, as if it were a trivial fact, but I cannot understand it.
Comment: Perhaps it would be clearer if the author instead wrote $< \int_{1/2} ^{1/2 + 1/(n+1)}(1 - (n+1)(x-1/2))^2 dx$, i.e. the integral of $f_n(x)^2$ over $(1/2,1/2+1/(n+1))$. Draw the graph of $f_n$ and $f_m$ and see where they overlap and where they differ. Convince yourself that $m\to \infty$ would give the biggest difference between the two functions.
Comment: When $m<n$, it is certainly true that $f_n \geq f_m$. The only nontrivial interval where the inequality is strict and the differences don't cancel is precisely the largest bounds of integration for when the function is not constant.
Comment: @Winther It's not so clear because for $\frac{1}{2} \leq x < \frac{1}{2} + \frac{1}{m+1}$ we have $f_n(x) - f_m(x) = (m-n)\left(x - \frac{1}{2}\right)$.
Comment: @Klaus The key is to realize (which you can see if you draw it) that $|f_n - f_m| < |f_n - f_\infty|$ (on $x\geq 1/2$). And then the interval you mention goes away.
Answer: Elaborating on my comment, it is clear that $f_n(x) \geq f_m(x)$ when $m>n$. The integral is only nonzero on the intervals where $f$ is nonconstant, giving us
$$\int_0^1|f_n(x)-f_m(x)|^2dx = \int_{\frac{1}{2}}^{\frac{1}{2}+\frac{1}{n+1}} |f_n(x)-f_m(x)|^2dx \leq   \int_{\frac{1}{2}}^{\frac{1}{2}+\frac{1}{n+1}} |f_n(x)|^2dx $$
Under the interchange $x \leftrightarrow 1 +\frac{1}{n+1} - x$ the integral becomes
$$= \int_{\frac{1}{2}}^{\frac{1}{2}+\frac{1}{n+1}}\left[(n+1)\left(x-\frac{1}{2}\right)\right]^2dx = \frac{1}{3(n+1)}$$
Comment: @Winther yes thank you for the correction. I have fixed it.


Attempting to recover CentOS7 server. Mounting partition taking a long time

Question: I have a CentOS 7 server that I am attempting to recover. I've got the install disk in the CD drive and am able to make it into the recovery process.
Once I make it into the recovery process I select the first option to mount the disc under /mnt/sysimage. However I get several thousand lines of = characters, and then the process eventually freezes and I have to restart the process all over again.
I know that there is a lot of data on this drive, does this process just take a long time to mount the drive? I don't get any errors while attempting the mount the drive, it just seems to freeze and stop doing anything.
Answer: Skip mounting sysimage. On the console, do recovery steps.
For example, image the volume to a new, working block device. Check for I/O errors logged, possibly due to failing storage.  fsck or xfs_repair the copy.
Comment: So the reason I need to mount the sysimage is that I need to reset the root password before I can do anything with the file system.
Comment: Mounting automatically does no good if it hangs due to I/O errors or similar. Skipping mounting allows you to do recovery steps manually.


What is model identifiability?

Question: I know that with a model that is not identifiable the data can be said to be generated by multiple different assignments to the model parameters. I know that sometimes it's possible to constrain parameters so that all are identifiable, as in the example in Cassella & Berger 2nd ed, section 11.2.
Given a particular model, how can I evaluate whether or not it's identifiable?
Comment: For a simple example see [indentification example](https://stats.stackexchange.com/questions/444336/why-is-x-not-an-identifiable-statistical-model)
Answer: For identifiability we are talking about a parameter $\theta$ (which could be a vector), which ranges over a parameter space $\Theta$, and a family of distributions (for simplicity, think PDFs) indexed by $\theta$ which we typically write something like $\{ f_{\theta}|\, \theta \in \Theta\}$.  For instance, $\theta$ could be $\theta = \beta$ and $f$ could be
$$
f_{\theta}(x) = \frac{1}{\beta}\mathrm{e}^{-x/\beta}, \ x>0,\ \beta >0,
$$
which would mean that $\Theta = (0,\infty)$.  In order for the model to be identifiable, the transformation which maps $\theta$ to $f_{\theta}$ should be one-to-one.  Given a model in your lap, the most straightforward way to check this is to start with the equation $f_{\theta_{1}} = f_{\theta_{2}}$, (this equality should hold for (almost) all $x$ in the support) and to try to use algebra (or some other argument) to show that just such an equation implies that, in fact, $\theta_{1} = \theta_{2}$.
If you succeed with this plan, then your model is identifiable; go on with your business.  If you don't, then either your model isn't identifiable, or you need to find another argument.  The intuition is the same, regardless: in an identifiable model it is impossible for two distinct parameters (which could be vectors) to give rise to the same likelihood function.
This makes sense, because if, for fixed data, two unique parameters gave rise to the same likelihood, then it would be impossible to distinguish between the two candidate parameters based on the data alone.  It would be impossible to identify the true parameter, in that case.
For the example above, the equation $f_{\theta_{1}} = f_{\theta_{2}}$ is
$$
\frac{1}{\beta_{1}}\mathrm{e}^{-x/\beta_{1}} = \frac{1}{\beta_{2}}\mathrm{e}^{-x/\beta_{2}},
$$
for (almost) all $x > 0$. If we take logs of both sides we get
$$
-\ln\,\beta_{1} - \frac{x}{\beta_{1}} = -\ln\,\beta_{2} - \frac{x}{\beta_{2}}
$$
for $x > 0$, which implies the linear function
$$
-\left(\frac{1}{\beta_{1}} - \frac{1}{\beta_{2}}\right)x - (\ln\,\beta_{1} - \ln\,\beta_{2})
$$
is (almost) identically zero.  The only line which does such a thing is the one which has slope 0 and y-intercept zero.  Hopefully you can see the rest.
By the way, if you can tell by looking at your model that it isn't identifiable (sometimes you can), then it is common to introduce additional constraints on it to make it identifiable (as you mentioned).  This is akin to recognizing that the function $f(y) = y^{2}$ isn't one-to-one for $y$ in $[-1,1]$, but it is one-to-one if we restrict $y$ to lie inside $[0,1]$.  In more complicated models the equations are tougher but the idea is the same.
Comment: (+1) Nice, comprehensive, down-to-earth explanation. The analogies you draw make the concepts clear.
Comment: +1, nice answer. It might be worth pointing out one classic & easy to see example of an unidentifiable model is the unconstrained version of the ANOVA:  $$y_{ij}=\mu+\alpha_1+\alpha_2+\ldots+\alpha_k+\varepsilon_i$$  To remedy this, *reference cell coding* is typically used, wherein the mean of one level is set as the reference (which is estimated by the intercept), & the grand mean is not explicitly estimated.
Comment: @cardinal, thanks.  To Jack, alright, I see.  How about this: if there's something above that isn't clear yet, and if you point it out to me, then I can try to flesh it out some more.  Or, if you'd prefer, you could write another question that asks for a "layman's" explanation or examples of these ideas.  I think it's fair to say that identifiability is a topic that usually comes up *after* the typical introductory period of study, so if you'd like to provide some context of why you're encountering this now it might help potential answerers.
Comment: You certainly answered the question I asked, but I'm too much of a novice to really understand your answer. If you know of an explanation that's better for a novice, please let me know.
Answer: One way is to inspect the covariance matrix, $\Sigma$, of your parameter estimates. If two parameter estimates are perfectly (approximately) correlated with each other or one parameter estimate is a (approximately) linear combination of several others, then your model is not identified; the parameters that are functions of the others are not necessary. In each of these cases, $\Sigma$ will also be (approximately) singular. So, if $\Sigma$ is approximately singular, this may give you reason to be concerned about identifiability issues. (Although I don't think this would detect non-linear relationships between parameter estimates that would give rise to non-identifiability).
The practical problem is that it is often difficult to calculate $\Sigma$ for even mildly complicated models.
If you are doing a maximum likelihood problem, then you know the asymptotic covariance matrix of your estimates is equal to the inverse of the fisher information evaluated at the MLE. So, checking the fisher information matrix for (approximate) singularity is also a reasonable way of assessing identifiability. This also works where the theoretical fisher information is difficult to calculate because it is often possible to very accurately numerically approximate a consistent estimator of the fisher information matrix by, for example, estimating the expected outer product of the score function by the observed average outer product.
In you are not doing an ML problem then you may be able to get a handle on $\Sigma$ by simulating data from the model and estimating parameters a large number of times and calculating a sample covariance matrix.
Comment: (+1) Well done.  I hadn't even thought to approach this question from that direction.
Comment: One reason the idea about calculating a covariance matrix based on simulated data is especially neat, is that one should simulate the data anyway to do a [Cook-Gelman-Rubin](http://www.stat.columbia.edu/~gelman/research/published/Cook_Software_Validation.pdf) check.

What is model identifiability?


Pandas - Replace row value from derived calculation

Question: I need to make an inplace value replacement based upon an row index value.  The replacement value is a sliced (both row and column) dataframe computation.
Setup
In [1]: import pandas as pd

In [2]: cols = [0, 1, 'A0', 'A1', 'A2', 'A3', 'B0', 'B1', 'B2', 'B3']

In [3]: data = [['sum', 4531.0010, 0, 0, 0, 2, 0, 0, 0, 7],
   ...:         ['', 4531.0010, 5, 6, 3, 0, 5, 4, 7, 0],
   ...:         ['', 4531.0010, 1, 3, 9, 0, 2, 2, 3, 0],
   ...:         ['sum', 5037.0022, 0, 0, 0, 8, 0, 0, 0, 5],
   ...:         ['', 5037.0022, 2, 2, 3, 0, 1, 3, 9, 0],
   ...:         ['', 5037.0022, 5, 4, 7, 0, 5, 6, 3, 0]]

In [4]: df = pd.DataFrame(data=data, columns=cols)

In [5]: df = df.set_index(list(df.columns[[0, 1]]))

In [6]: df
Out[6]:
               A0  A1  A2  A3  B0  B1  B2  B3
0   1
sum 4531.0010   0   0   0   2   0   0   0   7
    4531.0010   5   6   3   0   5   4   7   0
    4531.0010   1   3   9   0   2   2   3   0
sum 5037.0022   0   0   0   8   0   0   0   5
    5037.0022   2   2   3   0   1   3   9   0
    5037.0022   5   4   7   0   5   6   3   0

As you can see the row is multiindexed with index=1 is a number that represents a subset of the data.  Within each data subset there is a "sum" in index=0 which I would like to "distribute" up (or down) to the zero balances.
The computation is basically the "A" columns and the index 1 rows with the same value to be summed to a denominator.  Then the sum of the row for that data group is the numerator.  The ratio is then used to distribute the sum between the rows.
For the rows=4531.0010 and the columns with an A it would be computed as:
(5+6+3)/(5+6+3+1+3+9)*2 = row 1, column A3
(1+3+9)/(5+6+3+1+3+9)*2 = row 2, column A3
The resulting df would look like this:
Out[7]:
               A0  A1  A2     A3  B0  B1  B2     B3
0   1
sum 4531.0010   0   0   0  2.000   0   0   0  7.000
    4531.0010   5   6   3  1.037   5   4   7  4.870
    4531.0010   1   3   9  0.923   2   2   3  2.130
sum 5037.0022   0   0   0  8.000   0   0   0  5.000
    5037.0022   2   2   3  2.435   1   3   9  2.407
    5037.0022   5   4   7  5.565   5   6   3  2.593

The number of rows are not fixed - there could be one or there could be 10.
What I've tried
I've tried using variations of .pivot_table() but I can't figure out how to reverse the process using division.  As an example.
I've also used variations of .sum() but trying to constrain the df using slices eludes me.  One of many examples.
I think I can get this to work with a lot of python functions, but seems that it should be possible more efficiently.  Any direction is greatly appreciated.
Answer: Solution working, if unique first levels of MultiIndex:
cols = [0, 1, 'A0', 'A1', 'A2', 'A3', 'B0', 'B1', 'B2', 'B3']

data = [['sum1', 4531.0010, 0, 0, 0, 2, 0, 0, 0, 7],
        ['sum1', 4531.0010, 5, 6, 3, 0, 5, 4, 7, 0],
        ['sum1', 4531.0010, 1, 3, 9, 0, 2, 2, 3, 0],
        ['sum2', 5037.0022, 0, 0, 0, 8, 0, 0, 0, 5],
        ['sum2', 5037.0022, 2, 2, 3, 0, 1, 3, 9, 0],
        ['sum2', 5037.0022, 5, 4, 7, 0, 5, 6, 3, 0]]

df = pd.DataFrame(data=data, columns=cols)

df = df.set_index(list(df.columns[[0, 1]]))
print (df)
                A0  A1  A2  A3  B0  B1  B2  B3
0    1
sum1 4531.0010   0   0   0   2   0   0   0   7
     4531.0010   5   6   3   0   5   4   7   0
     4531.0010   1   3   9   0   2   2   3   0
sum2 5037.0022   0   0   0   8   0   0   0   5
     5037.0022   2   2   3   0   1   3   9   0
     5037.0022   5   4   7   0   5   6   3   0

#loop by first letters of values in columns
for c in df.columns.str[0].unique():
    #filter values by first letter
    df1 = df.filter(like=c)
    #get sum per rows
    s = df1.iloc[:, :-1].sum(axis=1)
    #get last column
    last_col = df1.iloc[:, -1]
    #replace 0 in last column to previous non 0
    last_col = last_col.mask(last_col == 0).ffill()
    #divide by sum per first level with multiple by last_col
    s = s.div(s.sum(level=0), level=0).mul(last_col)
    #add to last column
    df[last_col.name] += s
print (df)
                A0  A1  A2        A3  B0  B1  B2        B3
0    1
sum1 4531.0010   0   0   0  2.000000   0   0   0  7.000000
     4531.0010   5   6   3  1.037037   5   4   7  4.869565
     4531.0010   1   3   9  0.962963   2   2   3  2.130435
sum2 5037.0022   0   0   0  8.000000   0   0   0  5.000000
     5037.0022   2   2   3  2.434783   1   3   9  2.407407
     5037.0022   5   4   7  5.565217   5   6   3  2.592593

Comment: The row indexing is actually 5 deep - so, far more complex. But I was able to simply add a new reference column based on your answer and it works. I think I can get the iterator to use the multiindex depth and apply the .unique() and get there in one less step. Thanks.
Comment: Index 0 is not unique - - but, if I reset the row index and concatenate index 0 & 1 into new column that maybe could yield the same result?
Comment: @BillArmstrong - Not sure how in real data, but how is distingush groups? Are similar like in change your data sample or unique like in question?


Globally set custom Bootstrap 4 button color

Question: I am trying to set the color of Bootstrap 4 buttons. Precisely I want to change the color of btn-primary while holding a mouse click down on it. It has to be some button event I have to colorize, but it does not appear to be in hover, focus, or active.
In my tests I got the button with the class btn-primary entirely red except while clicking on it, which turns the button blue. For creating CSS I make use of Sass.
My app.scss file:
.btn-primary {
    &:hover {
        color: red;
        background-color: red;
    }
    &:focus {
        color: red;
        background-color: red;
    }
    &:active {
        color: red;
        background-color: red;
    }
}

How can I set the color of the button while clicking on it?
Answer: use with !important.

.btn-primary:hover {
  color: red;
  background-color: red !important;
}

.btn-primary:focus {
  color: red;
  background-color: orange !important;
}

.btn-primary:active {
  color: white;
  background-color: green !important;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>

<button type="button" class="btn btn-primary">Primary</button>

Or, without using !important:

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>

<button type="button" class="btn btn-primary">Primary</button>
Comment: Ok, `.btn-primary:hover { background-color: red !important;` solved the case. In my experience `!important` should be avoided though. Is there a way around it in this case?


Activity is null when try to take screen shot

Question: My project type is PCL in xamarin Forms. I want to take screenshot and I am using below code. But when I debug my code Activity is always null. I am trying to figure out the issue but not get success. Can you please tell what i am doing the mistake.
public interface IScreenshotManager
{
   Task<byte[]> CaptureAsync();
}

For Android:
[assembly: Xamarin.Forms.Dependency(typeof(ScreenshotService))]
namespace MyProject.Droid
{
    public class ScreenshotService : IScreenshotService
    {
        public static Activity Activity { get; set; }

        public async System.Threading.Tasks.Task<byte[]> Capture()
        {
            if (Activity == null)  // Activity is always null Error here
            {
                throw new Exception("You have to set ScreenshotManager.Activity in your Android project");
            }

            var view = Activity.Window.DecorView;
            view.DrawingCacheEnabled = true;

            Bitmap bitmap = view.GetDrawingCache(true);

            byte[] bitmapData;

            using (var stream = new MemoryStream())
            {
                bitmap.Compress(Bitmap.CompressFormat.Png, 0, stream);
                bitmapData = stream.ToArray();
            }

            return bitmapData;
        }
    }

}

Calling the function
 byte[] screenshotData = await DependencyService.Get<IScreenshotService>().Capture();

Answer: Obviously Activity is null if you don't assign it. You can use the CurrentActivity nuget package to get the current activity (or you may assign it in Activity OnCreate method as Xamarin uses always the same Activity from the start).
Comment: how can i assign activity onCreate
Comment: It should be ScreenshotService.Activity = this;
Answer: The old deprecated way would be var view = ((Activity)Xamarin.Forms.Forms.Context).Window.DecorView;
Xamarin automatically assigns the Activity to Forms.Context.Since the release of Xamarin 2.5, Xamarin.Forms.Forms.Context is obsolete.
Now you could use this :
var currentContext = Android.App.Application.Context;


Arnold's Trivium problem 51

Question:
Calculate $$ f(k) = \int_{-\infty}^{+\infty} e^{ikx}\frac{1 - e^x}{1+e^x}dx.$$

As far as I know, this is not a function but rather the Fourier transform in tempered distributions.

1) What is a rigorous proof of Arnold's problem ?
2) How people usually use and manipulate Fourier Transform of tempered distributions ?

Edit : Thx a lot to joriki and sos440 for two very nice and rigorous proofs.
To summarize,
joriki's idea is to get a regular integral by derivation and then using the Rediues Theorem ;
while sos440 is removing the 'constant' term that makes the integral diverge and treat it seperatly.
If anyone has another different method, I'd be glad.
Answer: We divide the integral into two parts:
\begin{align*}
f(k)
&= \int_{\Bbb{R}} \mathrm{sgn}(x) e^{-ikx} \, dx + \int_{\Bbb{R}} e^{-ikx} \left( \frac{1-e^{-x}}{1+e^{-x}} - \mathrm{sgn}(x) \right) \, dx
\end{align*}
The first one can be easily computed by integration by parts as follows:
\begin{align*}
\int_{\Bbb{R}} \mathrm{sgn}(x) e^{-ikx} \, dx
&= -\int_{\Bbb{R}} 2\delta(x) \frac{e^{-ikx}}{-ik} \, dx
 = -\frac{2i}{k}.
\end{align*}
Indeed, this manipulation can be justified in the context of tempered distributions. (Just observe what happens when the Fourier transform and the differentiation are interchanged.)
The remaining part is now integrable in ordinary sense, and we have
\begin{align*}
\int_{\Bbb{R}} e^{-ikx} \left( \frac{1-e^{-x}}{1+e^{-x}} - \mathrm{sgn}(x) \right) \, dx
&= 4i \int_{0}^{\infty} \frac{\sin (kx) \, e^{-x}}{1+e^{-x}} \, dx \\
&= 4i \sum_{n=1}^{\infty}(-1)^{n-1} \int_{0}^{\infty} \sin (kx) \, e^{-nx} \, dx \\
&= 4i \sum_{n=1}^{\infty}(-1)^{n-1} \frac{k}{k^2 + n^2}
\end{align*}
Combining,
\begin{align*}
f(k)
&= -2i \sum_{n=-\infty}^{\infty} \frac{k}{n^2 + k^2}
 = -\frac{2\pi i}{\sinh (\pi k)}.
\end{align*}
Comment: Is there an easy way to guess the very last line ?
Comment: @DamienL, It is not an easy identity at all, and actually we need some complex analysis technique or knowledge on Fourier series. One possible way, though neither easy nor elementary, is to began with the Weierstrass factorization of $\sinh x$ given by $$ \frac{\sinh \pi x}{\pi x} = \prod_{n=1}^{\infty} \left( 1 + \frac{x^2}{n^2} \right). $$
Comment: By the way, I like your answer very much. It is a pitty to end up with a nasty series. There should be an easier way to solve this problem.
Comment: @DamienL I uploaded 2 proofs enjoy
Answer: The poles are at $x=(2n+1)\pi\mathrm i$, and the corresponding residues are $-2\mathrm e^{-(2n+1)\pi k}$. If we ignore issues of convergence, this suggests that the integral is
$$
-4\pi\mathrm i\sum_{n=0}^\infty\mathrm e^{-(2n+1)\pi k}=\frac{-4\pi\mathrm i\mathrm e^{-\pi k}}{1-\mathrm e^{-2\pi k}}=\frac{-2\pi\mathrm i}{\sinh\pi k}\;.
$$
To make this rigorous in the context of tempered distributions, you can take the derivative of the function being Fourier-transformed, calculate the resulting convergent integral, and divide by $-\mathrm ik$ (see Tempered distributions and Fourier transform at Wikipedia). The residues are slightly more complicated to evaluate, but as one might expect the result is the same.
Comment: @DamienL, That a pole is of second order does not imply that the residue is zero, as you can confirm in the case $$ f(z) = \frac{1+z}{z^2}. $$ And in our example, at $z = (2n+1)\pi i$ we have $$ -\frac{2e^{z}}{(1 + e^{z})^2} e^{ikz} = \frac{2 e^{- (2n+1) \pi  k}}{(z-(2n+1) \pi i )^2} + \frac{2 i e^{-(2n+1) \pi  k} k}{z-(2n+1) \pi i } + \cdots. $$
Comment: The derivative is $\frac{-2e^x}{(1+e^x)^2}$ which has no residues. So what is a rigorous proof ? Is it possible to say that your series converges (in tempered distributions) to the fourier transform of the function ?
Comment: @Damien: Why doesn't it have residues? It has two second-order poles; I didn't write out the details but as far as I checked their residues come out right.
Comment: What I meant is that, because the poles are of second-order, then all the residues are zero.
Comment: Ok, very nice !
Answer: \begin{align*}
&\text{Initially, I considered that the integral does not converge because} \\
&\int_{-\infty}^{+\infty} {e^{ikx}\frac{1 - e^x}{e^x + 1}dx} \\
&= 2i \int_0^{+\infty} \frac{1 - e^x}{e^x + 1}\sin(kx)dx \\
&\text{given that } f(x) = \frac{1 - e^x}{e^x + 1}\cos(kx) \text{ is odd, while } g(x) = \frac{1 - e^x}{e^x + 1}\sin(kx) \text{ is even.} \\
&\text{Also, because } \lim_{x \to +\infty} \left(\frac{1 - e^x}{e^x + 1}\right) = -1, \\
&\text{I considered that the integral } \int_0^{+\infty} \frac{1 - e^x}{e^x + 1}\sin(kx)dx \text{ diverges.} \\
&\text{In collaboration with my friend Anastasis, we found that things are somewhat different:} \\
&\text{1st solution} \\
&\int_{-\infty}^{+\infty} {e^{ikx}\frac{1 - e^x}{1 + e^x}dx} \\
&= \int_0^{+\infty} {y^{ik}\frac{1 - y}{1 + y}\frac{1}{y}dy} \\
&= \int_0^{+\infty} {y^{ik}\left(\frac{1}{y} - 1\right)\frac{1}{1 + y}dy} \\
&= \int_0^{+\infty} {y^{ik}\left(\frac{1}{y} - 1\right)\left(\int_0^{+\infty} {e^{-(1 + y)x}dx}\right)dy} \\
&= \int_0^{+\infty} {e^{-x}\left(\int_0^{+\infty} {(y^{ik - 1} - y^{ik})e^{-yx}dy}\right)dx} \\
&= \int_0^{+\infty} {e^{-x}\left(\frac{\Gamma(ik)}{x^{ik}} - \frac{\Gamma(ik + 1)}{x^{ik + 1}}\right)dx} \\
&= \int_0^{+\infty} {e^{-x}\left(\frac{\Gamma(ik)}{x^{ik}} - \frac{ik\Gamma(ik)}{x^{ik + 1}}\right)dx} \\
&= \Gamma(ik)\int_0^{+\infty} {\left(x^{-ik} - ikx^{-ik - 1}\right)e^{-x}dx} \\
&= \Gamma(ik)(\Gamma(1 - ik) - ik\Gamma(-ik)) \\
&= \Gamma(ik)(\Gamma(1 - ik) + \Gamma(1 - ik)) \\
&= 2\Gamma(ik)\Gamma(1 - ik) \\
&= \frac{4i\pi}{{\sin(ik\pi)}} \\
&= \frac{4i\pi}{{e^{i(k\pi)} - e^{-i(k\pi)}}} \\
&= \frac{4i\pi}{{e^{-k\pi} - e^{k\pi}}} \\
\end{align*}
Answer: \begin{align*}
&\text{2nd solution} \\
&\text{Let } f(z) = e^{ikz}\frac{1 - e^z}{e^z + 1}, \text{ analytic in the upper half-plane with poles } z_n = i\pi(2n + 1) \text{ where} \\
&\text{Res}\left(f(z),z_n\right) = e^{iki\pi(2n + 1)}\left(1 - e^{i\pi(2n + 1)}\right)\lim_{z \to i\pi(2n + 1)} \frac{z - i\pi(2n + 1)}{e^z + 1} = -2e^{-k\pi(2n + 1)} \\
&\text{For } z = Re^{i\theta} \text{ with } \theta \in [0,\pi]: f(z) = e^{ikR\cos(\theta)}e^{-kR\sin(\theta)}\frac{1 - e^{R\cos(\theta)}e^{iR\sin(\theta)}}{e^{R\cos(\theta)}e^{iR\sin(\theta)} + 1} \\
&\Rightarrow |f(z)| = e^{-kR\sin(\theta)}\left|\frac{1 - e^{R\cos(\theta)}e^{iR\sin(\theta)}}{e^{R\cos(\theta)}e^{iR\sin(\theta)} + 1}\right| \\
&\leq e^{-kR\sin(\theta)}\frac{\left|1 - e^{R\cos(\theta)}\right|}{|e^{iR\sin(\theta)} + 1|} \xrightarrow{R \to \infty} 0 \\
&\text{If } (c) \text{ is the upper half-circle with diameter AB where } A(-R,0) \text{ and } B(R,0), \\
&\text{then } \int_c f(z)dz = 2\pi i\sum_{n=1}^\infty \text{Res}\left(f(z), z_n\right) \text{ and } R \to +\infty \text{ we have} \\
&\int_{-\infty}^{+\infty} e^{ikx}\frac{1 - e^x}{e^x + 1}dx = 2\pi i\sum_{n=0}^\infty \left(-2e^{-k\pi(2n + 1)}\right) \\
&= -4i\pi\frac{e^{-k\pi}}{1 - e^{-2k\pi}} = \frac{4i\pi}{{e^{-k\pi} - e^{k\pi}}} \\
\end{align*}

Arnold's Trivium problem 51


Indexing an array in .data faults with an address a lot higher than the array

Question: My homework to the change values inside an array in MASM, swapping pairs.
array[0] = array[1]
array[1] = array[0]
array[2] = array[3]
array[3] = array[2]

and so on....
I have abandoned using the var1 and var2 variables because I can't seem to get them to work. I have
.data
; add data here
array01 DWORD 100, 200, 300, 400, 500, 600
var1 DWORD ?
var2 DWORD ?

.code
main PROC
    mov edi, OFFSET array01         ; 1: EDI = address of array01
    mov ecx, LENGTHOF array01       ; 2: initialize loop counter
    mov eax, 0                      ; 3: sum =0

L1:                                 ; 4: Mark beginning of loop
    mov eax, [edi]                  ; 5: Get var1
    add edi, TYPE array01           ; 6: increment index
    mov ebx, [edi]                  ; 7: Get var2
    sub edi, TYPE array01           ; 8: decrement to get index to point to the right location

    mov array01[edi], ebx           ; 9: Change array01[i] to var1
    add edi, TYPE array01           ; 10: increment index
    mov array01[edi], eax           ; 11: Change array01[i] to var1
    loop L1                         ; 12: repeats until ecx is 0

    INVOKE ExitProcess, 0
main ENDP
End main

My problem is at instruction 9. It's giving me an error

Unhandled exception at 0x007C1032 in Assignment_03.exe: 0xC0000005: Access violation writing location 0x00F88004.

From the debugger, my EDI = 007C4000, and &array01 is at 0x007C4000, matching each other but not the data address reported for the fault.  (My EIP = 007C1032, the code address of the faulting instruction.)
An earlier run had Exception thrown at 0x00171029 in Assignment_03.exe: 0xC0000005: Access violation writing location 0x002E8000.
I understand that it's telling me I'm accessing something I'm not allowed to but I don't know how to fix it.

I have tried mov [numList+ebx],dh from
https://termspar.wordpress.com/2019/10/12/x86-assembly-swap-array-elements/  But I still get the same error.
What am I doing wrong? Can you please explain the solution. To be clear I don't want an answer to my homework. I want help in changing a value in an array.
mov dword ptr [array01], 700 works to change the first element, but indexing with EDI isn't working.
Comment: This loop has 6 iterations,  last one will exchange last element of `array01` with `var1`.  Maybe after `mov ecx, LENGTHOF array01`, program should have `shr ecx,1`. We just need `3 loops` because OP said swap only `[0]` <=> `[1]`, `[2]` <=> `[3]`, `[4]` <=> `[5]`. After each swap, move to another pair of elements `add edi, TYPE array01`.
Comment: 0x002E8000 is the first address in a new page, so somehow your loop went too many iterations, or your pointer got incremented too much some other way?   Or `.data` wasn't writeable in the first place?  It's not usual for the start of the `.data` section to be close to the end of a page; I'd expect it to be at or near the start.  What do you see for the address of `array01`?  And when you single-step, does your loop fault on the first iteration, or somehow run many iterations?  What's ECX doing?  It should be counting down from 5.
Comment: *I have abandoned using the var1 and var2 variables because I can't seem to get them to work.*  Good; you want registers for loop counters and temporaries, not more static storage!  Also, `mov eax, [edi]` / `mov edx, [edi+4]` / store reversed / `add edi, 8` would seem a lot easier than 2 adds and a sub (which only go forward by a net distance of one `TYPE array01`, by 4, so that's one element, not two.)
Comment: When I single step I get a fault on the first iteration.
ECX is counting down form 5
Comment: I'm also running this on an AMD processor. I don't know if that will make a difference. I got a computer from school that has an Intel chip that the teacher gave me to use for the semester. Don't know if that would make a difference.
Comment: Sounds like your `.data` section ended up read-only somehow!  That's weird, `.data` implies read-write.  What commands are you using to assemble + link this into an executable?
Comment: AMD64 is 100% compatible with Intel64 for all of these instructions, and for all the baseline x86-64 instructions you're going to use in normal user-space programs.  The Intel / AMD differences other than performance are in a few things the kernel has to care about (like an accidental(?) difference in semantics of a #GP fault in `sysret` returning to user-space with a non-canonical RIP), and stuff like atomicity guarantees for unaligned loads/stores within a cache line.  [What EXACTLY is the difference between intel's and amd's ISA, if any?](https://stackoverflow.com/q/38516823)
Comment: I'm just running this in debug mode. Nothing more than hitting `Local Windows Debugger`.
Comment: MASM is a command line program.  Are you running it from within Visual Studio?  Or some other GUI IDE?  IDK if it's possible you could be debugging an old executable that doesn't match your current source code.  Otherwise I'd guess there might be a difference between the source you posted on SO vs. what you're actually testing locally.  Put in another `.data` line right before the `array01` in case there's some weird non-ASCII character on the other line that's breaking something.
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/255494/discussion-between-funlamb-and-peter-cordes).
Comment: BTW, the fun way is `movdqu xmm0, xmmword ptr [array01]` / `pshufd xmm0, xmm0, 0b10_11_00_01`  (those are 2-bit indices for 4x 4-byte elements, packed into an 8-bit immediate.  NASM accepts that syntax for binary literals, MASM probably doesn't).  / `movdqu xmmword ptr [array01], xmm0`.  You might need to tell MASM to allow SSE2 vector instructions, but compilers use those by default even in 32-bit code these days.  But obviously using a 16-byte shuffle wouldn't teach you to write loops and use addressing modes (and not add the address to itself, as we discussed in chat.)
Comment: The other fun way is to write 64-bit code and do stuff like `ror qword ptr [rdi], 32` to do a 64-bit rotate by 32 to swap halves of a 64-bit chunk of memory.
Comment: I'm not having any lucky finding a duplicate for the problem of `array01[edi]` when EDI is a pointer instead of an index.  search terms like "site:stackoverflow.com assembly array index adding address twice" are finding questions with unrelated titles, although I'd expect that duplicates will have a title about something else. :/
Comment: Hrm, if we include the debugging details from chat, that `&array01` is at `0x007C4000` but the fault address is `0x00F88004`, and make the title something about accessing an address that's twice what was intended, that could perhaps be something that could get found in the future.
Comment: Can you add your answer so I can accept it?
Comment: I guess so, since I didn't find a duplicate.  I was resisting doing so because the actual bug  is so trivial and obvious once spotted.
Answer: EDI is already a pointer: use mov [edi], ebx.
mov array01[edi], ebx is adding the pointer in EDI to the address of of the array.  That would be correct if EDI was a small number, a byte offset from the start of the array.  But it's not in this case; you put a pointer into EDI with mov edi, OFFSET array01 before the loop.
That address calculation is like C int *ptr = array01; array01[ (int)ptr ] = tmp2; but without scaling by the type width.  In discussion in chat, you found the actual address of array01 was 0x007C4000 using the debugger, but the fault address was reported as writing to 0x00F88004.  That was the clue to take a more careful look at exactly what the code is doing.
0x007C4000 * 2 = 0xF88000, the fault address.  I don't know where the extra ...4 is coming from.  The first store is after the sub edi, 4 so should be with EDI back to its original value.  (And memory protection uses 4K page granularity, so if 0xF88004 faulted, 0xF88000 should have faulted in the first iteration, like your debugger is showing you actually happened.)

So why did it fault on the store but not the load?  You used the correct addressing mode for the loads, [edi], just dereferencing the pointer, not adding another address to it!
At first I was thinking it was odd there was read-only memory at that address, but no, the first access was with the stores.

BTW, it would be a lot simpler to load and store from [edi] and [edi+4], so your loop only needs one add edi, 8 to advance to the next pair.  (You're currently going forward 8 and back by 4 every iteration, for a net advance of one 4-byte element.)
You'll have to adjust your loop counter to avoid going off the end; it might be easier to work with a pointer to the end of the array and cmp / jb L1against that, instead of calculating an iteration count for the slowloopinstruction.  You need to stop even if there's 0 or 1 elements left, like the bottom of ado{... ; ptr+=8;}while(ptr < endp-4);` where endp is a label at the end of the array.

BTW, the fun way is to use SIMD to load 4x 32-bit elements (2 pairs), shuffle them, and store them back.  Since the problem size happens to be 2 pairs in this case, we can drop the loop :P
   movdqu xmm0, xmmword ptr [array01]   ; 16-byte load
   pshufd xmm0, xmm0, 0b10_11_00_01  ; 2-bit indices for 4x 4-byte elements, packed into an 8-bit immediate.
              ; NASM accepts that syntax for binary literals, MASM probably doesn't
              ; _mm_shuffle_epi32(vec, _MM_SHUFFLE(2,3, 0,1))
   movdqu xmmword ptr [array01], xmm0   ; 16-byte store

You might need to tell MASM to allow SSE2 vector instructions. C compilers use those by default even in 32-bit code these days. But obviously using a 16-byte shuffle wouldn't teach you to write loops.
The other fun way is to write 64-bit code and do stuff like ror qword ptr [rdi], 32 to do a 64-bit rotate by 32 to swap halves of a 64-bit chunk of memory.


Is there a way I can display one image field if another one does not exist using visibility rules in node template?

Question: I can do something like this with a text field, because I can compare it to an empty string, but I can't figure out how to do it with an image field.
Visibility rules supports content:exists, but this only applies to the content the rule applies to, not another field.
Is there a way I can display one image field if another one does not exist?
Answer: I would suggest using views to create a block based on the filter criteria where the first image field is empty.
Comment: Hmmm. maybe that could work. I need to show image field B only if image field A doesn't exist. It sounds like your solution is to use the view for the criteria and always show the view in the Node Template?
Comment: First you need to ensure that Image field B is hidden in the Display Mode, and even if the view block is always shown in the template it will be empty if the criteria is not full filled and hence will not matter.
Comment: Still having trouble. How do you set the criteria for a missing image? I have tried image:fid is not empty.
Comment: +1 for suggesting a view. See the solution that eventually worked for me.
Comment: I do not understand what I am missing in your issue, but I tested and it seemed to work.
Answer: Use a View with the "Views Is Empty" module
It seems there is no way to filter for an empty image or file. One way to filter for the existence of an image/file in a view is to add a relationship and also require the relationship. This only works if the image/file exists, but there is no converse (a test for it NOT existing).
The "Views Is Empty" module enables a view to display one image/file if it exists and another if it doesn't.
To use this, you:

Add both image/files to the view.
Exclude these from the view
Add the "View Is Empty" field
Select the two image/files in the settings for this new field.

In this solution, the view is added to the Node Template rather than either of the fields.
Answer: Let's say the two fields are called 'field_use_if_present' and 'field_fallback' and your content type is 'article'. Then you can use this code in custom module named 'yourmodule':
<code><?php
/**
 * Implements hook_node_view
 */
function yourmodule_node_view($node) {
  if ($node->type === 'article') {
    if (empty($node->content['field_use_if_present']) {
      $node->content['field_use_if_present'] = $node->content['field_fallback'];
    }
    // Don't use this next line if you're managing
    // show/hide/display of field_fallback with some other functionality.
    $node->content['field_fallback'] = array();
  }

}
</code>


How to find values from one dataframe in another using pandas?

Question: I have two dataframes:

    df1 = pd.DataFrame({'A': ['A0', 'A1', 'A2', 'A3'],'B': ['B7', 'B4', 'B0', 'B3'] })
    df2 = pd.DataFrame({'A': ['A4', 'A3', 'A7', 'A8'],'B': ['B0', 'B1', 'B2', 'B3']})

and i need to get all the common values from the column B, so here it would be  B0 and B3.
Using df1.B.isin(df2.B) gives me False False True True, but not a list of values.
Answer: You need boolean indexing:
print (df1[df1.B.isin(df2.B)])

    A   B
2  A2  B0
3  A3  B3

print (df1.ix[df1.B.isin(df2.B), 'B'])
2    B0
3    B3
Name: B, dtype: object

print (df1.ix[df1.B.isin(df2.B), 'B'].tolist())
['B0', 'B3']

Another solution with merge:
print (pd.merge(df1,df2, on='B'))
  A_x   B A_y
0  A2  B0  A4
1  A3  B3  A8

print (pd.merge(df1,df2, on='B')['B'])
0    B0
1    B3
Name: B, dtype: object


The probability of my winning?

Question: Let us assume that,  Me and My Cousin have started a game (Its Dice, the winner will be, who puts the six of the dice first ). There are  6 digits on the dice (1, 2 , 3  , 4,  5 , 6). 6 is the wining digit.  If I throw the dice first, then what is the probability that I will win. (thy way we  threw  the dice like  Me Cousin Me Cousin Me ... infinite)
If I won at the first time then the probability would be  1/6. But I would not get have a chance to win at the first throw!
Comment: Your question is quite unclear. Would you mind clarifying?
Comment: What have you tried?  Might be easier to start with coin tosses (winner being first to throw H).  Easy to write out all possibilities for 4 tosses or so...  Or just try the game and get a numerical estimate.
Comment: @Gummybears -  I think he means "Players #1 and #2 take turns throwing a fair die.  Winner is first one to throw a 6. Find the probability that #1 wins the game."
Comment: The possibility of throwing is infinity , therefore i think $\frac{a}{n-r}$ would work. I am not sure.
Comment: I guess... But I was trying to understand what he had tried on the question, which I suppose is given by the last line.. @lulu
Comment: @Gummybears, yes right you are!
Comment: @SabbirHasan.  True...in theory the tosses might go on forever. But that is a probability 0 event.  Try it (with the coins!  using the die will take too long).  If you get a very long string of T's there's something wrong with your coin.
Answer: Hint #1: Try to turn your problem into a geometric series.
Hint #2: There's a bit of factoring to be done.
Edit: Hint #3: You can win on either the turn number $1, 3, 5, ...$ - add up all these probabilities.
Comment: But, don't we have the same probability of  the all  turns?
Comment: The probability of winning on each turn *given that you've reached that turn* is 1/6. But it becomes less and less likely that you reach a particular turn the further out you go, because the chances are someone will have won already. So maybe the best way of thinking about this is to separate your concerns: 1) What's the probability of reaching a turn? 2) What's the probability of winning *given* that you've reached a turn. This leads to an infinite sum. However, Ofir Schnabel's solution is much slicker.
Answer: As you said, you will start throwing the dice first. So the probability that you will win on the first throw will be $\frac{1}{6}$
Now, consider that you don't win on the first throw. The probability of this happening is $x$. Now for you to win on your next throw, it is necessary for your cousin to lose on her throw, probability being $x$. So the possibility for you to win on your second throw (third throw overall in the game) is $x * x * \frac{1}{6}$
Continue writing for further tosses, and you will notice a pattern starting to emerge. Your overall probability of winning will simply by the sum.
Comment: This means   x^n *(1/6) = 1 ?
Comment: Why are you equating it with 1?
Comment: @SabbirHasan Did you try calculating the probability of you winning on your third toss?
Answer: I think that there is a very simple (and maybe wrong) solution to this problem.
Denote the probability that the first thrower to win by $x$.
Then the second thrower has probability $1-x$.
But it is clear that the probability of the second thrower is just the probability of the first thrower to miss (not throwing $6$) in the first throw, times $x$.
From here
$$1-x=\frac{5}{6}x\Rightarrow x=\frac{6}{11}.$$
Comment: I have not got  that how  the probability of the second thrower is  5/6 * x
Comment: @SabbirHasan there is a $\frac{5}{6}$ probability that the first thrower will miss. If he indeed misses, the you can think about the second thrower as the "new" first thrower, and hence his probability is $x$.

The probability of my winning?