Understanding what is function overloading concept while using the pow function

Question: I'm recently introduced in the programming world and the C language.
I've encountered a trouble understanding the following concept when I tried to
utilize the pow function from the math.h library, in order to do some calculations in my code.
While I passed as parameters to the pow function the two variables, x and i, both declared as integers, I got an Error from my IDE(Visual Studio 2012) stating
: "more than one instance of overloaded function "pow" matches the argument list" :
Function "pow(double _X, int _Y)"
Function "pow(float _X , int _Y)"
Function "pow(float _X , int _Y)"
Function "pow(long double _X, int _Y)"

Argument types are ( int, int ).

I know that the pow function returns a double value but what happens, let's say when you need to work only with integers ? Why is it not possible to store the return value of the function to a declared variable as a double and having two integers as parameters?
Searching Wikipedia ,when I couldn't find anything relevant here in Stack Overflow, the only given definition for function overloading is the following one:
"Function overloading or method overloading is a feature found in various programming languages such as Ada, C++, C#, D, and Java, that allows creating several methods with the same name which differ from each other in the type of the input and the output of the function. It is simply defined as the ability of one function to perform different tasks. "
What is function overloading exactly and how it affects the behavior of this particular function that I try to implement ?
Sorry in advance if the question is too trivial or answered, or I'm missing an obvious piece of the puzzle .
Comment: There is no function overloading in C.
Comment: Starting from C99 there is tgmath which is implemented by so-called type generic macros which are similar to function overloading but implemented with different rules.  http://pubs.opengroup.org/onlinepubs/009696699/basedefs/tgmath.h.html  That said, I think the OP is probably compiling with C++ mode rather than C mode
Answer: You are using a C++ compiler, there is no function overloading in (classic) C.
There, we have different functions for those cases (see the manual page here):

double pow(double x, double y);
float powf(float x, float y);
long double powl(long double x, long double y);

So it's always clear from the function name what the types involved are.
Since the C99 version of C, you can use generics to implement this, and it's already done in the <tgmath.h> header. This header gives you a function pow() which uses overloading.
It's pretty clear from your error output that you don't have such a C compiler, though.
Comment: Maybe mention how to do a C compile in VS12?
Answer: No function overloading in C.
The only overloading in C is operator overloading in the compiler (int + int , float + float, & as adress-of, & as bitwise-and, * as pointer-to, * as multipy...).
Answer: You can't overload a function. But if you are using double, int, short, long, float you can do a single function and pass casted argument.
double  pow(double, double);

int a;
int b;

int c = (int)pow((double)a, (double)b);

You have to take the largest type possible. it's a simple trick with the compiler.


Ideal of factor ring

Question: Let $J$ is ideal of $R={\Bbb Z_{5}[x]/}{\langle f(x)\rangle }$
Prove that there exists $g(x)$ such that $J={\langle g(x)\rangle/}{\langle f(x)\rangle}$ and $\langle f(x)\rangle \subseteq \langle g(x)\rangle $
Proof:
Let $\Phi$ be the map on $\Bbb{Z}_{5}[x]$ defined by $\Phi(g(x))=g(x)+\langle f(x)\rangle$, then $\Phi$ is onto and ring homomorphism.
Suppose $J$ is ideal of $R$, then $\Phi^{-1}(J)$ is ideal of $\Bbb Z_{5}[x]$
so there exists $h(x)$ such that $\Phi^{-1}(J)=\langle h(x)\rangle$.
Since $\Phi$ is onto, $J=\Phi(\Phi^{-1}(J))=\Phi(\langle h(x)\rangle)$
My question:
How to show $\Phi(\langle h(x)\rangle)={\langle h(x)\rangle/}{\langle f(x)\rangle}$ and $\langle f(x)\rangle\subseteq\langle h(x)\rangle$ ?
Comment: sorry. I'm not used to Mathjax yet. I just fixed it
Comment: No problem, it looks pretty ok now.
Answer: To answer your question, to see that $(f)\subseteq (h)$, note that $f\in\Phi^{-1}(J)$, since $\Phi(f)=0\in J$, so $f\in (h)$, which implies that $(f)\subseteq (h)$.
As for your other question, since $\Phi:\Bbb{F}_5[x]\to \Bbb{F}_5[x]/(f)$ is the quotient map, $\Phi((h))=(h)/(f)$, pretty much by definition of $(h)/(f)$. You'd have to be a bit more clear about what's confusing you here for me to know how to explain this further.
Comment: oh thanks to you, I understand

Ideal of factor ring


Does hibernate has some internal "commit id"?

Question: @file:Suppress("DuplicatedCode")

package test

import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
import org.springframework.data.repository.CrudRepository
import javax.annotation.PostConstruct
import javax.persistence.*

fun main(args: Array<String>)
{
    runApplication<TestApplication>(*args)
}

@SpringBootApplication
class TestApplication(
    val personRepository: PersonRepository,
    val vehicleRepository: VehicleRepository
)
{
    @PostConstruct
    fun init()
    {
        var p1 = personRepository.save(Person(name = "Fred", age = 30))

        println(" ")
        p1.vehicles += vehicleRepository.save(Vehicle(type = "Car", brand = "BMW"))
        personRepository.save(p1)

        println(" ")
        p1.vehicles += vehicleRepository.save(Vehicle(type = "Car", brand = "BMW"))
        personRepository.save(p1)

        println(" ")
        p1.vehicles += vehicleRepository.save(Vehicle(type = "Car", brand = "BMW"))
        personRepository.save(p1)
    }
}

interface PersonRepository : CrudRepository<Person, Long>
interface VehicleRepository : CrudRepository<Vehicle, Long>

@Entity
data class Person(
    @Id
    @GeneratedValue
    val id: Long = 0,

    val name: String,

    val age: Int,

    @OneToMany
    @OrderColumn
    @JoinColumn(name = "personId")
    val vehicles: MutableList<Vehicle> = ArrayList()
)

@Entity
data class Vehicle(

    @Id
    @GeneratedValue
    val id: Long = 0,

    var type: String,

    var brand: String
)

Log
Hibernate: select next_val as id_val from hibernate_sequence for update
Hibernate: update hibernate_sequence set next_val= ? where next_val=?
Hibernate: insert into person (age, name, id) values (?, ?, ?)
Hibernate: select next_val as id_val from hibernate_sequence for update
Hibernate: update hibernate_sequence set next_val= ? where next_val=?
Hibernate: insert into vehicle (brand, type, id) values (?, ?, ?)
Hibernate: select [...]
Hibernate: select [...]
Hibernate: update vehicle set person_id=?, vehicles_order=? where id=?
Hibernate: select next_val as id_val from hibernate_sequence for update
Hibernate: update hibernate_sequence set next_val= ? where next_val=?
Hibernate: insert into vehicle (brand, type, id) values (?, ?, ?)
Hibernate: select [...]
Hibernate: select [...]
Hibernate: update vehicle set person_id=?, vehicles_order=? where id=?
Hibernate: update vehicle set person_id=?, vehicles_order=? where id=?
Hibernate: select next_val as id_val from hibernate_sequence for update
Hibernate: update hibernate_sequence set next_val= ? where next_val=?
Hibernate: insert into vehicle (brand, type, id) values (?, ?, ?)
Hibernate: select [...]
Hibernate: select [...]
Hibernate: update vehicle set person_id=?, vehicles_order=? where id=?
Hibernate: update vehicle set person_id=?, vehicles_order=? where id=?
Hibernate: update vehicle set person_id=?, vehicles_order=? where id=?
Question
Each car that is added, hibernate is updating all the other cars again. I noticed that if I change personRepository.save(p1) to p1 = personRepository.save(p1), it works as expected and only updates the new car. Why is that? Does hibernate has some internal "commit id"?
Also, how could I transform this code into a transaction?
Thanks.
Answer: Each call to save is calling EntityManager#merge which flushes the current object state to the database, possibly returning you a new object which is then "managed" meaning that changes done to that object will be flushed at the end of the transaction automatically. You can run that code in a transaction by using the @Transactional annotation, but not sure if that also works for @PostConstruct. Within the transaction, every object that you save is managed, so the changes are flushed at the end of the transaction automatically. You could use code like the following:
@PostConstruct
@Transactional
fun init()
{
    var p1 = personRepository.save(Person(name = "Fred", age = 30))
    p1.vehicles += vehicleRepository.save(Vehicle(type = "Car", brand = "BMW"))
    p1.vehicles += vehicleRepository.save(Vehicle(type = "Car", brand = "BMW"))
    p1.vehicles += vehicleRepository.save(Vehicle(type = "Car", brand = "BMW"))
}


Cross correlation vs mutual information

