If $u_i$ are affinely independent, are they also linearly independent?

Question: I am wondering about affinely independent and just linearly independent. On Wikipedia it is explained that $u_i$ are affinely independent if $u_1 - u_0, ...,u_k -u_0$ are linearly independent. It is clear that if $u_i$ are linearly independent then $u_1 - u_0, ...,u_k -u_0$ are linearly independent. Is the other implication not also true? Then what is the difference between the two definitions?
Comment: **affinely** is for points whereas **linearly** is for vectors.
Comment: What if $u_0$ itself is a linear combination of $u_i$'s? Then certainly, $\{u_i-u_0\}$ are not linearly independent.
Comment: @xavierm02 Is the point/vector distinction that important? Also, how do you think about vectors? Do you think of them as just (equivalence class of) arrows?
Answer: The reverse implication is not true, consider the following three vectors in $\mathbb{R}^3$: $u_0=e_1, u_1=2e_1$ and $u_2=e_1+e_2$. The three vectors are affinely independent but not linearly independent.
The best way to understand the difference is from the picture on the wikipedia page. Think of $u_0$ as the "base vertex"and all the other $u_i$ as the positions of the other vertices. $u_i-u_0$ is then the position vector of all the other vertices relative to the base vertex, and we need these to be linearly independent (so that $u_0,\dots, u_k$ are affinely independent) so that we don't end up with three collinear vertices which would mess up our idea of what a simplex should be.
It should also be noted that the point $u_0$ is not special in the definition of affine indepenence, but in fact if $u_0,\dots,u_k$ are affinely independent then for anyfor any $j$, $u_0-u_j,\dots,u_k-u_j$ are all linearly independent. Check out this wikipedia page:
http://en.wikipedia.org/wiki/Affine_space#Affine_combinations_and_affine_dependence
Comment: The thing is, those two *are* equivalent, so long as $u_i$ are in a vector space. In an abstract affine space, $u_i-u_0$ doesn't even make sense.
Comment: @tomasz I'm a little confused, which two are equivalent?
Comment: Linear independence of $u_1-u_0,\ldots,u_n-u_0$ and affine independence of $u_0,u_1,\ldots,u_n$.
Comment: @tomasz I see, good point, I'll clarify the answer, thanks!
(In fact, I just deleted the edit, I misinterpreted the "which means" part of the wiki article and as such the edit was unnecessary.)
Comment: @TomOldfield If we only have 2 vectors, then are these two vectors affine independent by definition?


Conexão JAVA com BANCO

Question: Não estou conseguindo conectar o java com banco, pois aparece um erro como na imagem,

Alguém pode me ajudar?
Comment: Você configurou seu MySQL para utilizar a porta 3307? Pergunto, pois, a porta padrão é a 3306.
E quanto ao driver... Dê preferência para "com.mysql.jdbc.Driver". O driver que você está usando, apesar de compatível, era utilizado antes do projeto (o driver, no caso) ser doado para o MySQL.
Comment: Coloque o código não um print dele, assim ficará mais fácil de testar.
Comment: O servidor de banco está ativo? coloque o código fonte como texto e não como imagem assim outras pessoas tbm podem ajudar.
Comment: Sim!, o normal é 3306, estava testando 3307 e nehuma funciona, adicionei o drive do propio Netbeans o drive carrega normal , a conexão que não é feita, já instalei o xampp  novante e continua a msm coisa!
Comment: Poste o código, assim você abrange quem usa leitor de tela.
Answer: Somente wrapped exception retornada não ajuda, o ideal seria termos todo o stack trace e obter a root cause.
Porem vou indicar algumas possibilidades, que podem ajudar a quem obter uma Communications Link Failure:
Inicialmente encontre o arquivo de configurações do MySQL:

Linux   = /etc/mysql/my.cnf
Windows = C:\MinhaLocalizacaoDoRDBMS\mysql\bin\my.ini

- Porta correta?
A 3306 é a porta padrão do MySQL, você está usando a 3307.
Um netstat pode ajudar na investigação:

win = C:>netstat -an | findstr 3306
linux = $ netstat -ln | grep 3306

- Loopback interface está ok?
Tente alterar o localhost para 127.0.0.1, caso funcione vale a pena dar uma olhada como seu SO está resolvendo o loopback.

linux = /etc/hosts
windows = C:\Windows\System32\drivers\etc\hosts file

 - Configuração de binding
Problemas de binding são comuns, tente explicitar a configuração na guia [mysqld] o default seria 0.0.0.0 e aceitaria todos os hosts ipv4:
bind-address    = 127.0.0.1

ou explicite para todas as interfaces
bind-address    = 0.0.0.0

- Mantenha "Skip Networking" comentado
# Don't listen on a TCP/IP port at all. This can be a security enhancement,
# if all processes that need to connect to mysqld run on the same host.
# All interaction with mysqld must be made via Unix sockets or named pipes.
# Note that using this option without enabling named pipes on Windows
# (via the "enable-named-pipe" option) will render mysqld useless!
#
#skip-networking

Conexão JAVA com BANCO


Can't use JavaScript to change innerHTML to "\f"

Question: I'm honestly stumped. I was working on a program and I narrowed down the problem to an incredible degree; whenever I try to change the innerHTML of an element to "\f" it doesn't display.
Note: I've only tried this on CodePen and JSFiddle; 2 online code editors. I'm not sure if my problem is the websites, or JavaScript. I'd prefer to keep this online as it's the best choice for portability.
Also Note: Just in case anyone was wondering, I need this to use the MathJax Library for JavaScript. (\Frac specifically)
https://codepen.io/FoodLover195/pen/mBzoyG
HTML:

Hello World

Hello World

Hello World

JavaScript:
document.getElementById("Test").innerHTML = "\f";
document.getElementById("Test2").innerHTML = "\food";
document.getElementById("Test3").innerHTML = "\fried \food";

Comment: (Code blocks need a blank line above them)
Comment: If you really want to show `\f` then add another slash `.innerHTML = "\\f";`
Comment: Do you mean that you want to put `\f` in the text?  If so, use `\\f` to avoid escaping the f.
Comment: Even simpler: open your browser console and type `'\f'`… → `""`
Comment: ...there has to be a dupetarget for this...
Comment: Thanks for the real quick replies... like that was insanely fast.
Answer: \f is an escape sequence for a formfeed (U+000C) in a string literal in JavaScript (and most other languages with C-like syntax). To put an actual backslash in a string literal, use \\ (e.g., \\f).
Answer: \ is an escape character. You need to escape the \ character. In other words:
document.getElementById("Test").innerHTML = "\\f";
document.getElementById("Test2").innerHTML = "\\food";
document.getElementById("Test3").innerHTML = "\\fried \\food";


PHP - Why doesn't array_multisort function sort correctly?

Question: please view the following code with 2 arrays.  i use multisort function with sort flags for ascending and numeric then display.  as you can see in the output that array 2 starts with 100 when it should be last.  please explain what is causing this and how to sort it correctly.  thank you.
<?php
$array1 = array(1,7,10,6);
$array2 = array(100,20,25,10);
array_multisort($array1, SORT_ASC, SORT_NUMERIC, $array2);
print_r($array1);
echo "
";
print_r($array2);
?>

output:
Array ( [0] => 1 [1] => 6 [2] => 7 [3] => 10 )
Array ( [0] => 100 [1] => 10 [2] => 20 [3] => 25 )

Answer: Ah, yes, array_multisort is a bit tricky to understand the first time round.
Basically the sort is lexicographical, a fancy word meaning that the first array is sorted and the second arrays elements are ordered according to the first array.
Look at your first (output) array and see the order and map it to the initial second array and you'll see whats happening.
So the second array you take the 1st, 4th , 2nd and 3rd elements.
If you just want plain sorting for multiple arrays then just do them one by one or over a loop.


mkdir no android não funciona

Question: Estou tentando criar uma pasta no Android para salvar as fotos dos comprovantes, mas não estou tendo sucesso. Já dei permissão no Manifest
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="<meu.package>">

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

e, de acordo com as novas regras do Android 7.0, estou solicitando essas permissões em tempo de execução.
O código esta assim:
 private void CriaPasta() {
        pasta = Environment.getExternalStorageDirectory().getPath() + "/Android/data/" + getApplicationContext().getPackageName() + "/comprovantes/";
        File folder = new File(pasta);

        if (!folder.exists()) {
            if (!folder.mkdir()) ;
            Toast.makeText(this, pasta + " não pode ser criada.", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case WRITE_EXTERNAL_STORAGE: {
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    CriaPasta();
                }
            }
        }
    }

Aqui no metodo UpdateView desta activity eu verifico se já tenho permissão e tento criar a pasta caso ela não exista. Aqui o fluxo segue direto para a rotina CriaPasta porque essa permissão já foi pedida na entrada principal do programa.
    private void UpdateView() {

        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {

            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, WRITE_EXTERNAL_STORAGE);
        } else {
            CriaPasta();
        }
    }

