Como pegar valor do Form - Java - Swing

Question: Criei um formulário no Java com interface Swing, neste tem um campo textfield Texto e um botão Enviar, no código do botão preciso atribuir o valor informado no textfield a um variável do tipo String, qual a função para isto ?
Comment: `String str = textField.getText();` se entendi bem, creio que isso já resolva.
Comment: Poste seu código para darmos uma olhada.
Comment: @DiegoFelipe Qual o motivo do ```(String)```, é alguma conversão de dados ?
Comment: Corrigi, conforme a [**documentação do java**](https://docs.oracle.com/javase/7/docs/api/javax/swing/text/JTextComponent.html#getText()) neste caso não precisa fazer o cast, ele já traz direto como string.
Comment: @DiegoFelipe Vou testar assim que possível.
Answer: Edit: Não tinha visto os comentários, foi mal.
O seguinte código deve funcionar:
String s = textField.getText()
E a partir daí tu trata s como for necessário.
Caso surjam mais dúvidas a respeito do TextField, segue a documentação:
http://docs.oracle.com/javase/7/docs/api/java/awt/TextField.html
Abraço
Comment: @DiegoFelipe, ficou assim: o objeto -  ```JTextField texto = new JTextField();``` a variável - ```String textoaux = texto.getText();```, obrigado.
Comment: Sem problemas. Não respondi diretamente porque quis esperar o OP manifestar se o problema era simples assim mesmo. De qualquer forma, sua resposta é válida :)

Como pegar valor do Form - Java - Swing


Probability distribution question: Please verify answer

Question: Question
A k-out-of-n system is one that will function if and only if at least $k$ out of the $n$ individual components in the system function. Assume that individual components function independently of each other. Assume also each individual component functions with probability $0.9$
Determine the long-run proportion of 3-out-of-5 systems that will function.
My Working
The binomial distribution looks to be a good fit here.
Summarising the data:
$p$ (the probability of success) $= 0.9$
$n$ (the total number of trials) $= 5$
$x$ (the number of successes needed) $= 3$
3-out-of-5 means the system needs at least $3$ components to function which means the system will function at $3$ components, $4$ components $5$ components.
Which in turn means the answer will be $1 - prob$($0$ components + $1$ components + $2$ components)
Therefore $1 - 0.0815$
= $0.9185$
Is this correct?
Comment: The reasoning is correct, but the calculation is not: the probability is $0.99144$. If you show the details of your calculations, we can see where you went astray.
Comment: You on the right track, but your numbers do not look right. $\mathbb{P}(X=0) = (1-p)^5 = 10^{-5}$, $\mathbb{P}(X=1) =5 (1-p)^4 p = 45 \cdot 10^{-5}$, $\mathbb{P}(X=2) = 10 (1-p)^3 p^2 = 810 \cdot 10^{-5}$. I am getting 0.99144 for the answer, instead of 0.9185.
Comment: Thanks guys, indeed I made a calculation mistake. I did 1-binocdf(3,5,0.9) instead of 1-binocdf(2,5,0.9) - in matlab
Answer: I do not at this point see what went wrong in the computation.
The answer is
$$\binom{5}{3}(0.9)^3(0.1)^2+\binom{5}{4}(0.9)^4(0.1)^1+\binom{5}{5}(0.9)^5(0.1)^0.$$
The calculator gives me an answer of $0.99144$.
Because it is easy to make a mistake, I also calculated using your (correct) idea. The answer then would be
$$1-\left(\binom{5}{0}(0.9)^0(0.1)^5+\binom{5}{1}(0.9)^1(0.1)^4+\binom{5}{2}(0.9)^2(0.1)^3\right).$$
Again, I get $0.99144$.  This time, to make sure, I also did the calculation by hand.
Added: Maybe I have a good guess about what went wrong. Note that $\binom{5}{3}(0.9)^3(0.1)^2=.0729$. If we subtract this from $0.99144$, we get $0.91854$. So maybe in your calculation you used one term too many.
Comment: Thanks Andre, I made a silly error by doing 1-binocdf(3,5,0.9) instead of 1-binocdf(**2**,5,0.9) - in matlab
Comment: I had added that guess a few seconds ago, since I realized that that term probably accounted for the discrepancy.
Comment: What appears above is wrong.  It says $1-\binom{5}{0}(0.9)^0(0.1)^5+\binom{5}{1}(0.9)^1(0.1)^4+\binom{5}{2}(0.9)^2(0.1)^3$.  It should say $1-\left(\binom{5}{0}(0.9)^0(0.1)^5+\binom{5}{1}(0.9)^1(0.1)^4+\binom{5}{2}(0.9)^2(0.1)^3\right)$.
Comment: Thank you, I have inserted the parentheses.


Can I terminate serial link into same router?

Question: Can I terminate my serial link into the same Cisco router? I mean can I terminate both ends of serial (wan) link into the same router's two different serial ports? This is just for testing purposes.
sadiq.
Comment: What do you expect to happen when you do that?
Answer: thats not possible as the interfaces on the routers have to be in different subnets, but the interfaces at two ends have to be in same subnets..... so you see the two statements are contradictory....
Comment: Huh? Could you restate what you're trying to say?
Comment: OK, I got it. I wasn't following your wording.
Answer: No two interfaces IPs on the same router can be in the same subnet(on most vendors anyway).  The interfaces on each end of a serial connection must be in the same subnet.  So no you cannot do this.
If you wish to do this on Cisco IOS without hardware I would suggest you look into something like GNS3 or Dynamips.
Edit: Actually if you were using IPv6 and link local addresses you probably could do this, but if you're using IPv4 IOS is going to scream at you.


Java What is wrong with this code?

Question: class Ages {
    public static void main (String args[]){
        int age = 3;
        Scanner agescan = new Scanner(System.in);
        System.out.println("Hello. Enter your age here: ");
        age = agescan.nextInt();
    }
}

I'm trying to create something that says a certain thing depending on your age. I haven'y yet added the nested if and else stuff because this won't run.. WHY?
This is my error message:
Exception in thread "main" java.lang.NoClassDefFoundError: Age Caused by:
    java.lang.ClassNotFoundException: Age at
    java.net.URLClassLoader$1.run(URLClassLoader.java:202) at
    java.security.AccessController.doPrivileged(Native Method) at
    java.net.URLClassLoader.findClass(URLClassLoader.java:190) at
    java.lang.ClassLoader.loadClass(ClassLoader.java:306) at
    sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301) at
    java.lang.ClassLoader.loadClass(ClassLoader.java:247)

Comment: yes exactly `this won't run.. WHY?` what does it say when you run
Comment: The code you posted has a class named `Ages` while you are trying to run a class named `Age` (notice the missing s).
Comment: How are you trying to run it, and what error message do you get?
Comment: First of all, your code runs! It works as long as you enter a valid integer. May be you are giving it "3"  in your command line rather than 3. Or some other String which  rises exception.
Comment: This is my error message: Exception in thread "main" java.lang.NoClassDefFoundError: Age
Caused by: java.lang.ClassNotFoundException: Age
 at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
 at java.security.AccessController.doPrivileged(Native Method)
 at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
 at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
 at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
 at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
Comment: @RogerLindsjö thanks. i remember changing that thinking it would change the class name as well.
Answer: Your code does not have any errors. I ran it. Have you pressed Enter after entering the age?
import java.util.Scanner;

class Ages {
    public static void main(String args[]) {
        int age = 3;
        Scanner agescan = new Scanner(System.in);
        System.out.println("Hello. Enter your age here: ");
        age = agescan.nextInt();

        System.out.println("You entered: " + age);
    }

}

Comment: No issue with the code that I can see, and when run it's okay. Would be nice if the OP would state what the error was.
Comment: I'm using eclipse. This is the error message i get: Exception in thread "main" java.lang.NoClassDefFoundError: Age
Caused by: java.lang.ClassNotFoundException: Age
 at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
 at java.security.AccessController.doPrivileged(Native Method)
 at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
 at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
 at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
 at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
Comment: One  of the issues might be that your code is not compiled when you try to run it or something wrong with the classpath used at runtime
Comment: @user2634251 then the problem is not in the code you've posted. Until you post the real code that's giving you problems, there's no exact answer to your question.

Java What is wrong with this code?


Yii2 dropDownList

Question: Preciso de um exemplo, de dropDownList, onde eu possa fazer um dropDown entre dois sqls, neste caso A e B.
Abaixo apresento um pseudocódigo.
Introdução ao problema:
Tabela sql A
id_A
id_usuario
nome_A
descricao_A

Tabela sql B
id_B
id_A
nome_B
descricao_B