Question: What is the difference between Cross Correlation and Mutual Information. What kind of problems can be solved using these measures and when is it appropriate to use one over the other.
Thanks for the comments. To clarify, the question is prompted by an interest in image analysis rather than time series analysis although any enlightenment in that area would also be appreciated
Comment: Perhaps you mean [Canonical Correlation](http://en.wikipedia.org/wiki/Canonical_correlation) rather than [Cross-Correlation](http://en.wikipedia.org/wiki/Cross-correlation) which usually refers to the similarity between two waveforms (with a possible time lag)
Comment: @tdc No, I mean cross correlation. It is used extensively in image processing.
Comment: ah apologies. So without the lag this is just Pearson's correlation in two dimensions?
Answer: Cross correlation assumes a linear relationship between 2 sets of data. Whereas mutual information only assumes that one value of one dataset says something about the value of the other dataset.
So mutual information makes much weaker assumptions.
A traditional problem solved with mutual information is aligning (registration) of two types of medical images, for example an ultrasound and a x-ray image.
(typically, the types of images are called modalities, so the problem is named multi-modal image registration).
For both X-ray and ultrasound, a specific material, say bone, leads to a certain 'brightness' in the image. Whereas some materials lead to a bright x-ray and ultrasound image, for other materials (e.g. fat) it might be the opposite, one is bright, the other is dark.
Therefore, it is not the case that bright parts of the X-ray image are also bright parts of the ultrasound.
Therefore, mutual information is still a useful criterion for aligning the images, but cross correlation is not.
Answer: Cross correlation is used in time-frequency analysis  and is a inner product with a lag-parameter obtained between two functions varying over time, where one function is evaluated at  time $t$ and the other is evaluated at time $lag+t$. The cross-correlation theorem relates cross-correlation to the fourier transform of the individual functions, and hence a cros-correlation evaluated in a time domain is connected by this theorem to the spectral properties/frequency domain of the individual functions. Analogues to this exist in other areas like analyzing spatial data for example.
Comment: It is not clear to me that the OP meant cross correlation in the time-series sense when they used this term. It may well be a case of inadvertent imprecision. Perhaps we should ask for clarification from the OP.

Cross correlation vs mutual information


unexpected output with templates and non-templates functions

Question:
Possible Duplicate:
Template func and non template func call order

Why does this code code print
::foo(int)
::foo<T>(T)

template <typename T>
void foo(T)
{
   std::cout << "::foo<T>(T) \n";
}

template <typename T>
void bar(T baz)
{
   foo(baz);
}

void foo(int)
{
   std::cout << "::foo(int) \n";
}

int main()
{
   foo(0);
   bar(0);
}

while this
void foo(int)
{
   std::cout << "::foo(int) \n";
}

template <typename T>
void foo(T)
{
   std::cout << "::foo<T>(T) \n";
}

template <typename T>
void bar(T baz)
{
   foo(baz);
}

int main()
{
   foo(0);
   bar(0);
}

prints
::foo(int)
::foo(int)

as expected.
Comment: dup http://stackoverflow.com/questions/12174493/template-func-and-non-template-func-call-order
Comment: While I can't consider it an answer it is worth reading in the context of your question: http://www.gotw.ca/publications/mill17.htm.
Answer: The reason is because a template function only considers functions visible at the point of definition, not functions visible at the point of instantiation. If it picked functions based on instantiation visibility you'd be violating the one definition rule left and right most likely. There's a standard reference in my answer to the related question Adding specializations of template functions later
Comment: I think (not 100% on this) that if you were to put your function prototypes before any definitions that this would also solve this, even if the prototypes were in a semi-random order.  As long as they're all ahead of the definitions, I think that also works.


Is there a way to update host_vars file in Ansible from a task?

Question: I have a host_vars file with a variable mgmt_ip: "192.168.1.10"
In the playbook, I get an IP from an output and I would like to update this mgmt_ip for the next tasks within the playbook.
Comment: No you can't update host_vars but you can use facts you set in your playbooks (set_fact) and pass that information along to a role or play
Answer: You can simply run a local task to update the variable value directly in the file.
- local_action:
    module: lineinfile
    dest: ./host_vars/file
    regexp: 'mgmt_ip:'
    line: 'mgmt_ip: xx.xx.xx.xx'

The change won't however be reflected immediately, so for the subsequent tasks you need also to update the current fact value:
- set_fact:
    mgmt_ip: xx.xx.xx.xx


PHP e Javascript - Enviando anexo HTML em e-mail

Question: Criei no site do meu cliente uma função que emite um certificado de evento realizado e manda por e-mail. Como está a função no momento:
private static function setLayoutCertificado(){
    class_exists('Email') || include_once LIBRARY_CLASS_PATH . 'Email.class.php';

    $assunto = "Certificado de evento externo do colaborador " . $_SESSION['usuario']['nome'];
    $layout  = '

    Certificamos que o(a) colaborador(a) '.$_SESSION['usuario']['nome'].' participou da capacitação '.str_replace("'","",$_SESSION['eventoCert']).', com carga-horária de '.str_replace("'","",$_SESSION['cargaCert']).', realizado no dia '.str_replace("'","",$_SESSION['dataCert']).'.

            ___________________________________

            ___________________________________

            Nome 1

            Nome 2

            Cargo 1

            Cargo 2

';

    $o_email = New Email();
    $o_email->to = 'email@example.com';
    $o_email->subject = $assunto;
    $o_email->content = $layout;
    $o_email->sendSmtp(SMTPHOST, SMTPUSER, SMTPPASSWORD);
}

O que eu queria fazer era transformar esse código do HTML em um anexo (com extensão HTML mesmo) desse e-mail, pois o que sai no corpo do e-mail não fica muito bom. Como posso fazer isso?
Comment: Já fiz isso e preciso procurar o código, mas acho que no seu caso é melhor tentar formatar pra ir no e-mail mesmo mesmo porque indo como anexo a maioria das pessoas não vai nem abrir e alguns clientes de e-mail vão aumentar as chances de que seu e-mail seja considerado spam. Em último caso até um link ia ser melhor do que enviar como anexo.
Comment: @AntonioAlexandreAlonsodeSi Até não tem problema pra mim mandar já a formatação no corpo do e-mail ou o código HTML. Mas o problema é que na hora de imprimir o certificado não fica legal ele estando no corpo do e-mail, pelo menos no Gmail. Se tu tiveres o código aí, agradeço.
Comment: Vou pôr numa resposta um exemplo antigaço que eu fiz em 2012 de um envio de e-mail autenticado via smtp com arquivo em anexo. Teste e veja se ajuda.
Answer: Primeiro tem essa classe que fiz com base em umas funções que encontrei na internet em 2012:
EmailAuthenticator.php
<?
class EmailAuthenticator
{

var $conn;
var $user;
var $pass;
var $debug;
var $boundary;

function __construct($host)
{
    $this->boundary= "XYZ-" . date("dmYis") . "-ZYX";
    $this->conn = fsockopen($host, 25, $errno, $errstr, 30);
    $this->Put("EHLO $host");
}

function Auth()
{
    $this->Put("AUTH LOGIN");
    $this->Put(base64_encode($this->user));
    $this->Put(base64_encode($this->pass));
}

function addFile($corpo_mensagem, $arr_arquivo)
{
    $arquivo_path = $arr_arquivo["path"];
    $arquivo_type = $arr_arquivo["type"];
    $arquivo_name = $arr_arquivo["name"];

    if(file_exists($arquivo_path))
    {
        // Nesta linha abaixo, abrimos o arquivo enviado.
        $fp = fopen($arquivo_path,"rb");
        // Agora vamos ler o arquivo aberto na linha anterior
        $anexo = fread($fp,filesize($arquivo_path));
        // Codificamos os dados com MIME para o e-mail
        $anexo = base64_encode($anexo);
        // Fechamos o arquivo aberto anteriormente
        fclose($fp);
        // Nesta linha a seguir, vamos dividir a variável do arquivo em pequenos pedaços para podermos enviar
        $anexo = chunk_split($anexo);
        // Nas linhas abaixo vamos passar os parâmetros de formatação e codificação, juntamente com a inclusão do arquivo anexado no corpo da mensagem.
        $this->msg = "--".$this->boundary."\n";
        $this->msg.= "Content-Transfer-Encoding: 8bits\n";
        $this->msg.= "Content-Type: text/html; charset=\"ISO-8859-1\"\n\n";
        $this->msg.= "$corpo_mensagem\n";
        $this->msg.= "--".$this->boundary."\n";
        $this->msg.= "Content-Type: ".$arquivo_type."\n";
        $this->msg.= "Content-Disposition: attachment; filename=\"".$arquivo_name."\"\n";
        $this->msg.= "Content-Transfer-Encoding: base64\n\n";
        $this->msg.= "$anexo\n";
        $this->msg.= "--".$this->boundary."--\r\n";
    }
}

function Send($to, $from, $subject, $msg, $arr_arquivo=null){
    $this->msg = $msg;

    $this->Auth();
    $this->Put("MAIL FROM: " . $from);
    $this->Put("RCPT TO: " . $to);
    $this->Put("DATA");

    if($arr_arquivo!=null)
    {
        $this->addFile($msg, $arr_arquivo);
        $this->Put($this->toHeaderWithAttachment($to, $from, $subject, $this->boundary));
    }
    else
    {
        $this->Put($this->toHeader($to, $from, $subject));
    }

    $this->Put("\r\n");
    $this->Put($this->msg);
    $this->Put(".");
    $this->Close();
    if(isset($this->conn))
    {
        return true;
    }else{
        return false;
    }
}

function Put($value)
{
    return fputs($this->conn, $value . "\r\n");
}

function toHeader($to, $from, $subject)
{
    $header  = "Message-Id: <". date('YmdHis').".". md5(microtime()).".". strtoupper($from) ."> \r\n";
    $header .= "From: <" . $from . "> \r\n";
    $header .= "To: <".$to."> \r\n";
    $header .= "Subject: ".$subject." \r\n";
    $header .= "Date: ". date('D, d M Y H:i:s O') ." \r\n";
    $header .= "X-MSMail-Priority: High \r\n";
    $header .= "Content-Type: Text/HTML";
    return $header;
}

function toHeaderWithAttachment($to, $from, $subject, $boundary){
    $header = "Message-Id: <". date('YmdHis').".". md5(microtime()).".". strtoupper($from) ."> \r\n";
    $header = "MIME-Version: 1.0\n";
    $header.= "From: $from\r\n";
    $header.= "To: $to\r\n";
    $header.= "Reply-To: $from\r\n";
    $header.= "Subject: ".$subject." \r\n";
    $header.= "Date: ". date('D, d M Y H:i:s O') ." \r\n";
    $header.= "Content-type: multipart/mixed; boundary=\"$boundary\"\r\n";
    $header.= "$boundary\n";
    return $header;
}

function Close()
{
    $this->Put("QUIT");
    if($this->debug == true)
    {
        while (!feof ($this->conn))
        {
            fgets($this->conn) . "
\n";
        }
    }
    return fclose($this->conn);
}

}
?>

Depois tem esse arquivo aqui que usa a classe:
envia_autenticado_com_anexo.php
<?
error_reporting(E_ALL);
include ("EmailAuthenticator.php");

$from = "firstname.lastname@example.com";
$to =   "email@example.com";
$subject = "Teste da classe que envia e-mail autenticado com anexo";

// Aqui abaixo, vamos colocar o corpo da mensagem, como vamos utilizar padrão HTML, teremos de utilizar tags HTML abaixo
$corpo_mensagem = "

   <title>Teste de Envio</title>

Olá mundo!!

Este é mais um teste da classe que envia e-mail autenticado com anexo.

";

$arquivo_path=$_FILES["meuarquivo"]["tmp_name"]; //caminho do arquivo
$arquivo_name=$_FILES["meuarquivo"]["name"]; //nome correto do arquivo com a extensão correta
$arquivo_type=$_FILES["meuarquivo"]["type"]; //tipo do arquivo

$arr_arquivo = array( "path" => $arquivo_path,
                      "name" => $arquivo_name,
                      "type" => $arquivo_type );

// Envio Autenticado

$host = "mail.seuservidor.com.br";
$smtp = new EmailAuthenticator($host);
$smtp->user = "email@example.com";            /* usuario do servidor SMTP */
$smtp->pass = "suasenha";                               /* senha do usuario do servidor SMTP */
$smtp->debug =true;

if( $smtp->Send($to, $from, $subject, $corpo_mensagem, $arr_arquivo) )
{
    echo "ok";
}
else
{
    echo "error";
}
?>

E por último tem esse form que faz o post de um arquivo(para testar com qualquer arquivo de forma fácil, mas vc pode depois mudar a parte que chama $_FILES no arquivo acima pra onde tá seu arquivo no servidor):
form.html

    <form method="post" enctype="multipart/form-data" action="envia_autenticado_com_anexo.php">
        <input type="file" name="meuarquivo" />
        <input type="submit" value="Enviar" />
    </form>

Se este código tiver sido útil, dê uma moral e clique na setinha pra cima pra me dar pontos de reputação.
Se achar essa resposta adequada e que resolve o seu problema, caso a marque como respondida também estará me dando pontos de reputação.
Valew, falow, abraços. :)
Quaisquer dúvidas poste aqui nos comentários da resposta.


