Is it possible to map objects to part of an existing table?

Question: Is it possible to map an object to only part of an existing table in a database? For example:
public class Account {

    private Integer id;

    private Integer accountNumber;

    @Id
    public Integer getId() {
        return this.id;
    }

    @Column(nullable=false)
    public Integer getAccountNumber() {
        return this.accountNumber;
    }

}

In the database (just for the sake of the question):
 Account

 - id
 - accountnumber

 - lastmodified
 - localbranchid

Answer: Yes, you can only map a portion of the columns in the database table to the Account class (you simply just map the columns you are interested in), but if you ever have a need to insert new Accounts into the database and the unmapped columns have not-null constraints and no database default values, you will run into problems.
Answer: There shouldn't be any problems leaving out fields in relational mapping. There is really only one rule. If the class is to be updateable then you need to include all of the fields that make up the primary key so the updates can be propagated to the database.


Send different email response based on form options?

Question: I need to set up a Request Download form in which users choose which software they want from a drop-down. Is there any way to make it, so they are sent a unique email for each software? If not, is there a way to just show different responses on form submit?
Answer: I experienced the same problem a while ago. I wrote a blog post on it (link below) if you need more information. Basically you can change the email that gets sent based on the input of the form by creating your own webform-mail-[node-id].tpl.php. Within this template you can change the content based on submission data in the $submission variable.
<code><?php
  if ($submission->data[1]['value'][0] == 'General Application'){
    print 'Thank you for submitting your resumé and covering letter'."\n\n";
  } else {
    print 'Thank you for submitting your resumé and covering letter for the position of '.$submission->data[1]['value'][0]'."\n\n";
  }
 ?>
</code>
http://bouncingorange.com/blog/201204/custom-email-templates-webform
Comment: link is broken.
Comment: Try: https://web.archive.org/web/20160511081132/http://bouncingorange.com/blog/201204/custom-email-templates-webform :)
Answer: You should be able to do this with rules and webform rules integration.

RULES

The Rules module allows site administrators to define conditionally executed actions based on occurring events (known as reactive or ECA rules). It's a replacement with more features for the trigger module in core and the successor of the Drupal 5 workflow-ng module.

WEBFORM RULES

This module adds rules integration on webforms.
Did you ever want to react on webform submission using rules but couldn't find the proper event?
Webform Rules makes it possible to catch webform submissions by rules and do whatever you'd like to do with it (meaning: do whatever rules let you do with it).


JS e HTML DIV - TAB KEY

Question: Boas,
Eu quero fazer um genero de ScoreBoard como se ve nos jogos, mas para Site...
Se a pessoa Clicar TAB, aparece uma tabla ou uma div#especifica...
Como faço isso?
Answer: Segue um exemplo deste comportamento. Utilizei o modal do boostrap para demonstrar e escutando o evento de quando uma tecla é pressionada e quando é solta. O código keyCode 9 representa o TAB, então, estamos escutando os eventos e quando for o TAB pressionado, mostra o modal, quando soltar o TAB, esconde o modal.

$(function() {
  $("body").on('keydown', function(e) {
    var keyCode = e.keyCode || e.which;
    if (keyCode == 9) {
      e.preventDefault();
      $('#modal').modal('show');
    }
  });

  $("body").on('keyup', function(e) {
    var keyCode = e.keyCode || e.which;
    if (keyCode == 9) {
      e.preventDefault();
      $('#modal').modal('hide');
    }
  });
});
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" />

Clique aqui, segure TAB, depois solte o TAB.

Título

        Dados..

Answer: Vamos la, o código abaixo detecta quando uma determinada tecla do teclado foi clicada.
e.keycode == 13

Está linha está dizendo que quando a tecla enter for clicada, a função abaixo será executada.
Porque enter e não tab?
Quando clicamos na tecla tab ela acaba mudando a seleção do elemento que está na página, então só para melhor entendimento alterei para a tecla enter.

Neste link você encontra todos os keycodes do teclado.

Para que funcione com o tab, basta alterar o 13 para 9.

$(document).keyup(function(e) {
            if (e.keyCode == 13) {

              if($('.placar').css('display') == 'block')
              {
                $('.placar').css('display', 'none');
                }
                else
                {
                $('.placar').css('display', 'block');
                }
            }
        });
.placar{
  display: none;
}

Aqui aparece o placar

JS e HTML DIV - TAB KEY


PHP - How to update multiple row using foreach?

Question: so i'm making a php file that updates multiple rows to mysql but I'm having a problem whenever i submit,and I have no idea if I'm using foreach well. here is my code:
$query = "SELECT id, departments, deptName, headOfOffice FROM aip";
$result = mysqli_query($db,$query);
$count = mysqli_num_rows($result);

while ($row = mysqli_fetch_assoc($result)) {

        echo '
';
        echo '<input type="text" name="id[]" value="'.$row['id'].'" readonly>	';
        echo '<input type="text" id ="department_code" name="department_code[]" value="'.$row['departments'].'">	';
        echo '<input type="text" id="department_name" name="department_name[]" value="'.$row['deptName'].'">	';
        echo '<input type="text" id="department_head" name="department_head[]" value="'.$row['headOfOffice'].'">	';
        echo '
';

}

echo '
';
echo '	';
echo '	';
echo '<input type="submit" name="update" value="Update">';
echo '
';

if($_SERVER["REQUEST_METHOD"] == "POST"){

$deptid = $_POST['id'];
$code = $_POST['department_code'];
$dname = $_POST['department_name'];
$dhead =$_POST['department_head'];

foreach($_POST['id'] as $count){ \\ i don't know if this is right.

$query2 = "UPDATE aip SET deparments = '".$code[$count].'" WHERE id = "'.$deptid[$count]."'";
$result2 = mysqli_query($db,$query2);
}

 }