Preciso fazer um dropDownList com o sql B, onde deverá ser apresentado todos os campos do sql A que tenham o id_usuario = 10, porém no sql B não possuo o campo id_usuario, deverá algo do tipo inner join, porém usando o dropDownList do yii2.
A sintaxe abaixo, que estou usando não resolve, pois somente apresenta os campos
que satisfaz o id_A (sql A e B).
dropDownList(\yii\helpers\ArrayHelper::map(B::find()->where(['id_A' => $A->id_A])->all(),'id_B','nome_B') ,

P.S. Não quero colocar o id_usuario no sql B.
Answer: Encontrei a solução, no exemplo acima basta realizar a seguinte modificação:
$id_usuario = Yii::$app->user->identity->getId();

dropDownList(\yii\helpers\ArrayHelper::map(B::find()->([A])->where(['id_usuario' => $id_usuario])->all(),'id_B','nome_B')

Yii2 dropDownList


Select presselecionado com change do Jquery?

Question: Estou estudando Json e o evento change do Jquery.
O que eu preciso é o seguinte
Quando o usuário abrir a página já tenha resultados. (no select venha marcado todas)
O html vem vazio e só funciona quando mudo o select para alguma cidade.

   var cidade = "";

$('select').on('change', function() {

  cidade = this.value

  var url = "http://meusite?&cidade="+cidade;

//jsonrodando

  })

<select >
  <option>cidades</option>
  <option value" " selected=" ">todas</option>
  <option value"1"> cidade1</option>
    <option value"2">cidade2</option>

</select>

O json funciona perfeitamente quando seleciono a cidade correta no select.
Mas ele não vem pre carregado com todas. (Quando a variavel "cidade" na URL vem vazio aparecem todas)
Deve funcionar assim:
Abre página vem todas as cidades. (isso não funciona).
Usuário muda no select a cidade, e a cidade aparece (isso funciona perfeito);
O que precisa ser mudado no código ?
Answer: Resolvido. Modifiquei o código.

$( "select" ).change(function () {
    var str = "";
    $( "select option:selected" ).each(function() {
      str += $(this).val() + " ";
    });
    console.log(str);
    cidade=str;

    var url = "http://meusite.com?cidade="+cidade;

//json rodando perfeito aqui

  })
  .change();

<select  >
  <option value="2"> cidade 2</option>
  <option value="3" >Guamiranga</option>
    <option>Carama</option>
  <option  value=" " selected="selected">Todas</option>

</select>

Espero que isso ajude.


Select option with selenium

Question: <paper-radio-button name="NOT_MADE_FOR_KIDS" class="style-scope ytcp-audience-picker iron-selected" role="radio" tabindex="0" toggles="" aria-checked="true" aria-disabled="false" aria-selected="true" checked="" active="">

        <paper-ripple id="ink" center="" class="circle style-scope paper-radio-button" checked="">

I am trying to select the 'No, it's not made for kids' option when uploading a video to youtube,
I do
kids_box = driver.find_element_by_name('NOT_MADE_FOR_KIDS')
kids_box.click()

Also tried with class name and id, I tried clicking the id='onRadio' too. Any help on this is appreciated!
Answer: You are just clicking to the button as a whole and I think it is wrong.
Instead, you should be clicking to the desired option on the radio button. In order to do this, please try the code snippet below.
kids_box = driver.find_element_by_id('onRadio')
kids_box.click()

If the above solution does not work, what you should be doing is, right click to the option circles in the radio button, then click inspect in Google Chrome, then right click to the button again and then click inspect again.
After completing this progress, you will see the corresponding line of the radio button. Right click to it, select copy, then select copy xpath and use the function below:
kids_box = driver.get_element_by_xpath("//div[@id='a']/div/a[@class='click']")
kids_box.click()

You should paste the xpath to inside the parantheses.
Comment: thanks for your answer. I just found that this works for me: `kids_section = browser.driver.find_element_by_name("NOT_MADE_FOR_KIDS")
no_label = kids_section.find_element_by_id("radioLabel")
no_label.click()`

Select option with selenium


python search and replace using variables

Question: User providing me with search expression, e.g. "^.*/bin/run.sh"
Need to scan a file and replace search expression and replace with value also provided by user.

search = "^.*/bin/run.sh"
replace = "/path/to/bin/new_run.sh"

how do I search and replace in python 3?
Comment: `str.replace()`?
Comment: You *are* using regex, right ?
Comment: Yes using regex
Answer: Using the re module's re.sub method.
oline = re.sub(search, replace, iline)

Where you are looping through line by line.
Look at the fileinput and argparse modules for how to wrap this up into an application if that is what you want.


PowerShell Out-File is not working

Question: The following line of my code simply does not write to file the Out-File command:
Move-Item $item.Path $CaminhoCompleto -Force -WhatIf -Verbose |
    Out-File -Filepath $SaidaTXT -Append -NoClobber

On the screen it shows correctly, but the file is empty.
Answer: -WhatIf messages are written directly to the console and can't be piped or redirected without running the statement in a different PowerShell process. You  can capture the output with Start-Transcript, though.
Start-Transcript -Path $SaidaTXT -Append
Move-Item ...
Stop-Transcript

Comment: Yes, I noticed, then I used Start-Transcript.

Thanks.

PowerShell Out-File is not working


On the proof that $\sum n\arctan(n)$ diverges

Question: $\sum_{n=1}^{\infty} n\arctan(n)$ converge or diverge?
I know this diverges because $$\lim_{n\to\infty} n\arctan(n) = \infty \neq 0$$ So by divergence test this series clearly diverges. My question is, can I just say this and end the question?
Comment: Yes, if the limit of the summand diverges or converges to anything other than zero then the sum certainly diverges (as you noted). So yes, you can just say this and end the question.
Answer: Yes, that's enough.  It should be a rule in your notes that if $a_n$ doesn't converge to $0$, then $\sum a_n$ diverges.
Answer: This is too long for a comment. It has been added for your curiosity.
As Omnomnomnom already answered, what you wrote is enough to prove the divergence.
Just in case you would like to go further, considering $$S=\sum_{n=0}^\infty n\tan^{-1}(n)=\sum_{n=0}^p n\tan^{-1}(n)+\sum_{n=p+1}^\infty n\tan^{-1}(n)$$ for any $p$ we can use $$\tan ^{-1}(p)+\tan ^{-1}\left(\frac{1}{p}\right)=\frac \pi 2$$ and, for large $p$ $$\tan ^{-1}\left(\frac{1}{p}\right)=\frac{1}{p}+O\left(\frac{1}{p^3}\right)$$ which makes $$\sum_{n=p+1}^\infty n\tan^{-1}(n)\approx\sum_{n=p+1}^\infty n\left(\frac \pi 2-\frac 1 n\right)=\frac \pi 2\sum_{n=p+1}^\infty n-\sum_{n=p+1}^\infty 1$$
In fact, if you consider the partial sum $$S_p=\sum_{n=0}^p n\tan^{-1}(n)$$ using series, you could show that $$S_p\approx \frac{\pi  }{4}p^2+\left(\frac{\pi }{4}-1\right) p+c-\frac 1{3p}+\cdots$$ where $c$ is a small number.
Edit
Just for the fun, let $p=10^k$. The table below reports the "exact" value and what gives the above approximation limited to the two first terms
$$\left(
\begin{array}{ccc}
 k & \text{"exact"} & \text{approximation} & \Delta\\
  1 & 76.7773 & 76.3938 & 0.38355 \\
 2 & 7832.93 & 7832.52 & 0.411898 \\
 3 & 785184. & 785184. & 0.414881 \\
 4 & 7.85377\times 10^7 & 7.85377\times 10^7 & 0.415181 \\
 5 & 7.85396\times 10^9 & 7.85396\times 10^9 & 0.415211 \\
 6 & 7.85398\times 10^{11} & 7.85398\times 10^{11} & 0.415405
\end{array}
\right)$$
Comment: For what it's worth, I think this is great.
Comment: @Omnomnomnom. Be sure I appreciate !


What's am I doing wrong with this backup using PyODBC and SQL Express Server 2008

Question: For details I'm running a very recent version of python and PyODBC and am trying to remotely instantiate a backup on SQL. I don't know much about SQL. I've tried googling the issue and have tried a few tricks below including using .nextset() and trying different encodings just in case. I see a large surge on the local network of the PC with the SQL server but it very quickly tapers to nothing. I also can't seem to run a stored procedure as it will never seem to find it despite it existing and being able to run from my local machine using SSMS or the SSMS on the remote PC. Also I've given complete access to the remote account accessing the sql server as far as I know
Here is the relevant function:
<code>    def back_up_and_restore(self):

        if self.Arbin not in [3, 4]:
            self.errorString = "Not remote server!"
            return self.errorString

        self.cnxn = pyodbc.connect(self.connectionString(self.db[0]))
        self.cursor = self.cnxn.cursor()
        self.cnxn.autocommit = True
        if self.Arbin == 3:
            folder = "Fred"
        else:
            folder = "George"

         query = r"BACKUP DATABASE [%s] TO  DISK = N'\\10.130.130.5\TestLab\DATA\%s\ArbinMasterData.bak' WITH NOFORMAT, INIT,  NAME = N'ArbinMasterData-Full Database Backup', SKIP, NOREWIND, NOUNLOAD,  STATS = 10" % ("ArbinMasterData", folder)
        #query = "{CALL BackUp%s2}" % folder
        query.encode(encoding='UTF-8')
        print(query)
        self.cursor.execute(query)
        time.sleep(2)
        while self.cursor.nextset():
            pass
        self.cnxn.close
</code>
When I run the function it just dies quickly and doesn't say anything. If I try running a stored procedure it says that the stored procedure doesn't exist. Any help would be great.
Answer: This code is working great if you need an example of PyODBC making a backup. I unfortunately was looking in the George folder instead of Fred.


React Native - Navigation + Image

Question: Estou tendo uma dificuldade em solucionar um problema que estou tendo utilizando a lib navigation do react native.
Quando abro um post, por exemplo, enviando para ele o parâmetro da imagem, ele me retorna a mensagem de erro a seguir.

Meu código é o seguinte:
render() {
    const {params} = this.props.navigation.state;
    var image = require(images + params.image);
    return (
        <ScrollView style={styles.container}>
            <Image style={styles.cover} source={image}/>
            <Text>{params.title} {image}</Text>
        </ScrollView>
    );
}

Alguém que tenha passado por isso pode me ajudar, por favor?
Agradeço.
Answer: Isso é um erro muito comum no react-native e no proprio JS. Por algum motivo, o require() não funciona desta maneira.
Você pode fazer conforme abaixo para popular um array de objetos e fazer um map para popular a ScrollView, pegar as imagens dos objetos do array e depois na hora de mostrar uma tela de detalhe você pode passar os dados do seu array.
Exemplo usando array de objetos + react-navigation:
render() {
  const dados = [
    {
      imagem: require('./img1.png'),
      titulo: 'Usuario 1',
    },
    {
      imagem: require('./img2.png'),
      titulo: 'Usuario 2',
    },
    {
      imagem: require('./img3.png'),
      titulo: 'Usuario 3',
    },
    {
      imagem: require('./img4.png'),
      titulo: 'Usuario 4',
    },
  ];
  return (
    <ScrollView>
      {dados.map((dados, i) => (
        <View key={i}>
          <Image source={dados.imagem} />
          <Text>{dados.title}</Text>
          <Button onPress={() => this.props.navigation.navigate('telaExemplo', {
            imagem: dados.imagem,
            titulo: dados.titulo
          })} />
        </View>
      ))}
    </ScrollView>
  )
}

Comment: Luiz, valeu demais. Funcionou bem aqui.
Comment: Sem problemas @FernandoDias
Answer: Você também consegue resolver o problema utilizando Template String.
render() {
    const {params} = this.props.navigation.state;
    var image = require(`${params.image}`);
    return (
        <ScrollView style={styles.container}>
            <Image style={styles.cover} source={image}/>
            <Text>{params.title} {image}</Text>
        </ScrollView>
    );
}

React Native - Navigation + Image


Definite integrals: Calculating Volume

Question: Suppose $D$ is the region in the $xy$-plane bounded by the parabola $y=x^2$ and the line $y=2x$. Find the volume of the solid generated by rotating $D$ about
1)  $x$-axis
2)  $y$-axis.
Are the answers of 1) and 2) $64π/15$ and  $8π/3$ respectively?
Though it sounds silly, would anyone tell what how to solve this problem?
Comment: This problem is called finding the volume of a solid of revolution. Try looking up the general formula. Such questions have been answered several times.
Answer: I will do (1) as an example, from first principles:
Since we are revolving around the x-axis, it will be convenient to describe the volume we are integrating in cylindrical coordinates, so let \begin{equation} y=r \cos{\theta},\; z=r \sin{\theta},\;x=x,\end{equation} then we have the parabola and line described in terms of parameter $r$ with $x$ the dependent variable: \begin{equation} x=\sqrt{r}, \; x=\frac{r}{2}, \end{equation} and within these regions we have $r$ varying from $0$ to where we have $\sqrt{r}=r/2$, solving this equation, we have $r=4$ is the upper limit. And of course $\theta$ varies from $0$ to $2\pi$. So taking all of this together we have the following integration region: \begin{equation} D=\{(r,\theta,x):0\leq \theta \leq 2\pi, \; 0 \leq r \leq 4, \; \frac{r}{2} \leq x \leq \sqrt{r}\}, \end{equation} and since we are using cylindrical coordinates we must include the Jacobian of the coordinate transformation (read more here): in this case $r$, when integrating:
\begin{eqnarray}\text{Vol}(D) &=& \int_0^{2\pi}\int_0^4\int_{r/2}^{\sqrt{r}}r\text{ d}x\text{d}r\text{d}\theta. \end{eqnarray}
So then, calculating the integral, you will get $64\pi/15$, which is indeed the correct answer for number (1).
Answer: Hints:
For a solid generated by rotating $F(x)$ about x axis:
$$V=\int^b_a\pi\left(F(x)\right)^2dx$$
since $y=F(x)$, $x=F^{-1}(y)$, so, for a solid generated by rotating $F(x)$ about y axis:
$$V=\int^b_a\pi\left(F^{-1}(y)\right)^2dy$$
Answer: Is this a calc II volume of revolution homework problem?