How to hit four notes in a single beat with 2 hands for drum

Question: Sometimes when i am given a drum score , there will be four notes in a single beat , How do i hit four notes in a single beat given I only have 2 hands ???

The only way i know to hit 4 notes in a single beat if the four notes are  : Bass Drum , Foot Hi-Hat  + any 2 other notes
I am sure I am missing something , can someone elaborate to me ??
Comment: I thought that the idea of having several lines on the 'stave' was to differentiate the drums/cymbals. If so, why would the , for instance, SC(splash cymbal), not be all written on the same line, and each have its own line. It would be easier to read, surely ?
Answer: Well, LowTom (LT) and HiMidTom (HMT) with the Hands, open hihat (oH) with feet plays either mounted SC or strikes SC thru HMT in one stroke.
Comment: Open hi-hat with foot = stomp it like it's hot.
Comment: How do you play open Hi-hat with your feet ??
Answer: I've seen some drummers hold the stick in the middle and hit two drums at once, with each end of the stick. Doesn't look very easy though !
Why would anyone ask you to do this by the way ?  If it's a generated drum score of some sorct (eg for a drum machine) then perhaps explain that you're human ?
Comment: And cue drummer jokes ..
Comment: eg. You only ahve to punch the rhythm once into a drum machine .. etc ..
Answer: The graphic you have shown us in not any sort of "drum score" that I've ever seen.  Where did it come from?
As a live drummer, you've got two hands and two feet.   As computer programmers we can write as many simultaneous sounds as we like of course.  Keeping to what's physically possible for a real player can be a good rule so as not to muddy up the texture, but there's no need to be over-pedantic about it.


Distinguishing the odd population out

Question: I'm trying to determine the "special" population out of n populations.
I have measurements with n labels.
label          measurement
a              1.4
b              1.2
a              1.2
c              1.3
...

Measurements with n-1 of the labels are drawn iid from the same normal distribution with mean $\mu_{default}$ and variance $\sigma^2_{default}$.
One label is "special" and its measurements are drawn from a different normal distribution with mean $\mu_{special}$ and variance $\sigma^2_{special}$.
$\mu_{special}$ > $\mu_{default}$ but I don't de novo know anything about the variances. (In practice $\sigma^2_{special}$ is probably close to $\sigma^2_{default}$ but I'd prefer not to make that assumption if possible.)

My goal is to find probabilities that each label is special; that is, if the labels are a, b, and c, I can compute
p(a is special | data)
p(b is special | data)
p(c is special | data)

such that all probabilities add to 1.
I can run Welch's t-test for each label against the rest of the data to find p-values for each label – but these aren't likelihoods! This gives me good results to determine by inspection which label is special, but I don't know of a justifiable way to generate the probabilities I want above.

The above may be a bit confusing due to bad terminology, so here's an example that I hope helps motivate the problem:
Consider a game with a 6-sided die. The die is hidden from the player. Every turn, the die is rolled.

If the die rolls on value 1 (the "special" value), a random measurement m is taken from a normal distribution with parameters $\mu_{special}$ and $\sigma^2_{special}$. (1, m) is reported to the plauyer.
If the die rolls on any other value $v \in [2,6]$, a random measurement m is taken from a normal distribution with the parameters $\mu_{default}$ and variance $\sigma^2_{default}$ and (v, m) is reported.

The player can see all of the (die outcome, measurement) pairs but does not know anything about the underlying distributions other than that they are normal and $\mu_{special}$ > $\mu_{default}$
The player's goal is to derive the probabilities that each value is special, that is, derive p(1 is special), p(2 is special)... p(6 is special) given a long list of (die outcome, measurement) pairs. The player has is a uniform prior (the special value is chosen uniformly at random before the game starts.)
Comment: Your use of the terms "sample," "population," and "distribution" does not seem to make the standard distinctions, making your account rather confusing.  Are you perhaps equating "population" with "distribution"?  If not, what is the distinction?  Then, although your question is Bayesian and requires a prior distribution and application of Bayes' Theorem to address, why then are you introducing t-testing?
Comment: Thank you.  Good keywords to use in research include *mixture distribution* and *contaminated distribution.*  But the reference to a t-test remains confusing, because it suggests at least two different valid interpretations of your question.
Comment: It's been a long time since I did proper statistics, but I'll define what I mean here: Sample: a single measurement taken. Population: the set of data from which that measurement was taken. Distribution: the parameters that define the population. t-testing was my first guess about how to derive a likelihood – I could sum log-likelihoods or some such but I'm not sure doing so would be valid with populations of different sizes.
Comment: To further clarify my distinction between population and distribution: I have data that is labeled (a, b, c, d, e, f, ...). I know that all but one can be described by a normal distribution with "default" parameters as defined in the question, and one can be described by a normal distribution with "special" parameters. So, population === "the total set of data under some label," and distribution is "the distribution that describes n-1 and 1 of these populations." I've edited the question to replace "population" with "label" and "sample" with "measurement."
Comment: The word you are looking for is "outlier" and lots has been written about outlier detection. Searching for that keyword should help you find what you need.
Comment: I don't think I'm quite looking for outlier detection. What I'm looking for is something closer to this question: stats.stackexchange.com/q/490853/406016 except in my case, the actual distribution parameters are unknown.
Comment: *"but I don't know of a justifiable way to generate the probabilities I want above."* This can only be done with a Bayesian approach. You will need to use some prior probability distribution for the special population, but you also need an assumption for the distribution of the nuisance parameters $\mu$ and $\sigma$.
Comment: @SextusEmpiricus, I am curious what you think of my non-Bayesian maximum likelihood approach.
Comment: @MattF. it is interesting to use the formula $$P\big[\text{label }i\text{ is special}\ |\ data\big]=p_i/\sum_j p_j$$ but I am not sure it is right. I believe one should be using some integration over nuisance parameters. Also using the estimates $L/N$ and $Q/N-L^2/N^2$ does not take into account the condition in the model that $\mu_{special}>\mu_{default}$
Comment: Yep, assuming this is correct it's a super elegant answer but as @SextusEmpiricus said, the only thing it's missing is the condition. I've been playing with this a bit and in practice applying the condition helps a lot (when messing with a non-analytical approach) since the distributions can be close.
Answer: Here is a maximum likelihood approach.
For each label $i$, let $N_i$ be the number of observations with that label, let $L_i$ (the linear term) be the sum of those observations, and let $Q_i$ (the quadratic term) be the sum of their squares. Let $N$, $L$ and $Q$ be the sums over all $i$.
Let $p_i$ be the maximum likelihood of the data if label $i$ is special. On this assumption, label $i$ is normally distributed with mean $L_i/N_i$ and variance $Q_i/N_i-L_i^2/N_i^2$, the likelihood of the data for label $i$ turns out to be
$$f(N_i,L_i,Q_i)=\left(2\pi e\Big(\frac{Q_i}{N_i}-\frac{L_i^2}
{N_i^2}\Big)\right)^{-N_i/2}$$
and $$p_i=f(N_i,L_i,Q_i)\,f(N-N_i,L-L_i,Q-Q_i)$$
Since one of the labels must be special, this would yield $$P\big[\text{label }i\text{ is special}\ |\ data\big]=p_i/\sum_j p_j$$
Comment: ... and substituting maximum likelihood estimates $\hat{\mu} = \frac{1}{n}\sum_{i=1}^n x_i$, $RSS = \sum_{i=1}^n (x_i - \hat{\mu})^2$ and $\hat{\sigma}^2 = RSS/n$ you get