the error says "Undefined offset: 2"
I'm a newbie here, and this is my first time using arrays. hope someone could help. please!
Comment: You should use prepared statements, which make errors like this almost not possible.  Also, you might be able to do a single `UPDATE` instead of looping.
Comment: It's probably here `deparments = '".$code[$count].'" `
Comment: @GurV so what should i do about it?
Answer: foreach($_POST['id'] as $count => $id){
    $query2 = "UPDATE aip SET deparments = '".$code[$count]."' WHERE id = '".$deptid[$count]."'";
    $result2 = mysqli_query($db,$query2);
}

P.S. your code is vulnerable to SQL injection
Comment: i already made the changes, the errors are gone but still it doesn't update.
Comment: place updating code at the start of a file otherwise you don't see changes. Try to refresh page to see your changes.
Answer: There are two ways of using foreach:
foreach($array as $key => $value){
    ...
}

or
foreach($array as $value){
    ...
}

The foreach loop will then iterate through all elements in array, executing the code in brackets for each element once, holding the key name and the value of the element in $key and $value respectively (you can use other than $value and $key as well).
I don't fully understand what exactly you are doing in your code, so if you add an explanation, I will be able to solve your particular case;
Answer:
i have changed in your script..pls used my script. you do not need to changes any thing just copy and paste my script.

    if($_SERVER["REQUEST_METHOD"] == "POST"){
         $data = $_POST;

        if(count($data['id'])>0){
          foreach($data as $key=>$item){
              $query2 = "UPDATE aip SET deparments = '".$item['department_code'][$key]."', deptName = '".$item['department_name'][$key]."',headOfOffice = '".$item['department_head'][$key]."'  WHERE id = '".$item['id'][$key]."'";
              $result2 = mysqli_query($db,$query2);
        }
   }
}


How to iterate through the built-in types in C#?

Question: I want to iterate through the built-in types (bool, char, sbyte, byte, short, ushort, etc) in c#.
How to do that?
foreach(var x in GetBuiltInTypes())
{
//do something on x
}

Comment: Only the primitive value types?
Comment: @Bolt: yes, the primitive ones only.
Comment: Since they are built in (and not likely to change any time soon, maybe just make an enum with all the types and then iterate over that with a `foreach(Type builtInType in MyEnumTypes)`. . .?
Answer: System.TypeCode is the closest thing I can think of.
foreach(TypeCode t in Enum.GetValues(typeof(TypeCode)))
{
    // do something interesting with the value...
}

Comment: I like this solution. Thank you. For other solutions, thank you as well.
Comment: Here, have a "Nice Answer" badge :)
Answer: It depends on how you define "built-in" types of course.
You might want something like:
public static IEnumerable<Type> GetBuiltInTypes()
{
   return typeof(int).Assembly
                     .GetTypes()
                     .Where(t => t.IsPrimitive);
}

This should give you (from MSDN):
Boolean, Byte, SByte, Int16, UInt16, Int32, UInt32, Int64, UInt64, IntPtr, UIntPtr, Char, Double, and Single.
If you have a different definition, you might want to enumerate all of the types in common BCL assemblies (such as mscorlib, System.dll, System.Core.dll etc.), applying your filter as you go along.
Comment: System.TypeCode would provide string, char, and integer variants in one place.
Comment: Ah, the beauty (and slowness) of LINQ! Those solutions are always creative. :)
Comment: can we make a single function `GetBuiltInTypes` for all built-in primitive types including string, char, integer variants?
Comment: If you use LINQ, I think it'd be nice to use `return from type in typeof(int).Assembly.GetTypes() where type.IsPrimitive select type;` instead; what do you think? :)
Comment: @Mehrdad: I don't have a strong preference in this case between the two syntaxes. IMO, both are equally readable.
Answer: There's no built-in way to do that; you can try:
foreach (var type in new Type[] { typeof(byte), typeof(sbyte), ... })
{
    //...
}

Of course, if you're going to be doing this a lot, factor out the array and put it inside a static readonly variable.
Comment: This is invalid syntax. Did you perhaps mean foreach (var type *in* ...)?
Comment: @Cameron: Ooops, yeah... I was thinking half in D, half in C#. Thanks! :)
Comment: I just changed it, yeah it was a typo.


How to solve this with gamma and beta function

Question: I can't solve this, no matter how I try
Comment: So, what did you try ?
Comment: i tried to put (x=u\1+u)   to change the determenant to 0 and infinity and slove it with beta function but i cant reshape the problem to be like beta function famous formula
Comment: I think it could be good you include in the post everything you tried. Cheers.
Answer: Hint: Let $x=\dfrac1t~.~$ Now all that's left to do is evaluating $2I=\displaystyle\int_0^\infty\frac{dt}{\sqrt{1+t^4}}~,~$  which can be done by substituting $u=\dfrac1{1+t^4}.$
Comment: Lucian can you explain more please
Comment: @user297497: What do you get after you do the substitution ?
Comment: when you sustitute x=1\t then when x=0 ...t=infinity and when x=1...t=1..
Comment: http://i.stack.imgur.com/4BK2W.png that what it reached
Comment: @user297497: So you do agree that $2I=\displaystyle\int_0^\infty\frac{dx}{\sqrt{1+t^4}}$ ?
Comment: no lucian i dont agree i cant know how did you reach from the obve question to these formula
Comment: @user297497: Do you agree that, in general, $\displaystyle\int_a^bf(x)~dx+\int_b^cf(x)~dx~=~\int_a^cf(x)~dx$ ?
Comment: yes off course i agree
Comment: @user297497: Then we agree that $I+I=\displaystyle\int_0^\infty\frac{dt}{\sqrt{1+t^4}}~,~$ correct ?
Comment: do you mean wat written in the picture   [1]: http://i.stack.imgur.com/PZ78L.png   worng it worng the determenat is different you cant say that
Comment: @user297497: Let $a=0,~b=1,~c=\infty,$ and $f(t)=\dfrac1{\sqrt{1+t^4}}$


makefiles, função include

Question: Eu estou tentando analisar o makefile abaixo. Mas eu fico sem entender como se encaixa a parte de baixo com o resto.
%.d: %.cpp
<TAB> g++ $< -MM -MT '$*.o $*.d ' -MD $(CPPFLAGS)

cria um arquivo .d que contem uma informação de tipo
   Fraction.o: Fraction.cpp Fraction.h

ou seja o arquivo a compilar com suas dependências.
Vem depois o
-include $(CPPSOURCES:.cpp=.d)

que vai incluir a linha anterior no makefile
Beleza, isso vai mostrar as dependências de todos os arquivos cpp a compilar. Mas nenhum comando é associado.
O comando de compilar vem com o target:
 %.o: %.cpp
 <TAB> g++ -c $< $(CPPFLAGS) -o $@

Como esse target se associa com o include?
Aqui o código completo:
CPPUNIT_PATH=/diretorio_onde_esta_o_cppunit
INCLUDE_DIR=$CPPUNIT_PATH)/include
LIB_DIR=$(CPPUNIT_PATH)/lib
LIBS=-lcppunit

CPPFLAGS=-I$(INCLUDE_DIR)
LDFLAGS=-L$(LIB_DIR) $(LIBS)

CPPSOURCES = $(wildcard *.cpp)

all: ftest

ftest: $(CPPSOURCES:.cpp=.o)
<TAB> g++ -o $@ $^ $(LDFLAGS)

%.o: %.cpp
<TAB> g++ -c $< $(CPPFLAGS) -o $@

clean
<TAB> -rm -f *.o ftest *~

remade:
<TAB> $(MAKE) clean
<TAB> $(MAKE)

-include $(CPPSOURCES:.cpp=.d)

 %.d: %.cpp
 <TAB> g++ $< -MM -MT '$*.o $*.d ' -MD $(CPPFLAGS)

Answer: tl;dr

makefile faz a expansão de suas variáveis e comandos trabalhando com substituição de texto;
arquivos incluídos podem ser gerados novamente e, nesse caso, a leitura do makefile é reiniciada;
um alvo pode ter múltiplas dependências, inclusive dependências escritas em momentos distintos;
makefile é mágico, as vezes até demais, e isso é confuso ;-)

Um exemplo do item 3, que indica que Fraction.o depende ao mesmo tempo de Fraction.cpp e Fraction.h:
Fraction.o: Fraction.cpp
<TAB> g++ -c $< $(CPPFLAGS) -o $@

Fraction.o: Fraction.cpp Fraction.h

Primeiramente, gostaria de falar que conhecia o include file do makefile, mas esse -include file me intrigou.
O include sem o traço na frente força o makefile a inserir, ipsis litteris, o conteúdo do arquivo dentro do makefile atual. Obviamente que isso gera encrenca caso o arquivo não exista (e não seja possível criá-lo), então o make explode de maneira catastrófica.
Já o -include funciona de modo quase igual ao include, a única diferença está na ausência do arquivo incluído (e na incapacidade de gerá-lo novamente também). Nesse caso, o -include passa silenciosamente sem alertar erros. Mais detalhes pode ser encontrada na documentação do Include do GNU Makefile.
Aí vamos para o mistério dos arquivos .d. Segundo nota na documentação do GNU Makefile, arquivos .d são arquivos makefile normais. Nesse caso e em casos mais mundanos, o arquivo .d é um makefile gerado dinamicamente que é atualizado sob demanda, contendo regras de dependência implícitas. Note que você colocou o jeito como ele cria esse arquivos em seu próprio exemplo:
%.d: %.cpp
<TAB> g++ $< -MM -MT '$*.o $*.d ' -MD $(CPPFLAGS)

Aqui, você está dizendo que qualquer arquivo que termine em .d pode ser gerado a partir de um arquivo de mesmo prefixo porém extensão .cpp.
Agora vem a mágica. Você precisa compilar para um arquivo objeto .o uma fonte qualquer .cpp. Eu particularmente não lembro como o makefile lida com múltiplas regras de criação, mas eu me lembro como ele lida com dependências.
Vou focar aqui apenas nos arquivo Fraction, ignorando os outros por hora.
No começo, makefile irá ler seu arquivo e expandir todas as variáveis e comandos que ele encontrar (e que for possível). Eu vou ignorar algumas variáveis que são específicas suas, como $(INCLUDE_DIR), $(LIBS) e tantas outras. Então, a primeira expansão que ele irá se preocupar é CPPSOURCES = $(wildcard *.cpp). Como estamos agora focando só no Fraction, isso irá expandir para CPPSOURCES = Fraction.cpp. Até então, não há nenhuma linha de dependência no seu makefile, apenas variáveis.
Logo em seguida, ele encontra a primeira regra: all: ftest. Então, efetivamente, o seu makefile nesse momento tem o seguinte conteúdo:
all: ftest

Um alvo .PHONY, que não será gerado um arquivo com seu nome, mas tem um identificador para ajudar na hora de realizar o build.
A próxima linha com conteúdo é ftest: $(CPPSOURCES:.cpp=.o). Note que a variável CPPSOURCES está sofrendo uma expansão em que a string .cpp é trocada pela string .o. Como seu conteúdo nesse momento é Fraction.cpp, essa expansão retorna Fraction.o. O estado atual do makefile é:
all: ftest
ftest: Fraction.o
<TAB> g++ -o $@ $^ $(LDFLAGS)

A variável especial automática $@ expande para o alvo, portanto na hora de rodar o comando ela se chamará ftest; já a variável especial automática $^ expande para todas as dependências diretas de ftest, que no nosso caso é Fraction.o; note que, ao ter mais de um arquivo .cpp, a variável CPPSOURCES irá expandir para ter mútiplas valores .o na dependência de ftest. Como elas são variáveis especiais que dependem somente do target e das dependencies, irei deixar aqui. Mais sobre variáveis automáticas na documentação do GNU Makefile
Logo em seguida, encontra-se a regra %.o: %.cpp, que transforma um arquivo .cpp em um arquivo .o.
%.o: %.cpp
<TAB> g++ -c $< $(CPPFLAGS) -o $@

Aqui há o uso da variável especial automática $<. Diferente da $^, somente a primeira dependência é usada. Portanto, não importa quais outras dependências haja para gerar o arquivo .o, só será substituído em $< o nome do arquivo .cpp. Assim, temos que seu arquivo agora contém 3 dependências, com duas regras de criação:
all: ftest
ftest: Fraction.o
<TAB> g++ -o $@ $^ $(LDFLAGS)

%.o: %.cpp
<TAB> g++ -c $< $(CPPFLAGS) -o $@

Em seguida, entram mais dois alvos .PHONY antes de chegar no -include:
all: ftest
ftest: Fraction.o
<TAB> g++ -o $@ $^ $(LDFLAGS)

%.o: %.cpp
<TAB> g++ -c $< $(CPPFLAGS) -o $@

clean:
<TAB> -rm -f *.o ftest *~

remade:
<TAB> $(MAKE) clean
<TAB> $(MAKE)

Aqui, então, o makefile entra na linha da inclusão dos outros arquivos de makefile. Os arquivos são dados pela expansão $(CPPSOURCES:.cpp=.d). No nosso caso, essa expansão gera Fraction.d. Então, temos que o makefile irá interpretar o seguinte comando: -include Fraction.d. Aqui as coisas ficam interessantes.
Neste caso, existem 5 alternativas possíveis:

o arquivo não existe, mas existe uma regra de criação para ele;
o arquivo não existe, nem tampouco há regra de criação para ele;
o arquivo existe, mas há uma regra para ele indicando que ele está desatualizado;
o arquivo existe, e ele está atualizado de acordo com a regra;
o arquivo existe, porém não há regra para ele.

Até o momento, não é possível distinguir se o arquivo está nas alternativas 1,2 ou se está nas 2,3,4, pois não chegamos no final do arquivo e não encontramos regras de criação para ele. Vamos supor no momento que o arquivo exista, e que foi feita alguma alteração em Fraction.cpp. Nesse ponto, com essa suposição, o conteúdo do makefileé o seguinte:
all: ftest
ftest: Fraction.o
<TAB> g++ -o $@ $^ $(LDFLAGS)

%.o: %.cpp
<TAB> g++ -c $< $(CPPFLAGS) -o $@

clean:
<TAB> -rm -f *.o ftest *~

remade:
<TAB> $(MAKE) clean
<TAB> $(MAKE)

Fraction.o: Fraction.cpp Fraction.h

Logo em seguida, ele encontra uma regra para atualizar os arquivos .d, %.d: %.cpp. Como estamos na suposição de que o arquivo .cpp está mais atualizado do que o .d. Neste caso, os seguintes passos vão acontecer:

é usada a regra de geração para Fraction.d, pois ele é um arquivo incluído e, portanto, dependência deste makefile atual;
o makefile é lido novamente, do zero, desde o começo.

Se o arquivo Fraction.d não existisse a priori, ele também seguiria os mesmos passos de criar o arquivo e ler novamente o makefile. Mais você encontra na documentação do GNU Makefile.
Após o arquivo ser regerado, ele seguirá todos os passos de leitura e expansões do makefile novamente, até que finalmente ele termina no seguinte formato:
all: ftest
ftest: Fraction.o
<TAB> g++ -o $@ $^ $(LDFLAGS)

%.o: %.cpp
<TAB> g++ -c $< $(CPPFLAGS) -o $@

clean:
<TAB> -rm -f *.o ftest *~

remade:
<TAB> $(MAKE) clean
<TAB> $(MAKE)

Fraction.o: Fraction.cpp Fraction.h
%.d: %.cpp
<TAB> g++ $< -MM -MT '$*.o $*.d ' -MD $(CPPFLAGS)

Aqui, o arquivo Fraction.d está mais atualizado do que Fraction.cpp, pois acabou de ser gerado, portanto ele não precisará se preocupar novamente com a criação do Fraction.d. A partir daqui, o makefile irá executar as  construções; até então ele só estava se preparando.
Estou assumindo que você não passou nenhum parâmetro e que não exista nenhum arquivo chamado all no seu diretório de trabalho (para evitar que um arquivo chamado all impeça sua compilação, leia sobre alvos.PHONY). all depende de ftest e de nada mais.
Para executar ftest, você precisa de Fraction.o.
Existe uma regra de criação implícita para Fraction.o e, além disso, também há uma outra dependência declarada para ele. Ao todo, o conjunto dependências de Fraction.o é a união das dependências declaradas; no caso, temos Fraction.o: Fraction.cpp Fraction.h e %.o: %.cpp (que expande em Fraction.o: Fraction.cpp), daí a união é Fraction.o: Fraction.cpp Fraction.h (não se aceita repetições na união). Portanto, dado que o arquivo Fraction.cpp ou o Fraction.h seja atualizado, o arquivo Fraction.o precisa ser gerado.
Não há regras de criação nem para Fraction.cpp nem para Fraction.h, portanto o arquivo Fraction.o já está pronto para ser gerado com o comando g++ -c Fraction.cpp $(CPPFLAGS) -o Fraction.o.
Tendo todas as suas dependências geradas, ftest está pronto para ser gerado com o comando g++ -o ftest Fraction.o $(LDFLAGS).
Após ftest ser gerado, não há mais dependência para all, portanto o alvo foi gerado com sucesso.

makefiles, função include


HmacSHA256 returning different value in CryptoJs compared to .net/c#

Question: I have recently migrated a Blazor app to.net5 which no longer supports HmacSHA256 and hence I am trying to use jsInterop workaround to get it working. However, I see the value generated by CryptoJs HmacSHA256 is not the same as c#.
Javascript version with CryptoJS:
    var getHmac = (privateKey, data) => {
        const key = window.CryptoJS.enc.Utf8.parse(privateKey);
        const utfData = window.CryptoJS.enc.Utf8.parse(data);
        const hmac = window.CryptoJS.HmacSHA256(utfData, key);
        return hmac;
    }
   const result = CryptoJS.enc.Hex.stringify(getHmac("123","abc");

And the c# version:
        public byte[] HmacSha256(string key, string data)
        {
            var keyArray = Encoding.UTF8.GetBytes(key);
            var hashAlgorithm = new HMACSHA256(keyArray);

            return hashAlgorithm.ComputeHash(Encoding.UTF8.GetBytes(data));
        }
        public string ToHexString(IReadOnlyCollection<byte> array)
        {
            var hex = new StringBuilder(array.Count * 2);
            foreach (var b in array)
            {
                hex.AppendFormat("{0:x2}", b);
            }
            return hex.ToString();
        }
     var result = ToHexString(HmacSha256("123","abc"));

And they do not seem to have the same value. am I missing anything in the JavaScript implementation?
Thanks
Comment: Do you still get a difference if you use `Convert.ToHexString(array)` (https://learn.microsoft.com/en-us/dotnet/api/system.convert.tohexstring?view=net-5.0) instead of your own `ToHexString()` method?
Comment: The c# one works fine, I am trying to get the Javascript one to result in the same
Comment: Ah sorry, your question seems to be putting a lot more emphasis on the C# side than JS, implying that C# is wrong, not JS.
Answer: There is something strange... Testing in an online Javascript tester I get 8f16771f9f8851b26f4d460fa17de93e2711c7e51337cb8a608a0f81e1c1b6ae
// INIT
let privateKey = "123";
let data   = "abc";

document.getElementById("demo0").innerHTML = privateKey;
document.getElementById("demo1").innerHTML = data;

var getHmac = (privateKey, data) => {
    const key = CryptoJS.enc.Utf8.parse(privateKey);
    const utfData = CryptoJS.enc.Utf8.parse(data);
    const hmac = CryptoJS.HmacSHA256(utfData, key);
    return hmac;
}

const result = CryptoJS.enc.Hex.stringify(getHmac("123","abc"));

document.getElementById("demo2").innerHTML = result;

(I'm using crypto-js 4.0, the code is at https://codepen.io/gabrielizalo/pen/oLzaqx),
Testing with C# under .NET Core 5.0 (see https://dotnetfiddle.net/IfLyRa) (and 3.1) I get the same code.
Another online implementation (https://www.freeformatter.com/hmac-generator.html#ad-output) that says is using BouncyCastle returns the same result.


Constant conditional correlation (CCC) shows high spikes compared to Dynamic CC (DCC), why?

Question: I have calculated 5 beta factors (beta is defined as the ratio between covariance between two time series and the variance between the one series).
When I used CCC with GJR dynamics I get this

When calculating with DCC the picture looks very similar just without this extreme spikes of the blue line.
I am searching for an explanation. My first guess: The constant correlation matrix is not able to capture breaks in variance and covariance adequately?
But this is very high level. Do you have a more detailed idea for this phenomen?
Comment: what is CCC DCC GJR? people may not understand these terms, could you revise your title?
Comment: And while you are at it did you really mean wired?
Comment: I mean the high spikes for at least the one calculation...
Answer: The diagonal elements of the conditional covariance matrix are modelled separately by univariate GJRGARCH models in both CCC-GJRGARCH and DCC-GJRGARCH. Thus the fitted variances will be the same in both cases. Therefore, the differences in betas (which are ratios of covariances to variances) will be due to differences in cond. covariances, or more precisely cond. correlations.
When the spikes in betas are more pronounced in CCC than in DCC, it means cond. correlations at these spike periods are higher in CCC than in DCC. Since cond. correlations are constant in CCC, it means the fitted cond. correlations do not dip in those periods, while they do dip in DCC. (You can inspect the fitted cond. correlations to see if this is indeed the case.)
Whether CCC or DCC fits the data better can be seen by comparing the AIC or BIC values of the models.
Regarding breaks in variance and covariance, neither CCC nor DCC produces them by default. There is dynamics, but not breaks in the traditional sense. You would need to include dummy variables or fit the models on subsamples to properly account for breaks.


General method for solving problems like $17 \mid 2x + 3y \Longleftrightarrow 17 \mid 9x + 5y$

Question: Note: This is not a duplicate of Understanding a proof that $17\mid (2x+3y)$ iff $17\mid(9x +5y)$ or Understanding a proof that $2x + 3y$ is divisible by $17$ iff $9x + 5y$ is divisible by $17$.
I was reading through Naoki Sato's notes on number theory. I am somewhat unsatisfied with the given solution to this problem:

Example. Let $x$ and $y$ be integers. Prove that $2x + 3y$ is divisible by $17$ iff $9x + 5y$ is divisible by $17$.
Solution. $17 \mid 2x + 3y \Rightarrow 17 \mid 13(2x + 3y)$, or $17 \mid 26x + 39y \Rightarrow 17 \mid 9x + 5y$, and conversely, $17 \mid 9x + 5y \Rightarrow 17 \mid 4(9x + 5y)$, or $17 \mid 36x + 20y \Rightarrow 17 \mid 2x + 3y$.

I do understand the solution but it seems like an unmotivated approach. How would one get the numbers $13$ and $4$ except for clever guessing? Is there a general method for solving such problems? That is, some theorem that trivializes such problems. I don't know much about modular arithmetic but I've noticed that $13$ and $4$ are inverses modulo $17$, i.e. $17 \cdot 4 \equiv 1 \pmod{17}$. I believe it might have something to do with that.
Comment: The invertibility is why it's if and only if. Since $17$ is prime all non-zero elements are invertible. This allows you to solve for $x$ in terms of $y$ and vice versa because $2x + 3y \equiv0 \mod 17$. Do the same with $9x+5y$ and compare the answers.
Comment: See also https://math.stackexchange.com/questions/3046318/17-29x-18y-implies-17-23x-9y
Comment: You get 13 from solving $ 2 a \equiv 9 \pmod{17}$, and you get 4 from solving $ 9b \equiv 2 \pmod{17}$. This also explains why $ ab \equiv 1 \pmod{17}$ like you observed.
Comment: As mentioned in the dupes, scaling by a *unit (invertible)* $\,s\,$ always yields an *equivalent* divisibility (or congruence), thus $\,s(\color{#0a0}5y+\color{#c00}9x) \equiv \color{#0a0}3y+\color{#c00}2x\Rightarrow \color{#0a0}5s\equiv \color{#0a0}3\equiv 20\Rightarrow  s\equiv 4,\,$ and this works since it equalizes the $\rm\color{#c00}{coef}$ of $x$ too, i.e.  $\,\color{#c00}9s\equiv 9(4)\equiv\color{#c00}2,\,$ and $4$ is coprime to $17$ so is invertible. There are various equivalent ways of viewing this, likely all of which can be found in the dupes (and their links). $\ \ $
Answer: Let $(c,d)$ be an ordered pair in $((\mathbb{Z}/17\mathbb{Z})^*)^2$, and let $(x,y)$ is be any pair of integers s.t. $cx+dy$ is divisible by $17$. Then let $(c',d')$ be another pair in $((\mathbb{Z}/17\mathbb{Z})^*)^2$. Then $c'x+d'y$ is also divisible by $17$ iff either:

There is an element $a \in (\mathbb{Z}/17 \mathbb{Z})^*$ such that $(ac,ad)=(c',d')$, or

Both $x$ and $y$ are each divisible by $17$.

This is a straightforward exercise to check. Note that $17$ can be replaced by any prime $q$. Furthermore, this leads to a fast algorithm to check, as for any prime $q$, the equation $c=ac'$ can be solved for $a$ in time polylog$(q)$, and then it is straightforward to check whether the equation $d=ad'$ holds mod $q$.
Comment: Please strive not to post more (dupe) answers to dupes of FAQs. This is enforced site policy, see [here](https://math.meta.stackexchange.com/q/33508/242).
Answer: Remember that if $17|2x+3y$, this is the same as saying $2x+3y\equiv 0\mod(17)$, and therefore $2x\equiv -3y\mod(17)$. Solving for $x$ requires the multiplicative inverse of $2\mod(17)$, which happens to be $9$. Therefore  $x\equiv -(3\cdot9)y= -27y\equiv -10y\equiv 7y\mod(17)$
Now we do the same for the other divisibility statement: $17|9x+5y\Longrightarrow 9x\equiv -5\mod(17)$. We already know that $2$ and $9$ are multiplicative inverses $\mod(17)$, so this is equivalent to $x\equiv-10y\equiv 7y\mod(17)$.
Hang on, that's the same as what we got before! This means that assuming one of $2x+3y$ or $9x+5y$ to be divisible by $17$ leads to the other being divisible by it also, thus proving the claim.
Addendum: I got carried away with my method and forgot to answer the question you actually asked. $4$ and $13$ come from solving either $2m\equiv 9\mod(17)$ or $3n\equiv 5\mod(17)$. Solving the first requires the inverse of $2\mod(17)$, which we already know to be $9$; therefore $2m\equiv \frac{1}{2}\mod(17)\Longrightarrow m\equiv \frac{1}{4}\mod(17)$. The inverse of $4\mod(17)$ is $13$, so we conclude that $m\equiv 13\mod(17)$.
Now, solving for $n$ in $3n\equiv 5\mod(17)$ leads to $n\equiv\frac{1}{3}\cdot5\mod(17)$. The multiplicative inverse of $3\mod(17)$ is $6$, so we have $n\equiv6\cdot5=30\equiv 13\mod(17)$.
Thus $m=n$. What we have just done is found (and confirmed) the unique integer $k$ such that $k(2x+3y)\equiv 9x+5y\mod(17)$. This of course means that $2x+3y\equiv\frac{1}{k}(9x+5y)\mod(17)$, and if $13$ is substituted for $k$, we get $13(2x+3y)\equiv9x+5y\mod(17)$ and $2x+3y\equiv4(9x+5y)\mod(17)$. Since they are integer multiples of each other $\mod(17)$, assuming one to be an integer multiple of $17$ leads to the other being an integer multiple of $17$, i.e. they are both divisible by $17$.
In general: if you have $ax+by\equiv cx+dy\mod(p)$, where $p$ is a prime, then it is true that $p|ax+by$ and $p|cx+dy$ if and only if $a^{-1}c\equiv b^{-1}{d}\mod(p)$.
Comment: Please strive not to post more (dupe) answers to dupes of FAQs. This is enforced site policy, see [here](https://math.meta.stackexchange.com/q/33508/242).
Answer: I think a variation of Euclid's GCD algorithm can help out.
Line 1: $9x+5y=4(2x+3y)+x-7y$
Line 2: $2x+3y=2(x-7y)+17y$
Stop here since one of the coefficients of x or y is 0.
Suppose 17 divides $2x+3y$, then it must divide $(x-7y)$ by line 2.  If it divides both, 17 must also divide $(9x+5y)$ by line 1.
Combine the lines to get $(9x+5y)=4[2(x-7y)+17y]+x-7y=9(x-7y)+4 \cdot 17y$
So if $17$ divides $9x+5y$, it also divides $(x-7y)$. But by line 2, If 17 divides $(x-7y)$ then it divides $(2x+3y)$.
Comment: Please strive not to post more (dupe) answers to dupes of FAQs. This is enforced site policy, see [here](https://math.meta.stackexchange.com/q/33508/242).


Polymorphic static const member variables in an ABC?

Question: I have a rather strange situation where I would like to be able to define certain constants that a subclass of an ABC can override.
struct A {
    static const int a = 20;
    virtual int func() = 0;
};
struct B : public A {
    static const int a = 3;
    int func() { return 5; }
};
struct C : public A {
    static const int a = 4;
    int func() { return 3; }
};

Unfortunately, if I use A *aPtr = new B, aPtr->a will return 20, instead of 3.
One workaround I see is one-liner functions (along the lines of func in the above example), but the syntax of constants is quite a bit more appropriate for this particularly situation conceptually. Is there a syntactically reasonable way of resolving which constants to use at runtime, where the calling code doesn't need to know anything after initial object creation?
Comment: The reasoning behind wanting this may be flawed: A constant is supposed to be, well, *constant*. It's not sometimes constant and sometimes something else. Similarly, static members are properties of classes, not instances, so they play no role in inheritance, which is an *instance*-based concept.
Comment: possible duplicate of [Overriding static variables when subclassing](http://stackoverflow.com/questions/594730/overriding-static-variables-when-subclassing)
Answer: Constants, especially static constants, cannot be overriden like you are asking for.  You would have to use a virtual function instead:
struct A {
    virtual int get_a() { return 20; }
    int func() = 0;
};

struct B : public A {
    virtual int get_a() { return 3; }
    int func() { return 5; }
};

struct C : public A {
    virtual int get_a() { return 4; }
    int func() { return 3; }
};

Another option would be to use a template for the constant instead:
template< const int a_value = 20 >
struct A {
    static const int a = a_value;
    int func() = 0;
};

struct B : public A<3> {
    int func() { return 5; }
};

struct C : public A<4> {
    int func() { return 3; }
};

Comment: For the templated version one should note that the classes `B` and `C` are now entirely unrelated, since they have different base classes.
Answer: You can get answer from the example itself ! :) Just declare a method like get_a() which is virtual and override the same.
struct A {
    static const int a = 20;
    virtual int get_a() const { return a; }  // <--- for A
};
struct B : public A {
    static const int a = 3;
    virtual int get_a() const { return a; }    // <--- for B
};
struct C : public A {
    static const int a = 4;
    virtual int get_a() const { return a; }    // <--- for C
};

Also note that, only method can be overridden in C++ and not the variables.


Alternative Numerical Representation of Pitch

Question: I'm aware of a number of different ways of representing pitch as numbers (including one I developed for use in my own software) but am interested if there are others.
The most widespread is probably MIDI (where C4 is 60 and each semitone up/down adds/substracts 1 from the value).
The MIDI note value system conflates enharmonics (which is problematic for a lot of the work I'm interested in and pretty much a deal breaker) and can really only handle a 12eq but it does have the advantage that both pitch class and octave are incorporated in one number.
I've written a lot of code that uses my own circle of fifths system http://jtauber.com/blog/2007/12/13/numerical_representation_of_pitch/ assigning D to 0 and +1 means a fifth above and -1 a fifth below. This allows for distinct enharmonic spelling, and easy interval arithmetic (which makes it easy to give the correct answer to questions like: what's the augmented fourth above D♯?) and can easily test for enharmonic equivalence via a modulo operation. It can, however, extend beyond the 35 note names for non-12eq tunings. One disadvantage is it only represents pitch class so you need a second number to indicate octave.
Hewlett's Base-40 system http://www.ccarh.org/publications/reprints/base40/ is very clever in supporting distinct enharmonic spelling plus representing pitch class and octave in a single number in such a way that allows easy interval arithmetic. The only disadvantage I can see is it does assume 35 note names and so has a 12-note octave assumption built in.
Hewlett's page (linked to above) does mention work by Clements and Zimmerman.
Is Hewlett's Base-40 the dominant one used in computational musicology or are there other systems (that maintain interval invariance and enharmonic spelling differentiation) in use, and, if so, what are they?
Comment: I don't know if this will help you, but have you heard of pitch set theory?  It's good for abstracting relationships between a series of pitches, but does not assign absolute numbers.  http://en.wikipedia.org/wiki/Set_theory_(music)
Comment: Just represent the pitch using the frequency in Hertz. Problem solved. :) At least, as a physicist, this is what I would do.
Comment: @James Tauber: The answer to "Are there other systems in use in computational musicology?" is presumably yes. Are you looking for something in particular? For example: A system that provides greater advantages than the one you're using, with an explanation of it? If so, please add that information to the question; I don't see a real question here otherwise.
Comment: @Matthew Read: I've edited the final paragraph to make it clearer I'm interested in what other systems are in use
Comment: @Noldorin: joking aside, frequency isn't really that different than the MIDI note value. In fact, if you assume 12-eq and allow for non-integer MIDI note values, they are homeomorphic. Systems like Hewlett's and mine maintain note naming for us people that care that A♯ is not B♭ :-)
Comment: @cotroxell while not directly answering this question, your link is highly relevant to the broader questions I have; thanks!
Comment: @James Tauber: As a scientist, all I care about is complete information. I have that with frequency. :)
Comment: This answer outlines some information on working in the Tonnetz lattice similar to what's on the linked blog page: http://music.stackexchange.com/questions/20533/are-there-any-rules-of-thumb-for-shifting-the-key-signature-within-a-tone-net/26781#26781
Answer: There are many others.  Some piano technicians identify the keys on a piano by number, from 1 = the lowest A to 88 = the highest C.
In electrical engineering, the most common way is to use Hertz which is the number of cycles per second.  In standard pitch, A is 440.  A disadvantage of this system is that it is not linear, but you can convert it to a linear scale by taking the logarithm.  (What the piano technicians use is the log to base 22.5 of this number, if my math is correct.)  An advantage is that almost-exact values can be given for notes in different tuning systems and for enharmonics.  A disadvantage is that they can only be almost-exact because most of the numbers are irrational.
Harry Partch in his book Genesis of a Music formulated a system of ratios starting at a low G which is 1/1.  His system depends on instruments that are tuned using only rational numbers so that the intervals relate more closely to the harmonic series.  The D a fifth above low G is 3/2.
There are also systems that are not purely numerical.  There is a very commonly-used one in which the lowest C on the piano keyboard is CCC, the next is CC, the next is C, then c, then c', then c'' etc.  Another one labels the low C as C1, the next as C2 etc.
Early computer-based musical typology systems had only punched cards for input, so they needed a system.  This was for printed music, not sound generation.  One way is to indicate the staff line and note value; another is pitch class, octave and note value like "C5Q".
Comment: A better approach would be to abstract pitch class, tuning and enharmonic variations as three separate dimensions. Traditional notation has separate "dimensions" for diatonic pitch (vertical position on staff), accidental pitch modification (sharps and flats), note duration (note shape), position in time (note shape, rests, and horizontal position), overall loudness, single-note loudness (accents), musical phrasing, ornamentation, and separation of multiple parts (separate staves, or note stems up or down on one staff).  (But it doesn't answer your question.)
Comment: These systems are all either non-numerical or fail to maintain enharmonic spelling differentiation. I'm interested in whether Base-40 is still state-of-the-art or whether other systems have been developed in the last 25 years.


Trying to understand if a model is an empirical Bayes or not

Question: I am trying to understand if the model published in section 4.1.1 here is or is not an Empirical Bayes model (which the author claims it is). Or, maybe, if it is a valid one or not. The model looks as follows:
$$
X_i|\theta_i\sim N(\theta_i,\sigma),i\in\{1,2,\ldots,n\},\text{ and }\sigma \text{ known}\\
~\theta_i|\eta_i\sim N(\eta,\tau^2),i\in\{1,2,\ldots,n\},\text{ and }\tau^2 \text{ known}\\
\eta_i|\bar{X}\sim N\left(\bar{X},\frac{\sigma+\tau^2}{n}\right)
$$
I thought that using the data itself is not allowed when setting the prior. Is this sometimes okay, and others not?
I was also wondering if changing the model such that if we know that some $\theta_i=\theta_j ~ (i\neq j)$ and swapping $\bar{X}$ for $\bar{X}_j$ for the $\eta_i$s where we know them to be the same makes any difference?
Something like this:
$$
X_{ij}|\theta_{j}\sim N(\theta_j,\sigma),i\in\{1,2,\ldots,n\},j\in\{1,2,\ldots,m\},\text{ and }\sigma \text{ known}\\
~\theta_{j}|\eta_{j}\sim N(\eta_j,\tau^2),i\in\{1,2,\ldots,n\},j\in\{1,2,\ldots,m\},\text{ and }\tau^2 \text{ known}\\
\eta_{j}|\bar{X}_j\sim N\left(\bar{X}_j,\frac{\sigma+\tau^2}{n}\right)
$$
For simplicity assuming $\sigma,\tau$ to be the same for all data. $i$ are repeated measurements for the $j$:th mean.
Answer: The empirical Bayesian approach estimates the parameters from the data. In the case of the model described, it is an empirical Bayesian model because $\eta$ is estimated from the data. It is also discussed in the passage below the model definition

The choice of $\alpha(n) = n$ corresponds to an empirical Bayes model
that attempts to account for the uncertainty in estimating the "fixed"
parameter $\eta$ with  $\bar X$. This is justified by noting that
(4.3) with $\alpha(n) = n$ arises naturally by swapping $\eta$ and $\bar X$
in the sampling distribution of $\bar X$. However, in the interest of
remaining as general as possible, we permit $\alpha(n)$ to be any
positive function of $n$.

To learn more when it is ok, check the How is empirical Bayes valid? thread. Your re-parametrization just defines another model, that still has parameters calculated from the data, so is an empirical Bayesian model.
Comment: @Baraliuh you can use some other (e.g. historical) data to pick parameters for the priors in regular Bayesian models. In fact, almost always you pick the parameters based on your knowledge of the problem (so historical results) rather than picking the values completely out of the blue. Empirical Bayesian models use *the same* data, that's the difference.
Comment: Ok, cool. Thanks for clarifying and for the link. I've been told that even an EB is not allowed to use the data itself, but can draw information from "similar" data. I have a few datasets with one where n is very small (3) where I see using this type of model drastically improves performance while in other datasets n>4 it does not matter (even using an uninformative prior has the same performance). Just trying to avoid easy pickings for the reviewers :)


Last graph marker in matplotlib not showing fully

Question: I'm new to matplotlib. My graph in matplotlib doesn't show the last marker fully. I've tried increasing the figure size and nothing changes. I need to extend the figure so that it shows the last marker and also extend the line past the marker. Here's my code:
    import numpy as np
    import matplotlib.pyplot as plt

    x = np.array([1,2,5,10,15,20])
    y = np.array([0.049,0.080,0.123,0.166,0.209,0.335])

    A = np.vstack([x, np.ones(len(x))]).T
    m, c = np.linalg.lstsq(A, y)[0]

    x = np.array([0,1,2,5,10,15,20])
    y = np.array([c,0.049,0.080,0.123,0.166,0.209,0.335])

    plt.plot(x, y, 'r*', label='Original data', markersize=7)
    plt.plot(x, m*x + c, 'b', label='Fitted line')
    fig = plt.figure(1)
    fig.set_size_inches(9,8)
    fig.suptitle('THE GRAPH OF ABSORBANCE AGAINST CONCENTRATION',fontsize=20)
    plt.xlabel('CONCENTRATION',fontsize=15)
    plt.ylabel('ABSORBANCE',fontsize=15)
    plt.grid()
    fig.savefig('graph.jpg')

Would really appreciate your help.
Comment: possible duplicate of [How to autoscale y axis in matplotlib?](http://stackoverflow.com/questions/15375791/how-to-autoscale-y-axis-in-matplotlib)
Comment: http://stackoverflow.com/questions/14493334/add-margin-when-plots-run-against-the-edge-of-the-graph?lq=1
Comment: http://stackoverflow.com/questions/16003263/matplotlib-modify-autoscaling-rules/16003292#16003292
Comment: Did you get this sorted out?
Answer: (mostly copied from How to autoscale y axis in matplotlib?)
You want margins doc
ex
ax.margins(y=.1, x=.1)

Also see Add margin when plots run against the edge of the graph
matplotlib 1.3.x will include the rcParam values axes.xmargin and axes.ymargin to set a none-zero margin (code for it is in master already).


Get data from database if the input has one or more question marks.

Question: I'm tying to get inputs from a database if they have question marks on the inside.
For example:
GET FROM table
WHERE input = (As long as the input as a question mark inside)

For example, if the input is something like, "What's your name?", it'll get it from the database. But if it only says, "What's your name.", it won't get it from the database. How do I do that?
Comment: `GET FROM table`? I've never seen that in mysql.
Answer: In this case, like is a bit painful because ? is a wildcard.  One method is:
select t.*
from table t
where locate('?', input) > 0;

The alternative with like is to use the escape keyword:
where input like '%/?%' escape '/'


- Aparece esse erro entre o  , e dá diferença de espaço

Question: Como faço para remover este erro? Está causando espaçamento no cabeçalho do site.
Answer: Achei uma solução bem interessante, chama-se boom o arquivo.
Este arquivo php você pode colocar na pasta raiz do seu site, ele é uma espécie de scan, que por sua vez, acessa todos os arquivos e ajusta os valores de BOM de cada arquivo.
<?php
// Tell me the root folder path.
// You can also try this one
// $HOME = $_SERVER["DOCUMENT_ROOT"];
// Or this
// dirname(__FILE__)
ini_set('max_execution_time', 300);

$HOME = dirname(__FILE__);

// Is this a Windows host ? If it is, change this line to $WIN = 1;
$WIN = 0;

// That's all I need
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>UTF8 BOM FINDER and REMOVER</title>

<?php
$BOMBED = array();
RecursiveFolder($HOME);
echo '
These files had UTF8 BOM, but i cleaned them:

';
foreach ($BOMBED as $utf) { echo $utf ."
\n"; }
echo '
';

// Recursive finder
function RecursiveFolder($sHOME) {
  global $BOMBED, $WIN;

  $win32 = ($WIN == 1) ? "\\" : "/";

  $folder = dir($sHOME);

  $foundfolders = array();
  while ($file = $folder->read()) {
    if($file != "." and $file != "..") {
      if(filetype($sHOME . $win32 . $file) == "dir"){
        $foundfolders[count($foundfolders)] = $sHOME . $win32 . $file;
      } else {
        $content = file_get_contents($sHOME . $win32 . $file);
        $BOM = SearchBOM($content);
        if ($BOM) {
          $BOMBED[count($BOMBED)] = $sHOME . $win32 . $file;

          // Remove first three chars from the file
          $content = substr($content,3);
          // Write to file
          file_put_contents($sHOME . $win32 . $file, $content);
        }
      }
    }
  }
  $folder->close();

  if(count($foundfolders) > 0) {
    foreach ($foundfolders as $folder) {
      RecursiveFolder($folder, $win32);
    }
  }
}

// Searching for BOM in files
function SearchBOM($string) {
    if(substr($string,0,3) == pack("CCC",0xef,0xbb,0xbf)) return true;
    return false;
}
?>

O arquivo você pode colocar qualquernome.php, na raiz. Espero que possa ajudar a quem for necessário com este mísero e chato erro de bom.
Comment: Obrigado! mano.
Answer: &#65279 é um caráter especial do html, ou também, códigos do ISO Latin-1, que podem ser colocados no código-fonte como qualquer outro caráter alfanumérico, para produzir caracteres e símbolos que não poder ser gerados com comandos normais de teclado, são também conhecidos como html_entities numa breve abordagem.

Leitura Recomendada:
Special Characters in HTML
HTML Entities
Answer: Este valor (65279 == 0xFEFF) provavelmente é um BOM (byte-order mark) que está no seu arquivo (HTML). Abra o arquivo em um editor binário e veja se esses bytes estão no arquivo. Por exemplo, no Visual Studio, selecione "File -> Open", e no diálogo "Open File", selecione a opção "Open With..."

E selecione a opção "Binary Editor". Se você achar os bytes FEFF no arquivo, é só removê-los.
Comment: Abri pelo EditPlus, mas não achei...
Comment: Não conheço o EditPlus, mas alguns editores de "texto" escondem os BOM (o UltraEdit, que eu uso é um deles), mesmo no modo Hex Viewer...
Comment: Hmmm, mas eu até transformei o arquivo em bom + utf8, mas também não resolve o problema, tendo em vista que também há scripts em PHP
Comment: Entendi dorival, Mas não consegui mesmo achar uma solução, seu post talvez seria melhor esclarecer com qual programa eu poderia fazer isto, tendo em vista que não tenho esse que o Carlos citou... estou meio perdido ainda
Comment: É o VisualStudio Community? @carlosfigueira
Comment: Hmmm OK @DorivalZanetto - Vou testar sua solução pra ver... Mas eu já abri em vários editores e não consegui identificar onde está este código... :(
Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/30345/discussion-between-andre-baill-and-rafael-kendrik).
Comment: O VS Community tem essa opção também (eu estou usando o VS Professional).
Answer: O Carácter em questão &#65279 é o carácter unicode "zero width no-break space" (U+FEFF).
Pode ser que você copiou ele no seu codigo via copy and paste (CTRL + C e CTRL + V) sem perceber isso. O fato é que este não é visível se você está usando um editor de texto cujo o qual exibe carácteres unicode verdadeiros.
Uma opção é abrir o arquivo em um editor básico (por exemplo o editor de texto do windows) que não interprete unicode ou um que não interprete mas consiga exibir carácteres não ASCII.
Depois que você localizar o trecho de código, você pode excluir o bloco de texto em torno dele e o redigitar.
[Fonte: Stack Overflow]


What is the correct MySql FULL JOIN syntax?

Question: Following are my two tables; I want the results as illustrated in the third table. How can I do this in MySQL (assuming FULL JOIN)?
table_sales
product_id    quantity    date
c001          20        2013-09-03
t008          30        2013-09-01
t008          20        2013-09-03
c001          90        2013-09-09

table_returns
product_id    quantity    date
t008          40        2013-09-08
t008          30        2013-09-01
c001          10        2013-09-03

I want to get result like:
product_id     sale_qty      return_qty        date
c001           20            10              2013-09-03
c001           90            -               2013-09-09
t008           30            30              2013-09-01
t008           20            -               2013-09-01
t008           -             40              2013-09-08

Comment: Yep, that's a FULL JOIN — are you asking what the syntax is? Or how to alias things? Or…?
Comment: This has been asked before, see http://stackoverflow.com/questions/4796872/full-outer-join-in-mysql
Comment: @Alexander I can't found answer what i want so I give this post
Comment: You could always upgrade to Postgres ;) (SCNR)
Answer: My preferred method for doing a full join is to get the list of all ids and the left join to that list:
select driver.product_id, s.quantity as sale_qty, r.quantity as return_qty, driver.date
from (select product_id, date from table_sales
      union
      select product_id, date from table_returns
     ) driver left join
     table_sales s
     on driver.product_id = s.product_id and driver.date = s.date left join
     table_returns r
     on driver.product_id = r.product_id and driver.date = r.date;

I find that putting the union in the from clause makes the query more convenient.  Logic about handling the variables, formulas, and joins only have to be included once.
Here is the SQL Fiddle that demonstrates that it works.
Answer: MySQL lacks support for FULL OUTER JOIN.
So if you want to emulate a Full join on MySQL take a look here .
This is a very helpfull link, describing the workaround for full join
sample workaround will be like
SELECT  t_13.value AS val13, t_17.value AS val17
FROM    t_13
LEFT JOIN
t_17
ON      t_13.value = t_17.value
UNION ALL
SELECT  t_13.value AS val13, t_17.value AS val17
FROM    t_13
RIGHT JOIN
t_17
ON      t_13.value = t_17.value
WHERE   t_13.value IS NULL
ORDER BY
COALESCE(val13, val17)
LIMIT 30


'Required parameter {0} not set'.format(identifier))

Question: I'm setting up my AWS for my static files. Basically, when user upload a picture it will directly stored the pictures on my AWS S3. I've done all the procedures, but it gives me an error saying Value error at //profile/ and Required parameter name not set. On my local machine it works, but it wasn't working when I deploy it.
I tried to restart my database then migrate it to heroku command but still get the same error
<code>models.py
class Profile(models.Model):
    user = models.OneToOneField(User, on_delete =models.CASCADE)
    image = models.ImageField(default='default.jpg', upload_to='profile_pics')
    update = models.DateTimeField(default = timezone.now)
    def __str__(self):
        return f'{self.user.username} Profile'

    def save(self, *args, **kwargs):
        super(Profile,self).save(*args, **kwargs)

        img = Image.open(self.image.path)

views.py
def profile(request):
    profile = Profile.objects.get_or_create(user=request.user)
    if request.method == 'POST':
        u_form = UserUpdateForm(request.POST, instance=request.user)
        p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile)
        if u_form.is_valid() and p_form.is_valid():
            u_form.save()
            p_form.save()
            messages.success(request, f'Your account has been updated!')
            return redirect('profile')
    else:
        u_form = UserUpdateForm(instance=request.user)
        p_form = ProfileUpdateForm(instance=request.user.profile)
    context = {
        'u_form':u_form,
        'p_form':p_form
    }
    return render(request,'users/profile.html',context)

settings.py
STATIC_URL = '/static/'
STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
STATICFILES_DIRS=(
    os.path.join(BASE_DIR,'static'),
)
STATIC_ROOT=os.path.join(BASE_DIR, 'staticfiles')
MEDIA_ROOT=os.path.join(BASE_DIR, 'media')
MEDIA_URL='/media/'

AWS_LOCATION = 'static'
AWS_ACCESS_KEY_ID= os.environ.get('AWS_ACCESS_KEY_ID')
AWS_SECRET_ACCESS_KEY= os.environ.get('AWS_SECRET_ACCESS_KEY')
AWS_STORAGE_BUCKET_NAME= os.environ.get('AWS_STORAGE_BUCKET_NAME')
AWS_S3_FILE_OVERWRITE = False
AWS_DEFAULT_ACL = None
DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'

</code>
I expect the functionality will be the same as my local,because on my local I can load my picture and see the url of AWS, but when I deploy it gives me an error.
Comment: Please show the full error message and traceback. You've omitted the part which tells you which identifier was not defined.
Comment: That's all the error message i get but it also gives me an error during template rendering and it highlights my  on my base.html
Answer: Make sure that the environment variables AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY and AWS_STORAGE_BUCKET_NAME are correctly set in the remote environment. Check that those are passed to Django and for testing purpose only, try to output them on some log


Is there a way to use wildcards in block restrictions first?

Question: I know that for restricting blocks to only certain pages you can do a path such as:
blog/*
I'd like to know if anyone knows a way to do a path such as:
*/blog
Basically, due to views not being able to use contextual links as the first URL argument (www.example.com/%/events is not a valid URL but www.example.com/events/% is) - I would like to be able to have an * first since I plan on having multiple contextual views that would have different first terms, but the same second term.  It would just allow me to write one line of restrictions vs. a line or 5 for each view.
Anyone know if this is possible in a Drupal 7 environment?
Thanks!
Answer: You can use the Rules block visibility module for this. Here is a quote from its project page:

The Rules block visibility module allows Rules components to be used to control block visibility. This provides Drupal administrators and developers extreme flexibility in controlling when blocks should be displayed on their websites, in addition to the default visibility options provided by Drupal.
The general idea is that if you can do it with Rules, you can use it to control block visibility, so the possibilities are limitless.
Need to show a block only for users registered more than a month ago?
Perhaps you have a block that must be shown only between 8am-5pm on weekdays?
What about displaying or hiding a block based on current weather conditions?
All of this can be done by using Rules block visibility.

With that, and as per the "if you can do it with Rules, you can use it to control block visibility" above, you've reduced your question to making Rules "check the path of the current page" (so that the block is only shown on those pages that have a path ending with "<code>/blog</code>").
For an illustration of how to use this module, refer to my answer to "How to stop a Views block from displaying to administrators, such as user/1?". It includes a Rules Component (in Rules export format), which you should replace by this variation of it to make it match your specific question):
<code>{ "rules_block_visibility_show_on_selected_blog_pages" : {
    "LABEL" : "Show block on selected blog pages",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "module" : { "label" : "Module", "type" : "text" },
      "delta" : { "label" : "Delta", "type" : "text" },
      "result" : { "label" : "Result", "type" : "boolean", "parameter" : false }
    },
    "IF" : [
      { "text_matches" : {
          "text" : [ "site:current-page:path" ],
          "match" : "\/blog",
          "operation" : "ends"
        }
      }
    ],
    "DO" : [ { "data_set" : { "data" : [ "result" ], "value" : "1" } } ],
    "PROVIDES VARIABLES" : [ "result" ]
  }
}
</code>
Comment: Thanks Pierre, I haven't gotten around to being able to try this yet as other more pressing matters have come up, but I will get to it.
Comment: Hey Pierre, I got it working.  It required a rule set, as I had to set the default value to true first, then add the rule that you wrote to set the result to false.  In my case I actually wanted the block to not show up on certain pages, but that was my fault for not being clear enough.

Thanks for the help!
Comment: @Dan Great, good news! Now you also know how interesting this "hidden gem" module is (there are dozens of usecases for it). PS: merci for the accept/upvote also!


Be confused with argument in c++ function?

Question: What is the difference between 2 fucntions?
//a

template <typename T, int N>
int g( T (&a)[ N ] )
{
    return N;
}

//b

template <typename T, int N>
int g( T &a[ N ] )
{
    return N;
}

It is ok to compile the code //a, but for //b I get an error: "declaration of 'a' as array of references".
Can anyone explain this error more clearly to me?
Thanks!
Answer: In C++, the syntax for some types are weird because of which such confusion often arises.

T (&a)[N] is a reference to an array of T of size N, which is allowed by the language, hence the first code compiles.
T &a[N] is an array of references (to T) of size N which is NOT allowed by the language, hence it doesn't compile.
Comment: Thank you. But I want to ask 1 more question.
//c
void f(int &a);

So function f is in situation which is similar to //a or //b? Is it a? (that's what I think)
Thanks :)
Comment: @user3425082: `int &a` declares `a` as reference to an int which is allowed by the language.
Comment: So, in conclusion, I can make a reference to a single object not an array of it?
Comment: @user3425082: No. You can make reference to an array (of non-reference) also. But you cannot make an array of references.
Comment: Yeah, that's what I mean. Sorry about my terrible english >"<. Thank you very much.
Answer: In the second case, operator precedence means that the indexing [] comes before the reference &. In the first case, you are making a reference to an array with N objects of type T, whereas in the second case, you have an array with N references to objects of type T, which is not valid.


Send email on behalf of clients

Question: We're a communications company primarily doing printing of statements / utility bills, then mailing them out in the post.
A few clients have asked for e-Delivery. Pretty much take the print output as a PDF, and instead of printing and mailing, email it as a PDF attachment. Whats the best way to send out these types of communications on behalf of our clients to their customers?
e.g. send through their mailserver, set up a mailserver ourselves on a generic domain (e.g. clientname.genericmailname.com), or set up a mailserver and send from the client's domain.
Doesn't email sent from a server that doesn't match the MX record usually get flagged as spam? (e.g. if we send an email from our mailserver from email@example.com).
Also, if we need to set up a mailserver, what's a few recommendations? We're a windows shop, and if I can avoid getting down and dirty with sendmail or postfix or the q one, I'd prefer it? We would probably do the actual emailing in an SSIS script or something.
Cheers
Answer: WIth the proper use of e-mail headers it is possible for you to setup and use your own mail server, but send the e-mail message with the "appearance" of coming from your customer.
This is not a spam tactic. This is a proper use of several e-mail message headers for this purpose.
<code>From: "ABC Company" <firstname.lastname@example.com>
Sender: firstname.lastname@example.com
To: firstname.lastname@example.com
Date: 13 Jul 2009 15:39:42 -0400
Subject: Your bill from ABC Company
Return-Path: firstname.lastname@example.com
</code>
By specifying both the sender and the return-path parameter to your e-mail server you are accurately identifying the source e-mail server that this message was originated from. Bounces will come back to your mail server.
If the user clicks on "reply" then they send their e-mail message to your customer (email@example.com in the example).
This is a legitimate technique that many e-mail marketing companies use, and they are VERY concerned about not looking like spam. Here is a link to a MailChimp description.
You should also setup SPF records for your mail servers, and ideally use DKIM. I recommend, and use a solution from Email Architect.
Comment: is "Return-Path" the same as "Reply-To"?
Answer: I would recomend setting up your own mail server to send email as the client, then add the correct SPF records to prevent you being flagged as spam.
Comment: You'd have to add SPF records to the client's DNS, which seems unlikely.
Answer: I suggest using MDaemon for doing your mail.  If you are sending in high volumes then look to Port25 and PowerMTA for your sending.  Stick some form of a mail queue (MSMQ for example) in front of what ever mailer you use so that the email that is generated from your program or website isn't actually sent from the program or web site...freeing that app to continue on using its worker thread without being blocked by connecting to a mail server.  NEVER SEND IT DIRECT FROM THE APP!  Then create a windows service to read through the queue and send through your mail server.
On the subject of relaying mail (sending it through your clients servers) this is not suggested.  You might not only be received as spam...more importantly you might get black listed by certain IPs.  Depending on the volume of mail that you send you may need to send the mail direct from your servers (you manage it) and you might need to manage the volume of email that you send to a given domain per minute/hour/etc. to avoid being black listed.
You might look to someone like EmailLabs to take care of the infrastructure management.  You can access them via their API's for sending your mail.
Big subject!
Answer: I recommend Ipswitch's IMail for a windows based mail server.  The company offers great support.  It is priced competetively, and is easy to set up and get running with a full suite of useful features.  We have been using it as our corporate mail server for several years now, and even host email for some other customers with it as well.  I think using the clientname.genericname.com is probably the safest.  You can set forwarders for the replies to the customers mail accounts.  Then you do not have to worry as much about relay problems and spam blocking problems because you are using a legitimate DNS which you own and control.  Plus you control the mail server.
Answer: Sending utility bills in the email to a bad idea due to identy theft if they are sniffed.
Instead you should look at how you get into an existing eBiller system.  In Canada here Canada Post runs one, they have the secure site and almost ALL my bills are in one secure area that I can log into.  Very nice and less to remember for each bill.
If you don't want to do that or can't, I'd look at doing it like a bank where people log into your system and view them from there using an SSL session.  Much more secure.
Answer: Ask the user for his email and password. Then create a session with his email server ( now you have valid  credentials ) and push the email from there.
There is no need to fake server or anything.
Comment: Don't do this primarily because it compromises your client's security. But then also consider if the client is using a shared hosting & email service. Is the client's email setup capable of handling the volume of emails? How will you handle bounces? Is their email setup correctly? If you were to design and build a setup that your client controls and manages (perhaps with you providing support) then I would say it's ok to use their infrastructure.
Comment: If he has a 1000 clients to do this with...does he manage and store credentials for each one?  What about clients that don't have their own servers for such services?
Comment: Revote up, It's still a reasonable doubt!
Comment: This answer shows a misunderstanding of a standard client-customer relationship.

Send email on behalf of clients


Prove that if $diam(G) = 3$ for a regular graph G, then $diam(\bar{G}) = 2.$

Question:
Prove that if $diam(G) = 3$ for a regular graph G, then $diam(\bar{G}) = 2.$

I know that without using regularity one can show that if $diam(G) \geq 3, \text{then } diam(\bar{G})\leq 3$. How do I use regularity to show that it must be exactly 2?
Answer: Suppose $G$ is a graph with $\operatorname{diam}(G)\gt2$ and $\operatorname{diam(\overline G})\gt2;$ I will show that $G$ is not regular.
More precisely, let $x,y,v,w$ be vertices with $d_G(x,y)\gt2$ and $d_{\overline G}(v,w)\gt2;$ I will show that $\deg(v)+\deg(w)\gt\deg(x)+\deg(y),$ the degrees being computed in $G.$
Clearly $x,y,v,w$ are four distinct vertices, $vw\in E(G),$ and $xy\in E(\overline G).$ Since $d_{\overline G}(v,w)\gt2,$ at least one of the edges $xv,xw$ is in $E(G);$ without loss of generality, we assume that $xv\in E(G).$ It readily follows that $yv\in E(\overline G),\ yw\in E(G),$ and $xw\in E(\overline G).$
Let $S=V(G)\setminus\{x,y,v,w\}.$ Let $m$ be the number of edges (of $G$) between $S$ and $\{v,w\},$ and let $n$ be the number of edges between $S$ and $\{x,y\}.$ Then $\deg(v)+\deg(w)=m+4,$ and $\deg(x)+\deg(y)=n+2.$ Since each vertex in $S$ is joined (by an edge of $G$) to at least one vertex in $\{v,w\}$ and to at most one vertex in $\{x,y\},$ we have $m\ge n;$ it follows that $\deg(v)+\deg(w)=m+4\gt n+2=\deg(v)+\deg(w).$
Answer: Let $G$ be a $k$-regular graph with $\text{diam}(G) \ge 3$. There exists two vertices $u$ and $v$ such that $\text{dist}_G(u,v) \ge 3$. Note that $u$ and $v$ have no common neighbors and are not adjacent. Thus,
$$\deg_G(u) + \deg_G(v) = 2k \le n-2 \implies k \le \frac{n-2}{2}.$$
This implies that for all $w \in V(\overline{G})$,
$$\deg_{\overline{G}}(w) = n-1-k \ge n-1-\frac{n-2}{2} = \frac{n}{2}.$$
Consider a pair of nonadjacent vertices in $\overline{G}$. Since the sum of their degrees is at least $n > n-2$, by the pigeonhole principle, they must have a common neighbor. Therefore, every pair of vertices in $\overline{G}$ are either adjacent or have a common neighbor. Therefore, $\text{diam}(\overline{G}) \le 2$.


I need help fixing an error when I upload a database into myPHPadmin

Question: I am trying to restore a wordpress site and upload the database backup into myPHPadmin.
After uploading my database, i get the following:
<code>Error
SQL query:

# Table: `staging_wp_options`

# Delete any existing table `staging_wp_options`

DROP TABLE IF EXISTS `staging_wp_options`;

MySQL said:

#1046 - No database selected
</code>

how do I fix?
Answer: you haven't specified which database you want to use before uploading your backup file.
Go to phpmyadmin, in the left bar go to your database by clicking on it (or if you want, create a new one). then Go to import tab and import your file.


Can someone help me solve this word problem on vector and magnitude?

Question:
A river is 2000 feet wide and flowing at 6mph from north to south. A guy in a boat starts on the east shore and heads west at a normal paddling speed of 2mph. In what direction (measured clockwise from the north) will he actually be traveling? And how far downstream from a point directly across the river will he land?

My attempt:
I am having trouble solving this problem. I don't know how to start; like what steps should I take? how I can go to through it, including how you got the answer. I basically would like a walkthrough of the problem. I'm brushing up on my math skills. It's been a long while and I'm really bad at understanding vectors and magnitude.
Thanks!
Comment: Have you drawn a picture? And how do you want your direction measured? In degrees?
Comment: @miiworld2: He was not asking for _art_, just for a diagram of the situation. The first step for such geometric problems is to draw a diagram.
Comment: The problem didn't specify. And I'm not a good artist.
Comment: I don't care for ART. I care about the PROBLEM. And I know about the first step already from class.
Answer: I made a sketch really fast. (I forgot to add north, but north is upwards. The flow is southwards and hence is draw with a vector that has a downwards direction in the sketch)
Adding the paddlingvector and the flowvector gives us the directionvector in which the person moves. This holds by the parrallelogramrule for vectors or basis vectoraddition.
Now, the flowvector has a length of 6 and the paddlingvector a lenght of 2.
Basic trigonometry says that the angle between the directionvector and the vector pointing south is $\alpha = \tan^{-1}(\frac{2}{6})=\tan^{-1}(\frac{1}{3})$. Add a 180 degrees (for the missing half circle) and we have the angle of direction from the northern vector.
Now for where he lands:
The crossingtime is determined only by the paddling vector, since - assuming the river is 2000 ft at all points - we need to cross 2000 ft horizontally wise. Hence we determine the time needed for crossing 2000 ft while going 2 mph. A easy calculation (distance/speed) shows that we need 0,1893 hour for crossing the river.
During this time he's moved 0,1893*6=1,1364 miles downward due to the flow of the river. This is the point where he will be when he has crossed.
Comment: Where he lands? On the other side of course. We have the angle; the time calculation is completely unnecessary.
Comment: The questions was: how far downstream from a point directly across the river will he land? The time calculation is one way. An other is to fit the vectors in the river. A other is with trigoniometry. But it is not completely unnecessary.
Comment: Beg to differ, but that wasn't the question. The question was "In what direction (measured clockwise from the north) will he actually be traveling? And how far downstream from a point directly across the river will he land?". Two part questions usually have a purpose in leading the student.


Images Form a Topology?

Question: I have a function $f:X\rightarrow Y$ between two topological spaces $(X,\mathcal{T}_1)$ and $(Y,\mathcal{T}_2)$ that is $\mathcal{T}_1$-$\mathcal{T}_2$ continuous, and I'm asked to determine if the set of images {$f(V):V\in \mathcal{T}_1$} is a topology on $Y$.  I've been wracking my brain on this one for days, and can't find a counterexample, but can't find a formal proof either.  Help would be appreciated!
Answer: The result is not true in general.
Let $X=(0,1)$ and $Y=\mathbb{R}$. Let $f\colon X\to Y$ be the inclusion map. For $\{F(V):V\in\mathcal{T}_{1}\}$ to be a topology on $\mathbb{R}$, we need $\mathbb{R}\in \{f(V):V\in\mathcal{T}_{1}\}$, which we don't have.
Comment: @lattice.  See my answer where I give an counter example and a proposition.
Comment: However, if $f$ is onto, the statement is true.
Comment: @lattice.  For the inclusion map or in general?
Comment: I guess I'm stuck on the terminology of "a topology on $Y$".  So that means that $Y$ HAS to be the set?  I guess I am confused, cause I'm thinking that ${{0},{1},{0,1},\emptyset$ is a topology on \mathbb{R}, but I guess it's more of a subspace topology, is that fair?
Comment: @Craig.  Y is a set.  A topology for Y  is a subset of the power set of Y.  The crammed together and lacking a bracket set you defined is not a topology for R.  Why?
Comment: Cause R's not it in the set itself.  I guess I'm stuck on whether "a topology on Y" necessarily means Y is in the set, or whether it could also mean subsets of Y that do not necessarily include Y. (e.g., like {{0},\emptyset} is a topology, and 0 and the emptyset are both subsets of Y).  I'm thinking a "topology on Y" strictly means the Y is the largest open subset in our topology.
Comment: @Craig.  Read the definition of a topology T_S, for a set S.  You ' ll find that both S and emptyset are in T_S.
Comment: @WilliamElliot I believe this should be true for any continuous and onto map $f$, if the sets $f(V)$ are the open sets of the new topology $\mathcal{T}_3$. In this case, we have $\emptyset=f(\emptyset)$, $Y=f(X)$, $\cup_i f(V_i)=f(\cup_i V_i)$ and $f(U)\cap f(V)=f(U\cap V)$. So all the requirements for $\mathcal{T}_3$ to be a topology on $Y$ follow from the fact that $\mathcal{T}_1$ is a topology on $X$. Or am I missing something?
Comment: I was too late to edit my post. Actually, the above shows that we don't even need $\mathcal{T}_2$ or the continuity of $f$ into this space. So a correct statement should be: Given any map $f:X\to Y$ where $X$ is a topological space, the sets $f(V)$ for $V\subset X$ open define (as open sets in $im(f)$) a topology on $im(f)$.
Answer: If f:X -> Y is a continuous surjection, then T = { f(U) | U open }
may not be a topology for Y.  Example:
X = [0,2],  Y = S^1,  f(x) = (sin pi.x, cos pi.x)
[0,1) and (1,2] are open, so f([0,1}) cap f((1,2]) = {(0,1)}
should be open but there is no open U for which f(U) is a
singleton.
However if f is a bijection, then T is a topology for Y.
The continuity of f is unimportant.  Only that X is a
topological space and f is a bijection.
Exercise.  If f is an injection, show f(A cap B) = f(A) cap f(B).

Images Form a Topology?


Let $S = X + U, T = X + V$ for ind.normal r.v $X, U,V$. Is it possible to find $a, b$ real numbers such that $\mathbb{E}[X|S,T] = \mathbb{E}[X|aS+bT]$

Question: Suppose we have random variables
$$X \sim  N(0, \sigma_X^2) \\
U \sim N(0, \sigma_U^2) \\
V \sim N(0, \sigma_V^2), $$
where $X$, $U$ and $V$ are independent. And
$$ S = X + U \\ T = X + V. $$
Is it possible to define a linear combination of $S$ and $T$ such that conditioning on
$$R := aS + bT, \ \ \ a, b \in
 \mathbb{R}$$
is equivalent to conditioning on both $S$ and $T$, i.e.,
$$ \mathbb{E}[X\mid S,T] = \mathbb{E}[X\mid R]. $$
I think knowing $S$ and $T$ is more than just knowing their sum or average.
Comment: I think the answer depends on the full joint distribution of $(X,U,V)$ and not just on their marginal distributions.  Are you perhaps supposing the joint distribution is multivariate Normal?
Comment: I forgot to mention that U and V should be independent.
Comment: I formatted some math symbols.  However, many statements in your post are conceptually wrong and better to be corrected by yourself.  For example, the conditional mean and variance of $X$ given $S = s$ is obviously not as you stated (please refer to the link in my answer below for the correct conditional distribution formula), and why after saying $U$ and $V$ are normal, then stating "$U$ and $V$ are uniformly distributed"???
Comment: Thank you for the advice. I will try to correct the statements. In the last part I was trying to tell why I thought that knowing S and T is more than knowing their average only. For this explanation I simplified U and V to uniform. However, I removed it from the question because it was rather confusing.
Answer: Without loss of generality, assume $X, U, V \text{ i.i.d. } \sim N(0, 1)$ (in general the analysis below requires the joint normality of $(X, U, V)$). The joint normality of $(X, U, V)$ and transformations
\begin{align*}
\begin{bmatrix}
X \\
S \\
T
\end{bmatrix} =
\begin{bmatrix}
1 & 0 & 0 \\
1 & 1 & 0 \\
1 & 0 & 1
\end{bmatrix}
\begin{bmatrix}
X \\
U \\
V
\end{bmatrix}, \quad
\begin{bmatrix}
X \\
R
\end{bmatrix}
= \begin{bmatrix}
1 & 0 & 0 \\
a + b & a & b
\end{bmatrix}
\begin{bmatrix}
X \\
U \\
V
\end{bmatrix}
\end{align*}
then indicate that
\begin{align*}
\begin{bmatrix}
X \\
S \\
T
\end{bmatrix} \sim N_3\left(0,
\begin{bmatrix}
1 & 1 & 1 \\
1 & 2 & 1 \\
1 & 1 & 2
\end{bmatrix}\right),
\quad
\begin{bmatrix}
X \\
R
\end{bmatrix} \sim
N_2\left(0,
\begin{bmatrix}
1 & a + b  \\
a + b & 2a^2 + 2ab + 2b^2
\end{bmatrix}\right).
\end{align*}
It then follows by the conditional distribution of multivariate normal distribution that
\begin{align*}
& E[X|S, T] = \begin{bmatrix} 1 & 1 \end{bmatrix}\begin{bmatrix} 2 & 1 \\ 1 & 2
\end{bmatrix}^{-1}\begin{bmatrix} S \\ T \end{bmatrix} = \frac{1}{3}(S + T), \\
& E[X|R] = \frac{a + b}{2a^2 + 2ab + 2b^2}R = \frac{a + b}{2a^2 + 2ab + 2b^2}(aS + bT).
\end{align*}
So the equality holds if and only if
\begin{align*}
\begin{cases}
3a(a + b) = 2a^2 + 2ab + 2b^2 \\
3b(a + b) = 2a^2 + 2ab + 2b^2
\end{cases}.
\end{align*}
This equation holds for any $a, b$ such that $a = b$.
For the general $(X, U, V) \sim N(0, \Sigma)$ case (the zero-mean condition is essential and cannot be relaxed), repeating the argument above yields $E[X|S, T] = AS + BT$ for some constants $A, B$ depending on $\Sigma$ (in the above i.i.d. case, $A = B = 1/3$). Now apply the argument in Yves's answer would give you at least one choice of $(a, b) := (A, B)$, because $\sigma(R) = \sigma(AS + BT) \subset \sigma(S, T)$ and the law of iterative expectations:
\begin{align*}
E[X|R] = E[E[X|S, T]|R] = E[R|R] = R = E[X|S, T].
\end{align*}
Answer: I assume that we have $U,V,X$ independent. Then...

One may describe the observation $X,S,T$ by a multivariate normal distribution.

We can always transform a multivariate normal distribution into another by using a linear transformation. So it should be possible to describe this with three other values
$$\begin{array}{l}X\\
     R = aS + bT \\
     Q = cS + dT \\\end{array}$$
and the trio $X,R,Q$ is also multivariate normal distributed and $R, Q$ carry the same information as $S, T$.

If we choose the coefficients for $Q$ as $c = -d = 1$ such that $Q = S - T = U-V$ and $\text{Cov}(Q,X) = 0$.
If we choose the coefficients for $R$ as $a = 1/\sigma_U^2$ and $b = 1/\sigma_V^2$ such that $\text{Cov}(Q,R) = 0$.
then the multivariate normal distribution of X,R,Q can be factorized (in the fashion of the Fisher-Neyman factorization
theorem). We can rewrite the joint distribution as a product $$f(X,R,Q) = g(X,R) \cdot h(Q)$$ where $g$ and $h$ are independent distributions. This makes that $Q$ is an ancillary statistic independent of $X$ and  only $R$ will contain information and $R$ will be a sufficient statistic.

As a heuristic, I think knowing $S$ and $T$ is more than just knowing their sum.

You know more, but not more about $X$. It is similar to the principle that the sample mean of iid normal distributed variables provides all information about the mean of the distribution.


All functions $g:\mathbb{N}\to\mathbb{Z}$ such that $m+n~|~g(m)+g(n)$

Question: I just thought about the following question: Find all functions $g:\mathbb{N}\to\mathbb{Z}$ such that $m+n~|~g(m)+g(n)$ for all $m,n\in\mathbb{N}$.
Clearly every polynomial $g(X)\in\mathbb{Z}[X]$ in which $X$ only occurs to an odd power is a solution.
Taking $m=n$ gives $m~|~g(m)$ and hence, introducing $h(m)=m\cdot g(m)$, we can rewrite the condition as $m+n~|~n(h(m)-h(n))$ for all naturals $m$ and $n$. This in turn is equivalent to $m+n~|~h(tm)-h(tn)$ for all naturals $m,n,t$.
But now I am stuck. Do you have any ideas or solutions? Do you think/spot/know that there are more solutions than the mentioned polynomials?
Comment: You can use '\mid' instead of '|' to fix spacing around the divisor sign.
Comment: Constant polynomials contain $X$ to an even power, $X^0$, @BillDubuque. Basically, he's saying that $g(X)$ is an odd polynomial.
Comment: You need to exclude nonzero constant polynomials from the statement in your second paragraph, i.e. all integral polynomials that are *odd* $\,g(-x) = -g(x)\,$ are solutions since  $${\rm mod}\ m\!+\!n\!:\,\ m\equiv -n\,\Rightarrow\, g(m)\equiv g(-n)\equiv -g(n)\,\Rightarrow\,g(m)+g(n)\equiv 0$$
Comment: @Thomas Of course, but that's not what was written. My comment concerns that imprecision (and gives a proof for readers who might need one).
Answer: First, note that the set of functions satisfying your condition has the property that it is closed under integer linear combinations. Give two such functions, $p,q,$ and integers $a,b$, the function $r(n)=ap(n)+bq(n)$ has the above property.
Let $p_k(x)=x(x^2-1)\dots(x^2-k^2)$. This is a polynomial with only odd degrees.
Then for any sequence of integers $a_k$, you can define:
$$p(n)=\sum_{k=0}^\infty a_kp_k(n)$$
This is well defined because for $k>n$, $p_k(n)=0$, so it is, locally, a finite sum for any $n$. (Left to the reader: show $p(n)$ has your property. It does.)
This means that there are uncountably many such functions.
This is related to an old question of mine: finding all $f:\mathbb N\to\mathbb Z$ with $m-n\mid f(m)-f(n)$. There, I answered my own question, but I think your question might be slightly different. Still, the above is "like" what I did in that older question, so possibly worth checking out.
In particular, if $g:\mathbb Z\to\mathbb Z$ is an odd function with $\forall m,n:m-n\mid f(m)-f(n)$, then $g$ restricted to the natural numbers is in your class. These functions are classified by a sequence of integers, $a_k$ using the functions:
$$\sum_{k=0}^\infty a_k\frac{\mathrm{lcm}\{1,\dots,2k+1\}}{(2k+1)!}p_k(x)$$
But your condition is really that such odd function satisfy $m-n\mid f(m)-f(n)$ only for $n<0$ and $m>0$. So that might allow for more functions.
But I think I can outline a proof much like my proof for my question. Namely, if we have the values $f(0),\dots,f(n)$, that determines the value of $f(n+1)$ modulo ${\mathrm{lcm}\{n+1,\dots,2n+1\}}$ since we know:
$$f(n+1)\equiv -f(d)\pmod{n+1+d}$$
for $d=0,\dots,n$. (The case $d=n+1$ follows from the case $d=0$.)
But $\mathrm{lcm}\{n+1,\dots,2n+1\} = \mathrm{lcm}\{1,\dots,2n+1\}$.
So we can inductively find $a_k$ so that:
$$f(n)=\sum_{k=0}^\infty a_k\frac{\mathrm{lcm}\{1,\dots,2k+1\}}{(2k+1)!}p_k(n)$$
This also means that your condition implies $\forall m,n.m-n\mid g(m)-g(n)$ too. I wondered if there was a direct proof of this, and I asked here and got a quick easy proof.
That easy proof lets you re-use my result directly when classifying your functions, since it means that your $g$ can be extended to a function $g_1:\mathbb Z\to\mathbb Z$ with $m-n\mid g_1(m)-g_1(n)$ and $g_1(-m)=-g_1(m)$. So that lets us use my classification result.
Comment: Isn't the fact that there uncountably many functions with the posters property a direct consequence of the linearity observation?
Comment: No, since there are only countably many finite (integer) linear combinations. The trick is that you can do an infinite linear combination which *locally* looks like a finite linear combination. Essentially, just linear combinations gives you a subset of $\mathbb Z[x]$, which is countably infinite.
Comment: I get it now, $a_k$ is arbitrary so there are uncountably many, but the linearity is only integer linearity.  Thanks~~


Create Locale Directories and String Files

Question: I'm starting to learn programming for Android and I have problem with THIS LESSONThere was similar questions, but related to an earlier version of Android Studio.
I can't create new folder (for country values), like this:
CLICK FOR IMAGE or this:
MyProject/
    res/
       values/
           strings.xml
       values-es/
           strings.xml
       values-fr/
           strings.xml

P.S. Sory for my bad english :D
Comment: Can you explain in more detail about 'why' you "can't create new folders" ?
Comment: Is this about programming or about how to create a folder in general?
Comment: I'm starting to learn the Android Studio. This is not a a bug, but just do not know how can I create a new folder (values-es). Can you help me? D
Comment: Actually I just had the same problem you did, 1 min, I'll write it up
Answer: You need to create the folder using the explorer like Finder on mac os...or something else in windows or linux. After that copy the file of strings to that folder and Android Studio automatically will detect it.
If you want to use the Android Studio, just right click in your strings.xml file and open the translations editor
.
In the translation editor click on add locale

Comment: Thanks, but "strings.xml (fr)" can be located in a folder values?
I do not need to create a folder "values-fr" for it?
Comment: Yup, and name the file `strings.xml`
Comment: So how to create a folder values-fr? I know, i'm begginer :D
Comment: Just follow the steps in my answer.
Comment: Ok, now i know (i think so :D) Thanks
Comment: I checked, it works Thanks
Answer: to create the directories (similar, but possibly slightly different named than the example you linked) in Android Studio by [right click] on 'res' and select 'new' -> 'android resource directory'.
This will open pop up window asking you some info.
find 'locale' in the list on the left. then select it. Then press the ">>" button.
This will ask you the language (and if you choose 'region' where that language is spoken, so 'en-rUS' is English-US, where as 'en' is just English (no region))
Click the 'ok' button.
Then you will need to 'sycn' your project with your gradle files.
To do this, click 'Tools' -> 'Android' -> 'Sync Project with gradle files'
I just tested this with Android Studio 1.5.1 right now. Should work for you. (the 'translate Strings.xml' as was recommended by Sandro Machado is also valid, but I would personally prefer to make the folders first, but that is just me)

So Android Studio 'hides' the folders from you. if you look at your file system, then you will see you DID create the folders. However you will first need to copy strings.xml into each folder before Android Studio will show you a screen like what I have. (honestly I think this is stupid... and hadn't realized this behavior before) But I hope that explains the situation to you. (the above method will make the right directories if you want, but you'd have to copy the strings.xml from your /values folder to each folder after that.
The 'Translations Editor' might be alright for small projects, but I feel the raw text files would be better for large projects. (just a 'feeling', nothing to back that up, and possibly just my own work-flow more than anything.)
Comment: I haven't "android resource folder" option  ( 'res' and select 'new' -> 'android resource folder'.)
http://images.tinypic.pl/i/00740/wmx78jngg2ql.png
Comment: Sorry, "folder" and "directory" are basically interchangeable. (technically they aren't on windows, but for most people they are the same) I'll update the answer.


Menu item with update text (title) in real time

Question: I have a menu where one of the items (menu links) is a link to a view where I can see all comments that I have to moderate. Which I need is (if it is possible) to have the title of this link that change in realtime (or every time I load a page/node).
Think to my situation where I don't know how many comments I need to moderate so in this moment every X minutes I reload the page with all comments that I have to moderate. But this is frustating. So my necessity is to have a menu item like "Comments to moderate: FOO" where FOO is a number (from 0 to infinite) that I can calculate in realtime at every page load or every BAR minutes.
M.
Comment: do you solve the problem?
Answer: This is how I solved a similar problem:
You need implement the hook_menu() and use the 'title callback'
function YOUR_MODULE_menu() {
    $items = array();

    $items['perfil-usuario'] = array(
        'title' => 'perfil',
        'description' => t('User Profile'),
        'title callback' => 'change_title_profile_link',
        'page callback' => 'go_to_profile',
        'access callback' => 'user_is_logged_in',
        'expanded' => TRUE,
        'weight' => 100,
        'menu_name' => 'main-menu',
        'options' => array('attributes' => array('class' => array('perfil-usuario'))),
        );

    return $items;
}

In this function you can change the link title
function change_title_profile_link() {
    return rand();
}

Here you can redirect to the desire url, if the url change you can implement this function
function go_to_profile() {
}


the probability that a patient recovers from a rare blood disease

Question: The probability that a patient recovers from a rare blood disease is 0.4.. if 15 people are known to have contracted this disease what is the probability that
(a) at least 10 survive
(b) from 3 to 8 survive
(c) exactly 5 survive
Comment: Have you tried anything?
Comment: Hint: http://en.wikipedia.org/wiki/Binomial_distribution
Comment: @fgp i tried but it seems to be wrong especially when others answered
Comment: @LobnaMagdy Please include what you tried. Otherwise you will get noone to help you...;-)
Answer: @Lobna Magdy;
c)
$$ (1-p)^{15-n} p^n \binom{15}{n} $$
n = number that survive.
p = 4 / 10.
$$P(\text{exactly 5 survive})=\left (1-\frac{4}{10}  \right )^{15-5} \left (\frac{4}{10}  \right )^5 \binom{15}{5} =\frac{5674372704}{30517578125}\\ \\ \approx .185937844764672 $$
You do one...
Answer: You should use the binomial distribution. The probability that at least 10 people survive is:
$$P(X\geq 10) = P(X=10) + P(X=11) + P(X=12) + P(X=13)+P(X=14)+P(X=15)=\displaystyle{\sum _{n=10}^{15} \binom{15}{n} 0.4^{n} \cdot (1-0.4)^{15-n}}$$
Since using the bonomial distribution, $P(X=k)=\binom{15}{k} 0.4^k \cdot (1-0.4)^{15-k}$.
Comment: Why binomial distribution is used? Just to understand answer
Answer: A)  15C10 * (0.4)^10 * (1-0.4)^5 + 15C11 * (0.4)^11 * (1-0.4)^4 + 15C12 * (0.4)^12 * (1-0.4)^3 + 15C13 * (0.4)^13 * (1-0.4)^2 + 15C14 (0.4)^14 * (1-0.4) + 15C15 * (0.4)^15


MySQL installation stuck on debian

Question: I am following this guide to install mysql on debian how-to-install-the-latest-mysql-on-debian-10.
However, i'm stuck on this screen

I tried clicking ok and pressing enter nothing happned.
Restarted the device still same thing.
Comment: Press the tab and then it will highlight `` then press Enter.
Comment: Added an answer from the comment. You can accept it so if others have a similar issue they can get an answer.
Answer: The issue is that the screen has a <Ok> button but it's not highlighted, so without that if you press Enter, it will do nothing. This is how the GUI works on the console.
Use tab to highlight <Ok> button and then press Enter.

MySQL installation stuck on debian


Preserving xattr on download

Question: I'm trying to store some metadata in a .txt file using xattr on a website, then download it. If I use PHP's xattr_set on the temporary file when running the website locally, both xattr_list in PHP and python-xattr on the command line show me the attributes I set. However, when I download the file using readfile, the attributes no longer show up. Is there any way to  preserve these attributes on download?
Answer: Not directly. HTTP has no way of specifying filesystem extended attributes, so you will need to package them in an appropriate archive format that allows specifying them in the metadata, e.g. GNU tar with <code>--xattrs</code>.
Comment: Well that's annoying. Thank you for the quick response!

Preserving xattr on download


What version of Drupal am I running?

Question: I have a really old site that has been neglected for almost 20 years, it runs Drupal, only problem is that I cannot figure out which version of Drupal I am running.
Index.php has this:
// $Id: index.php,v 220.127.116.11 2006/12/12 13:50:59 killes Exp $
Comment: In addition to the answers below, you should also consider that a Drupal 4.7 site that hasn't been touched is likely compromised, either the site itself from unapplied patches or issued addressed in later versions, or the server itself since the Apache 1.x  / PHP 4.x.
Answer: That's a version somewhere between 4.7.5 and  4.7.11.
You mentioned in a deleted comment that you were hoping to upgrade one version at a time, presumably to a much more recent version; to be honest, I'm not sure there's much hope of upgrading a site that old.
I don't think there was an official migration path from 4.x to 5.x, maybe not even a proper one for 5.x to 6.x. 6.x to 7.x had a path, but was a pretty challenging process if memory serves. Same again for 7.x to 8.x.
It might be worth considering whether a rebuild, or a custom migration straight out of the old database into Drupal 10, is a better option.
Comment: Thank you! Then I guess I will be trying to extract the data directly from the DB. Seems an interesting challenge.
Comment: Thinking it through a bit more, I don't think it'll be too difficult - the shape of the data back then was a lot more simple. Migrating HTML into a suitable text format, and transferring files, might be the trickiest bits. Good luck!
Answer: That comment is one of those comments CVS created by replacing the $Id$ string present in files.
In that comment you read the CVS username of the person who committed the last change to that file, firstname.lastname@example.com, who was a Drupal 4.7 core maintainer, and who helped to push out the release during Dries' absence between March and April 2006.
To answer your question, that site is running on Drupal 4.7. It could be Drupal 4.7.5, 4.7.6, 4.7.7, 4.7.8, 4.7.9, 4.7.10, or 4.7.11, for which the first lines of the index.php file are the following ones.
// $Id: index.php,v 188.8.131.52 2006/12/12 13:50:59 killes Exp $

/**
 * @file
 * The PHP page that serves all page requests on a Drupal installation.
 *
 * The routines here dispatch control to the appropriate handler, which then
 * prints the appropriate page.
 */

require_once './includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

$return = menu_execute_active_handler();

If you look at the same lines for that same file in Drupal 4.7.4, you will see they are the following ones.
<?php
// $Id: index.php,v 1.90 2006/01/27 18:51:51 dries Exp $

/**
 * @file
 * The PHP page that serves all page requests on a Drupal installation.
 *
 * The routines here dispatch control to the appropriate handler, which then
 * prints the appropriate page.
 */

require_once './includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

$return = menu_execute_active_handler();

If you look at the content of the other files, you could be able to understand exactly which Drupal 4.7 version is, but that would not help you much, as migrating a Drupal 4.7 site would be problematic independently from the exact Drupal 4.7 version the site is using.

What version of Drupal am I running?