$$\pi\cdot \int_0^2 \left((2x)^2-(x^2)^2\right)\ dx$$
$$ 2\pi\cdot \int\left(x\cdot(2x-x^2)\right)\ dx$$

Definite integrals: Calculating Volume


Ajuda, gerar gráficos com json

Question: Preciso gerar um gráfico do tipo Pie Cart utilizando js e json, tenho o arquivo json com o nome dos cursos e quantidade de aprovados por curso, preciso que o js leia essas informações e gere o gráfico com elas
"Não consigo gerar o gráfico exemplo: ler o json e tratar os dados para que ele mostre no gráfico automaticamente. Quero que os nomes dos Cursos e os números de aprovados que estão no json, preencham os campos necessários e gere os gráficos."
var nome_course;
var aprovados;

$(document).ready(function () {
$.getJSON("./report/report_curso.json", function (json) {

let nome_curso = json["nome_curso"];
let aprovados = json["matriculados"];

});
});

Chart.defaults.global.defaultFontFamily = 'Nunito', '-apple-system,system-
ui,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif';
Chart.defaults.global.defaultFontColor = '#858796';

// Pie Chart Example
var ctx = document.getElementById("myPieChart");
var myPieChart = new Chart(ctx, {
type: 'doughnut',
data: {
labels: [nome_curso],
datasets: [{
  data: [aprovados],
  backgroundColor: ['#4e73df', '#1cc88a', '#36b9cc'],
  hoverBackgroundColor: ['#2e59d9', '#17a673', '#2c9faf'],
  hoverBorderColor: "rgba(234, 236, 244, 1)",
  }],
  },
  options: {
   maintainAspectRatio: false,
   tooltips: {
  backgroundColor: "rgb(255,255,255)",
  bodyFontColor: "#858796",
  borderColor: '#dddfeb',
  borderWidth: 1,
  xPadding: 15,
  yPadding: 15,
  displayColors: false,
  caretPadding: 10,
  },
   legend: {

  display: false
   },
   cutoutPercentage: 80,
   },
   });

Json:
[{"nome_curso":"Curso 1","matriculados":"673"},{"nome_curso":"Curso2","matriculados":"906"},{"nome_curso":"Curso3","matriculados":"489"}]
Comment: Qual seria o problema ?
Comment: Não consigo gerar o gráfico exemplo: ler o json e tratar os dados para que ele mostre no gráfico automaticamente. Quero que os nomes dos Cursos e os números de aprovados que estão no json, preencham os campos necessários e gere os gráficos.
Comment: Queres usar o resultado da consulta `getJSON` no gráfico é isso ?
Comment: Para ler um json é preciso utilizar métodos do Javascript para tanto como **map()** ou **forEach()** por exemplo, se vc ainda sabe mexer com tais ferramentas acredito que ainda não esteja preparado par mexer com gráficos.
Comment: sim isso mesmo no caso do gráfico ali onde está "Labels:" seria inserido o nome dos cursos no formato EX: ["nome do curso 1","nome do curso 2"]. E onde está "data:" o número dos matriculados no formato EX:["673","906"]
Comment: sei trabalhar também com forEach(), porém bem pouco, por isso vim pedir ajuda, alguma luz para que consiga fazer oque necessito.
Answer: Antes de tudo é necessário relembrar de algumas coisas.

Temos que relembrar que o JS é síncrono, ou seja, ele não espera a sua consulta ajax para após gerar o gráfico, ele vai fazer isso tudo de um vez, pode ser que em alguns casos que a consulta seja instantânea, consiga atribuir o valor à variável, mas isso é um risco enorme.
Para facilitar use um retorno json baseado nessa lógica
{
    "matriculados": ["673", "906", "489"],
    "nome_curso": ["Curso 1", "Curso 2", "Curso 3"]
}

Qual seria a solução para o problema?
Solução 1

Criar o gráfico dentro da sua consulta ajax, assim após a consulta será possível usar os valores do gráfico sem nenhum problema, ficando algo parecido com isso:
$.getJSON("./report/report_curso.json", function (json) {
    var ctx = document.getElementById("myPieChart");
    var myPieChart = new Chart(ctx, {
        type: 'doughnut',
        data: {
            labels: json.nome_curso,
            datasets: [{
                data: json.matriculados,
                backgroundColor: ['#4e73df', '#1cc88a', '#36b9cc'],
                hoverBackgroundColor: ['#2e59d9', '#17a673', '#2c9faf'],
                hoverBorderColor: "rgba(234, 236, 244, 1)",
            }],
        }
    });
});

Solução 2

Tornar sua função assíncrona, ou seja, fazer com que obrigatoriamente, antes de criar o gráfico seja necessário aguardar o retorno da consulta ajax , ficando algo parecido com isso:
const createGraph = async () => {
    let nome_curso = [];
    let matriculados = [];

    $.getJSON("./report/report_curso.json", function (json) {

        nome_curso = json.nome_curso;
        matriculados = json.matriculados;

    });

    var ctx = document.getElementById("myPieChart");
    var myPieChart = new Chart(ctx, {
        type: 'doughnut',
        data: {
            labels: [nome_curso],
            datasets: [{
                data: [matriculados],
                backgroundColor: ['#4e73df', '#1cc88a', '#36b9cc'],
                hoverBackgroundColor: ['#2e59d9', '#17a673', '#2c9faf'],
                hoverBorderColor: "rgba(234, 236, 244, 1)",
            }],
        }
    });
}

Solução 3

Caso queria continuar usando o formato json como no anunciado, pode realizar a lógico da consulta ajax dessa forma:
$.getJSON("./report/report_curso.json", function (json) {

    let cursos_json = [];
    let matriculados_json = [];

    for (let index = 0; index < json.length; index++) {
        cursos_json.push(json[index].nome_curso); // add nome do curso no array
        matriculados_json.push(json[index].matriculados);  // add matricula no array
    }

})

Referências:
ChartJs
Funções assíncronas
Comment: Entendi tudo certinho o problema é que o meu json é automaticamente gerado de outro lugar, então ele vem no formato que passei :(
Comment: Editei a resposta, basta usar essa lógica na consulta `ajax` e atribuição das variáveis.
Comment: deu certinho, muito obrigado!

Ajuda, gerar gráficos com json


How many groups of 5 with a given group leader can be selected from 12 people?

Question: Out of 12 people, only 2 groups of 5 can be formed
My answer: C(12,5) = 792
I feel like my answer might be incorrect because 1 of the 5 people should be a leader. Does this change anything?
Answer: Once you chose the $5$ people for the group you need to choose who is the leader. You have $5$ options to choose him, so multiply your answer by $5$. The answer is $792\times5=3960$.
Answer: The number $\binom{12}5$ is the number of ways of choosing groups of $5$ people from a pool of $12$.
You can choose the leader first ($12$ possibilities) and the remaining team after ($\binom{11}4$ possibilities). Thereby, the answer is $12\times\binom{11}4=3\,960$.


Cost function of neural networks can be non-convex, then why do we use it?

Question: I saw a thread here (Cost function of neural network is non-convex?). After I read this, I am really confused.
I am wondering that if the cost function is not convex, and we do backpropagation, then can it be "well-backpropagated?"
Because it is not convex, we cannot optimize a model.
My hypothesis was wrong? I want to know this...
Answer: "Because it is not convex, we cannot optimize a model."
It is not true that you can't optimize a non-convex function, it just means there is no guarantee of a unique global minimum and that there may be local minima.  This isn't actually as much of a problem as often we don't want to find the global minimum (especially for an unregularised neural network) as it would almost certainly horribly overfit the data.  It is possible that these local minima are actually beneficial.
For a multi-layer perceptron type network, you will get multiple local minima just by permuting the hidden layer neurons, and by negating the input-to-hidden and hidden-to-output weights (for a network with one hidden layer).  These modifications do not change the function of the network but give different weight matrices, demonstrating that these local minima are functionally equivalent and therefore not problematic.
In practice, there are also likely to be local minima that are not functionally equivalent.  The solution to this is normally to train the MLP several times, starting from different random initialisations of the weights, and retain the network that gives the best performance (e.g. using a validation set).
Note that convexity is often given as an advantage of kernel learning methods, such as the support vector machine.  However these methods tend to have kernel and regularisation hyper-parameters that are often optimised by cross-validation.  The cross-validation loss that is being optimised is unlikely to be a convex function of the hyper-parameters, so kernel learning method are not truly convex either.
Comment: Okay, if it is fine that it is not a convex loss function, then why cost function is important to be a convex? Or why do we study on convexity of loss function?
If cost function is a convex function, then it has some advantages? That's all?
Comment: If cost function is a convex function, then it has some advantages? That's all?
Comment: Yes, mostly the guarantee of a single global optimum, but also likely to be better convergence and the possibility of more efficient algorithms.  However there is a downside as well, which is that the models may be less flexible or more computationally expensive to achieve equal flexibility.


Batted ball hits bat again in the box

Question: The batter squares to bunt and makes contact with the pitch.  The ball bounces in front of home plate.  The ball then bounces up and hits the bat again.  Both feet of the batter are still in the box.  Is is a foul ball?  Is the batter out?
Answer: While a bounced ball could never be a called strike, a batter is allowed to swing at such pitches, so the ball is in play regardless of the bounce.
Since the ball strikes the bat twice and the batter is still in the box, this would be under 5.09(a)(7)

5.09(a) A batter is out when:
...
(7) His fair ball touches him before touching a fielder. If the
batter is in a legal position in the batter's box, see Rule
5.04(b)(5), and, in the umpire's judgment, there was no intention to interfere with the course of the ball, a batted ball
that strikes the batter or his bat shall be ruled a foul ball;

Unintentional contact while in the batters box: foul ball.

Batted ball hits bat again in the box


How to create a new entity that is fieldable

Question: I am currently learning how to create entities in Drupal 7. I have successfully defined a new entity and made it fieldable. My question is how do a create a new instance of that entity? I understand that if I want to create a form in a normal module I use the field API to create the form to collect the information that I want. Since the entity is fieldable, I am assuming that there must be a function that creates the form for you based on the form elements that you have defined. I mean that would make sense considering the field definitions are stored in a consistent format in the database so it would stand to reason that a function could be created to automate the process of creating the form from that information. I assume this is what happens when you create a new article that has had fields added to it.
Does anyone know what this function is or what the proper procedure is to accomplish this task?
Answer:
I am assuming that there must be a function that creates the form for you

Not quite - you need to create the form yourself with the API as normal, but you can use field_attach_form() to have the field elements added automatically. You'll also need the complementary field_attach_validate() and field_attach_submit() in your form's validate and submit handlers respectively.
Elements for your entity type's properties need to be added manually.
The best place to look for code examples is the entity example module in the Examples project, it has all of this in it and is pretty well commented.


Knowing $A, P$, find the diagonal matrix $D$

Question: Say we have a matrix $A$ which is Diagonalizable, and $P$ which can be used in diagonalizing $A$. We are tasked to find the diagonal matrix $D$ such that $A = PDP^{-1}$
Since we know $A,P$, and it is given that $P$ can be used in diagonalizing $A$ why can't we just do $P^{-1}AP = D$?
$A = \begin{pmatrix}
-3&-4\\
-9&-3\\
\end{pmatrix}, P = \begin{pmatrix}
2&-2\\
3&3\\
\end{pmatrix}, P^{-1} = \begin{pmatrix}
3&2\\
-3&2\\
\end{pmatrix}$
Multiplying $P^{-1}AP$ yields  $\begin{pmatrix}
-108&0\\
0&36\\
\end{pmatrix}$
Yet, $D$ is actually $\begin{pmatrix}
-9&0\\
0&3\\
\end{pmatrix}$
May someone explain to me why, if we know $A,P,P^{-1}$ and we use legitimate operations to compute $D$, we still don't get $D$? I mean I get a form of $D$ (aka. row equivalent, if I were to divide by $12$, but I don't know this just doing the calculation itself)..
Thanks in advance!
Answer: You're getting the wrong result because your inverse is incorrect. You are forgetting to divide by the determinant of $P$.
Comment: Ahhh right, forgot that it's not simply  $(\begin{pmatrix}
a&b\\
c&d\\
\end{pmatrix})^{-1} = \begin{pmatrix}
d&-b\\
-c&a\\
\end{pmatrix}$! Thanks!