$$\mathcal{L}(\hat{\mu}_{mle},\hat{\sigma}_{mle}) = \left(2\pi e\right)^{-2/n} \left(\frac{RSS}{n}\right)^{-n/2}  $$
Comment: The power $n/2$ can be absorbed into the exponent. $$\left(e^{x/n}\right)^n = e^x$$
Comment: @SextusEmpiricus, it's not getting any nicer! The base in that expression is $2\pi e$ times a difference, not $2\pi$ times an exponential; and if you change notation to make $Q_i$ a sum of squared residuals for the special label, that makes it awkward to write down the probability of the other labels in the second factor of $p_i$.
Comment: It comes from a straightforward calculation of the likelihood using the MLE mean and variance, then simplifying using $L_i$ and $Q_i$, and then cancelling — I'd welcome anyone editing the post to write out the intermediate steps, but I'm happy just seeing the conclusion.
Comment: @MattF. you are right, the exponential disappears from the expression. The likelihood is related to the residual sum of squares in the following way. The full equation for the likelihood

$$\mathcal{L}(\hat{\mu},\hat{\sigma}) = \prod_{i = 1}^n \frac{1}{\sqrt{2\pi\hat\sigma^2}}\exp\left(-\frac{(x_i-\hat\mu)^2}{2\hat\sigma^2}\right) = \hat\sigma^{-n} \left(\frac{1}{2\pi}\right)^{n/2} \exp\left(- \frac{1}{2\hat{\sigma}^2} \sum_{i=1}^n (x_i - \hat\mu)^2\right)$$ ...
Comment: Once I justify this to myself it's exactly what I'm looking for. As an added bonus it looks like it would be trivial to adapt this to online updates
Comment: Possibly using the sum of squared residuals may give a nicer expression for the likelihood.
Comment: @MattF. It is confusing how you derived that expression.
Comment: @MattF. without the exponential it seems like you have been using the log likelihood instead of likelihood and it shouldn't have the power.
Comment: I don't think it's helpful for me to defend my algebra further, so I'll stop engaging on this question.
Answer: I have no direct solution to the problems below, but I believe that it important to mention, to warn that a straightforward answer is not as simple as it looks like and it should be nuanced that they do not give an exact solution.

It is possible to fit different models based on different hypotheses, and compute the likelihood in the fitted point. But a tricky part of the question is that the true variance might be different from the fitted variance, and the problem becomes a variant of the Behrens Fisher problem.
In addition, one may compare likelihoods, but it is not ensured that we will see the true model as relatively most often with the highest likelihood.
An example computation is below where we have 5 populations and for small effect sizes the special population is recognized less than 20% of the time.
(the computations below are for different groups sizes to make the effect more clear, and we tested the hypothesis $\mu_{special} \neq \mu_{default}$ instead of the more difficult $\mu_{special} > \mu_{default}$)

set.seed(1)

power = function(effect = 0, n = 500) {
  count = 0 ### counter to keep track of right decisions

  ### simulate n times
  for (i in 1:n) {

    ### simulate a sample
    x1 = rnorm(5)
    x2 = rnorm(5)
    x3 = rnorm(5)
    x4 = rnorm(5)
    y  = rnorm(50,effect,1)

    ### compute log-likelihood for different models
    l1 = logLik(lm(c(x1,x2,x3,x4) ~ 1))+logLik(lm(c(y) ~ 1))
    l2 = logLik(lm(c(x2,x3,x4,y) ~ 1))+logLik(lm(c(x1) ~ 1))
    l3 = logLik(lm(c(x1,x3,x4,y) ~ 1))+logLik(lm(c(x2) ~ 1))
    l4 = logLik(lm(c(x1,x2,x4,y) ~ 1))+logLik(lm(c(x3) ~ 1))
    l5 = logLik(lm(c(x1,x2,x3,y) ~ 1))+logLik(lm(c(x4) ~ 1))

    ### convert to likelihood
    p1 = exp(l1-min(l1,l2,l3,l4,l5))
    p2 = exp(l2-min(l1,l2,l3,l4,l5))
    p3 = exp(l3-min(l1,l2,l3,l4,l5))
    p4 = exp(l4-min(l1,l2,l3,l4,l5))
    p5 = exp(l5-min(l1,l2,l3,l4,l5))

    ### keep track when the true group has the highest likelihood
    if (p1 > max(p2,p3,p4,p5)) {count = count +1}
  }
  return(count/n)
}

### create a plot
plot(c(-1,2), c(0.2,0.2),
     xlim = c(0,0.5), xlab = "effect size",
     ylim = c(0,1), ylab = "fraction recognized",
     type = "l", lty = 2)

### add points for probability of correct decisions as function of effect size
for (effect in seq(0,0.5,0.05)) {
    points(effect,power(effect))
}

This relates to the discrepancy between frequentist and bayesian analyses. A Bayesian analysis will give the probabilities conditional on the observations and not conditional on the hypothesis. That's why we can get low <20% values, when we condition on the hypothesis (we had a fixed hypothesis). See also Why does a 95% Confidence Interval (CI) not imply a 95% chance of containing the mean?
Comment: This is helpful, thanks. A bayesian approach with weak assumptions should work fine. I'm curious about your comment "The situation here is a bit different from the t-test where the variance is a nuisance parameter. In your case it is part of the parameters to be estimated." – I don't actually care about the variance in practice; I just want to find the one distribution with a higher mean. wouldn't that mean that the variance is a nuisance parameter as in a t-test? (obviously, running a t-test isn't really statistically valid. Just trying to grok what you mean by "nuisance.")
Comment: @vroomfondel so you want to determine which population has a different mean, and not which population has a different mean and/or variance?
Answer: From a frequentist perspective, your problem can form several binary regression models of predicting the probability of a special label based on a continuous measurement, under different assumptions of which label is special. We choose the model that fits a manipulated response best, corresponding to one of the several assumptions of which label is special. If your label is controlled, so each experiment consists of one run of each label and all labels are tested each time, then you can use multinomial regression. Your analogue of throwing dices shows that the binary regression fits your need best. Although your measurements follow normal distributions, you can use logit, probit, or any other link function because the model specification is based on error assumptions instead of predictor distributions.
Unlike a typical data set for binary regression, you have to manipulate the response variable as many times as the number of labels. If we assume that Label A is special, then the response variable takes 1 if the Label is A and 0 otherwise, as shown below.
label      measurement   response
    a              1.4          1
    b              1.2          0
    a              1.2          1
    c              1.3          0
...

If we assume that Label B is special, then the response variable takes 1 if the Label is B and 0 otherwise. If we assume that Label  C is special, then the response variable takes 1 if the Label is C and 0 otherwise. Then we fit three different binary regression models. In R, the models are fitted as
ModelA <- glm(I(label == "a") ~ measurement, data = ..., family = binomial(link = "logit"))
ModelB <- glm(I(label == "b") ~ measurement, data = ..., family = binomial(link = "logit"))
ModelC <- glm(I(label == "c") ~ measurement, data = ..., family = binomial(link = "logit"))

Thus we have three candidate models. The first model assumes Label A is special, whereas the last model assumes Label C is special. Each model gives a maximized log likelihood, which should be higher if the assumption of special label is correct and lower and equal among other models. Suppose AIC values based on the log likelihoods are 100, 102, and 110. Then the first model is exp((100 − 100)/2) = 1.00 times as probable as the first model to minimize the information loss; the second model is exp((100 − 102)/2) = 0.368 times as probable as the first model to minimize the information loss; the third model is exp((100 − 110)/2) = 0.007 times as probable as the first model to minimize the information loss. Therefore, the probability of ModelA is the true model is
exp((AIC(ModelA) - AIC(ModelA))/2) / sum(
  exp((AIC(ModelA) - AIC(ModelA))/2) +
  exp((AIC(ModelA) - AIC(ModelB))/2) +
  exp((AIC(ModelA) - AIC(ModelC))/2))

which is 1/(1 + 0.368 + 0.007) = 0.7274752. We can derive the probability for B and C being special as 0.368 /(1 + 0.368 + 0.007) = 0.2676232 and 1/(1 + 0.368 + 0.007) = 0.004901689. And the three probabilities sum up to one. See the logic at "How to use AIC in practice" at https://en.wikipedia.org/wiki/Akaike_information_criterion.
On the other hand, you can also model the process as linear models of predicting the population mean of measurements based on labels. In R, we fit three models
ModelA <- glm(measurement ~ I(label == "a"), data = ..., family = gaussian(link = "identity"))
ModelB <- glm(measurement ~ I(label == "b"), data = ..., family = gaussian(link = "identity"))
ModelC <- glm(measurement ~ I(label == "c"), data = ..., family = gaussian(link = "identity"))

Based on the log likelihoods and AIC, we can derive the three probabilities as shown above for binary logistic models. To relax the equal-error-variance assumptions which correspond to equal variances of measurements among all labels, we can use generalized least squares that allow the residual standard deviation to differ by a ratio between the assumed special label and other labels.
ModelA <- nlme:gls(measurement ~ I(label == "a"), weights = varIdent(form = ~ 1 | I(label == "a")), data = ...)
ModelB <- nlme:gls(measurement ~ I(label == "b"), weights = varIdent(form = ~ 1 | I(label == "b")), data = ...)
ModelC <- nlme:gls(measurement ~ I(label == "c"), weights = varIdent(form = ~ 1 | I(label == "c")), data = ...)

Comment: The tricky part of the question is that the variance might be different and the problem becomes a variant of the Behrens Fisher problem. These glm models assume equal variance and solve a different problem.
Comment: What about the generalized least squares GLS models I listed at the end of the answer? Does their relative likelihood answer the question?
Comment: the GLS models allow the use of different variance, which allows to compute a likelihood, but is it the right likelihood? The variances used are based on fitted variances and may not need to be the true variances.
Comment: Another thing, the `glm` and `gls` functions do not allow fitting with boundary conditions. The coefficient describing the effect needs to be non-zero.