Porém na rotina CriaPasta a mensagem dizendo que a pasta não pode ser criada ocorre todas as vezes.
Esse é parte do arquivo build.gradle.
android {
    compileSdkVersion 26
    buildToolsVersion "26.0.2"
    defaultConfig {
        applicationId "<meu.package>"
        minSdkVersion 17
        targetSdkVersion 26

Parece ter a ver com essa versão, porque em outros aplicativos meus a criação de pastas semelhantes ocorre normalmente no mesmo aparelho.
Aliás, quando instalo os outros aplicativos o Android cria a pasta emulated/0/Android/data/ automaticamente e nesse aplicativo isso não acontece.
Comment: A única razão que encontro para não conseguir é que o directório não esteja acessível. Pode verificar utilizando [getExternalStorageState()](https://developer.android.com/reference/android/os/Environment#getExternalStorageState()). De qualquer forma, a partir da versão 19 (Android 4.4) não deve utilizar esse método. Ao lidar com o *External Storage* tenha presente o que é dito nesta [resposta](https://pt.stackoverflow.com/a/70277/2541).
Answer: Há um método mais natural para alcançar o diretório em que está tentando criar suas pastas:
Context.getExternalFilesDir(@Nullable String type)

Retorna o caminho absoluto para o diretório no dispositivo de armazenamento primário compartilhado/externo onde o aplicativo pode colocar
arquivos persistentes de sua propriedade. Esses arquivos são internos
aos aplicativos e normalmente não são visíveis para o usuário como
mídia.

Esse método retorna um File apontando para /memóriaInterna/Android/data/nome.do.pacote/files
Então, tente substituir dessa forma:
private void CriaPasta() {
    File pasta = new File(getExternalFilesDir(null), "comprovantes");
    /*
       /memóriaInterna/Android/data/nome.do.pacote/files/comprovantes
    */
    if (!pasta.exists()) {
        if (!pasta.mkdirs()) { // <- mkdirs()
            Toast.makeText(this, pasta + " não pode ser criada.", Toast.LENGTH_SHORT).show();
        }
    }
}

Perceba que usei mkdirs() que cria a pasta, incluindo qualquer diretório pai necessário, mas inexistente.
Comment: Perfeito Lennoard. Funcionou corretamente.

mkdir no android não funciona


SVN : How to get path of repository knowing its URL?

Question: I'm trying to backup my SVN respository with svnadmin dump command. So I must give it the path of my repository which I don't know how to find it. I'm using svn over http.
How can I find this?
FYI: I'm having TortoiseSVN installed too if that could help.
Answer: I guess that you ask about svnadmin dump because there is no svn dump subcommand in Apache Subversion.

You can use svnrdump tool to get the dump over HTTP(S). You will get the dump of all version-history your user account has access to in the repository.
You must have direct access to the repository on disk to use svnadmin (i.e. you have to be an administrator), you can't get a dump via HTTP(S) using svnadmin dump.

NOTE: Subversion repository dump contains revision history only, it does not include hook scripts, access rules or any repository config customizations you might've done.
Comment: Firstly, SVN 1.6 is unsupported since 2013. Moreover, you don't need your server to be 1.6, it's just about **client-side tools**. `svnrdump` is packaged with all Subversion command-line distributions. Grab one at https://www.visualsvn.com/downloads/
Comment: Thank's @bahrep I've edited my question ;) what about users and their passwords ? are they backed ? what are hook scripts ?
Comment: @mounaim You have to be server's administrator to get access rules and a list of users and hooks.  If you don't have access to the server that hosts your repos then you can't get them unless you use some shared SVN repo hosting which allows you to get them from some kind of web control panel.
Comment: Unfortunately svnrdump is unavailable in SVN 1.6 which I'm using


Como funciona o GroupBy no LINQ?

Question: Estou com dificuldades para entender o operador GroupBy no LINQ.
Comment: http://www.dotnetperls.com/groupby
Comment: Você tem alguma dúvida específica?
Comment: não entendi a sintaxe
Comment: quero um exemplo
Answer: GroupBy serve para agrupar elementos de acordo com um determinado valor em comum entre eles. Por exemplo:
public class Fruta {
    public String Cor { get; set; }
    public String Nome { get; set; }
}

Suponha algo assim:
var frutas = new List<Fruta>();

Suponha também que colocamos várias frutas, com cores em comum, e queremos agrupar pelas cores:
var grupos = frutas.GroupBy(f => f.Cor);

grupos é um objeto que implementa IEnumerable<IGrouping<String, Fruta>>. Ou seja, é uma lista de elementos de grupos.
Um objeto que implementa IGrouping basicamente tem dois elementos em sua estrutura:

Key, ou seja, o valor chave do agrupamento (no nosso caso, o nome da fruta, uma String);
GetEnumerator, ou seja, os elementos agrupados pelo valor chave. Aí aqui você pode usar o objeto diretamente, fazer um ToList(), usar outra extensão Linq, etc, etc, etc.

Repare que ele se parece muito com um dicionário.
Se quiser imprimir o nome dos grupos, posso fazer assim:
foreach (var nomeGrupo in grupos.Select(g => g.Key)) {
    Debug.WriteLine(nomeGrupo);
}

Se quiser imprimir as frutas de cada grupo, posso fazer assim:
foreach (var listaDeFrutasPorCor in grupos) {
    Debug.WriteLine("Imprimindo frutas da cor: " + listaDeFrutasPorCor.Key);
    Debug.WriteLine("-----------------------");
    foreach (var fruta in listaDeFrutasPorCor) {
        Debug.WriteLine(fruta.Nome);
    }
}

Fiz um Fiddle aqui.
Comment: Perfeito Obrigado !
Answer: Como o nome diz, ele agrupa dados baseado em algum critério. Ele funciona igual ou pelo menos de forma semelhante ao GROUP BY do SQL.
Com ele você gera um conjunto de dados baseado em outro conjunto que deve ter alguma "coluna" repetida. Você elimina a repetição deste dado.
Retirado da documentação:
using static System.Console;
using System.Collections.Generic;
using System.Linq;

public class Program {
    public static void Main() {
        List<Pet> pets =
            new List<Pet>{ new Pet { Name="Barley", Age=8 },
                new Pet { Name="Boots", Age=4 },
                new Pet { Name="Whiskers", Age=1 },
                new Pet { Name="Daisy", Age=4 } };
        //está agrupando por idade e depois po nome.
        //Como existe dois pets com mesma idade eles serão agrupados
        var query = pets.GroupBy(pet => pet.Age, pet => pet.Name);
        foreach (var petGroup in query) {
            WriteLine(petGroup.Key);
            foreach (var name in petGroup) WriteLine("  {0}", name);
        }
    }
}

class Pet {
    public string Name { get; set; }
    public int Age { get; set; }
}

Veja funcionando no ideone. E no .NET Fiddle. Também coloquei no GitHub para referência futura.

Como funciona o GroupBy no LINQ?


Average number of throws of 2 dice in order for the sum to be a prime number

Question: If I throw 2 dice, what's the average number of throws that I need to do in order for the sum of the 2 dice to be a prime number?
My attempt:
The probability that the sum will be a prime number is $\frac{4}{9}$.  And, by applying the formula of mathematical expectation($\frac{1}{p}$) I get $\frac{1}{\frac{4}{9}}$ then $\frac{9}{4} > 1$. Which is not correct.
Comment: Why do you think that getting an answer that's greater than one is incorrect? You're not looking for a probability, rather the "average" number of times that you need to roll the dice, so it *should* be at least one!
Comment: Check the probability. A six by six table is helpful.
Comment: It is actually $\frac{15}{36}$ but it is still not right. since $\frac{36}{15}> 1$
Comment: I've realised that after 1 hour. 1 hour wasted because of 1 simple logical error.
Answer: As A. Webb notes above, check your assumption that the sum being prime is 4/9ths. Two independent dice of six faces give you thirty six different results, many of which turn into the same sums, and since that's a very countable number actually making a chart can be really helpful.
Now, I'm not sure what you are saying with the formula of mathematical expectation (between the original question and your edit) but I believe it is  that you have some number of independent throws which each have some chance 'p' of being a prime. I think you are trying to use the reciprocal of that (1/p) to give you the chance of it NOT being prime.
That's not how you get there. You have the chance of the sum being a prime 'p,' what you want is its complement: one minus p. What's that mean? One in probability is a 100% chance, so one minus "the chance of a prime" is "the chance of it NOT being prime" that I think you're looking for as your intermediate step.
If that isn't your intention, feel free to comment.
Comment: For probability p of success, the mean number of throws needed to get the first success is indeed 1/p. Not sure the confusion you describe is related to what the OP describes.
Answer: Prime numbers between $2$ and $12$ are $2,3,5,7,11$
which can be obtained in $15$ ways as $\boxed{1-1}\boxed{ 1-2/2-1}\boxed{1-4/4-1,\; 2-3/3-2}\boxed{1-6/6-1,2-5/5-2,3-4/4-3}\boxed{ 5-6/6-5} $
Thus P(prime number) = $\dfrac{15}{36} = \dfrac5{12}$
and $E[X] = 1/p = \dfrac{12}5 = 2.4$


How many $p$-adic numbers are there?

Question: Let $\mathbb Q_p$ be $p$-adic numbers field. I know that the cardinal of $\mathbb Z_p$ (interger $p$-adic numbers) is continuum, and every $p$-adic number $x$ can be in form $x=p^nx^\prime$, where $x^\prime\in\mathbb Z_p$, $n\in\mathbb Z$.
So the cardinal of $\mathbb Q_p$ is continuum or more than that?
Comment: By your decomposition, we just need to find the cardinality of $\mathbf{Z} \times \mathbf{R}$. It seems like [Cantor-Schroeder-Bernstein](http://en.wikipedia.org/wiki/Cantor%E2%80%93Bernstein%E2%80%93Schroeder_theorem) could be used to show that this has the cardinality of $\mathbf{R}$.
Answer: The field $\mathbb Q_p$ is the fraction field of $\mathbb Z_p$.
Since you already know that $|\mathbb Z_p|=2^{\aleph_0}$, let us show that this is also the cardinality of $\mathbb Q_p$:
Note that every element of $\mathbb Q_p$ is an equivalence class of pairs in $\mathbb Z_p$, much like the rationals are with respect to the integers.
Since $\mathbb Z_p\times\mathbb Z_p$ is also of cardinality continuum, we have that $\mathbb Q_p$ can be injected into this set either by the axiom of choice, or directly by choosing representatives which are co-prime.
This shows that $\mathbb Q_p$ has at most continuum many elements, since $\mathbb Z_p$ is a subset of its fraction field, then the $p$-adic field has exactly $2^{\aleph_0}$ many elements.
Answer: To complete Student's answer : $\mathbb Z_p \subset \mathbb Q_p \subset \mathbb C_p$, and since $\mathbb C_p$, the algebraic closure of $\mathbb Q_p$, is isomorphic to $\mathbb C$, the field of the complex numbers, we know that
$$
|\mathbb R| = |\mathbb Z_p| \le |\mathbb Q_p| \le |\mathbb C_p| = |\mathbb C| = |\mathbb R| \quad \Longrightarrow \quad |\mathbb Q_p| = |\mathbb R|.
$$
by the Cantor-Bernstein theorem, which states that if $|A| \le |B|$ and $|B| \le |A|$ then $|A| = |B|$.
EDIT : One REALLY more easy way to see this (in the sense that I can assume less non-trivial things) is that we get an injection from $\mathbb R$ to $\mathbb Q_p$ (and vice-versa) by choosing one representation for each element on each side and associate them in the following manner :
$$
\sum_{k=-\infty}^n a_k p^k = \underset{\in \mathbb R}{x} \longleftrightarrow \underset{\in \mathbb Q_p}{y} = \sum_{k=-n}^{\infty} a_{-k} p^k
$$
(i.e.  you flip the number over) which doesn't give us a bijection but rather two surjections. (If I wanted to have a bijection with this I would have trouble with the possible two representations of a number on each side.) Thus I can apply Cantor-Bernstein.
Comment: Where I come from, $\Bbb C_p$ is standard notation for the *completion of* an algebraic closure of $\Bbb Q_p$, not that algebraic closure itself. They happen to have the same cardinality and are both algebraically closed (which by the way means they are isomorphic as fields as well, which just shows how crazy that whole argument about field isomorphisms with AC is), but one is strictly contained in the other, one is complete and the other is not.
Comment: You write "...and since $\mathbb C_p$, the algebraic closure of $\mathbb Q_p$, is isomorphic to $\mathbb C...$" This is far from evident and I am not sure that there is no circularity here. How do you justify this claim?
Comment: I am not saying it is trivial, I'm just saying it's true, and I don't think that an isomorphism between $\mathbb C_p$ and $\mathbb C$ can possibly assume that $\mathbb Q_p = \mathbb R$... I'll take a look at the actual proof and give you a hint on how to justify this.
Comment: Whew. It is definitively non-trivial. Quote from Wikipedia, on the article p-adic number r :
"The field $\mathbb C_p$ is isomorphic to the field $\mathbb C$ of complex numbers, so we may regard $\mathbb C_p$ as the complex numbers endowed with an exotic metric. It should be noted that the proof of existence of such a field isomorphism relies on the axiom of choice, and does not provide an explicit example of such an isomorphism."
Comment: I am having trouble making my new solution understandable with the notation ; the idea is just to flip the number over itself.
Comment: @PatrickDaSilva: You need to check that the map is well defined.  It also gives two surjections, not two injections.
Comment: The answer before the edit is circular. The way one shows that $\Bbb C_p$ is isomorphic to $\Bbb C$ is by using the fact that two algebraically closed fields of the same characteristic and the same cardinality are isomorphic. So one cannot use this isomorphism to determine the cardinality of $\Bbb C_p$.
Comment: For the two surjections you mentioned it isn't immediately clear why they are surjections.  For a real number $x \in \mathbb{R}$, it doesn't have a unique representation as a series in the form you wrote it, as you mentioned.  Therefore, for a a choice of such a mapping, we a do not reach all laurent series with coefficients between $0$ and $p-1$, and thus we dont know if your map reaches all p-adic numbers $\mathbb{Q}_p$.
Answer: Well, $\mathbb{Q}_p\subset \mathbb{C}$ ...
Comment: What sort of help is that??? $\{0\}\subseteq\mathbb C$ as well...
Comment: @Asaf It would show that $\mathbf{Q}_p$ isn't larger than $\mathbf{C}$. And he has the other inequality. What's bogus about this? Besides showing that there is such an embedding :)
Comment: Sorry for the confusion, I was answering to the part of the question asking "is it bigger than continuum ?" : By $\mathbb{C}$, I indeed meant the fields of complex numbers, but I agree that "$\subset$" is a bit vague. What I have in mind is that $\mathbb{C}$ is fields-isomorphic to $\mathbb{C}_p$, the fields of complex $p$-adic numbers, which contains $\mathbb{Q}_p$ and thus gives an upper bound for its cardinal, but maybe I commit a reasoning mistake !
Comment: Student, you should aim for a complete and comprehensible answer, not one that is "the first" requires a later addition in the comments.
Comment: What is $\mathbb C$?

How many $p$-adic numbers are there?


Why is there no umpires call with DRS ball pitching?

Question: When a team either reviews to get a wicket or to over turn a wicket, there is umpires call for impact in line with the stumps and impact of the stumps.
When the ball is close to pitching in line with the stumps in DRS, why is it the case that there is no umpires call and is either pitching in line or outside leg stump.
Answer: Pitching position is determined by the actual ball on a flat surface. To the extent that an error exists, it consists of a pixel on a screen.
For the ball hitting the pads, it is not possible to reliably say from current camera angles the height at which the ball hit the pads, and therefore the error is large enough to be applied.
For the ball hitting the stumps, this is only available from computer modelling, and a fixed margin of error of half the ball's width is applied to the result.


Get name / alias of column in PySpark

Question: I am defining a column object like this:
column = F.col('foo').alias('bar')

I know I can get the full expression using str(column),
but how can I get the column's alias only?
In the example, I'm looking for a function get_column_name where get_column_name(column) returns the string bar.
Answer:
One way is through regular expressions:
from pyspark.sql.functions import col
column = col('foo').alias('bar')
print(column)
#Column<foo AS `bar`>

import re
print(re.findall("(?<=AS `)\w+(?=`>$)", str(column)))[0]
#'bar'

Comment: I'm doing this for some kind of generic module, where I'm working with columns that aren't bound to a dataframe.
Comment: I have similar problem where I get column object that may or may not have an alias
OR a string containing column name and I need to return string "table_alias.column_name" (where table_alias I add to that column name, its not taken from that column object). Its a bummer that column object dont have property returning qualified name
Comment: I had the same thought as you, but I was hoping for a way to do this via the spark API directly. But this will work for now, thanks a lot!
Comment: @surjikal if you had the dataframe you could get the columns after the transformation: something like `df.select(column).columns`
Comment: I want w/e alias was given last, since that's what the resulting column would be named. I tweaked it to ``re.findall(r"(?<=AS `)\w+(?<!`)", str(column))[-1]``
Answer: Alternatively, we could use a wrapper function to tweak the behavior of Column.alias and Column.name methods to store the alias only in an AS attribute:
from pyspark.sql import Column, SparkSession
from pyspark.sql.functions import col, explode, array, struct, lit
SparkSession.builder.getOrCreate()

def alias_wrapper(self, *alias, **kwargs):
    renamed_col = Column._alias(self, *alias, **kwargs)
    renamed_col.AS = alias[0] if len(alias) == 1 else alias
    return renamed_col

Column._alias, Column.alias, Column.name, Column.AS = Column.alias, alias_wrapper, alias_wrapper, None

which then guarantees:
assert(col("foo").alias("bar").AS == "bar")
# `name` should act like `alias`
assert(col("foo").name("bar").AS == "bar")
# column without alias should have None in `AS`
assert(col("foo").AS is None)
# multialias should be handled
assert(explode(array(struct(lit(1), lit("a")))).alias("foo", "bar").AS == ("foo", "bar"))

Answer: The following function works well with cases like:

several aliases
aliases containing several words
intentional backticks in aliases

def get_col_name(col):
    if str(col)[-3] != '`':
        return str(col).split("'")[-2].split(" AS ")[-1]
    return str(col).replace('``', '`').split(" AS `")[-1].split("`'")[-2]

Testing:
from pyspark.sql import functions as F

cols = [
    F.col('foo'),
    F.col('foo').alias('bar'),
    F.col('foo').alias('bar').alias('baz'),
    F.col('foo').alias('foo bar'),
    F.col('foo').alias('foo AS bar'),
    F.col('foo').alias('foo AS bar').alias('bar AS baz'),
    F.col('foo').alias('foo AS bar').alias('baz'),
    F.col('foo').alias('foo AS bar').alias('````bar AS baz````'),
]

for c in cols:
    print(get_col_name(c))

# foo
# bar
# baz
# foo bar
# foo AS bar
# bar AS baz
# baz
# ````bar AS baz````

Answer: Regex is not needed. For PySpark 3.x it looks like backticks were replaced with quotes, so this might not work out of the box on earlier spark versions, but should be easy enough to modify.
Note: requires  Python 3.9+
from pyspark.sql import Column

def get_column_name(col: Column) -> str:
    """
    PySpark doesn't allow you to directly access the column name with respect to aliases
    from an unbound column. We have to parse this out from the string representation.

    This works on columns with one or more aliases as well as unaliased columns.

    Returns:
        Col name as str, with respect to aliasing
    """
    c = str(col).removeprefix("Column<'").removesuffix("'>")
    return c.split(' AS ')[-1]

Some tests to validate behavior:
import pytest
from pyspark.sql import SparkSession

@pytest.fixture(scope="session")
def spark() -> SparkSession:
    # Provide a session spark fixture for all tests
    yield SparkSession.builder.getOrCreate()

def test_get_col_name(spark):
    col = f.col('a')
    actual = get_column_name(col)
    assert actual == 'a'

def test_get_col_name_alias(spark):
    col = f.col('a').alias('b')
    actual = get_column_name(col)
    assert actual == 'b'

def test_get_col_name_multiple_alias(spark):
    col = f.col('a').alias('b').alias('c')
    actual = get_column_name(col)
    assert actual == 'c'

def test_get_col_name_longer(spark: SparkSession):
    """Added this test due to identifying a bug in the old implementation (if you use lstrip/rstrip, this will fail)"""
    col = f.col("local")
    actual = get_column_name(col)
    assert actual == "local"

Comment: When the alias contains multiple words separated using spaces, this function returns the column name enclosed in backticks.

Get name / alias of column in PySpark


Não consegue capturar o erro no sql

Question: try
       DModuleGrid.ZQuery1.Close;
       DModuleGrid.ZQuery1.SQL.Clear;
       DModuleGrid.ZQuery1.SQL.Add('SELECT * FROM tdcupant');
       DModuleGrid.ZQuery1.SQL.Add('WHERE numcupom = :co2 AND ccf = :cc3 AND dtcompra = :dtc4 AND impcaixa = :ip5');
       DModuleGrid.ZQuery1.ParamByName('co2').AsString := copy(lTemp,53,6);
       DModuleGrid.ZQuery1.ParamByName('cc3').AsString := copy(lTemp,47,6);
       DModuleGrid.ZQuery1.ParamByName('ip5').AsString := copy(lTemp,4,20);
       DModuleGrid.ZQuery1.ParamByName('dtc4').AsDate := StrToDate(dtcompratxt);
       DModuleGrid.ZQuery1.Open;
     except
       on e: Exception do
       begin
       ercp := e.Message;
       StatusBar1.Panels[0].Text := 'Erro ao encontrar registros! ' + ercp;
     end;

Acredito que esta certo. Porém ele fica indicando o erro do próprio sql.
Bom, o erro que dá é:

Para ser preciso, ele apenas precisa capturar uma exceção para caso nenhum dos registros que comparei nos parâmetros sejam encontrados no banco de dados.
Comment: Qual erro? testou a consulta direto no banco?
Comment: @RamonRuan Exception ao realizar o open não significa que não encountou registros. Um erro de sintaxe é quando sua query está escrita errada. Transcreva o erro para que fique mais fácil podermos ajudar. E se você tratar `on e: Exception`significa todo tipo de exceção e portanto nunca irá cair no seu `else`. Se o que você quer é lançar uma exceção se não encontrar registros, aí é outra coisa
Comment: @perdeu Sim, a consulta apresentada ai, é que precisa de ter os registros cadastrados no banco para igualar com os parâmetros, porém, obviamente não é todo arquivo .txt que existe os registros corretos que está no banco de dados, o erro é de `Sql Sintaxe`, que é quando não encontra nenhum registro, depois que percorre todo o banco e o arquivo txt.
Comment: @perdeu, mas é exatamente isso que estou fazendo, provocando erro selecionando um arquivo errado, para eu tratar ele, mas não está tratando.
Comment: @Caputo, segue logo em cima a imagem do erro. O else, foi só um pequeno teste, como estou reaprendendo a linguagem, tem muita coisa que perdi e falta aprender. haha
Comment: Não será a falta de um espaço entre `SELECT * FROM tdcupant` e `WHERE...`?
Comment: @JorgeB. acredito que não, pois eles estão em linhas diferentes quando são adicionadas. Mas só para teste, fiz, mas msm assim aparece.
Comment: Experimenta por um espaço antes de `WHERE`. Costuma ser a maior parte dos meu problemas com SQL.
Comment: Antes do `DModuleGrid.ZQuery1.Open` dá um `Showmessage(DModuleGrid.ZQuery1.SQL.Text)` e diz o que aparece, por favor.
Comment: @Filipe.Fonseca `SELECT * FROM tdcupant WHERE numcupom = :co2 AND ccf = :cc3 AND dtcompra = :dtc4 AND impcaixa = :ip5`, esta mensagem, com `sql`.
Comment: Ia postar como comentário, mas ficou grande d+, então foi como resposta. Se não funcionar edito posteriormente.
Comment: @Filipe.Fonseca, eu estava olhando meu código, e debugguei em outro canto, pus um ponto para cada começo de while e if existente naquele procedimento, e achei uma linha aonde, "se não encontrasse nenhum registro ele iria dar um  valor=''..." sql não aceita nada no campo e sim um 0. Vou postar a resposta agora mesmo.
Answer: Não conheço seu componente de acesso a dados, porém, acho que vale tentar:
Substitua
       DModuleGrid.ZQuery1.Close;
       DModuleGrid.ZQuery1.SQL.Clear;
       DModuleGrid.ZQuery1.SQL.Add('SELECT * FROM tdcupant');
       DModuleGrid.ZQuery1.SQL.Add('WHERE numcupom = :co2 AND ccf = :cc3 AND dtcompra = :dtc4 AND impcaixa = :ip5');
       DModuleGrid.ZQuery1.ParamByName('co2').AsString := copy(lTemp,53,6);
       DModuleGrid.ZQuery1.ParamByName('cc3').AsString := copy(lTemp,47,6);
       DModuleGrid.ZQuery1.ParamByName('ip5').AsString := copy(lTemp,4,20);
       DModuleGrid.ZQuery1.ParamByName('dtc4').AsDate := StrToDate(dtcompratxt);
       DModuleGrid.ZQuery1.Open;

Por:

       DModuleGrid.ZQuery1.Close;
       DModuleGrid.ZQuery1.SQL.Clear;
       DModuleGrid.ZQuery1.SQL.Text := Format('SELECT * FROM tdcupant WHERE numcupom = %s AND ccf = %s AND dtcompra = %s AND impcaixa = %s', [copy(lTemp,53,6),copy(lTemp,47,6),copy(lTemp,4,20),FormatDateTime('yyyymmdd',StrToDate(dtcompratxt))]);
       DModuleGrid.ZQuery1.Open;

Comment: testei o seu jeito e funcionou tambem, mas continuou o erro, então fiz o que postei e deu certo tambem. Obrigado pela atenção.
Answer: Então cara, esse erro é por erro de SINTAXE no comando SQL, debuga ele e veja todos os valores das variáveis que está utilizando para compor o comando, feito isso pegue o conteúdo e rode o comando direto no Banco de dados com os valores no lugar das variáveis.
Ficará muito mais fácil de você encontrar o erro no comando dessa forma.
Também verifique aquele parâmetro "IP5", pois não vi ele sendo utilizado em nenhuma parte do comando.
Espero que ajude.
Comment: esta sendo usado sim, olha la, na `SELEÇÃO` e nos `PARAMETROS`.
Answer: Debugguei o código mais uma vez e encontrei
  DModuleGrid.ZQuery2.Close;
  DModuleGrid.ZQuery2.SQL.Clear;
  DModuleGrid.ZQuery2.SQL.Add('SELECT * FROM tabc460 LIMIT 0, '+valor);
  DModuleGrid.ZQuery2.Open;

Esse valor, é um incremento de caso encontre registros divergentes. Mas, pensem assim, se não encontra nenhum registro, não vai incrementar nenhum valor né?
Bom, está aí, eu pensei que só era naquele momento ali,  por que estava percorrendo todo o banco de dados, daí deu certo.
if (valor = '') then
  begin
    valor := IntToStr(0);
  end;

Fiz apenas esse tratamento, pra caso não encontra nada, encontre 0;
Comment: Resolveste o problema? Não percebi como...
Comment: @JorgeB. Aquele código lá em cima é apenas para SELEÇÃO e COMPARAÇÃO, esse mesmo código entra em um loop para identificar divergências entre os campos do DB e campos do ARQUIVO .txt, então como disse em cima, o incremento `valor`, será usado para caso haja divergências entre os campos, e esse codigo nesta resposta corresponde à SELEÇÃO DOS ÚLTIMOS DADOS INSERIDOS NO BD, que no caso, são as divergências.

Não consegue capturar o erro no sql


Best method to upload / link to multimedia files in D6?

Question: I need a solution to allow users to upload multimedia files (audio, video, images, documents, links to such) to a node. Ideally, something like a combination of FileField + Embedded Media Field that supports different media and styles the viewer accordingly.
I know that module Media is supposed to solve this problem on D7, but I'm looking for a D6 solution.
I've tried:

jQuery Media but it doesn't handle many file types that I need - plus I prefer a server-side solution.
Styles + FileField Styles but they just don't work.
Comment: Styles 6.x-1.x does work with FileField Styles but the functionality is very poor - it only supports images at this time.
Answer: Have you looked at the MediaFront module? Here is a quote about it (from the module's project page):

... is a front end media solution for Drupal. It employs an innovative and intuitive administration interface that allows the website administrator to completely customize the front end media experience for their users without writing any code. In addition, this module provides an interface to which 3rd party media players can integrate and utilize settings presets to display rich media. Out-of-the-box, this module provides two media player solutions.
Comment: Yes, I've used it in the past. MediaFront is a video player, whereas I am looking for a solution to upload and view arbitrary media files (audio, video, images, docs) via a consistent interface.
Answer: Have a look at ShadowBox, it supports a lot of formats and the FileField module which I think is essential for your set up:

Media extensions supported:
  - Images (png, jpg, jpeg, gif, bmp)
  - Video (avi, mpg, mpeg)
  - Quicktime (dv, mov, moov, movie, mp4)
  - Windows Media Player (asf, wm, wmv)
  - Flash (swf, flv)
  - IFrame (asp, aspx, cgi, cfm, htm, html, pdf, pl, php*, phtml, rb, rhtml, shtml, txt, vbs)

Source: Comparison of Lightbox-type modules.
There's algo the Lightbox2 module with is aroung since a long time and have quite a big installed base.
Comment: This looks good, thanks! Will try it and update this thread.
Answer: My solution was to use 2 multiple-value fields in my media content type:

A FileField with a custom formatter that detects the MIME type of the uploaded file and renders a different theme for known type/subtype combinations, defaulting to the standard FileField link.
An oEmbed field with Embed.ly support for media links. This API works much better than EMField.

The whole trick was to theme the media views and forms such that media from both those fields make up a single visual list, not two.


Bing Ads PHP Example

Question: I'm using the Bing Ads php code for downloading Keyword Performance Reports. Here:
http://msdn.microsoft.com/en-us/library/bing-ads-reporting-request-and-download-a-keyword-performance-report-in-php.aspx
Is there any way i can specify multiple CampaignID's in my Keyword Performance Report? As of now, i'm only able to download reports for a single CampaignID and as you can imagine, this is really inefficient since i have more than 10 Campaigns. Any help would be greatly appreciated.
Answer: Instead of
<code> $report->Scope->Campaigns = array ();
</code>
Just have the line below and it will pull all campaigns. It only pulls on campaign level if they are specified.
<code>$report->Scope->Campaigns = null;
</code>

Bing Ads PHP Example


Backpropagation on a convolutional layer

Question: Online tutorials describe in depth the convolution of an image with a filter, etc; However, I have not seen one that describes the backpropagation on the filter (at least visually).
First let me try to explain how I understand backpropagation on a fully connected network.

For example, the derivative of the $Error$ with respect to $W_1$ is the following:
$$
\frac{\partial Error}{\partial W_1} = \frac{\partial Error}{\partial HA_1} \frac{\partial HA_1}{\partial H_1} \frac{\partial H_1}{\partial W_1}
$$
The last partial derivative is the most interesting one in this case ... and it is equal to the value of the first input (Single value).
$$
\frac{\partial H_1}{\partial W_1} = I_1
$$
EDITED

The original question was how does one perform backpropagation on a convolutional layer - for example $$\frac{\partial Error}{\partial W_1} = ?$$

The convolutional layer as described online.

$$
G_1 = V_1W_1 + V_2W_2 + V_4W_3 + V_5W_4 \\
G_2 = V_2W_1 + V_3W_2 + V_5W_3 + V_6W_4 \\
G_3 = V_4W_1 + V_5W_2 + V_7W_3 + V_8W_4 \\
G_4 = V_5W_1 + V_6W_2 + V_8W_3 + V_9W_4
$$
Notice that there are groups of pixels that share the same weights ($W$s), so I can picture the equations above as follows:

So, applying the chain rule as in the first example, we get the following:
$$
 \frac{\partial Error}{\partial W_1} = \frac{\partial Error}{\partial G_1}\frac{\partial G_1}{\partial W_1} + \frac{\partial Error}{\partial G_2}\frac{\partial G_2}{\partial W_1} + \frac{\partial Error}{\partial G_3}\frac{\partial G_3}{\partial W_1} + \frac{\partial Error}{\partial G_4}\frac{\partial G_4}{\partial W_1}
$$
And the derivatives of interest ...
$$
\frac{\partial G_1}{\partial W_1} = V_1 \\
\frac{\partial G_2}{\partial W_1} = V_2 \\
\frac{\partial G_3}{\partial W_1} = V_4 \\
\frac{\partial G_4}{\partial W_1} = V_5
$$
That's it! Chain rule all the way.
I don't like to answer my own question - so if you leave some feedback or tell me I am wrong - I 'll give you the credit.
Comment: You're not merely *permitted* to answer your own question, but if you've found the answer on your own, you are *encouraged* to answer your own question. Moreover, this question has had no answers for several months, so I think that it's more than fair for you to answer it.
Comment: I think it can be summarized this way: backprop of a convolution is again a convolution.
Comment: Backpropagation is the reverse mode (accumukation) of automatic differentiation (a.k.a. algorithmic differentiation) applied to neural networks.
Comment: I wonder if we could play Wans diagrammatic method to it.
Answer: Could you not simply say that the backpropagation on a convolutional layer is the sum of the backpropagation on each part, sliding window, of the image/tensor that the convolution covers?
This is important as it connects to the fact that the weights are shared over multiple pixels and thus weights should reflect general local features of the images independently from their location.
Comment: I think that could be true if there is no overlap - so window and stride are equal.
Comment: It's true in general. If you consider the overlapping parts of the images. In other words if the same pixel is in position x1,y1 in window (image part) 1 and in position  x2,y2 in window (image part) 2, it will affect the gradient of a different weight for each image part. Still, the total gradient for each weight will be the sum of the gradients of the weight for each window/image part.


Does MusicXML support roman numerals and/or functions?

Question: Does MusicXML support roman numerals and/or functions (such as T for tonic)? I know this can be done via a workaround, namely using lyrics and a special font. But I am talking about dedicated support.
Related: Software support for roman numerals and functions
Comment: [related github issue](https://github.com/w3c/musicxml/issues/295)
Answer: Yes for roman numerals. Maybe for functions (such as T for tonic). Look into the element Harmony in direction.mod.
The harmony elements are based on Humdrum's **harm
encoding, extended to support chord symbols in popular
music as well as functional harmony analysis in classical
music.
...

The harmony object may be used for analysis or for
chord symbols.

A root is a pitch name like C, D, E, where a function
is an indication like I, II, III. Root is generally
used with pop chord symbols, function with classical
functional harmony. It is an either/or choice to avoid
data inconsistency. Function requires that the key be
specified in the encoding.


Best practice for getting View dimensions, possibly before they are drawn to screen

Question: I've seen a ton of different questions and answers to the problems people are having with retrieving height and width of views, particularly this thread.
The following are mentioned methods to retrieve View dimensions:

onWindowFocusChanged() in your activity
Subclassing the type of view you're using and overridding either onSizeChanged(), onLayout(), or onMeasure()
Using a ViewTreeObserver and addOnGlobalLayoutListener()

Each of them seem to work in some cases, while in other cases people say something doesn't work correctly. Since there isn't a setOnDimensionsKnown(OnDimensionsKnown odk) or similar method for the View class, which of these methods (or possibly one not mentioned) will give me the dimensions my view will eventually have, regardless if it's drawn yet, has wrap_content or fill_parent parameters, or it has explicit height and width set in px, dp, or similar?
EDIT: Perhaps a specific example would be helpful, I'm trying to make a PopupWindow wrap it's contents, and to be offset in the -x direction by the value of it's width. The problem is that the contents width, and thus the popupwindows width, are not measured until after I show the popup. So basically I can't think of a good way to measure the width it will be before it is drawn to screen.
My usual approach is to override whatever view class I need the dimensions of before it being drawn, and create my own setOnDimensionsKnown(OnDimensionsKnown odk) method and fire it with the width and height values that onMeasure is called with. This works it every case I've needed, but it doesn't seem very elegant to override every view class to do this.
I can post code to help explain the example more.
Answer: Good way of doing it is adding an OnGlobalLayoutListener() to the view, as stated in this answer (point 3 in your question, in my opinion that's the most reliable for any View). The way I do it for a PopupWindow is to inflate it's layout and then call measure on it:
popupView = getActivity().getLayoutInflater().inflate(R.layout.popup_layout, null);
popup = new PopupWindow(popupView, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, true);
popupView.measure(view.getMeasuredWidth(), view.getMeasuredHeight()); //the view is parent's layout (not sure if those are correct values, but it measures okay in my case)

and then just get the numbers by calling popupView.getMeasuredHeight() and .getMeasuredWitdh().
Your problem is probably long gone by now, but hopefully someone else will stumble upon this and find it helpful. :)


C++ Builder XE2: Resource compile "Allocate failed"

Question: I have a resource script in my C++ Builder project. It has been the same for the last 6 years and never complained in compile.
Today suddenly I get "resource.rc(4):Allocate failed" everytime I try to compile. I have tried to reastart and do a clean. Still the same error. This is my resource script:
//-------------------------------------------------------------------
// DOCUMENT ICONS
//
IDI_DOCUMENT0   ICON      "Documents\\Pictures\\IDI_APPLICATION.ico"
IDI_DOCUMENT1   ICON      "Documents\\Pictures\\IDI_DOCUMENT2.ico"
IDI_DOCUMENT2   ICON      "Documents\\Pictures\\IDI_DOCUMENT3.ico"

//-------------------------------------------------------------------
// CUSTOM CURSORS
//
IDC_DELETE   CURSOR     "Documents\\Pictures\\IDC_DELETE.cur"
IDC_ADD      CURSOR     "Documents\\Pictures\\IDC_ADD.cur"
IDC_MOVE     CURSOR     "Documents\\Pictures\\IDC_MOVE.cur"

It fails on the first item IDI_APPLICATION.ico and if I remove it it compiles. This is strange because it has not been changed in 6 years and now suddenly it will not compile. This particular icon file's size is 201KB the other two are 158KB each and the 3 cursors are 8KB each. When you add all upp it looks like it passes the magical boundary 512KB, but hey, a resource section can be much larger than that?
Answer: I found out what the problem was. It seems like C++ Builder XE2 doesn't support compressed 256x256 icons (have not found this confirmed anywhere). When I regenerated the icons without compression, it compiles again.
I have no idea why this suddenly happen, but I'm not surprised. Ever since Embarcadero took over C++ Builder the quality has been on a steady down slope...
Answer: I used RC.EXE (the Windows SDK resource compiler) which can be set on the project resources options and it did the job.


If $A^4=4A^2$ then $m_A(x)=x^2-4$ and if it isn't diagonalaziable over $\mathbb R$ then $0$ is an eigenvalue

Question:
Given $A_{n\times n} \in \mathbb R$ such that $A^4=4A^2$ then

if $A$ is invertible and isn't of the form $cI, c\in \mathbb R$ then $m_A(x)=x^2-4$.

if $A$ isn't diagonalizable over  $\mathbb R$ then $0$ is an eigenvalue of $A$.

From the given we get $x^2(x-2)(x+2)=0$ zero $A$ so the eigenvalues of $A$ are from $\{0,2,-2\}$ (btw, are all of them have to be from this set?).

since $A$ is invertible then it's hard to find a counter example that won't allow to lose the $x^2$ from $x^2(x-2)(x+2)=0$ , is there a theorem that say that if $A$ is invertible then $A^2\neq0$?

here we can tell that the equation $|A-xI|=0$ doesn't have a real solution since it isn't diagonalizable over  $\mathbb R$, but $0\in \mathbb R$ so how can this be?
Comment: If $A$ is invertible (and $n>0$) then it obviously cannot also be nilpotent (as in $A^2=0$) since $(A^{-1})^kA^k=A^0=I$; you don't need a theorem for that.
Answer: The minimal polynomial of $A$ divides $x^4 - 4x^2 = x^2(x-2)(x+2)$ and the characteristic polynomial and the minimal polynomial have the same irreducible factors (possibly with different multiplicities), so a priori, you can only tell that the possible eigenvalues are $0,\pm 2$ and not necessarily all must occur (for example, the matrix $A = cI$ where $c \in \{ 0, 2, -2 \}$ satisfies the polynomial equation but has $c$ as the only eigenvalue).

If $A$ is invertible, then $0$ can't be an eigenvalue of $A$. Thus, by the result mentioned above, the only possibilities for the minimal polynomial of $A$ are $x-2$, $x + 2$ and $x^2 - 4$. Since $A$ is not a scalar matrix, we must have $m_A(x) = x^2 - 4$.
If $0$ is not an eigenvalue of $A$, then the minimal polynomial of $A$ must divide $(x-2)(x+2)$ and thus splits into distinct linear factors which implies that $A$ is diagonalizable.
Answer: You are given that $A^2(A^2-4)=0$. Now

If $A$ is invertible, multiply by $A^{-2}$ to get $A^2-4=0$; if in addition it is given that $A$ is not a scalar matrix, its minimal polynomial has degree${}>1$, so must be $X^2-4$.
Here we remark that $X^2(X^2-4)=X^2(X+2)(X-2)$ splits over$~\Bbb R$. If $A$ were annihilated by a spilt polynomial without repeated factors, then $A$ would be diagonalisable. Since it is given that this is not the case, and $X$ is the only repeated factor in the annihilating polynomial $X^2(X^2-4)$, it must be that $X^2$ divides the minimal polynomial, which in particular implies that $0$ is an eigenvalue of $A$ (and even that $0$ is a double root of the minimal polynomial).


LogSine Integrals $\int_0^{\pi/3}\theta \ln^2\big(2\sin\frac{\theta}{2}\big)d\theta$.

Question: Hi this will soon end my posts on Log Sine integrals, and we can progress into other classes of integrals.
Given the generalized log sine integral,
$$\rm{Ls}_n^{(k)}(\sigma) = -\int_0^{\sigma}\theta^k \Big(\ln\big(2\sin\tfrac{\theta}{2}\big)\Big)^{n-1-k}\,d\theta$$
The log sine integral I am trying to calculate is given by $k=1$, $n=4$,
$$
\rm{Ls}_4^{(1)}\big(\tfrac{\pi}{3}\big)=-\int_0^{\pi/3}\theta\, \ln^2\big(2\sin\tfrac{\theta}{2}\big)\,d\theta=-\,\frac{17\pi^4}{6480}.
$$
What a beautiful closed form!
This integral is known as one of many "Log Sine integrals at $\pi/3$."  It also seems that many people have not been responding to these log sine integral posts.  This is quite puzzling as these integrals are fundamental to mathematical analysis and are quite old..
If anybody wants literature on these integrals, please let me know.
I am not quite sure how to evaluate this.  Perhaps  a change of variables or logarithmic expansion may work.  Thanks for your help.
EDIT:  This is also of interest when discussing Mahler measures.  http://en.wikipedia.org/wiki/Mahler_measure
Comment: In the following answer,sos440 ends up evaluating that integral. His approach starts out similar to how I evaluated $ \int_{0}^{\pi /6} \log^{2}(2 \cos x) \ dx$, but then it deviates a bit. http://math.stackexchange.com/questions/402937/proof-of-sum-n-1-infty-frac1n4-binom2nn-frac17-pi43240/403105#403105
Comment: [Special Values of Generalized Log-sine Integrals](http://arxiv.org/pdf/1103.4298v1.pdf) by Borwein & Straub (2011).
Comment: Please keep comments polite and on-topic.
Comment: @RandomVariable As always, Thanks.
Comment: This particular result is also discussed in the paper cited by Marin.
Answer: Hint:
$$\int_0^\frac{\pi}{3}\theta\ln^2\left(2\sin\dfrac{\theta}{2}\right)d\theta$$
$$=\int_0^\frac{\pi}{3}\theta\ln^2\sqrt{2(1-\cos\theta)}~d\theta$$
$$=\int_0^\frac{\pi}{3}\dfrac{\theta}{4}\ln^2(2(1-\cos\theta))~d\theta$$
$$=\int_0^\frac{\pi}{3}\dfrac{\theta}{4}(\ln2+\ln(1-\cos\theta))^2~d\theta$$
$$=\int_0^\frac{\pi}{3}\dfrac{\theta}{4}(\ln^22+2\ln2\ln(1-\cos\theta)+\ln^2(1-\cos\theta))~d\theta$$


Solving the system $x^2+2y^2-y-2z=0$, $x^2-8y^2+10z-1=0$, $x^2-7yz=0$

Question: How to solve this system using elimination:
$$\begin{align}
x^2+2y^2-y-2z&=0 \\
x^2-8y^2+10z-1&=0 \\
x^2-7yz&=0
\end{align}$$
I feel like it should be easy but I have tried many different ways and cannot seem to solve for any of the variables.
If you take equation 3 and subtract equation 2 you end up getting
$8y^2-7yz-10z+1=0$ and using the quadratic I could solve for y with respect to z but it didn't get me any closer to solving the system.
Comment: Find $z$ in terms of $y$ in the equation you have gotten and then replace $z$ with it, to get an equation only in terms of $y.$
Answer: I actually think eliminating $x^2$ is the easiest first step, since $x$ only appears as $x^2$ and is not multiplied by any other variable.  So from the third equation, $x^2 = 7yz$, hence the first two equations become
$$\begin{align}
2y^2 - y + 7yz - 2z &= 0, \\
-8y^2 + 7yz + 10z - 1 &= 0. \end{align}$$  Then the next step is to observe that these equations are linear in $z$ but quadratic in $y$, so we collect like terms in $z$ and get
$$\begin{align}
(7y-2)z &= y - 2y^2, \\
(7y+10)z &= 8y^2 + 1. \end{align}$$
Therefore, $$(7y+10)(y - 2y^2) = (7y-2)(8y^2+1).$$  Now we have a cubic in $y$ that we can solve:
$$70y^3 - 3y^2 - 3y - 2 = 0.$$  Unfortunately, this cubic is not "nice," so the roots are very complicated to write out.  The unique real root is
$$y = \frac{1}{210} \left(3+\sqrt[3]{135162-945 \sqrt{20165}}+3 \sqrt[3]{5006+35
   \sqrt{20165}}\right) \approx 0.368933448565128\ldots,$$ which can then be substituted back into the earlier equations to get
$$z \approx 0.166015453844704, \\ x \approx \pm 0.654782847449611.$$  Substitution into the system verifies this result.  There are other solutions but they are complex-valued.
A visualization of the three equations in $\mathbb R^3$ is shown below.  The solution set is depicted as purple spheres (they're a bit hard to see but you can follow the surfaces and locate where all three mutually intersect).
Comment: @user607408 There are two complex-valued solutions for $y$, each of which admits a single complex-valued solution for $z$.  Since each $(y,z)$ pair yields two $x$ solutions, the total number of complex solutions is $4$.
Comment: Wow, thank you so much for that explanation. Is there any way to know how many complex solutions there are?


Can I be confident of my $R^2$ score?

Question: I have a dataset with 10 variables and 158 observations.
I used cross-validation, grid-search and ElasticNet algorithm.
To evaluate the model I checked the Pearson correlation between the 10 variables and known output. The correlation is not good, but the model $R^2$ score is near 0.98.
How can I be confident in my $R^2 $value? Because I didn't expect an $R^2$ like this. This is higher that I expected.
Comment: An $R^2$ so high is very unusual and you are right to be wary. Check the correlation between your explanatory variables and your dependent variable. If one of them is very high, investigate why this happens. Check Spearman's $\rho$ too. Please clarify what you mean by "*the correlation is not good.*". Also please consider presenting the model summary so we can have more information.
Answer: When you perform a regression on the ten variables, you are using all of them together to predict the outcome. Thus, each variable can, on its own, be a rather poor predictor that has fairly low correlation with the outcome. For instance, in the simulation below, I get an $R^2$ close to your value of $0.98$, yet the correlations between individual variables and the outcome are all around $0.3$.
<code>set.seed(2023)
N <- 158
p <- 10
X <- matrix(rnorm(N * p), N, p)
B <- rep(1, p)
Ey <- X %*% B
e <- rnorm(N, 0, 0.5)
y <- Ey + e
L <- lm(y ~ X)
cors <- rep(NA, p)
for (i in 1:p){
    cors[i] <- cor(X[, i], y)
    print(cors[i])
}
summary(L)$r.squared # I get almost 0.98
summary(cors) # Range from 0.236 to 0.38
</code>
While $R^2=0.98$ is suspiciously high for some fields, the goal of predictive modeling is to make accurate predictions. If you validate the performance (some kind of out-of-sample testing or bootstrap, perhaps a congratulations is in order for getting a model to reliably make such accurate predictions!
Comment: @whuber That is fair. Removed.
Comment: +1. For more insight, consider (approximately) orthonormal explanatory variables $X_1,\ldots, X_k$ and let $y = X_1+\cdots X_k + \varepsilon$ where $\varepsilon$ has a tiny variance. That ensures the regression of $y$ on the $X_j$ has (arbitrarily) high $R^2,$ while the individual correlation coefficients are $\operatorname{Cor}(y,X_j)\approx 1/\sqrt{k}.$ With $k=10,$ that gives plausibly "not good" correlations around $0.32.$ I believe that explains what your code is doing.
Comment: I think it's a little misleading to suggest a multiple regression where all the univariate regression coefficients are zero could have a large $R^2$ or even a nonzero $R^2.$ That observation relies on sometimes counting nonlinear combinations of the original variables among the explanatory features and sometimes not. The only meaningful comparison here would include *all* features. Another issue concerns your misleadingly large choice of $n:$ $10000$ is *hugely* greater than the $158$ reported in the question.
Comment: @whuber I do not see where I suggest anything about how the coefficients are zero. In this example, all of the coefficients are one. // I dropped the sample size to 158 and got pretty similar results of $R^2\approx 0.98$ and the individual correlations between $0.236$ and $0.380$, so slightly different but not alarmingly so.
Comment: "Coefficients are zero" is equivalent to zero pairwise correlations, which is the extreme case of "poor predictor."
Comment: @whuber Do you mean when I write about nonlinear basis functions?
Comment: What I find misleading is the assertion "the individual variables might have zero correlation with the outcome, yet the combination of the features and polynomial functions (or other nonlinear functions) might explain everything." It's correct but it's irrelevant because it introduces a procedure outside the scope of the question; namely, adjoining new features to the regression.

Can I be confident of my $R^2$ score?


Linux implementation similar to Adaptec Intelligent Hybrid RAID?

Question: I could explain it in my bad english, but looking at this page is the fastest way:
http://www.adaptec.com/en-us/_common/hybrid-raid/
Do you know of any linux implementation for this outstanding feature? (to be so able to use it without the adaptec controller?)
Answer: There is at least BCache kernel patch for the brave souls; I have no idea if it's maintained, though. Any better suggestions are gladly welcome.
+1 for interesting question!
Comment: I also thought that Facebook's flashcache (https://github.com/facebook/flashcache) could be suited for this, while not exactly what i was hoping to find.
Thanks for the +1 and the answer ;)


Let $n$ be an odd nine digit number divisible by $375$. How many $n$ exist such that the second to second-last digit are in an increasing order.

Question: So if $n=\overline {a_1a_2a_3a_4...a_9}$
$a_2\le a_3\le a_4\le a_5\le...\le a8$
$n=2k+1$
$n=375q$
I'm completely stumped. There's so many cases to look at. I don't know how to incorporate the criteria of being divisible by $375$ with the criteria of the increasing order of the  middle digits. I can find either of them, but I don't know how to combine them?
Comment: It's not a strictly increasing order.
Comment: 375=3*5^3 so you need digit sum divisible by 3 and also last four digits divisible by 125.
Comment: Is the latter the criteria for divisibility by 125?
Comment: John: Not quite. I should have said only the last 3 digits. Note that 1000=125*8 so only the last three digits are involved for divisibility by 125.
Comment: Ugh, I'm trying to solve it but I just don't get the right solution. So many cases to look at.
Comment: The number of cases is very small: If an odd number is divisible by $125$, it ends in $125$, $375$, $625$, or $875$.
Comment: Yes, I got that, but following on that, how do I decide the ways I can arrange the digits before $125$ and $375$?
Comment: I suspect the problem has not been described correctly. We are left with $125$ at the end or $375$. Neither works, since we can't avoid bigger digits to the left of the $1$ or the $3$.
Comment: Well, for example the $125$ forces the second to sixth to be all $0$'s, or $00001$,  and so on up to $11111$. Now apply the divisibility by $3$ condition in each case to decide on the first digit. The other one is a bit more messy.
Comment: John Doe -- I just added a better explanation of how to finish the count to my answer below. I wound up with 186 such $n$
Comment: That is indeed the correct answer. Thank you :)
Answer: The final three digits must form a number divisible by 125, and with the added requirement that for such a number $a,b,c$ we need $a \le b$ (the $c$ being the units digit of our number, so not affected) there are only the ending three digits 000, 125, 250, 375. The other multiples 500, 625, 750,875 all break the nondecreasing digit rule. Oops, yuu also need odd numbers, so only 125 and 375 qualify for endings.
For each of these it should then be relatively easy to find how many ways to pad it out to a nondecreasing sequence with sum 0 mod 3. For example with last digits 375 we need a decreasing sequence of length 6 all at least 3, and we have a final leading digit which has no requirement re. decreasing with the other digits.
We're in luck in a sense, since if the number is say hvwxyz375 then the digit sum without the h determines the high digit h mod 3, and also h cannot be 0 in a 9 digit number, so there are 3 choices each for the digit h, once it is known mod 3. For hvwxyz375 we can fill out the subsequence vwxyz using any digits from 0,1,2,3. The nondecreasing requirement then means we have for this subsequence say a 0,s, then b 1's, then c 2's, then d 3's where each of a,b,c,d is arbitrary nonnegative and a+b+c+d=5. The number of solutions to that is, using stars and bars, $\binom{5+3}{3}=56.$ Multiplying that by 3 for the choice of h then gives 168 values of $n$ ending with 375. A similar analysis for strings ending 125 gives another 18 values of $n$ So (if this is right) the total number of $n$ is $168+18=186.$
Comment: The number has to be odd as well. How do you calculate the amount of decreasing sequences? Additionally, the first digit doesn't have to be in decreasing order.
Comment: @JohnDoe Yes, just fixed my answer taking odd integers into account. There are counting formulas for nondecreasing sequences, I think looking up "stars and bars" gives some ways to do it.
Comment: I don't think stars and bars deal with this specific kind of questions.
Comment: One has to define the difference set. For example the nondecreasing sequence $2,5,5,6,8,9$ gives the internal difference sequence $(3,0,1,2,1)$ whose sum is 7, agreeing with $9-2.$


Binding data to the Listbox where ListBox has textblocks

Question: <ListBox Height="498" Margin="2,0,0,0" Name="listBox1" Width="879"  ItemsSource="{Binding}" >
   <ListBoxItem >
       <StackPanel Width="418" Orientation="Horizontal">
           <TextBlock Name="MedicineName" Text="Alamoxy"
                      FontWeight="Bold" FontSize="18"
                      Margin="5" Width="205" >
            </TextBlock>
            <TextBlock Name="ListBoxLetter" Text="Amoksilin"
                       FontSize="18" Margin="0" Width="255" Height="23">
            </TextBlock>
       </StackPanel>
    </ListBoxItem>
</ListBox>

I want to bind data to the listbox.
Textblock will show seprate fields. How i can do it?
please Help me about this/
Answer: Use an ItemTemplate to make it look something like this.
<ListBox Width="400" Margin="10" ItemsSource="{Binding myItems}">
   <ListBox.ItemTemplate>
     <DataTemplate>
       <StackPanel>
         <TextBlock Text="{Binding Path=MedicineName}" />
         <TextBlock Text="{Binding Path=ListBoxLetter}"/>
       </StackPanel>
     </DataTemplate>
   </ListBox.ItemTemplate>
 </ListBox>


Non-normally distributed data - Box-Cox transformation?

Question: I have data that is not normally distributed. The problem seems to be that there are too many of one value relative to other values.
What I have tried to make data normal:

I have tried a log transformation, with adding a 1 to all values (i.e., the relatively frequent values are 0's and I understand one cannot perform a log transformation on values with 0's) but this did not fix the data and did not change the Shapiro-Wilk significance from p<.001 even slightly.
I also read that ANOVA does not need the dependent variable to be normally distributed but only for residuals to be normally distributed. However, residuals were still significantly different to each other as shown by another Shapiro-Wilk test.

Could a Box-Cox transformation make data normally distributed?

One source (page 27) suggests that using a Box-Cox transformation is another possible solution after the log transformation has not worked. However, the problems is that I am aware this function for a Box-Cox transformation is not available on SPSS.
I have not found a working syntax for this transformation, I am not familiar with R which I understand can perform the Box-Cox transformation and I have a deadline to submit my report by meaning I do not have time to get familiar with R, and I am not in a position to purchase Excel statistical software packages.

The data

It might be useful to add a histogram of the data to get a good idea of what it is like which is below.

It is a repeated measure design where each participant had what is referred to in the histograms as low and high load conditions.
As predicted by our hypothesis the high load condition should lead to none to very few "images" (i.e., intrusions) and so the data support our hypothesis. Therefore, it seems strange that data which is expected to act in a certain way is problematic in terms of it's normality because in some cases it's expected to be not normal.
Perhaps I am misunderstanding something though or carried out an incorrect test so if so then it would be good to know.

Why not do nonparametric analyses?

I prefer to carry out parametric tests and hence why I want to make the data normally distributed; this might be an incorrect view, but from reading many articles I very rarely see papers which use nonparametric analyses when reported data.
Only if the data I have seem as if it is not possible to turn it into parametric data then I will have to use a nonparametric test but first I want to try the choices out there of transforming the data.

Questions
1) Is it a good idea to use a Box-Cox transformation to try fix the data, or other there better ideas that I haven't tried?
2) If a Box-Cox transformation is in fact a good idea to try out, are there any suggestions of how I could do this (e.g., whether it is information about SPSS syntax, an Excel formula etc.)?
Information from answers:

This is count data
It has a Poisson distribution and so an analysis with such a distribution would be ideal
There are many zeroes in the data with a small range (i.e., values from 0 to 4)
Good links are provided in the comments below by Scortchi for more information about transforming non-negative data with zeros, a test for significant difference between two repeated measures count variables, regression models for count data when counts are often zero, and using Poisson Repeated Measures ANOVA.
The Poisson RM ANOVA has very good information on the idea and theory behind using such a distribution for count, non-parametric data with many zeroes.
As my next step was to get an understanding of the specific area of carrying out a Poisson distribution analysis in SPSS for repeated measures data, I have asked a new question here.
Although the aim will be to carry out an analysis using a Poisson distribution, according to one source (half way through page, under Reason 6: Data Follows a Different Distribution) it seems that the data will still remain nonparametric.

(If however I should not have asked a separate but related question as I did please let me know and I will change this - I'm new so I'm still getting a feel for the conventions for posting here but I'm happy to learn and get feedback on how I post to make it clearer for all.)
Comment: In that case [significance of difference between two counts](http://stats.stackexchange.com/q/155307/17230) &
[Regression model for proportion or count when counts of outcome and total events are often zero](http://stats.stackexchange.com/q/88588/17230) are more relevant. [You should now have the necessary reputation to add the links - please also add that the data are counts (that'll save people from having to trawl the comments for that important information).]
Comment: I missed that you had a repeated-measures design: see [Poisson Repeated Measures ANOVA](http://stats.stackexchange.com/q/57859/17230). I've added the `repeated-measures` & `count-data` tags to the question, as these are key points.
Comment: You can't transform Poisson data into normal by Box-Cox or Log transform.
Comment: Are your data *counts*? No transformation's going to make counts between 0 & 4 look very much like they came from a normal distribution. Even if they're not, having exact zeros suggests you might have trouble using a continuous distribution to model them - see [How should I transform non-negative data including zeros?](http://stats.stackexchange.com/q/1444/17230).
Comment: Not necessarily everything in the comments (you want to be concise), but info. essential to answering the question - e.g that it's count data.
Answer: The data are highly skewed & take just a few discrete values: the within-pair differences must consist of predominantly noughts & ones; no transformation will make them look much like normal variates. This is typical of count data where counts are fairly low.
If you assume that counts for each individual $j$ follow a different Poisson distribution, & that the change from low to high load condition has the same multiplicative effect on the rate parameter of each, you can extend the idea in significance of difference between two counts to a matched-pair design by conditioning on the total count for each pair, $n_j$:
$ \sum_{j=1}^m X_{1j} \sim \mathrm{Bin} (\sum_{j=1}^n n_j, \theta)$
where $m$ is the no. pairs. So the analysis reduces to inference about the Bernoulli parameter in a binomial experiment— 7 "successes" out of 24 trials if I read your graphs right.
Check the homogeneity of proportions across pairs—& note if they're too homogeneous it might indicate underdispersion (relative to a Poisson) of the original count variables.
Note that this approach is equivalent to the generalized linear model suggested for Poisson Repeated Measures ANOVA†: while it tells you nothing about the nuisance parameters, point & interval estimates for the parameter of interest can be worked out on the back of a fag packet (so you don't need to worry about software requirements).
† Parametrize your model with the log odds $\zeta=\log_\mathrm{e} \frac{\theta}{1-\theta}$: then the maximum-likelihood estimator is $$\hat\zeta=\log_\mathrm{e}\frac{\sum x_{1j}}{\sum n_j - \sum x_{1j}}=\log_\mathrm{e}\frac{7}{24-7}\approx  -0.887$$ with standard error $$\sqrt\frac{\sum n_j}{\sum x_{1j}(\sum n_j-\sum x_{1j})}=\sqrt\frac{24}{7\cdot(24-7)}\approx 0.449$$ for Wald tests & confidence intervals. If you want to adjust for over-/under-dispersion (i.e. use "quasi-Poisson" regression) , estimate the dispersion parameter as Pearson's chi-squared statistic (for association) divided by its degrees of freedom (22) & multiply the standard error by its square root.
Comment: You might want to hold off on accepting for a while (in general - in this case unaccept) to encourage more answers & see some different options. Also I intend to expand this - when I get time - to discuss diagnostics & assumptions.
Comment: Right okay! My bad, I've unaccepted now. I have just asked [a follow-up question of how to do the analysis](http://stats.stackexchange.com/questions/166538/poisson-distribution-analysis-in-spss-nonparametric-count-repeated-measures). Do you think it would be a good idea for me to remove this separate post, to combine it into this post or to just wait, for yourself and others, to expand on this post?
Comment: I feel I understand the idea behind using a Poisson distribution for my data. Finally, I want to make sure I'm clear of the next step to take. So in terms of the analysis I am doing now am I correct in understanding I would want to do a multilevel or mixed model analysis as this would allow me to analyse the two dependent variables I have and to use a Poisson distribution? Also, as a point I forgot to clarify, I will be treating the data as a nominal rather than ordinal? My bad that I still need to clarify this point though I'm finding this really interesting and am doing my best to understand


angular-daterangepicker.js - Include in ranges list options "Single Date" option

Question: I'm trying to create a new option similar with "Custom Range" option but to offer the possibility to choose only one date(like "Single Date Picke"r). So, this will make it full option and will cover all what I need. In other words, a new option under "Custom Range", named like "Single Date" will offer the possibility to show up one calendar in order to pick a date. This scenario can be done also using "Custom Range" but my requirements are to make this flow using only one calendar.
Please, knows someone a quick way to handle this feature? Thank you!
Answer: I accomplished something similar.
A calendar directive that accepts multiple scope parameters.
showRange=boolean,
fromDate=dateObject,
toDate=dateObject

If the directive receives true for showRange an ng-show is triggered on a button that will display a date range when clicked.
In my calendar-directive, I have the HTML built out for both a single and range picker.
This way, if you are using the calendar directive in many areas, you can decide whether or not to show the show-range button by passing a boolean to the directive.
Comment: The only recommendation I would have if you take this route is to use ngIf instead of ngShow.  The difference being that ngIf conditionally adds and removes elements to/from the DOM, whereas ngShow adds both and conditionally shows/hides them via css.
Comment: I agree with @jme11, you don't need to write the button to the DOM.


Equation of a line parallel to $5x-3y=7$ That goes through the point (3,-1)

Question: This is a study question in preparation for my midterm. It's multiple choice. The answers are:
A) $y=(5/3)x-(7/3)$
B) $y=(3/5)x-(14/5)$
C) $y=(5/3)x-6$
D) $y=-(3/5)x+(4/5)$
Here is my process:
$5x-3y=7$
Move the 3x over and change the sign.
$5x=3y+7$
Move the 7 over and switch it to negative.
$3y=5x-7$
Divide entire formula by 3.
$y=(5x/3)-(7/3)$
Which is answer A), so I know that answer A is not correct, since this is not a parallel line, it is the same line.
Now I use the point slope equation:
$y-y_1=(5(x-x_1))/3$
$y+1=(5(x-3))/3$
$y=(5x-15-1)/3$
$y=(5x-16)/3$
So I know only (C) can be the correfct answer, since it has the same slope as the original equation, but my y intercept is off in my equation. I would appreciate some help as to how to arrive at the $-6$ in answer C.
Also, I don't know how to create fractions on this forum, any correction of my equations for clarification would be appreciated.
Comment: -15-3=-18 not -14.  That's where you made an arithmetic error.
Answer: You multiplied $5$ times $3$ and got $14$.  It should be $15$.  Then you need to bring the $1$ from $y+1$ over.
Comment: I simply skipped a step, I'll add it to my question if it clarifies things.
Comment: Just seeing now that it should have been $-16$ not $-14$
Comment: @user2435 You have to subtract the $1$ after you distribute the $\frac{5}{3}$.  So, multiply $-3$ by $5$ to get $-15$.  Then divide by three to get $-5$.  Then subtract $1$ to get $-1$.
Answer: You just made an arithmetic error trying to do two things at once. $$y=\frac{5(x-3)}3-1=\frac{5x-15}{3}-1=\frac53x-5-1=\frac53x-6$$
Comment: Oh I see, this makes more sense, thank you.
Answer: The line in question has the same slope as yours since they are parallel, so the slope $m=5/3$. Using the point-slope equation of the line we obtain $y+1=(5/3)(x-3)$, or $y=(5/3)x-6$.


Using multiple datasources with Wildfly

Question: I am using multiple datasources in my java web-application.
Here is Wildfly configuration (standalone mode):
<datasource jta="false" jndi-name="java:jboss/datasources/DS1" pool-name="DS1" enabled="true" use-ccm="false">
   <connection-url>URL1</connection-url>
   <driver>ojdbc7</driver>
   <security>
        <user-name>login</user-name>
        <password>password</password>
   </security>
   <validation>
        <validate-on-match>false</validate-on-match>
        <background-validation>false</background-validation>
   </validation>
   <statement>
        <share-prepared-statements>false</share-prepared-statements>
   </statement>
</datasource>

<datasource jta="false" jndi-name="java:jboss/datasources/DS2" pool-name="DS2" enabled="true" use-ccm="false">
   <connection-url>URL2</connection-url>
   <driver-class>org.h2.Driver</driver-class>
   <driver>h2</driver>
   <security>
        <user-name>sa</user-name>
        <password>sa</password>
   </security>
   <validation>
        <validate-on-match>false</validate-on-match>
        <background-validation>false</background-validation>
   </validation>
   <statement>
         <share-prepared-statements>false</share-prepared-statements>
   </statement>

Jboss.xml in my ejb subproject:
<session>
    <ejb-name>Bean1</ejb-name>
    <resource-description>
        <res-ref-name>DS1</res-ref-name>
        <jndi-name>java:jboss/datasources/DS1</jndi-name>
    </resource-description>
</session>
<session>
    <ejb-name>Bean2</ejb-name>
    <resource-description>
        <res-ref-name>DS2</res-ref-name>
        <jndi-name>java:jboss/datasources/DS2</jndi-name>
    </resource-description>
</session>

In EJB Bean1/Bean2 datasources are called via
@Resource(name="DS1/DS2")
private DataSource dataSource;

....

Connection connection = dataSource.getConnection();

Using shown configuration I have faced following problems :

I can access datasource only if it is set as a default in <default-bindings> section of my standalone-full.xml. If it is empty, I get
"JBAS014771: Services with missing/unavailable dependencies"

pointing to the list of datasources used in beans during deployment.

If I set DS1 as a default one, next time DS2 is injected, it will contain
LocalManagedConnectionFactory

pointing to DS1 in dataSource.mcf variable
As I've understood from this topic
Why different persistence units with separated data sources query the same data source?
this problem may be caused by container-managed persistance.
But in given case I am not using any ORM. So I am only able to manipulate datasources using jndi and server configuration.
So is there any way I can resolve this situation by using some additional wildfly configuration / any manipulations with application or I have to use ORM and manage persistance by myself ?
Thanks for replies.
Answer: it's recommended to use an ORM (JPA in best case), so you will use entityManager and persitence.xml for using multiple data sources.
 <persistence-unit name="DB1_PU">
    <jta-data-source>java:jboss/datasources/ds1</jta-data-source>
</persistence-unit>
<persistence-unit name="DB2_PU">
    <jta-data-source>java:jboss/datasources/ds2</jta-data-source>
</persistence-unit>

and you can call the DS like :
@PersistenceContext(unitName = "DB1_PU")
protected EntityManager entityManager1;

@PersistenceContext(unitName = "DB2_PU")
protected EntityManager entityManager2;

Comment: you have an typo: persitence.xml -> persi**s**tence.xml

Using multiple datasources with Wildfly


Failure to Compile HTMLCollectionOf

Question: I'm writing an eCommerce app, so I have a popup for user when clicks add to cart which allows user to select the variety and quantity of the product user want to add. The popup includes a select form and a number input. I then have to access what was input into these to show the appropriate information in the cart.
I tried to access the information using:
let input = (<HTMLInputElement>document.getElementsByClassName('number_input'));

But that gives this error:

ERROR in src/app/layout/products/products.component.ts(93,18): error TS2352: Type 'HTMLCollectionOf' cannot be converted to type 'HTMLInputElement'.
    Property 'accept' is missing in type 'HTMLCollectionOf'.
  src/app/layout/products/products.component.ts(111,14): error TS2352: Type 'HTMLCollectionOf' cannot be converted to type 'HTMLInputElement'.

Failed to compile
Visual Studio recommended that I include unknown in addition to HTMLInputElement to access the information, so I tried:
let input = (<HTMLInputElement><unknown>document.getElementsByClassName('number_input'));

But that gives this error:

ERROR in src/app/layout/products/products.component.ts(91,37): error TS2304: Cannot find name 'unknown'.
  src/app/layout/products/products.component.ts(109,33): error TS2304: Cannot find name 'unknown'.

This is the code for my inputs. It utilizes a modal from bootstrap

AGREGAR {{ bebida.descripcion }}

              Variaded:
                <select class="form-control" id="variadedes">
                    <option *ngFor="let detalle of detalle_bebida">{{detalle.variedad}}</option>
              </select>

Cantidad: <input type="number" name="cantidad" min="1" style="width: 70px;" class="number_input" value="1">

        <button type="button" class="btn btn-secondary" data-dismiss="modal">CERRAR</button>
        <button type="button" class="btn btn-primary" (click)="onModalAgregarClick($event)" data-dismiss="modal">AGREGAR</button>

I want to be able to access the data without any errors so I can compile the app to run.
Comment: Did you try ``?
Comment: If you are using Angular, You should use [(ngModel)] instead of trying to access the DOM element.
Comment: Since `getElementsByClassName()` can give you a list of DOM elements,  you can typecast it to ``. If you want to process each element individually, you can use ``.
Comment: `` gives this error: Type 'HTMLCollectionOf' cannot be converted to type 'HTMLInputElement[]'.
  Property 'includes' is missing in type 'HTMLCollectionOf'

And Typecasting to `` is what I tried above that gave me the original error.

Any other ideas? I'm going to look into `[(ngModel)]` right now
Answer: You are getting a compilation error because you are trying to cast an HTMLCollection to an HTMLElement.
Your call to document.getElementsByClassName() does not return an HtmlElement, it returns an HTMLCollection. Here's some helpful documentation from Mozilla on this function. You'll need to update your cast and then access the first element of the collection, if it even exists.
let numberInputs: HTMLCollection = document.getElementsByClassName('number_input');
let firstNumberInput: HTMLSelectElement = numberInputs[0];
console.log(firstNumberInput.value);

That being said, when working with Angular it's strongly recommended to use directives in this case. I would instead use the [(ngModel)] directive or build a reactive form to access the value of the inputs.
Comment: I know that it's a Collection, but I thought you could cast it as `HTMLInputElement` to access the inputs. I was following this github article [link](https://github.com/Microsoft/TypeScript/issues/10453)

The mozilla link talks about accessing the individual elements, but when I do that I get property 'value' does not exist on typle element
`let input = (document.getElementsByClassName('number_input'));
    cantidad = input[0].value;
`
Comment: using `[(ngModel)]` was an effective fix. Thanks!

Failure to Compile HTMLCollectionOf


Unable to create a breakpoint in Eclipse and Tomcat

Question: Since yesterday, I get a strange error message when I start my Tomcat (6.0.35) under Eclipse Juno (build 20120614-1722):

Among the things I tried in order to get rid of the error:

Check in Preferences -> Java -> Compiler if all "Classfile Generation" checkboxes where checked. I did that for both general preferences and project preference
Uncheck them, build, check them build again (found on another question)
Add org.eclipse.jdt.core.compiler.debug.lineNumber=generate to my .settings/org.eclipse.jdt.core.prefs file
Use a new CVS checkout (same symptoms)

And now, I don't know what to do anymore. The problem is really stopping me from get anything done. I can't work anymore.
Crazy is: the problem doesn't happen on every class, only on some of them. Neither does it happen on my other Eclipse projects. And it didn't happen before yesterday, even if I can't remeber having done anything weird. Actually, I have never seen a problem like this in almost 10 years I'm using Eclipse...
If you have any idea, I would be really grateful...
Edit:
I also tried to ignore the message and go on with my tests: If I create another breakpoint upstream from my problematic class, when I enter this problematic class, it tries to open a $Proxy132 class, which means it actually opens an empty page, with a source not found message
Comment: Take a look at this  [SO][1] response to see if it helps

  [1]: http://stackoverflow.com/questions/8195091/i-cant-debug-using-breakpoints
Comment: I didn't say it in the question, but I also tried to ignore the message and go on with my tests: If I create another breakpoint upstream from my problematic class, when I enter this problematic class, it tries to open a $Proxy132 class, which means it actually opens an empty page, with a "source not found" message. I will change my question in order to reflect this info.
Comment: @Traroth is the code that is getting deployed on the server compiled through Eclipse or through a build tool such as Ant/Maven
Comment: I currently compile it with Eclipse. I also have a pom.xml, but I'm not using it currently.
Comment: Could you try doing a `mvn install` and use that jar for deployment instead of the eclipse one. This is so that, we can eliminate the case that it is an issue with the Eclipse compiler.
Comment: I guess it might be late already but, how about: running "mvn clean" and making sure that all .class / target folder contents are deleted before building again?
Comment: I tried it and it didn't solve the issue. What I did in the end is install new instances of Eclipse and Tomcat, which was painful, but at least I was able to work again. Actually, a new install of Eclipse didn't solve the issue, but using a fresh install of Tomcat did the trick, so the issue must be somehow Tomcat-related...
Answer: Whenever I would see this kind of message in Eclipse Helios it was because the compile step (Ant in my case) was not set to include debug information.  When using Ant, we had a build.xml file that had a flag stating debug="true".  This would be just a higher-level way of setting the "-g" parameter to javac.  Once I set my debug flag to "true", the "-g" option would be sent to the compiler and the source code would build with line number information included.  This had to be done on all Java files, so if you have modules that aren't compiled automatically as part of a bigger Java process, you will need to make sure those flags get sent to the compiler in those modules as well.  Basically, everywhere you need to debug has to have the "-g" flag set when compiling it.  Hope this helps.


Non-independence in data and GLMMs

Question: I am working with a dataset that consists of categorical variables and count data. My response variable is DPM SpeciesA (detection positive minutes of Species A, where for each hour I have a count of how many minutes species A was vocalizing), and my predictors are Season, Time of day (classified as "Morning", "Evening", "Night" and "Day"), Tidal cycle ("High tide", "Ebbing tide"...) and DPM SpeciesB.
I am wondering how to account for the non-independence in my data. Because the vocalizations of Species A are being recorded, but we have no way of knowing which individual is vocalizing, there is non-independence since the same individual may be vocalizing for multiple minutes, or different individuals, and each hour it could be the same individuals, or different individuals.
So my question is, is it not possible to use GLMs in this case because of the non-independence? And if it is not possible, then how could I account for the non-independence in a mixed model? I don't understand how to incorporate any dependency into the model because I can't add the ID of the individual as a random factor, since we never know which individual is being counted.
Thanks for your help everyone!
Edit: I have now included some plots that I have made to try to determine whether violating independence would be a problem (at least in terms of temporal autocorrelation) in a quasipoisson GLM for this data. These are Acf, Residuals vs Index and a residuals lag plot. But I am not very experienced interpreting these plots! To me it looks like there is no particular problem with the residuals vs index (except that everything is above zero, not sure if there should also be negatives) but the Acf and Residuals lag both seem to have a pattern.
Answer: Welcome to the site, roc. It may be possible to employ a mixed modeling framework to your data. How many different species did you record? If there are 10-15 or more, then you could have the grouping variable be species. This would indicate that you believe that vocalization frequency is more correlated within species than it is across different species. That being said, this doesn't really solve the problem you identified about individual members of the species. That is not something you can deal with given your data. You would have to use some sort of machine learning algorithm to try to identify individuals within species, and I'm not sure that would work (it might, I just don't know much about that).
However, if you only have two species (you mention SpeciesA and SpeciesB), then you are in a more difficult position. Since you cannot identify individuals within SpeciesA and SpeciesB, you cannot account for the likely fact that some members of the Species will be more likely to repeatedly call. Is it correct to assume that you want to have a predictor for SpeciesB in the model for SpeciesA vocalizations? Or were you just saying you wanted to generate the same model for each species?
If you have multiple species, there are many different R packages for doing this type of analysis with your count outcome, including glmer() in lme4, glmmTMB() and GLMMadaptive.
Comment: Hi @ErikRuzek, thanks for your suggestions! I want to use mixed modelling but the problem is, I don't know how to do the grouping. The main thing I am concerned about is violating independence with temporal autocorrelation or with the same individuals vocalizing over and over. I am only looking at two species - however, including SpeciesB in the model is not essential, it is just a predictor variable I am interested in.
My struggle is when I am looking at mixed models, they would add a random factor such as Site ID or Individual ID but in this case I only have the variables mentioned.
Comment: Did you measure vocalizations at different sites? You could look at whether vocalization frequency is correlated within sites. But the bigger problem is that you have no way to determine if the same or different individual is vocalizing. That means that a mixed model doesn't make a lot of sense. Unless, as noted earlier, you have many sites and vocalization patterns are correlated within site.
Comment: no, the model will only be for one site. Do you have any suggestions for other types of models or, looking at the plots I have made, whether they suggest there is actually a violation of independence? To me it seems as though the residuals vs index shows no pattern, but the ACF has a big spike near 0.
Comment: or would it be possible to add Time as a random factor?
Comment: Can you add the exact syntax of the model you are running in your original post? Are you using an offset in what I am assuming is a Poisson model? You may also consider a negative binomial count model. I would compare these same plots between the Poisson and negative binomial models. You can also run a likelihood ratio test comparing the two models as the negative binomial has an additional parameter to deal with overdispersion (a gamma-distributed random effect).
Comment: I am using a syntax like so: FullDPM.nb1 <- glm.nb(SpeciesA_DPM ~ Diel+Tidal_cycle*Tidal_phase*Season*DPMSpeciesB), but I have also tried this using Presence/Absence (0s and 1s) instead of the minute counts. I have tried FullDPMglm <- glm(SpeciesA_DPM ~ Diel + Tidal_cycle*Tidal_phase*Season*DPMSpeciesB, poisson) and quasipoisson as well.

Non-independence in data and GLMMs