Booting FreeBSD from whole-disk ZFS pool?

Question: I have a FreeBSD fileserver configured with one ZFS pool created from whole disk devices.  That is, the pool was created like this:
zpool create pool0 raidz ada0 ada1 ada2

This means the disks have ZFS disklabels, rather than FreeBSD disk labels.  This is the recommended way of using disks with ZFS:

ZFS  can use  individual  slices or partitions, though the recommended
  mode of operation is to use whole disks. [ from zpool(1M)]

Formatting the disks like this maximizes the portability of the filesystem between various ZFS implementations.  Unfortunately, it means there's nowhere to put a freebsd-boot partition containing the FreeBSD loader...or at least, I think that's what it means, but I'm looking for confirmation.
The system currently boots from a CF card containing the embedded loader (as well as the /boot directory, although this could live in ZFS just fine).  This works just fine, but Im curious -- is there any way to install the embedded loader onto the ZFS-labelled disks?
EDIT: I've been trying to answer this myself. I thought maybe I could apply a GPT label non-destructively to the ZFS disks, and then try embedding the boot code -- but while the GPT label didn't cause a problem with ZFS, ZFS seems to tromp on the label somehow.  So here's a different question: does OpenSolaris support GPT disk labels?  The ultimate goal here is to have a disk pool that will work under both FreeBSD and OpenSolaris while being able to boot from it into FreeBSD.
Comment: What version are you running. I know 8.1 and prior can not boot from ZFS without fairly extensive hacking. I can't remember off the top of my head if 8.2 has boot support; I believe 9-Current does and I know it will be backported to either 8.2 or 8.3.
Comment: Booting from ZFS is relatively easy (that's what I meant when I said that `/boot` can reside on ZFS without a problem).  I just need somewhere to the `gptzfsboot` code, which right now is on a `freebsd-boot` partition on a CF card.
Answer: Well, it's looking like the answer is, "you can't do that".
The rest of this answer is for anybody who happens to come across this
entry and is curious about how this is set up:
I have my boot code on a CF card, and everything else (aka, the
/boot directory) on ZFS.  The CF card is partitioned like this:
# gpart show ad0
=>     34  7847213  ad0  GPT  (3.7G)
       34      128    1  freebsd-boot  (64K)
      162  7847085       - free -  (3.7G)

I installed the boot code like this:
gpart bootcode -b /boot/pmbr -p /boot/gptzfsboot -i 1 ad0

And set the appropriate bootfs property on my ZFS pool:
zpool set bootfs=pool0/sys/freebsd pool0

Where pool0/sys/freebsd is my FreeBSD root filesystem (and contains,
among other things, the /boot directory).
Answer: It looks like it is possible to boot from ZFS pool created from whole-disk devices.
Just install zfsboot according to zfsboot man page:

zfsboot is typically installed using dd(1).  To install zfsboot on the ada0 drive:
 dd if=/boot/zfsboot of=/dev/ada0 count=1
 dd if=/boot/zfsboot of=/dev/ada0 iseek=1 oseek=1024

The Section 1.4: Boot Block of the ZFS specification says that 3.5MB of reserved space is at this position. This explains why the 64k of zfsboot fit in there without bothering the filesystem.
I haven't personally tried it yet.
Sources:

https://forums.freebsd.org/threads/boot-from-zfs-root-on-raw-disks.50525/
https://forums.freebsd.org/threads/documentation-for-boot-zfsboot.32886/


Split Menu in two

Question: I'm trying to create a page where the main menu will be a horizontal nav structure, but split into two groups of links so that I can have a logo in the centre of the nav menu and half the links either side of it.
Has anyone done this with Drupal? Any ideas on how it would be done?
Answer: Just create a link to the home page, move it to the middle and then grab it with CSS to show the logo as background image, hide text and space out the left and right sides.
Check out also Menu Icons which allows you to upload images for menu items.

Split Menu in two


Missing data imputation in univariate meta analysis with binary data using WinBUGS

Question: I want to impute missing data in univariate meta-analysis. My outcome (no. fractures) is a binary variable. Below is the WinBUGS code I have tried. The code is compiled and I got an output. My question is, why there are no meaningful values in this output, i.e. why most of them are zeros?
model{
for(i in 1:11)
{

rt[i]~dbin(pt[i],nt[i])
rc[k]~dbin(pc[i],nc[i])
phi[i]<-logit(pc[i])

logit(pt[i])<-phi[i]+theta[i]

theta[i]~dnorm(mu,t)

pc[i]~dunif(0,1)

}
mu~dunif(-4,4)
tau.sqrd~dunif(0,3)
t<-1/tau.sqrd

OR<-exp(mu)

}
list(rt=c(17,175,9,2,14,NA,NA,NA,NA,NA,NA),rc=c(107,181,20,6,35,NA,NA,NA,NA,NA,NA),nt=c(1372,627,66,23,91,30,17,161,167,33,126), nc=c(1381,635,66,24,99,33,19,164,167,30,129))

This is the output I have got
node     mean    sd     MC error    2.5%    median  97.5%   start   sample
    OR  0.3913  0.239   0.00314   0.1184    0.3414  0.9814  3000    7001
rc[6]   16.39   9.802   0.1048    0.0       16.0    33.0    3000    7001
rc[7]   9.508   5.724   0.07085   0.0        9.0    19.0    3000    7001
rc[8]   82.06   47.69   0.5446    4.0       82.0    160.0   3000    7001
rc[9]   83.56   48.85   0.6197    4.0       83.0    164.0   3000    7001
rc[10]  15.06   8.998   0.08587   0.0       15.0    30.0    3000    7001
rc[11]  64.14   37.57   0.4124    2.0       64.0    126.0   3000    7001
rt[6]   10.24   9.191   0.1113    0.0        7.0    29.0    3000    7001
rt[7]   5.853   5.349   0.06115   0.0        4.0    17.0    3000    7001
rt[8]   55.35   48.6    0.5245    0.0       41.0    156.0   3000    7001
rt[9]   58.0    51.05   0.6429    0.0       42.0    162.0   3000    7001
rt[10]  11.52   10.22   0.1186    0.0        8.0    32.0    3000    7001
rt[11]  43.7    38.54   0.4732    0.0       32.0    123.0   3000    7001

Could you please help me to solve this problem?
Answer:
My question is, there are no meaningful values in this output.(most of them are zeros)

The fact that your 2.5% quantiles are mostly zeros, that is not meaningless information, and it might indicate that your data contains a lot of zeros.
This makes me think of a zero-inflated model or discrete data.
Comment: Thank you for your comment.                                                                                when  I removed missing data (NA) and compiled this code again, I got the same value for the OR. I think there is some problem with the missing data imputation procedure.
Comment: Thank you for your comment. I'll refer to the zero-inflated model which you mentioned here. when I removed missing data (NA) and compiled this code again, I got the same value for the OR. I think there is some problem with the missing data imputation procedure.
Comment: @MAttanayaka possibly I do not understand your problem. Could you explain why you believe that the values are not meaningful.
Comment: Actually, I want to impute missing data. When I remove all the missing data and compiled code with only completed data, then I got the result of OR=0.39. When I impute missing data, then I got again the same result for the OR. That's why I believe that some problem with my code.
Answer: The model will not impute the missing observations. Studies with double-zeros (or no events) do not contribute to the analysis. Still, you can see the posterior (predicted)  number of successes per group for each study with missing counts. The median/mean counts are shrunken toward the summary mean.
Comment: Thank You for your comments.
There are no zero events in my data set. Can you give me more explanation about the other option you have mentioned here?
Comment: Studies both double zeros or both NR in the events cells do not contribute to the analysis.
Comment: I got it. I am not clear about the option which you have suggested based on the posterior. Could you please explain more?
Comment: Based on what you described, you are not imputing counts, and you are just seeing the posterior distribution of counts - given the evidence available in the meta-analysis. If you have more specific questions, we can help more.


Connect local computers without local static IP

Question: I have 3 PCs, one is server others are clients. Clients connects to server by entering the server local IP. All works good but problem occurs when the router restarts and server get assigned a different local IP. Now, need to enter IP address again of server in clients. I can solve this by using a local static IP but is it possible to connect without setting local static IP ?
Edit:
Using TCP Socket.
Comment: Can you go by the hostname?
Comment: What is the nature of the connection between the clients and the server? TCP? UDP? some higher level protocol?
Comment: Why not use local dns name ?
Comment: Wow people're overreacting for asking this question.
Comment: @xmenW.K. not overreacting, asking for more details ;)
Comment: 2 people voted to close the question. Dont know who else will ;)
Comment: how do you establish connections? `Socket`? `WCF`?
Comment: What is TCP Socket? `TcpClient` and `TcpListener`? `System.Net.Sockets.Socket` ?
Comment: The app is not yet completely written, its currently is just for testing. Anything can be used later, currently all I need is to connect to the server without static IP Address. I hope I've cleared things :)
Answer: Use the hostname for connecting to remote computer rather its IP address.
You will have to rely on DNS lookup though.
Answer: Your problem occurs because you use DHCP function of router. D of DHCP stands for "Dynamic", so IP addresses may be changed in some occasion.
The most simple solution is 'Not to use DHCP'.
[Detail of solution]
Assign fixed IP addresses for your PCs, and use that IP addresses to access among them.
Usually, router uses local IP address in range from 192.168.1.1 to 192.168.1.255 and 192.168.1.1 is used for router itself.
You may be able to use IP addresses 192.168.1.2, 192.168.1.3 and 192.168.1.4 for 3 PCs respectively.
Comment: True but asking this to normal users can be hard to them. Not all users can define static IP address. Thats why I left this solution to be last. Thank you :)
Comment: If new IP address is assined to the server by DHCP function of the router, how can you know the new IP address? If you know the MAC address of the server, you can use ARP protocol to get IP address of the router. Unfortunately most of user had never programmed code usign lower layer protocol like ARP.
Answer: One thing you could do, how about you give the server an endpoint that is unique, something like
http://<server>/isthisme

Then you just go through all IP adresses in the network and then try to reach that endpoint. The one where it returns 200 that is your server.
To get the IPs is a bit complicated, you first need to get your own IP, then go with the subnetmask over it and at the end you can just go the following way:
for (int p1 = 1; p1 < netmask[0]; p1++) {
    for (int p2 = 1; p2 < netmask[1]; p2++) {
        for (int p3 = 1; p3 < netmask[2]; p3++) {
            for (int p4 = 1; p4 < netmask[3]; p4++) {
                var ip = new IPAdress(p1, p2, p3, p4);
                if (trytoreach(ip)) {
                    return ip;
                }
            }
        }
    }
}