Distinguishing the odd population out


Does the CSS property "text-transform" affect SEO results?

Question: I am building a site with a ton of 1999 style capitalization of navigation and headings. I have been simply adding in the text content as it appears (capitalized), but the other designer on the project insists on using lower case text in his HTML and capitalizing it with an applied style:
<code>.tedious {text-transform:uppercase;}
</code>
I understand the argument of separation of style from content, but in this case it really doesn't matter because I personally will not maintain the site, nor do I ever imagine that the client will need to un-capitalize all of this text. The question is: 1. will search engines pay any attention at all to capitalization of text in a document and 2. would a crawler go so far as to read my style sheet and look for such things (me thinks not). I know that BOLD, STRONG, EM, etc have a (diminishing) effect on SEO so I can imagine a scenario where CAPS would, but have never heard of anyone actually claiming, let alone confirming this.
Digging this site the last few months. First post.
Comment: IIRC, Google does read style sheets, e.g. to check whether text is being hidden using CSS. However, I don't see any reason for them to even consider checking for text-transform. It doesn't change the message, and that is all Google cares about. I also doubt that bold, strong, and em have a *diminishing* effect on SEO. From my personal experience, quite the opposite is the case, as long as they are used sparingly. Then again, nobody can claim to know for sure what Google does (even inside Google, only few people know all the details), and whatever it does is subject to permanent change anyway.
Comment: Since this is you first question, welcome to SO :)
Comment: I can't find an answer, too, but perhaps Google's forum at http://www.google.com/support/forum/p/Webmasters is a more appropiate place to ask.
Answer: if i was a search engine - I wouldn't care about casing.  I would care about the content.
From a human readability standpoint - upper case isn't as easy to read.
Answer: It will only effect what is shown in the search results, you colleagues work will show as lower case in the results.
You mentioned separation of style from content, but i'm not convinced that text-transform is a style really, it's a change of content, i'm sure some people would argue the other side though.
Comment: Depends what you consider to be content. If it's all-caps for the sole sake of presentation, then that sounds to me like it's presentational, and should be in CSS. My preferred style for something like this would be to make the nav links capitalized naturally - "Home" - and then apply all-caps in the style if I *really* cared that much.
Comment: If you really want all-caps in every browser, then you should write it all-caps in your markup. Visitors with browsers without CSS-capabilities (like Lynx) or people browsing with CSS turned off (they do exist) will also see all-caps.
Comment: Excellent point, ALL CAPS in search results can be a bit of an eyesore. thx
Answer: Well, I was taught at school that all proper nouns (eg names and names of places) should begin with capital letters.
How would Google know whether I was talking about reading (as in a book) or Reading (as in the town of Reading, Berkshire), without taking into account the capitalisation? I would argue that capitalisation is definitely a semantic indicator rather than simply a case of aesthetics, and is therefore one factor that could be used for SEO.
As noted elsewhere, Google clearly does have knowledge of the CSS being used to render a page (eg Google can spot black-hat techniques such as white text on a white background).
So if capitalisation (or lack of) is a relevant SEO factor, can the CSS text-transform (or lack of) value also be an SEO factor?
Yes - because Google considers page speed to be an important factor. Text that doesn't need to be transformed by CSS will display faster.
Comment: How about "font-variant-caps"?
Answer: Answer from google:
I don't think we'd do anything special with all-caps headings, but it feels like the kind of thing you'd want to do in CSS instead of in the content, since it's more about styling.
https://mobile.twitter.com/JohnMu/status/1438159561391751170?s=19


New files added in a patch are removed during uninstall - even when marked permanent

Question: Using InstallShield 2013 in a Basic MSI project. We have some ancient Microsoft COM DLLs that are shipped in merge modules which we include in our MSI. We now need to update a few of these DLLs with newer ones in a minor upgrade patch (MSP).  We don't have new merge modules from Microsoft so I'm trying to figure out how to get these new DLLs installed in our application.
I've added 2 new components, one for each file, and built the new MSP.  The files get installed properly, though I did have to register them manually in a custom action, otherwise the patch would be uninstallable (b/c I changed the Class table).  This is all good - so far.  However, when I remove the patch, these 2 new files are deleted!!  This is the problem. I would be OK with them being put back to the previous version - but no.  They're straight up deleted.  I marked the files as Permanent - same problem.  I nulled out the GUID for these two new files - same problem.  I would be OK with them being left at the new version since they're MS files.  I suspect it's not keeping these around because I'm only marking it permanent in the patch, not in the original MSI. Right?
<code>Here's some MSI log info during the installation of the MSP:

MSI (s) (FC:C4) [16:53:38:949]: File = comctl32.ocx: Final State = Install
MSI (s) (FC:C4) [16:53:38:949]: File = osl.dll1.BD822168_4484_412B_AA08_455F82BE5E0F: Final State = Install
MSI (s) (FC:C4) [16:53:48:371]: SELMGR: Component 'comctl32.ocx' is a new component added to feature 'WDCoreComp'
MSI (s) (FC:C4) [16:53:49:371]: Component: comctl32.ocx; Installed: Absent;   Request: Local;   Action: Local;   Client State: Unknown
MSI (s) (FC:C4) [16:53:53:199]: Baseline: Existing comctl32.ocx version 220.127.116.11 does not match any baseline. Will not be cached.

Here's MSI log info from the uninstall of this MSP:
MSI (s) (FC:B8) [16:57:33:236]: File = comctl32.ocx: Final State = Remove
MSI (s) (FC:B8) [16:57:33:236]: File = osl.dll1.BD822168_4484_412B_AA08_455F82BE5E0F: Final State = Overwrite
MSI (s) (FC:B8) [16:58:01:939]: Executing op: FileRemove(,FileName=C:\Windows\SysWOW64\comctl32.ocx,,ComponentId={100B5DC4-FD2D-4311-9ADE-2B65B814F446})
</code>
I included the osl.dll in there to indicate a normal patching routine for one of our DLLs where it's overwriting it with the old version, but it's removing the comctl32.ocx.
Other options seem VERY undesirable:

use Orca to hack the new bins into the old merge modules and rebuild the installer. Hopefully
the patch would recognize that they're new and install them properly
do this all manually in custom actions: during install save a copy of these files then install the new ones. During uninstall, restore the old versions from our saved copies
install the files in a temp folder, copy them to the official MS location, then register them there. Uninstall would only remove them from the temp folder and not the official MS location

Number 3 sounds least objectionable but still bad form to do all this manually in custom actions.
Answer: I first tried #3 but InstallShit thwarted me at every turn. I couldn't copy files into the "Common Files...\VBA" folder no matter what I tried. So, I ended up doing #1, though I used InstallShield to edit the merge modules. Fortunately, I was able to just replace the bins and resave the merge modules.


How to use hook_menu title arguments

Question: Reading hook_menu it says this:

"title": Required. The untranslated title of the menu item.
"title callback": Function to generate the title; defaults to t(). If you require only the raw string to be output, set this to FALSE.
"title arguments": Arguments to send to t() or your custom callback, with path component substitution as described above.

So how to use it? Right now i have this
function custom_gmap_neo_menu(){
    $item = array();

    $item['custom_gmap_neo/%/%/%'] = array( // hotel/origin/destination
        'title' => 'Get directions to @hotel',
        'title arguments' => array(1),
        'page callback' => 'custom_gmap_neo_show',
        'page arguments' => array(1,2,3),
        'access callback' => TRUE,
    );

    return $item;
}

function custom_gmap_neo_show($hotel, $origin, $destination){
    dpm($hotel);
    dpm($origin);
    dpm($destination);

    return '';
}

So knowing that default function for title callback is t() how to actually pass the @total wildcard to the t() function?
Answer: When you define title arguments as an array, each array element will be passed as arguments in that sequence.
Now you have title arguments defined as array(1), which means the actual call would mimic t('something') if the URL path was custom_gmap_neo/something/something_else/something_else_1.
If you want to call t() function as t('Get directions to @hotel', array('@hotel' => 'something')), you need to define your own title callback, because automatic integer to path argument translations only happen in the root level array elements.
<?php
function custom_gmap_neo_menu(){
    $item = array();

    $item['custom_gmap_neo/%/%/%'] = array( // hotel/origin/destination
        'title arguments' => array(1),
        'title callback' => 'custom_gmap_neo_get_map_title'
        'page callback' => 'custom_gmap_neo_show',
        'page arguments' => array(1,2,3),
        'access callback' => TRUE,
    );

    return $item;
}

function custom_gmap_neo_show($hotel, $origin, $destination){
    dpm($hotel);
    dpm($origin);
    dpm($destination);

    return '';
}

function custom_gmap_neo_get_map_title($hotel) {
  return t('Get directions to @hotel', array(
      '@hotel' => $hotel
    ));
}
?>

However, if your first URL argument (hotel) is a node, consider using %node as the path wildcard, because it can load the node for you, and handles page not found errors automatically if node_load returns an empty result. Otherwise you will have to call node_load twice. node_load caches results, but there are many loader functions that do not cache results.
Comment: hmm i see it clear now, thank you. hotel it is not a node it is just a string

How to use hook_menu title arguments


Carregar ficheiro em java

Question: Preciso fazer o upload de um arquivo .xlsx que está em um diretório para minha ferramenta.
Qual API ou implementação posso utilizar para realizar o upload?
Answer: Você pode usar a bliblioteca Apache POI para isso
Abaixo segue um exemplo de como você pode carregar um arquivo .xlsx com a biblioteca Apache POI, posteriormente você pode salvar a mesma em um diretório que achar mais conveniente.
<code>import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;

public class ExcelReader {
    public static final String XLSX_FILE_PATH = "./arquivo-excel.xlsx";