This is a way you could go by. It is not optimized so feel free ^^
Here is a gist with the method https://gist.github.com/DerKnerd/ff9c34087955efce0970. Just the part with the subnetmask you need to figure out. I don't guarantee that it will work though.
Comment: That sounds good, can you tell what method is that to get all local computer IPs.
Comment: @xmenW.K. check the update. I once had the problem with raspberry PIs. I used something like that to get the IPs.


the image of finite blaschke product

Question: I'd like to show that the image of finite blaschke product from the unit disc on $\mathbb{C}$ onto inself.
I'm sure that this mapping is continuous and the domain, i.e., the unit disc is compact and connected, so is the image under this mapping.
And I know that the unit circle is mapped onto itself and that there is some point in the domain which is mapped to $0$.
But I cannot fill in the gap between 0 and the unit circle.
Could you give me a little hint? I'd like to prove this with my own.
Thank you for your kind answer in advance.
Answer: Hint: Let $f$ be a finite Blascke product. If some $a\in \mathbb D$ is not in the range of $f,$ consider $\phi_a\circ f.$
Comment: Or use the fundamental theorem of algebra and show that if $B$ is a finite blaschke product of order n and $|\lambda|<1$ or $|\lambda|=1$ the equation $B(z)=\lambda$ becomes a polynomial equation of degree precisely $n$ when clearing denominators and hence it has $n$ roots counted with multiplicity; but by topological reasons, the roots when $\lambda$ is inside the disc are also inside the disc and same on the unit circle; with a little more work one can show that on the unit circle the roots are actually distinct
Comment: $\phi_a(z) = \dfrac{a-z}{1-\bar a z}.$
Comment: @Conrad Why is the surjectiveness of the mapping related to the distinctness of the roots on unit circle ?
Comment: It is not related directly of course but it is one of the more striking properties of finite blaschke products
Comment: What is $\phi_a$?
Comment: @zhw. Let me explain what I'm thinking. By assumption, the new defined function cannot assume 0. and it is a nonconstant analytic on the unit disc. Since the unit disc is compact and the new function is continuous, it has to have a minimum modulus. But on the boundary, its modulus is 1. And inside the boundary, it could assume a smaller modulus than 1. So this function has to assume its minimum modulus inside the circle. If this is so, the new function  should be a constant, which contradicts the assumption. Is it right? If not, could you point out where I failed?
Comment: Right, an analytic function that is nowhere $0$ cannot have a minimum modulus inside a connected domain unless it is constant.

the image of finite blaschke product


Is it possible to change the parent of an element in Vue?

Question:

                <call-item
                    v-for="(call, index) in callsSorted"
                    v-bind:key="call.id"
                    v-bind:call="call"
                    v-bind:sorted=true
                    v-bind:order="{order: index}"
                    v-on:update-calls="updateCalls"
                ></call-item>

Is it possible to move a one selected call-item element into an showOperation element? That is, I want to remove an element from the list and insert it into another element. Is it possible to do this using Vue?
Comment: Your html seems to be data driven, so I think you can just pull the item out of your callsSorted array
Answer: It is definitely possible - you will need two lists of elements. The first list will be rendered inside the panels window while the second list of elements will be rendered inside the shown operations container. Something like this:
<template>

        <call-item
            v-for="(call, index) in callsSorted"
            v-bind:key="call.id"
            v-bind:call="call"
            v-bind:sorted=true
            v-bind:order="{order: index}"
            v-on:update-calls="updateCalls"
        />

    <call-item
        v-for="(call, index) in operationsShown"
        v-bind:key="call.id"
        v-bind:call="call"
        v-bind:sorted=true
        v-bind:order="{order: index}"
        v-on:update-calls="updateCalls"
    />

</template>


Confidence interval on binomial effect size

Question: Suppose I have a binomial test, with 9 successes in 12 trials, expected p=1/3. In other words, in R you might do:
binom.test(9,12,p=1/3)

Now, I'm under the impression that relative risk is an appropriate effect size measure. In this case, RR=0.75/(1/3)=2.25.
First - is this actually an appropriate effect size measure?
Second - how would I put a confidence interval on this? The resources I have found for calculating RR confidence intervals (e.g., http://sphweb.bumc.bu.edu/otlt/mph-modules/bs/bs704_confidence_intervals/bs704_confidence_intervals8.html) assume that the p=1/3 came from a sample with a known n, rather than a theoretical probability.
Answer: The relative risk is $\text{RR}=p/p_0$ where $p_0=1/3$ in your example. The binomial count $X$ have distribution $\mathcal{Bin}(n,p)$ which we can write as $\mathcal{Bin}(n,p_0\cdot\text{RR})$. Then we can use a binomial regression with log link function, see Calculation of Relative Risk Confidence Interval.  That gives an estimate of the RR, and we can calculate a CI by likelihood profiling. An example with your data in R:
n <- 12
x <- 9
p0 <- 1/3

mod <- glm(cbind(x, n-x) ~ offset(log(p0)),
           family=binomial(link="log"))
 mod

Call:  glm(formula = cbind(x, n - x) ~
offset(log(p0)), family = binomial(link = "log"))

Coefficients:
(Intercept)
     0.8109

Degrees of Freedom: 0 Total (i.e. Null);  0
Residual
Null Deviance:      -6.661e-16
Residual Deviance: -6.661e-16   AIC: 4.709

exp(confint(mod))
Waiting for profiling to be done...
   2.5 %   97.5 %
1.416876 2.784264

Answer: If $\theta$ is the true probability value and $\theta_0$ is your comparative value then $RR = \theta/\theta_0$ is the corresponding true relative risk (compared to your assumed comparative value).  If you generate a confidence interval for $\theta$ you can easily get a corresponding confidence interval for $RR$ by applying this transformation.  I recommend you use the Wilson score interval for estimating the binomial proportion (see O'Neill (2021) for details).
#Compute the 95% Wilson score interval
x     <- 9;
n     <- 12;
alpha <- 0.05
CONF  <- stat.extend::CONF.prop(alpha,
             sample.prop = x/n, n = n);

#Alter the interval to refer to the relative risk
prob0   <- 1/3;
CONF_RR <- CONF/prob0;
attributes(CONF_RR) <- attributes(CONF)
attributes(CONF_RR)$parameter <-
"relative risk parameter for infinite
 population";

#View the confidence interval
CONF_RR;

        Confidence Interval (CI)

95.00% CI for relative risk parameter for
infinite population
Interval uses 12 binary data points with sample
proportion = 0.7500

[1.4030839951993, 2.73317499481784]


Sampling to validate a cluster

Question: I am trying to compute the silhouette coefficient in a clustered dataset which is 550k, but as the process is computational intensive I run out of memory and I cannot compute the silhouette coefficient.
So, I wonder if instead of validating the entire dataset, I take a sample (random or stratified) and then compute the silhouette coefficient on that sample?
Comment: In addition to Anony's excellent answer I might remark that there exists a version of Silhouette criterion which can be computed without computing the distance matrix. That is the "deviation from centroid" aka "simplified" Silhouette. If your data are continuous and clusters can reasonably have centroids (means), that version of Silhouette is a nice choice.
Answer: Yes, for a simple aggregate such as the Silhouette coefficient it is reasonable to compute it on a sample only. In many cases, it may also be fine to do the entire clustering only on such a sample (in particular if you do not know what works) rather than wasting the time to compute it on the full data.
In general there is little use in clustering huge data sets - it's expensive, and if you don't get additional knowledge compared to a sample, that was a waste of time. People tend to treat clustering as a toy exercise and scale it to huge data sets where the results don't yield any benefit...
The smart way of using it is as a hypothesis generator; and a reasonably sized sample will be enough for that. You can then hypothesize what classes of customers you have etc. and - after human analysis and verification - label your data accordingly. Clustering never was something that you could fully automate, and it never will be.
Comment: Thanks. Stupid Gboard autocorrect.
Comment: (+1) I assume you mean 'never' and not 'need' in the final line.

Sampling to validate a cluster


How to predict single instance with Logistic Regression using sci-kit learn?

Question: I'm trying to build a Logistic Regression model which can predict new instance's class.
Here what I've done:
path = 'diabetes.csv'
df = pd.read_csv(path, header = None)
print "Classifying with Logistic Regression"
values = df.values
X = values[1:,0:8]
y = values[1:,8]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.10, random_state=42)
model=LogisticRegression()
model.fit(X_train,y_train)

X_test = []
X_test.append(int(pregnancies_info))
X_test.append(int(glucose_info))
X_test.append(int(blood_press_info))
X_test.append(int(skin_thickness_info))
X_test.append(int(insulin_info))
X_test.append(float(BMI_info))
X_test.append(float(dpf_info))
X_test.append(int(age_info))
#X_test = np.array(X_test).reshape(-1, 1)
print X_test
y_pred=model.predict(X_test)
if y_pred == 0:
    Label(login_screen, text="Healthy").pack()
if y_pred == 1:
    Label(login_screen, text="Diabetes Metillus").pack()

pregnancies_entry.delete(0, END)
glucose_entry.delete(0, END)
blood_press_entry.delete(0, END)
skin_thickness_entry.delete(0, END)
insulin_entry.delete(0, END)
BMI_entry.delete(0, END)
dpf_entry.delete(0, END)
age_entry.delete(0, END)

But I got this error:

Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample.

If I uncomment this line X_test = np.array(X_test).reshape(-1, 1) this error appears:

File "/anaconda2/lib/python2.7/site-packages/sklearn/linear_model/base.py", line 305, in decision_function
      % (X.shape[1], n_features))
  ValueError: X has 1 features per sample; expecting 8
Comment: Possible duplicate of [Preprocessing in scikit learn - single sample - Depreciation warning](https://stackoverflow.com/questions/35082140/preprocessing-in-scikit-learn-single-sample-depreciation-warning)
Answer: You have to give it as
X_test = np.array(X_test).reshape(1, -1))

or you can directly do,
y_pred=model.predict([X_test])

The reason is predict function expects a 2D array with dimension (n_samples, n_features). When you have only record for which you need prediction, create a list of list and feed it! Hope it helps.
Answer: You can create a one-line data frame in a way which can make the code more readable:
sample_df = pd.DataFrame({
        "pregnancies_info": pregnancies_info,
        "glucose_info": glucose_info,
        "blood_press_info": blood_press_info,
        # etc
}, index=[1])

y_pred = model.predict(sample_df)


Video capturing Issue in ios

Question:
Possible Duplicate:
recored video using UIImagePickerController

I am new in iOS development. Now i am working on video recording app. But my app sometimes record video. And some times it closes camera Give me warning as
<code>UIImagePickerController: ignoring request to stop video capture; camera is not currently capturing video.
</code>
Comment: Refer [**this Link**](http://www.raywenderlich.com/13418/how-to-play-record-edit-videos-in-ios) , I think may be helped you.
Happy Coding
Answer: I am capturing Video and store in document directory like this way:-
<code>-(IBAction)cameraLibraryButtonClick:(id)sender{
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        UIImagePickerController *videoRecorder = [[UIImagePickerController alloc]init];
        videoRecorder.delegate = self;
        NSArray *sourceTypes = [UIImagePickerController availableMediaTypesForSourceType:videoRecorder.sourceType];
        NSLog(@"Available types for source as camera = %@", sourceTypes);
        if (![sourceTypes containsObject:(NSString*)kUTTypeMovie] ) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil
                                                            message:@"Device Not Supported for video Recording."                                                                       delegate:self
                                                  cancelButtonTitle:@"Yes"
                                                  otherButtonTitles:@"No",nil];
            [alert show];
            [alert release];
            return;
        }
        videoRecorder.sourceType = UIImagePickerControllerSourceTypeCamera;
        videoRecorder.mediaTypes = [NSArray arrayWithObject:(NSString*)kUTTypeMovie];
        videoRecorder.videoQuality = UIImagePickerControllerQualityTypeLow;
        videoRecorder.videoMaximumDuration = 120;

        self.imagePicker = videoRecorder;
        [videoRecorder release];
        [self presentModalViewController:self.imagePicker animated:YES];
        newMedia = YES;
    }
    else {
        [self displaysorceError];
    }

}

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {

        NSURL *videoURL = [info objectForKey:UIImagePickerControllerMediaURL];
        NSData *videoData = [NSData dataWithContentsOfURL:videoURL];
        //self.fileManager = [NSFileManager defaultManager];
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory , NSUserDomainMask, YES);

        NSString *ZipLibrary = [paths objectAtIndex:0];

    NSString *FileFullPath = [ZipLibrary stringByAppendingPathComponent:@"%@.mp4"];

    NSLog(@"Ziplinrnr oadfjaidfjidfjidjfid %@",FileFullPath);
        [videoData writeToFile:FileFullPath atomically:YES];

    [self dismissModalViewControllerAnimated:YES];

}

-(void)displaysorceError{
    UIAlertView *alt = [[UIAlertView alloc]
                        initWithTitle:@"Error"
                        message:@"Camera Image Sorce Not Available"
                        delegate:nil cancelButtonTitle:@"OK"
                        otherButtonTitles:nil];
    [alt show];
    [alt release];
}
</code>

Video capturing Issue in ios


Does $\int^{\infty}_0 \frac{\cos x}{1+x}\,\mathrm dx$ converge?

Question: The integral
$$\int^{\infty}_0 \frac{\cos x}{1+x}\,\mathrm dx$$
is shown to be equal to
$$\int^{\infty}_0 \frac{\sin x}{{(1+x)}^2}\,\mathrm dx$$
through integration by parts. The latter one converges absolutely (i.e the integral still exists if you take the absolute value of the function) as the function is dominated by the function $1/{(1+x)}^2$. But the first integral does not converge absolutely as stated in Rudin "Principles of Mathematical Analysis" ch 6 exercise 9.
Why is it so?
Comment: Someone edit this question.
Comment: If $A$ and $B$ is a sum or an integral then just knowing that $A = B$ does not tell you anything about the internal properties of $A$ and $B$ (like if they both converge absolutely or if both have just positive terms or if both have infinitely many non-zero terms etc. etc. etc.). Here is a similar example with series: $\sum_{n=1}^\infty \frac{(-1)^{n-1}}{n} = \frac{6\log(2)}{\pi^2}\sum_{n=1}^\infty \frac{1}{n^2}$. The series on the right hand side converges absolutely while the left hand side does not.
Comment: @Winther Pretty example.
Answer: By integrating by parts,
$$
\int_0^M \frac{\cos x}{x+1}\:dx=\frac{\sin M}{M+1}+\int_0^M \frac{\sin x}{(x+1)^2}\:dx, \quad M\ge0,
$$ and letting $M \to \infty$, one has
$$
\left|\int_0^\infty \frac{\cos x}{x+1}\:dx\right|=\left|\int_0^\infty \frac{\sin x}{(x+1)^2}\:dx\right|<\int_0^\infty \frac1{(x+1)^2}\:dx<\infty
$$ the given integral is then convergent, there is no contradiction with
$$
\int_0^M \left|\frac{\cos x}{x+1}\right|\:dx \to \infty
$$ as $M \to \infty$, since we have
$$
 \left|\int_0^M \frac{\cos x}{x+1}\:dx\right| <\int_0^M \left|\frac{\cos x}{x+1}\right|\:dx.
$$

Remark. One may observe that
  $$
\int_{(2n-1)\frac{\pi}2}^{(2n+1)\frac{\pi}2} \left|\cos x\right|\:dx=2,\qquad n=1,2,\cdots,
$$ giving
  $$\int_{(2n-1)\large\frac{\pi}2}^{(2n+1)\large\frac{\pi}2}  \left|\frac{\cos x}{x+1}\right|\:dx \ge \frac1{(2n+1)\large\frac{\pi}2+1}\int_{(2n-1)\large\frac{\pi}2}^{(2n+1)\frac{\pi}2}  \left| \cos x \right| dx \ge \frac{2}{(n+1)\pi}$$
  and by summing
  $$\int_{\large \frac{\pi}2}^{(2N+1)\large \frac{\pi}2}  \left|\frac{\cos x}{x+1}\right|\:dx \geq \frac{2}{\pi}\sum_{n = 2}^{N+1} \frac{1}{n}\qquad N\ge1,$$
  which shows that
  $$\int_0^\infty \left|\frac{\cos x}{x+1}\right|dx$$
  is divergent.
Comment: Thanks a lot, this answers my question (sorry for late feed back due to my vacation)
Answer: The first one does converge, actually. The catch is that if an integral does not converge absolutely, it doesn't mean it is not convergent.
The integration by parts technique is one way to show that it actually is convergent! To understand intuitively why it is so, it is helpful to look at the graph of $f(x) = (\cos x){(1+x)}^{-1}$:

As you can see, the function is alternating between positive and negative values. As the Riemann integral takes into account the sign of the function, all these areas will cancel out each other. In this case, the result is approximately $0.343378$, and that's because the area between the function and the $x$ axis is progressively smaller and smaller.
Conversely, being $|f(x)|$ non-negative, if you integrate it you will be summing all those areas, which are all positive, and the sum does not converge because its general term is asymptotically equivalent to $1/x$, whose sum diverges.
In general, it can be proved that the Riemann integral has the property
$$\left | \int_a^b f(x)\,\mathrm dx \right | \leq \int_a^b \left | f(x) \right |\,\mathrm dx$$
and it can be extended to improper integrals as well.


Wyse ThinOS MirrorFileServer Setting (FW 8.3 - 8.5)

Question: I have a support ticket open with Dell, at the moment they're saying they're unable to reproduce the issue. I'm hoping someone else with a Wyse environment can test and provide some feedback.
It appears to me that the MirrorFileServer parameter has been broken since 8.3_012. Starting with 8.3_012 the MirrorFileServer parameter appears to force the thin client to run off the cached wnos.ini file, changes made on the FTP server are therefore ignored.
This can be tested as shown.

Perform Factory Reset
Set TCP Timeout to 2 x 30
Set Static IP, Subnet Mask, and Gateway
Set FTP Server
Restart thin client
Check terminal name (should be TC001)
Change terminal name on FTP Server
Restart thin client
Check terminal name (should be TC002)

wnos.ini
MirrorFileServer=yes

Terminalname=TC001
;Terminalname=TC002
DNSIPVersion=ipv4 DNSServer=188.8.131.52;22.214.171.124 DNSDomain=fqdn
SignOn=No

I have tested 8.3_012, 8.3_014, 8.3_109, 8.4_105, 8.4_112, 8.5_009, and 8.5_012. None of them work as expected, after the 2nd restart the terminal name is still TC001. 8.2 and older do work as expected, the wnos.ini file is downloaded from the FTP server and the terminal name is changed to TC002.
Answer: Starting with 8.3 I have found I need to add the following to my configuration.
wnos.ini
WDMService=No Discover=No
CCMEnable=No Discover=No

My assumption is in a FTP only environment, WDM and CCM are taking too long to timeout and are interrupting the FTP download.


How to word the results if a chi-square test of independence is significant, but no single post-hoc test is?

Question: I ran a chi-square test of independence on a 2-dimensional cross table, which resulted in a significant p-value.
I then ran post-hoc tests for all pairs of populations and adjusting by a bonferroni correction (I used the function chisq.post.hoc from the fifer package in R, if that matters).
There, no single pair was significant.
I understand that this can happen and is not out of the ordinary, but it's hard to put a justification for this result in writing. How would you word this situation correctly? I am thinking of something to the likes of:

The significant p-value of the chi-squared test on the whole cross table suggests a dependency between the variables A and B. However, no specific group was found in the subsequent post-hoc tests, meaning that the overall dependency could not be linked to a specific pair of populations.

To me, this sounds correct but not helpful. Is there a better way to describe what the significant overall-test means if no single pair of population is found in the post-hoc tests?
Answer: Taking a stab:

A chi-squared test works by assuming that variables A and B are
  independent and then looking for evidence that contradicts that
  assumption. The stronger the overall evidence against independence,
  the lower the p-value will be. In this case, the low p-value from the
  test on the whole table suggests significant evidence for a dependency
  between variables A and B. A follow-up post hoc analysis found that
  the overall conclusion results from the accumulation of small amounts of
  evidence from many cells in the table rather than from large
  contributions of evidence from any particular cells.


Create a view field that contain the sum of specific fields for a specific user

Question: I created a content type (Donation) that contains 3 fields:

a Donor Name field (user reference).
a date field (for the donation month).
the amount of the donation.

I am trying to create a view that returns a table with 2 columns:

one for Donor Name
one for the total/sum of all donation for that Donor.

My question: How can I achieve the second column (the sum of donations for the specific Donor/user) using views?
Answer:
Try View Aggregation setting:

Goto Advanced tab, scroll down below and set "Use aggregation" to
'Yes'.
Filter Your View with Name field (user reference).
Now there must be "Aggregation settings" inline with your field
"the amount of the donation"
Goto "Aggregation settings" for "the amount of the donation"
field and select 'Aggregation type' to 'Sum'.

Thats it, you are good to go now.


Como faço para mostrar uma imagem de acordo com determinado Número sendo que este número é pelo random no python?

Question: import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
import cv2

def showfig(image, ucmap):
    imgplot=plt.imshow(image, ucmap)
img0 = cv2.imread("zero.jpg",0)
img1 = cv2.imread("um.jpg",0)

from random import randint  #gerar número aleatório, ou seja, randomizar número inteiro
from time import sleep

computador = randint(0,9) #Faz o computador pensar
print('-=-' * 20) #Para definição de começo da pergunta do computador
print('Vou pensar em um número entre 0 e 9. Tente adivinhar...')
print('-=-' * 20) #Para definição de começo da pergunta do computador
jogador = int(input('Em que número eu pensei?')) #jogador tenta adivinhar
print('Processando...')
sleep(3)

jogador = 0
computador = 0

if jogador == computador:

    plt.figure(figsize=(5,5))
    plt.title('Imagem de Entrada')
    showfig(img0, "gray")
    print('Parabéns: você ganhou!')

else:
    print('Ganhei: Eu pensei no número {} e não {}!'.format(computador, jogador))

jogador = 1
computador = 1

if jogador == computador:

    plt.figure(figsize=(5,5))
    plt.title('Imagem de Entrada')
    showfig(img1, "gray")
    print('Parabéns: você ganhou!')

else:
    print('Ganhei: Eu pensei no número {} e não {}!'.format(computador, jogador))