    public static void main(String[] args) throws IOException, InvalidFormatException {

        //Criando um Workbook de Uma Arquivo Excel (.xlsx ou .xls)
        Workbook workbook = WorkbookFactory.create(new File(XLSX_FILE_PATH));

        //Visualizando Todas as Sheets presentes na planilha
        for(Sheet sheet: workbook) {
            System.out.println("=> " + sheet.getSheetName());
        }

        // Visualizando os valores das células da primeira aba da planilha
        Sheet sheet = workbook.getSheetAt(0);

        for (Row row: sheet) {
            for(Cell cell: row) {
                String cellValue = dataFormatter.formatCellValue(cell);
                System.out.print(cellValue + "\t");
            }
            System.out.println();
        }

        workbook.close();
    }
}
</code>
Terminologia do Apache POI

Workbook: Uma pasta de trabalho é a representação de alto nível de uma planilha.
Sheet: Representa uma aba da planilha. Uma pasta de trabalho pode conter muitas abas.
Row: Como o nome sugere, representa uma linha na planilha.
Cell: uma célula representa um elemento na coluna da planilha.
Comment: Obrigado pela alternativa, usei e funcionou

Carregar ficheiro em java


adding or remove multiple classes with attributes.addClass

Question: In my page template I can add a single class and remove a single class like this
 But now I want to add a single class and remove two classes, and this does not work
 <asideright{{attributes.addClass(sidebar_second_classes).removeClass('content_classes','sidebar_first_classes') }}>
Answer: From the documentation for addClass and removeClass:

attributes.removeClass()
Removes a class from an Attribute object. Used similarly to addClass.
  Let's say you get the classes variable from somewhere else like a
  preprocess function.
{% set classes = [ 'red', 'green', 'blue' ] %}

 outputs

.

So either you need to use an array to remove multiple classes or make multiple calls the removeClass and a single class.


How can I activate the CSS hover state of an element below a block of text (w/o Javascript)?