Comment: Olá. Identifiquei e já foi corrigido, obrigada!
Comment: Oi Julia, pode ser mais especifica? Você já tentou algo? Está tendo algum código de erro como retorno? Acho que pode ser interessante também mostrar como está sua pasta de arquivos, para saber se o caminho que está puxando a imagem está correto.
Answer: Ao invés de usar uma variável para cada imagem, use uma estrutura indexável, como listas ou dicionários. Para números a partir do zero, uma lista serviria, mas eu prefiro usar dicionários, para o caso de precisar de mais imagens que não são números depois:
imgs = {
    0: cv2.imread("zero.jpg", 0),
    1: cv2.imread("um.jpg", 0),
}

Aí depois na hora de mostrar a imagem, é só usar esse dicionário para referenciar a imagem certa de acordo com o número sorteado:
computador = randint(0, 9)
...
showfig(imgs[computador], "gray")

Comment: , o primeiro método eu usei, o segundo eu usei parecido, mas deu certo. Obrigada!
Comment: @JuliaOliveira Que bom que conseguiu! Se a minha resposta resolveu, considere marcá-la como aceita, para fechar a pergunta. Se quiser compartilhar o que você fez de diferente, posso editar a resposta para que fique mais completa.


javaHG with hg.exe not set as an environmental variable

Question: I am using javaHg on our company's web-application.
I want to avoid installing mercurial when I setup the new release on our server. Do I need to go into details as to why management doesn't want "external" applications installed on the server?
I have a windows portable mercurial in a sub-directory. Is it possible to "point" javaHg to that hg.exe, rather than setting the directory path as an environmental viariable? There must be no tweaking and setups when employing the new release.
Answer: Yes, you don't need to set PATH for this. There is a RepositoryConfiguration class that you should use, see the setHgBin method. You pass the configuration object to the Repository object when you create it and it will then use the configured Mercurial binary to start the command server.


How get subscribe to user flag on a node

Question:
I have a node for example news
I have Message module installed
I've enabled the flag subscribe to user

I want people to be able to subscriber to
a user. To get updates on thier latest post.

I want to add the subscriber user flag to the node template for

This is what flag module suggests to do
Placing a flag link on a page
<code>$account = menu_get_object('user');
print flag_create_link('fools', $account->uid);
</code>
How would I add this to a node?
Answer: You could create a block with a php filter or create a custom template for that node. You can also alter that node from from template.php
http://www.webomelette.com/altering-node-content-it%E2%80%99s-rendered-page-drupal-7
Comment: Welcome to Drupal Answers! Whilst this may theoretically answer the question, [it would be preferable](http://meta.stackoverflow.com/q/8259) to include the essential parts of the answer here, and provide the link for reference.


Bass clef changed to treble clef in the middle of the sheet music

Question: The bass clef changed to treble clef in the middle of the music sheet. Do both hands play above the middle c?
Comment: No, that looks like it's about voice. This is about a clef change.
Comment: The point is this: Usually, a piano grand staff has the treble clef on top and the bass clef on bottom, and the pitches are absolute. However, piano notation implies that the upper clef is the part played by the right hand, while the lower clef is the part played by the left hand. So if the range of the notes in either hand goes much higher or much lower, it can be notated with two staves with a treble clef on each, or two staves with a bass clef on each, etc.
Comment: possible duplicate of [Piano music with two treble clefs, and notes between staves](http://music.stackexchange.com/questions/11463/piano-music-with-two-treble-clefs-and-notes-between-staves)
Answer: Yes, you play with both hands above the middle C. This is quite common for instruments that are written in both clefs, not only in piano.
This will help you, because if the bass clef goes really high, it is really hard to read all those extra lines. So, since you are basically in the treble clef, the music usually shifts clefs.
Answer: It is pretty common to change clefs in the middle of a piece. There are 4 fairly common clefs (treble, alto, tenor, bass), and which one a piece is written in really depends on where the notes are on the clef. Each clef puts middle C in a different place on the staff.
If the left hand is centered above middle C, it makes more sense to use a treble clef than a bass clef. Read it just like you would a normal treble clef. If it's a short passage (just a few notes) you may be crossing hands; in that case, the left hand part would be written higher than the right hand part. Otherwise, you'll probably find the right hand high on the treble clef or even 8va (octave higher).
You may also find the right hand in the bass clef, though that is not as common. The left hand moving into treble range is pretty common. The other clef doesn't change at all.
Comment: Two treble clefs or two bass clefs is very common in quatre mains piano pieces.


Form positioning when using TStyleManager in Delphi XE7 application

Question: I'm trying to make a Delphi application form remember it's position and recall it the next time the application is started:
procedure TForm1.LoadSettings;
var
  xml : IXMLDocument;
  node : IXMLNode;
begin
  [ ... initializing XML ...]

  // Loading theme
  if node.HasAttribute('Theme') then TStyleManager.SetStyle(node.Attributes['Theme']);

  // Loading position & size
  if node.HasAttribute('PosTop') then self.Top := StrToInt(node.Attributes['PosTop']);
  if node.HasAttribute('PosLeft') then self.Left := StrToInt(node.Attributes['PosLeft']);
  if node.HasAttribute('PosWidth') then self.Width := StrToInt(node.Attributes['PosWidth']);
  if node.HasAttribute('PosHeight') then self.Height := StrToInt(node.Attributes['PosHeight']);

  [ ... some other stuff ... ]
end;

Everything works fine when the "Theme" is set to default "Windows" theme. With any theme, the form appears at it's default position set up by Windows, close to the upper left display corner, no matter where the form was located before.
Any ideas about what may be the cause and how to fix that?
Thanks in advance!
Comment: We can't tell when you call this function. Can't we have a [mcve]? We don't need any xml. That's irrelevant. Hard code the coords.
Answer: If you want to properly restore form's position you have to set it initial Position property to poDesigned in form designer.
Default Position property is poDefaultPosOnly. That means your form position will be determined automatically by Windows. Depending at which point you trigger your own form positioning during the form creating process and depending on other code you may either successfully change forms position or not.
However, if the Position property is poDesigned all positioning will be left to Delphi code itself and you will be able to properly apply your setting.
Why?
Because if you use any code that will trigger form's window recreation, that code will again try to set your form's position to Windows default one and can interfere with your positioning process.
Calling TStyleManager.SetStyle does exactly that.

Simple test case for above would be creating new VCL project, adding some style to it and put following code in FormCreate event
procedure TForm1.FormCreate(Sender: TObject);
var Styled: boolean;
begin
  Styled := true;

  if Styled then TStyleManager.SetStyle('Silver');

  Top := 200;
  Left := 300;
  Width := 800;
  Height := 600;
end;

If Styled is false setting position works, if it is true it doesn't.
Comment: I knew it must be something that simple. Works like charm, many thanks!!!
Comment: If this answer solved your problem then please accept it. [How does accepting an answer work](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work)


How to analyze residuals of Poisson log-linear model?

Question: I have bird count data and use classical poisson loglinear model, i.e. we have counts obs(i,j) - observed count for site i and year j, and the model is:
ln(model(i,j)) = site_effect(i) + year_effect(j)

where model(i,j) is expected count for site i and year j, and it is assumed that counts are poisson distributed, i.e. obs(i,j) ~ Poiss(lambda = model(i,j)). Serial correlation and overdispersion was taken into account.
Now I need to analyse residuals of this model as a dependent variable in another regression with some explaining variables (Please don't tell me I should put these variables in the above model - to be brief, there are some technical issues behind that.)
The problem now is:
1) how to define the residuals
2) what is their distribution
3) which regression use to explain them.
Possible solutions of residual definition and analysis:
A) obs/model with another poisson loglinear regression
B) log((obs+1)/model), normal distribution -> normal linear regression
C) log((obs+1)/(model+1)), normal distribution -> normal linear regression
D) ... any other??
Ad Solution A: use obs/model,i.e. divide observed value by the expected value from model (for each i,j). But what is their distribution? I would say Poisson, but the numbers are not whole numbers! So I multiplied by 20 and rounded to whole numbers to be able to fit poisson. Is this a good idea, or is it nonsense? Or how should I fit poisson to real number continuous random variable? Here is the distribution:

Note that the Poisson distribution doesn't fit (used goodfit() test in R).
So there is a problem that obs/model are real numbers - not whole natural, as the poisson distribution. Moreover, I'd like to avoid another poisson loglinear regression if possible, as I'm quite infamiliar with how to analyze the explaining variables, the explained/unexplained variability etc. as in the normal regression.
Ad Solution B/C: use something like log((obs+1)/model) or log((obs+1)/(model+1)). There is a problem of zero observed counts (there are no zero model counts), so I can't just use log(obs/model) as I would like to. How to solve this problem?? It is better to use solution B or C?
Here are the distributions.

Note that also in this case, the normal distributions don't fit. Nothing really fits, but this is quite normal with real count data. :-)
So, summary:
- which solution you think fits best?
- how to overcome the problems each solution has?
- is it a big mistake to use B/C and go for normal linear regression, if I'd like to avoid the poisson? Should I use B or C?
Thanks a lot!
Comment: I'm not sure the first parenthetical remark, which I read as "don't tell me to do X because I won't", is helping here.  Perhaps reconsider?
Answer: This sounds like a hierarchical model (or multi-level model), but not explained in those terms.  Firstly, note that a Poisson "residual" is not really the same thing as you would find in the case of a normal error term.  The reason is that a poisson random variable cannot be separated out easily into a "systematic part" and "random part".  One standard way is to use the "deviance residuals", defined by:
$$d_{i}=sgn(Y_{i}-\hat{Y}_{i})\sqrt{2Y_{i}\log\left(\frac{Y_{i}}{\hat{Y}_{i}}\right)-2(Y_{i}-\hat{Y}_{i})}$$
These quantities are analogues to the residuals in OLS regression, and can be easily obtained from residuals(glm.object, "deviance") function in R.  You can show that the sum of squared deviance residuals has an approximate chi-square distribution, but I wouldn't know how to figure out the exact distribution.
An alternative is to add further structure to the Poisson GLM by introducing "random effects" into the model equation.  For the Poisson model with canoncial log-link function we have $\log(\mu_i)=x_{i}^{T}\beta$.  In your case $x_{i}^{T}$ is a row of a "design matrix" (all zeros and ones) which picks out the relevant beta coefficient for your site effect and year effect.  This addition of random effects basically says that the above relationship only holds "on the average" rather than deterministically (can think of this as a "softer" link function). So that we actually have $E\left[\log(\mu_i)\right]=x_{i}^{T}\beta$.  The "actual link" is given by:
$$\log(\mu_i)=x_{i}^{T}\beta+z_{i}^{T}u_{i}$$
Where $z_{i}^{T}$ is a known set of covariates, and $u_i$ is a random effect for the $i$th observation with $E[u_{i}]=0$.  Now if you were to set $z_{i}^{T}=1$ then you have a good definition of the residuals, given by the random effects $u_i$.  All that is needed to do now is to assign a probability distribution to the random effects and do the maths/coding work to either give point estimates or posterior probability distributions for $u_{i}$ to use in your subsequent model.  These are often called Generalised linear mixed models, and $u_i$ is often chosen to have a normal distribution.
The nlme package should be able to do this kind of modelling
Answer: I'm not quite sure what you're trying to achieve, but another option is to do another Poisson regression, using the linear predictor of the first model (that is, the log of the predicted value) in the offset of the second model.
However, without knowing more about why you want to do all this, it is difficult to recommend a course of action.
Comment: Thank you very much, Simon, the first paragraph explains what I needed to know... +1
Answer: For a poisson process, let:
O = Observed count
E = Expected count
Then:
(1) u1 = O^.5 - E^.5 is ND(0,.5)
(2) u2 = (O-E)/E^.5 is ND (0,1)
and even better:
(3) u1 + .5*u2 is ND(0,1)
Comment: Consider formatting you answer using _mathJax_, it's really hard to read as it stands now.


Neural Net for multivariate regression

Question: I need to build a model (M) that converts a 10 dimensional space of inputs (A) into a 20 dimensional space of outputs B.
Both the inputs and outputs are analog, so this is not a classification problem but rather a regression one.
A * M = B
In order to allow some bias I included a last row of 1s in A:
$A = \begin{bmatrix}
       A & 1
     \end{bmatrix}$
My first approach was to just to left multiply by the pseudoInverse of A to obtain M:
$M=A^{-1}B$
However this is not getting good results.
Analyzing what I did, I think it's equivalent to using a one layer neural network with bias but without activation function and without regularization.
Now, to improve my model I want to make it more complex using neural networks, but some questions arise.
I find a lot of examples in internet using neural networks for classification, where each output neuron represents a class and it's output is associated to the probability of the input belonging to that class.
However my problem has nothing to do with classification (think about it as an operator that takes some location in a 10 dimensional space and "moves" it to a new location in a higher dimensional space).
Is there some specific neural network topology (type of activation function, regularization, training method) that is specific for this problem? How would you approach such a problem?
Thanks a lot.
Answer: Before giving up on linear models, you could also try regularized linear models. For example, you can penalize the $\ell_2$ norm of the weights (ridge regression), which expresses a preference for smaller weights. You can also penalize the $\ell_1$ norm (lasso), which induces sparse solutions (you can think of this as a kind of automatic feature selection). There's also the elastic net, which is a combination of $\ell_1$ and $\ell_2$ penalties. These techniques are very popular, and can improve generalization performance when appropriately matched to the problem. They can also make it possible to solve problems where the number of input variables exceeds the number of data points. You'll often see these techniques discussed in the context of regression problems with a single scalar output. But, you can also apply them in the case of vector-valued outputs. If searching for sparse solutions, you'd have to decide whether or not the weights for all outputs should share the same sparsity structure (i.e. should all columns of $M$ have zeros in the same rows as each other?).
As for neural nets, you're correct that your model is equivalent to a shallow network with linear activation functions. Many people use neural nets for regression, and producing vector-valued outputs is no problem. You'll want a feedforward network. The input layer should contain 10 units, and the output layer should contain 20 units. Because you're solving a regression problem, the output layer should use linear activation functions, which can represent any real number (unlike most nonlinear activation functions, which are either squashed or clipped to a specific range). For regression, you should also typically use the squared error as the loss function. If you want the network to implement a nonlinear function, you'll need at least one hidden layer with nonlinear activation functions (e.g. sigmoid, ReLU, etc.). Typically all units in the network would have a bias term. You'll probably want to pre-process your inputs by at least centering and standardizing them, and possibly performing PCA. Other than these recommendations, the world of neural nets is wide open, and the proper choices depend heavily on your problem (the number, size, and activation functions of hidden layers; initialization procedures; optimization/learning rules; regularization; etc.). The upside of this is that neural nets are very powerful. The downside is that you may have to spend a considerable amount of time exploring different choices.
You could also consider other nonlinear regression methods. For example, many standard techniques like k nearest neighbors, random forests, boosted decision trees, etc. could produce vector-valued outputs. These methods require fewer choices on your part than neural nets.
Comment: The goal is to predict the output as a function of the input. Standardizing/whitening is an invertible transformation, so you're not losing any information. Normalizing the input can be essential for getting good performance out of some learning algorithms. For example, it can strongly affect how gradient-based training methods update the parameters, which matters a lot for neural nets. See Lecun et al. (1998). Efficient BackProp. and here:http://stats.stackexchange.com/questions/41704/how-and-why-do-normalization-and-feature-scaling-work?newreg=cb1ec1dda52e45b3be7d1688a57d07ad and
Comment: The problem that I see is that if I normalize the input I'll loose some valuable information between the inputs. The inputs are not independent, but correlated data, so some valuable info might be hidden in the relations between inputs. This relations will be lost if I normalize.

Neural Net for multivariate regression


Why does minimizing absolute value and squares of residuals in a regression give different answers?

Question: We are minimizing either the $1$ norm of the residuals, least absolute value, or the $2$ norm, least squares.
Least absolute value:
$$\min_\beta||y - x \beta||_1$$
Least squares:
$$\min_\beta||y - x \beta||_2$$
But by the equivalence of norms, they only differ by some constants $c$, $C$:
$$c||y - x \beta||_1 \le ||y - x \beta||_2 \le C||y - x \beta||_1$$
If they are only different by a constant, why then is the minimizer different?
Comment: It can be helpful to work through the simplest example you can construct.  One of the simplest I can find is for the $(x,y)$ data $(1,0), (1,1), (1,5).$ You have to minimize $|\beta-0|^p + |\beta-1|^p + |\beta-5|^p$ for the cases $p=1,2.$ For each $p,$ plotting this expression as a function of $\beta$ can also provide insight.
Comment: "differ by a constant" $\ne$ "difference is less than a constant"
Comment: So, in your saying, minimizing wrt max. norm should also give the same solution. Does it?
Answer: They aren't different by a constant. If that were so, you would be right. But what the formula you post says is that they are different by at least some constant and at most some other constant.  Further, the norms are the single numbers that are the total for all the values. But the individual contributions of each point can vary.
For the least squares, the contribution of extreme points is higher than for absolute value.
Comment: Consider two points, one with an absolute error of 5.0 and one with an absolute error of 1.0. When squared, these values become 25.0 and 1.0 which is why outliers can dominate a standard sum-of-squared-error regression - their *squared* errors become very large.
Answer: Let $x$ be scalar and equal to one to consider the most simple example. Then consider minimizing
$$\min_\beta \mathbb E[(Y-\beta)^2]$$
The first order condition:
$$0 = -2 \int_{-\infty}^\infty (Y - \beta)dF(y) = -2(\mathbb E[Y] - \beta)$$
implying that the solution for minimizing $\beta$ is $\beta^* = \mathbb E[Y]$.
Consider then the problem $$\min_\beta \mathbb E[\lvert Y - \beta\lvert]$$
again differentiating (absolute norm is convex so we can use subgradients from convexity theory to generalize the differential operator) to get the first order condition
$$0 = \int_{-\infty}^\infty \delta(Y-\beta) dF(y)$$
where $\delta(.)$ is the subgradient of the absolute norm and hence $\delta(Y-\beta) = - 1$ for $Y<\beta$ and $\delta(Y-\beta) =  1$ when $Y>0$. Therefore
$$0 = \int_{-\infty}^\infty \delta(Y-\beta) dF(y) = - \int_{-\infty}^\beta dF(y) + \int_{\beta}^\infty dF(y)$$
which is equivalent to
$$0 =  - F(\beta)+  (1-F(\beta))$$
implying that
$$F(\beta) = \frac{1}{2}$$ hence the solution for $\beta$ must be $\beta^* = F^{-1}(1/2)$ which is the median of the distribution $F$.
Using sample moments instead of expectations the solution become respectively the sample mean and the sample median. And in case of covariates $x$ it result in standard regression in the case of squared errors and median regression in case of the absolute norm.


JPA many-to-one mapping for potentially null foreign key

Question: Problem
When running a query on an entity and an attribute of a many-to-one mapped entity, that may or may not be null, no records are returned on records where the mapped many-to-one is null, even if the main entity may match the search criteria. This behavior seems to be acting like an INNER JOIN instead of an OUTER JOIN.
Everything works fine for CRUD operations, the only problem is when the query is run.
Expected
I expect this to behave like a LEFT OUTER JOIN, and return records that match even if the mapped entity is null.
Expecting a query similar to this to return both property records below, when only preperty #10 is returned.
SELECT Property.* FROM Property
LEFT JOIN Resident ON Resident.id = Property.Resident_id
WHERE Property.Address LIKE "%test%" OR Resident.Name LIKE "%test%"

Environment

MySQL v8
Eclipselink v2.7.7

Tables
Property

id
Address
Resident_id

10
123 Test Dr.
20

11
456 Test St.
null

Resident

id
Name

10
John Doe

11
James Williams

Entities
Property
@Entity
@Table(name = "Property")
public class Property
{
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @Column(name = "Resident_id")
    private Integer residentId;

    @Column(name = "Address")
    private String address;

    @ManyToOne(optional = true, fetch = FetchType.LAZY)
    @JoinColumn(name = "Resident_id", referencedColumnName = "id", updatable = false, insertable = false, nullable = true)
    private Resident resident;

Resident
@Entity
@Table(name = "Resident")
public class Resident
{
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @Column(name = "Name")
    private String name;

Query
public List<Property> search(String str)
{
    List<Property> list = new ArrayList<>();

    if(str == null || str.isEmpty())
        return list;

    try
    {

        String sql = "SELECT x FROM Property x WHERE " +
                " x.address LIKE :str OR x.resident.name LIKE :str" +
                " ORDER BY x.address";

        Query q = this.getEntityManager().createQuery(sql);

        q.setParameter("str", "%"+str+"%");

        list.addAll(q.getResultList());

    }
    catch(Exception e)
    {
        e.printStackTrace();
    }

    return list;
}

Comment: Using '.' path expressions is defined as an inner join in a JPQL query; you must specify an outer join if that is what you want.
Answer: JPQL requires providers to treat '.' path expressions as inner joins, so calling x.resident.name will exclude null residents from the selection.
What you want is more along the lines of
String JPQL = "SELECT x FROM Property x left join x.resident resident " +
                "WHERE x.address LIKE :str OR resident.name LIKE :str" +
                " ORDER BY x.address";

Comment: Thank you for the answer! Do you know of anyway to override this behavior?
Comment: No, it is part of the specification. EclipseLink's native expression framework allowed specifying 'get' or 'getAllowingNull', but that isn't done in JPQL or Criteria api; both JPA query mechanisms only allow specifying the joinType via explicit joins.


Why is the average of sum of cost function used to update weight values in neural network?

Question: I have a question about neural network.
I was reading this online book and stuck on the part of description for the way of updating weights. In the book they update weights by calculating the average of the sum of cost value but why do they have to use the average? How did they come up the idea to use the average?
I find that reasonable for some reason but because I feel like the weight values go down for some reason but I'm not 100% sure why they chose the average.
Answer: Under some standard assumptions (training data iid etc) mean is an unbiased estimator of expected value of error.
You could also equivalently take a sum of the errors for your training data.  Mean is more useful than that, because if you took the sum on batches of different size, the scale would be different.


Is a lift of a topological embedding still an embedding?

Question: Let $p\colon E\to X$ be a covering map and $f\colon Z\to X$ a topological embedding. Suppose $F\colon Z\to E$ is a lift of $f$. Is $F$ still an embedding? What if I assume that $Z$ is connected and locally connected?
It seems that this is a trivial question. Somehow, I just couldn't answer it. Any help?
Answer: Let $g\colon f(Z) \to Z$ denote the inverse of $f$. By definition of an embedding, $g$ is continuous. Now
$$g \circ p \colon F(Z) \to Z$$
is clearly a continuous map, and $g \circ p$ is the inverse of $F$. Hence $F$ is an embedding.
Comment: Thank you so much! I've never thought that this could be this easy!