Question: I have a grid of elements over which I have an h1 text tag. Each of the grid elements has a hover action, and I would like to activate that hover action for the grid elements below the text. However, I cannot put the z-index of the grid elements higher, as that would obscure the text.
A basic idea of the html: (and here's an actually useful JSFiddle link: http://jsfiddle.net/evd3v/)

...

My Page Title

Designed by Me

Comment: Can you please provide some code or even better a [jsFiddle](http://jsfiddle.net)?
Comment: You can't hover something unless your mouse can touch it. If there's text over-top, you can't touch the element behind... unless the text was somehow actually a part of hover elements.  Actually, depending on your actual situation (showing some code would help), this might work with a background image, as long so you don't need to select the text. But it would be a lot of CSS.
Answer: You can make the h3 ignore mouse (pointer) events with
h3{ pointer-events:none; }

but this only works with FF/Chrome/Webkit
Comment: For IE support, check this link: http://stackoverflow.com/questions/5855135/css-pointer-events-property-alternative-for-ie
Answer: Set the background of the grid elements to background: transparent and then give them a higher z-index?
Comment: the transition is on the background of the grid elements, so I can't get rid of the background.


Why same sample have different loudness in FL and Live?

Question: I loaded same sample (Kick) in FL v20.x and Ableton Live v10.x, in FL the volume is around -8db and in Live is around -6db, why?
Answer: It's almost certain that Live and FL have different metering algorithms for their channels and/or busses. Also the summing algorithms and panning laws are probably different.
Comment: Good info, is this documented some where? I see you wrote almost/probably so I think you are not sure about that, am I right?
Comment: @MehdiDehghani They don't seem to describe their meter algorithms in the documentation, but it does seem like the FL default meter is peak only while the Live meter is combined peak & RMS. One important aspect of a meter is its *integration time*. Especially with percussion noises, the levels shown on meters can vary greatly between different integration times. There's no standard for meter integration time so there's no reason to expect any two meters to use the same one. Also with 32 bit audio as is used in both, there's no expectation of using the same calibration point.
Comment: @MehdiDehghani I wonder why you would expect the two meters to show the same thing in the first place. That's like expecting two different cars to have the same size glove box or two different restaurants to have the same chairs. Meters are not some standard thing that work exactly the same in every software package. Pro Tools has something like ten different metering algorithms to choose from. Just cause FL and Live don't say which ones they are using doesn't mean we should assume they are using the same one.
Comment: I think I should mentioned couple of thing here, 1. I check the loudness using `FabFilter Pro-L 2`, that's why I expected same value in both. 2. I think -3db is important, because if I want to hear same thing in FL as I hear in Live, I should change the Master volume, or PC's volume, am I right?
Answer: Most probably it's due to different panning laws
https://www.gearslutz.com/board/music-computers/814978-fl-circular-triangular-panning-law-other-daws-getting-clear-mixes.html
Try switching the panning law between "triangular" vs "circular" in FL Studio.
https://www.image-line.com/support/flstudio_online_manual/html/songsettings_settings.htm
Comment: +1 for the links, thanks. but as I mentioned in above answer's comment, is this documented or your answer is based on mentioned link?
Comment: Did you try changing the setting in FL Studio? Do you think the FL Studio reference manual I linked to doesn't qualify as documentation? Did you read what it says?
Comment: I changed the setting and nothing changes, still same value. yes I read both links and some other articles, now I know that FL and Live uses different panning law
Comment: @MehdiDehghani if the pan law setting doesn't do what the manual says it does, then it's a bug and you should file a bug report at ImageLine / FL Studio
Comment: Did you try to change the setting, if so, did you see the change which is mentioned in the docs?
Comment: @MehdiDehghani no I don't have FL Studio. Contact ImageLine's support, that's what it is for https://www.image-line.com/support/


Is it safe to plug guitar processor output directly into laptops's 3.5 mm slot?

Question: I sometimes record my guitar using Audacity, I use a 3.5 mm converter and connect my guitar cable directly into my laptop.
But I was wondering if I can do the same with my vox stomplab IIG processor to get effects like high gain distortion and all.
I heard somewhere that you shouldn't connect stompboxes output directly as it may damage laptop's inbuilt sound card.. but is it same case with guitar processors too?
Answer: Connecting guitar -> sound card directly isn't much different than connecting guitar -> pedal -> sound card. It won't hurt your sound card. But it probably doesn't sound very good either, does it? You're missing both an amp and speaker which are essential to how an electric guitar sounds.
Your Vox modeling pedal will sound much better because it includes amp/speaker emulation and probably has a line-level output. Look for an "output" setting on the Vox and make sure it's set to "line" or something similar and you should be good to go.
Then if you later get into layering tracks like recording 2 guitar parts or playing over a drum track, you'll probably want something like ASIO4ALL to deal with the latency of a stock sound card.
Answer: It all depends on the output your guitar processor gives you. They should all be in the same voltage range. But connecting a guitar or stomp box directly to the laptop will never give you a good sound. You should always use a sound card or audio interface. These are designed for the job, have the correct impedance and can cope with a wide range of voltages, gain, etc.
Answer: Your laptop is probably expecting a line level input. Your guitar is not a line level output, so you'll need something in between, either a preamp or your Vox processor. Otherwise, your guitar signal will be very quiet.
You shouldn't have any problems connecting your processor. When connecting the processor, set the volume output on the processor low and raise it gradually until the levels look good on the laptop (I usually shoot for -18dBFS). Since the processor's output is a headphone output, it will be higher than line level. You'll need to compensate for this or even a clean tone will sound distorted on the laptop.
What you really should get is a USB audio interface. They are not expensive (


Exception in compiling groovy & java using maven

Question: My groovy file contains:
<code>@Grapes([

    @Grab('org.codehaus.groovy.modules.http-builder:http-builder:0.7'),
    @Grab('org.apache.httpcomponents:httpmime:4.5.1')

])
</code>
.......code
I am trying to compile groovy and java code. But I am getting below error:
<code>java.lang.RuntimeException: Transform groovy.grape.GrabAnnotationTransformation@69bda33a cannot be run
</code>
Answer: This works for me, note that I did change HttpBuilder to v.0.7.1:
<code>@Grapes([
    @Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.7.1'),
    @Grab(group='org.apache.httpcomponents', module='httpmime', version='4.5.1')
])
</code>
Comment: Thanks but unfortunately, its not working for me. I am compiling using maven: **mvn compile install**
Answer: Likely way too late for you to care, but I saw the same error just now.
I suspect the problem is that the @Grab annotation can't take effect because Maven is controlling the dependencies, or perhaps because Maven is trying to compile both Groovy and Java code, and the class loader created by the @Grab annotation can't influence the Java code.
Upshot is, I suspect you (and I) need to move the dependency out of the Groovy class in question, and put it into the pom.xml file Maven is using.


How to solve this sum with factorials

Question: $$
\sum _{i=1}^{n-k+1}\frac{\left(n-k\right)!\left(n-i\right)!}{\left(n-k-i\right)!}
$$
I dont know how to solve this sum with factorials.
Comment: Are $n$ and $k$ both fixed?
Answer: Since $n$ and $k$ are both constants, let's let $m=n-k$ and rewrite it in the visually simpler form
$$\sum_{i=1}^{m+1}\frac{m!(m+k-i)!}{(m-i)!}\,.$$
The denominator is negative when $i=m+1$, so we might as well lower the upper limit to $m$ and make it
$$\sum_{i=1}^m\frac{m!(m+k-i)!}{(m-i)!}\,.$$
As $i$ runs from $1$ up to $m$, $m-i$ runs from $m-1$ down to $0$. And $m-i$ appears in two of the three factorials, so let's let $j=m-i$: with that substitution it becomes
$$\sum_{j=0}^{m-1}\frac{m!(k+j)!}{j!}=m!\sum_{j=0}^{m-1}\frac{(k+j)!}{j!}\,.$$
The fraction inside the summation looks like part of a binomial coefficient:
$$\binom{k+j}j=\frac{(k+j)!}{j!k!}\,,$$
so
$$\frac{(k+j)!}{j!}=k!\binom{k+j}j\,,$$
and the sum can be rewritten as
$$m!k!\sum_{j=0}^{m-1}\binom{k+j}j=k!(n-k)!\sum_{j=0}^{m-1}\binom{k+j}j\,.$$
This last summation is a form of the hockey stick identity [PDF], and with that I'll let you finish off the simplification.
Added: By the way, I was writing this as I thought my way through the solution, so this write-up very closely mirrors my actual thought processes, and you can take it as an illustration of how one might actually think about attacking such a problem.

How to solve this sum with factorials


Can a binomial distribution have negative x values?

Question: The Poisson distribution makes a big deal that its great for modeling "Counts" of stuff (aka counts of monthly users) because its a non negative discrete distribution.
Well, aren't Binomial and Bernoulli distributions also non negative?
I can't think of any discrete distributions that can have negative x values. (Normal distribution i believe is a continuous distribution so it doesn't count)
Comment: 2. ""I cant think of any discrete distributions that can have negative x values." ... if you're asking for examples, one such (named) example is the [Skellam](https://en.wikipedia.org/wiki/Skellam_distribution) (the difference of two independent Poisson r.v.s, with potentially different parameters). There are a number of questions on site that relate to it ... https://stats.stackexchange.com/search?q=skellam
Comment: Counts are intrinsically non-negative.  But other examples, such as the positions of a random walk with discrete steps certainly can.
Comment: Note that the Poisson distribution is usually used not because it has non-negative support, but rather because the law of rare events (https://en.wikipedia.org/wiki/Poisson_distribution#law_of_rare_events) says that if we count an independent events each occuring with small probability, then the total count can be approximated with a Poisson distribution.
Comment: 1. '*The Poisson distribution makes a big deal that its great for modeling "Counts" of stuff (aka counts of monthly users) because its a non negative discrete distribution.*'. No it doesn't, the Poisson is not able to take any such action. Some people might, but it would be quite odd for a person to single out the Poisson for this specific characteristic alone; which makes me wonder -- what are you reading??
Answer: Poisson, binomial, Bernoulli, negative binomial, etc. are just model distributions - that is distributions that are analytically tractable and/or can be derived under rather simple assumptions. One could thus reformulate the question as:

Are there known model discrete distributions with a support containing negative numbers?

Then the question becomes obviously about how we define these discrete distributions - the most well-known ones are defined with support on non-negative integers. Specifically the binomial has support
$$
k\in\{0,1,...,n\}$$
As @Tim pointed out in their answer, we can easily define a distribution with negative support, using the one with positive support.
This brings us to the phenomena that we actually describe: thinking of a problem where negative counts arise naturally could suggest a distribution (which is not necessarily a known and/or model one.) However, many real counts are by nature positive - like the mentioned counts of monthly users (unless we explicitly shift the origin, just as in @Tim answer.)
Remarks:

Wikipedia has a list of discrete probability distributions, many of which are the distributions on integers. On a brief glance none of them has support extending to negative numbers.
A similar question: Can the discrete variable be a negative number?
Comment: @Katsu Correct: majority of practical situations concern counting items and events, whose number is by nature non-negative. There are situations when negative numbers are needed/useful - like price variation, temperature, etc., but they are rare, so no special model distributions were developed (or at least, they have not become famous.)
Comment: Good answer. So to summarize, in most real world situations, since discrete number counts itself is non-negative, the resulting distribution will also be non negative.
Answer: The binomial distribution is a distribution for a sum of Bernoulli trials: the sum of zeros and ones is non-negative. But it is not true that all discrete distributions are non-negative.
For a trivial example, say that $X$ follows a Poisson distribution and you create another variable $Y = -X$. $Y$ would be discrete and all its values would be smaller than or equal to zero by definition. The distribution for $Y$ does not have a name (it's like a Poisson distribution, just look at the $-y$ values), but as noted in the comments, there are named examples like the Skellam distribution.
Comment: An even more trivial example is that opinion scores on an ordered scale could be taken as $-2(1)2$ or $-3(1)3$ with $0$ as a neutral category. It's just a matter of convention that people often or even usually work with $1(1)5$, $1(1)7$, or whatever.
Comment: @NickCox Does $a(b)c$ mean integers from $a$ to $c$ inclusive in increments of $b$?
Comment: Precisely. It's an interesting question to me who introduced this notation (it is certainly in Tukey _Annals of Mathematical Statistics_ 1948 as if self-evident)  but it is standard in what I read and in software I use.
Answer: A less intuitive but important example for a discrete distribution with negative support would be the distribution of (unit or dollar) sales for a particular product at a given point of sale, conditional on various predictors like the day of the week, time of the year, promotions etc.
This is discrete because most products are sold by units (and therefore, dollar sales are also discrete). It has potential negative support because of product returns. Anecdotally, US consumer electronics retailers have quite a problem with big screen TVs that are bought right before the Super Bowl and returned for a full refund right after the game.
Comment: Yeah... let me add to that "Anecdotally" comment, it's a real thing.
Comment: @jbowman: thanks! Since the plural of "anecdote" is "data", two people with the same anecdote is a bona fide data point! :-)
Comment: I've known people boasting about buying stuff with a card on one floor of a big store and getting a cash refund on another floor a few minutes later.


Switch from existing firewalld configuration to nftables

Question: I'm running a low-RAM VPS with CentOS 8. I've noticed that firewalld service uses way too much RAM (up to 20%). So I guess it may be better to switch to use only built-in nftables.
I'm quite familiar with old iptables as well as firewalld syntax.
However, I'm not familiar with nftables syntax and configuration (and currently I cannot afford learning it and manual rewrite due to time restrictions).
Is it possible to export existing firewalld rules so nftables would be using them "directly" and it will be possible to completely disable firewalld service?
P.S. Will it be possible for fail2ban to work with nftables directly in such configuration?

EDIT: It's not a question of budget/RAM increase. This VM is running on existing on-premise infrastructure, without spare resources left, so its RAM is limited to 256MB (OpenVZ), and, unfortunately, cannot be easily enlarged - without updating the infrastructure, but it's out of my sphere of responsibility (and rebuilding the infrastructure will require way more time than simply exporting configuration from firewalld to nftables).
Currently it's running OK, but uses almost all RAM, so I'm looking for ways to optimize it. AFAIK, firewalld is just a front-end to nftables, so my idea is to use it only for configuration, and leave the main job to nftables - if that's possible.
Comment: Ouch. 256MB is just not enough to even maintain the system. And the cost of your labor to try to "optimize" this is probably orders of magnitude more than the cost of simply upgrading the server's memory. And that's not even getting into what a bad idea OpenVZ is.
Comment: For CentOS 8 you need at least 1GB of RAM+swap just to update the system's packages while running whatever your workload is, and not running out of memory. Having anything less than that, you're going to run into trouble with something sooner or later. And your low end VPS should have at least that much RAM or you're probably paying too much. If you're on an extreme budget, see https://lowendbox.com/
Comment: @MichaelHampton, thank you for you suggestions. I've edited the question to be more specific.
Answer:
I'm not familiar with nftables syntax and configuration (and currently
I cannot afford learning it and manual rewrite due to time
restrictions).

Keep firewalld if you are not going to learn nftables. Risking a misconfigured firewall is not worth what might be merely tens of MB of RAM savings. Hopefully, your time is valuable enough where you can justify renting a VM with slightly more resources, and be done with it. (If that's even necessary, I'm not convinced you have a performance problem.)
Firewall rules are not a one time thing, eventually they will need updating. How are you going to ensure that 6 months from now, this write firewalld and convert process will be followed?
EPEL 8 fail2ban-firewalld package is naturally firewalld based. Easy enough to switch to a nftables based jail, but that is still a configuration you will want to test.
Comment: Thanks! My original idea was to use `firewalld` only for configuration (initial and further updates), and to leave the main job to `nftables` - if that's possible. I've edited the question to be more specific.


How can i add 5 grace notes before a note, when only one grace note can fit in? (GuitarPRO)

Question: Here's a part (measure 3) of "Tango En Skaï" (Roland Dyens) I am trying to write out.

You can see there are 5 grace notes before the A, how would I add this in GuitarPRO?

Here what it looks like when I try and add a grace note before.
Please help if you know how.
Update:

You can do it Sibelius!
Answer: As of Guitar Pro 7.5, it is not possible to add multiple grace notes in this way.

Grace-note before the beat: A Grace note is an ornamentation that consists in a very short note played
before an other one. In Guitar Pro, you can add a grace note for each string.
However, it is not possible to set several grace notes on the same string. A grace note does not count for the bar duration and for the rhythm display.

(Guitar Pro 7.5 User Guide, page 92).
Comment: @jumpmanjo I know MuseScore can do it. Likely others (especially Sibelius and Finale), but you'd have to check.
Comment: is there any software I can use that would allow me to add several grace notes before a beat? Thank you for the answer.
Comment: Noteflight does support 5 grace notes on the same string.
[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/SsGf8.png


jQuery toggle nested ul from a link in parent li

Question: This should be simple, but I can't get it to work when the 'trigger' is an anchor inside the li. I want the anchor, when clicked to toggle the appropriate nested ul.
Here is the HTML:

top level li

top level li

li to trigger nested list first trigger or second trigger.

Title 1

something

something

Title 2

something

something

I would like to do it so I don't have to write a function for reach, to make it more global. Here is what I've tried but I come up with it either not working or adding the # to the url
$(function() {
    $('.trigger').click(function() {
        $(this).attr('href').toggle(slow);
        return false;
    )};
});

thank you very much for any help.
Comment: Save yourself a WHOLE lot of time.....just use Superfish.
Comment: @bpeterson - interesting...I use that for navigation drop downs but hadn't thought to use it here....
Answer: Here's an attempted fix:

top level li

top level li

li to trigger nested list first trigger or second trigger.

Title 1

something

something

Title 2

something

something

$(function() {
    $('.trigger').click(function() {
        $("'#" + $(this).attr('href')).toggle('slow');
        return false;
    )};
});

http://jsfiddle.net/kcq7K/2/
Slightly modified version that doesn't rely on ids rather position:
$('.trigger').click(function() {
    $(this).siblings('ul').eq($(this).index()).toggle('slow');
    return false;
});

http://jsfiddle.net/kcq7K/3/
Comment: works exactly as I asked for it to with the addition of ul li ul {display:none;} how do I get them to work so only one is visible? that is if you trigger the first list, then click the second trigger it would slide the first up as the second slides in? kind of accordion like?
Comment: That's bit tricky but to give you an idea, see this: http://jsfiddle.net/kcq7K/5/
Comment: excellent, thank you. I actually understand what you coded, just couldn't come up with it by myself. thx again.
Answer: Try this:
HTML:

top level li

top level li

li to trigger nested list first trigger or second trigger.

Title 1

something

something

Title 2

something

something

JavaScript:
$(function() {
    $('.trigger').click(function() {
        var id = $(this).attr('href');
        $('#' + id).toggle('slow');
        return false;
    });
});

Comment: toggle(slow) should be toggle('slow'), `)};` should be `});`,
Comment: No big deal - I make mistakes like that all the time. BTW, I'm not stalking you :).
Comment: I guess we're just both on the jQuery questions today.
Comment: @Matt - so I have it working, and thanks you answered exactly what I asked, but I omitted something. Is it possible to make one close when the other opens, so there is only one being displayed at a time?


print results to text file in tabular form

Question: I am currently printing onto console, can I print the output onto a text file in tabular form?
I am trying to write the file with:
with open("increment.txt", "w") as file:
    file.write(i, mol)
    file.close()

Here is the program:
import numpy as np

    i: int
    for i in range(1, 100,5):
        mol = int((i*5)/(i+2))

        print('i & mol are:',i, mol)

    with open("incre.txt", "w") as file:
        file.write(i, mol)
        file.close()

Error message..
file.write(i, mol)
TypeError: write() argument must be str, not tuple
Comment: Possible duplicate of [Writing data to text file in table format](https://stackoverflow.com/questions/26229140/writing-data-to-text-file-in-table-format)
Comment: You are passing a tuple to the `.write()` method. Remove redundant parentheses.
Answer: You are defining mol inside of your loop; here is the corrected code as far as I understand your question:
    with open("incre.txt", "w") as file:
        for i in range(1, 100, 5):
            mol = int((i * 5) / (i + 2))
            file.write(str(i) + " " + str(mol))
        file.close()

This will write your i variable separated by a space, then your mol variable. Note since you haven't specified an output directory, it will create the file wherever your python script is stored.
Here is a more pythonic approach:
def write_example(output_path):
    with open(output_path, "w") as file:
        for i in range(1, 100, 5):
            mol = int((i * 5) / (i + 2))
            file.write(str(i) + " " + str(mol) + "\n")
        file.close()

outpath = "/home/some_path_here/test.txt"
write_example(outpath)

This produces a txt file with the following contents:
1 1
6 3
11 4
16 4
21 4
26 4
31 4
36 4
41 4
46 4
51 4
56 4
61 4
66 4
71 4
76 4
81 4
86 4
91 4
96 4
Each of these being on a new line.
Let me know if this helped! Cheers!
Comment: Thank you, this helped! Also is there a way to give headers to list of output? For example: i and mol followed by their values onto a text file? I am trying with tabulate, is there any other efficient way, please suggest!
Comment: @user1234 Sorry for the late reply, but I would try the pandas module's to_csv function https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_csv.html you can make a dataframe object and then convert this into a csv file.


Angular 2 Webpack Production Build & Node: can't get direct URLs to serve

Question: I followed the instructions to create a webpack build environment from the angular.io site: https://angular.io/docs/ts/latest/guide/webpack.html, and got it working. Then, I took the Tour of Heroes tutorial that I got working, and I migrated it to a webpack environment.
If I run the Tour of Heroes using the webpack dev environment (with npm start), it works great. If I then create a production build (with npm run build), and serve the resulting files with node, I cannot get the server to respond when I try to access a URL directly. Below I will outline the steps to create the environment and the problem step-by-step. I believe the solution is to modify my server.js file, but I don't know what is needed.
How to recreate:

Create the webpack build environment per the instructions on the website (link above).
Copy the app folder from the Tour of Heroes liteserver environment to the src folder of the webpack environment
In index.html of the webpack environment, comment out (or remove) all the scripts for polyfills and Configure SystemJS. Index.html should look like this:

    <base href="/">
    <title>Angular 2 QuickStart</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <my-app>Loading...</my-app>

Modify the package.json so it has what is needed from both environments. Mine looks like this:
{
  "name": "angular2-webpack",
  "version": "1.0.0",
  "description": "A webpack starter for Angular",
  "scripts": {
    "start": "webpack-dev-server --inline --progress --port 8080",
    "test": "karma start",
    "build": "rimraf dist && webpack --config config/webpack.prod.js --progress --profile --bail"
  },
  "licenses": [
    {
      "type": "MIT",
      "url": "https://github.com/angular/angular.io/blob/master/LICENSE"
    }
  ],
  "dependencies": {
    "@angular/common": "~2.1.1",
    "@angular/compiler": "~2.1.1",
    "@angular/core": "~2.1.1",
    "@angular/forms": "~2.1.1",
    "@angular/http": "~2.1.1",
    "@angular/platform-browser": "~2.1.1",
    "@angular/platform-browser-dynamic": "~2.1.1",
    "@angular/router": "~3.1.1",
    "angular2-cool-storage": "^1.1.0",
    "angular2-in-memory-web-api": "0.0.20",
    "bootstrap": "^3.3.6",
    "core-js": "^2.4.1",
    "reflect-metadata": "^0.1.3",
    "rxjs": "5.0.0-beta.12",
    "zone.js": "^0.6.25"
  },
  "devDependencies": {
    "@types/core-js": "^0.9.34",
    "@types/node": "^6.0.45",
    "@types/jasmine": "^2.5.35",
    "angular2-template-loader": "^0.4.0",
    "awesome-typescript-loader": "^2.2.4",
    "css-loader": "^0.23.1",
    "extract-text-webpack-plugin": "^1.0.1",
    "file-loader": "^0.8.5",
    "html-loader": "^0.4.3",
    "html-webpack-plugin": "^2.15.0",
    "jasmine-core": "^2.4.1",
    "karma": "^1.2.0",
    "karma-jasmine": "^1.0.2",
    "karma-phantomjs-launcher": "^1.0.2",
    "karma-sourcemap-loader": "^0.3.7",
    "karma-webpack": "^1.8.0",
    "null-loader": "^0.1.1",
    "phantomjs-prebuilt": "^2.1.7",
    "raw-loader": "^0.5.1",
    "rimraf": "^2.5.2",
    "style-loader": "^0.13.1",
    "typescript": "^2.0.3",
    "webpack": "^1.13.0",
    "webpack-dev-server": "^1.14.1",
    "webpack-merge": "^0.14.0"
  }
}

From the webpack folder, run npm install
From the webpack folder, run npm run build to create prod build files. This is what the webpack tutorial says to do.
Create a node server environment.
Create a server.js file at the root that looks like this:
var express = require("express");

var app = express();

app.use(function(req, res, next) {
    console.log("Request recieved for:", req.url);
    next();
});

app.use(express.static('public'));

app.use(function(req, res, next) {
    res.status(404);
    res.send('404 file not found');
});

app.listen(4040, function() {
    console.log("yes: 4040");
});

In the node environment, create a public folder, and put all the files from the dist folder that was created in step 6 into the public folder.
Run the node server with node server.js
Go to localhost:4040. Everything works fine when accessed this way.
Enter this URL directly: http://localhost:4040/heroes
Get the 404 Error.
From the webpack environment if you run npm start, you can go to the URL directly http://localhost:4040/heroes and it works fine.

If you want to see all the code for this, here is the github repo: https://github.com/joshuaforman/heroeswebpack
Comment: Try changing the `` to `` ?
Comment: What happens with `http://localhost:4040/#/heroes` ?
Comment: @Searching: it sends me to the page that is loaded if I were to enter only `http://localhost:4040` - in this case, the dashboard page. And what shows in the URL is `http://localhost:4040/dashboard#/heroes`. It does this no matter what I put in place of `heroes`. For instance, I can say `http://localhost:4040/blah`, and still go to the default page loaded, with this in the URL: `http://localhost:4040/dashboard#/blah`. So, closer to what I need, but not yet there. What is that `#` doing?
Comment: @ErtySeidohl : changing to `` in the index.html file does not change the behavior.
Answer: I've got it figured out. The issue was in the server.js. After more research, I found this: https://expressjs.com/en/starter/static-files.html. Need to add more middleware after the express.static middleware: app.use('/heroes', express.static('public'));. The direct URLs work as needed with this server.js file:
var express = require("express");

var app = express();

app.use(function(req, res, next) {
    console.log("Request recieved for:", req.url);
    next();
});

app.use(express.static('public'));
app.use('/heroes', express.static('public'));
app.use('/dashboard', express.static('public'));

app.use(function(req, res, next) {
    res.status(404);
    res.send('404 file not found');
});

app.listen(4040, function() {
    console.log("yes: 4040");
});

The app I'm working on also needs to pass params, so if you need to do that, you will need middleware of this format:
app.get('/peopledetails/:uid', function(req, res){
    var uid = req.params.uid,
        path = req.params[0] ? req.params[0] : 'index.html';
    res.sendFile(path, {root: './public'});
});

Thanks to this stack question for the above: Serve Static Files on a Dynamic Route using Express.
Thanks for the help, folks.