Transpose of matrix inverse: $(AA^T)^{-1}A^Tb \stackrel{?}{=} (A^TA)^{-1}A^Tb$

Question: Given the matrix equation:
$$ x^TA^TA = b^TA $$
I'm trying to find the least squares solution (i.e.; trying to minimize $r=||Ax-b||$). The matrix $A$ is not necessarily symmetric.
When I solve it in following way I find $x$ as:
$$ \begin{array}{rcl}
x^TA^TA &=& b^TA \\
x^T &=& b^TA(A^TA)^{-1} \\
x &=& (AA^T)^{-1}A^Tb
\end{array} $$
But I find a different solution for $x$ when I solve it this way:
$$ \begin{array}{rcl}
x^TA^TA &=& b^TA \\
A^TAx &=& A^Tb \\
x &=& (A^TA)^{-1}A^Tb
\end{array} $$
Apparently the latter one is the correct solution. But what is wrong with the first one? What am I doing wrong?
Answer: The last step of the first approach should be,
$x = ((A^TA)^{-1})^TA^Tb$
As $A^TA$ is symmetric, its inverse should also be symmetric. (if exist)
Thus $x = (A^TA)^{-1}A^Tb$
Answer: In the first derivation the transpose was done wrong on the RHS of the last step, ${(A^TA)^{-1}}^T$ = ${(A^TA)^{T}}^{-1}$ = ${(A^TA)^{-1}}$
Comment: But why? Any references?
Comment: @hkBattousai: The transpose of a product is always the reverse of the transposes: $(AB)^T = B^T A^T$. So $(A^T A)^T = A^T (A^T)^T = A^T A$. And [inverse and transpose commute.](http://math.stackexchange.com/questions/340233/transpose-of-inverse-vs-inverse-of-transpose/340234#340234)


Views block visibility

Question: I want to show the block only on this page /category and not show on every next like /category?page=1
As I see it's a big problem for Drupal 8?
Answer: You can set the visibility of a block in the block page (admin/structure/block).
In the visibility tab select 'Show for the listed pages' and in the 'Pages' just add /category. Use /category/* to display the block in all the pages.

Views block visibility


Somar parcelas em aberto com Join

Question: Tenho duas tabelas, Cliente e Parcela.
A tabela Parcela possui o id do cliente como chave estrangeira, uma coluna pagamento que é null ou contém a data de pagamento em formato date e uma coluna valor que é float e contém o valor pago ou null caso aberto.
Preciso somar todas as parcelas pagas e todas as parcelas abertas de todos os clientes.
Estou tentando fazer assim, mas está somando todas as parcelas e mostrando apenas o primeiro cliente.
select c.nome_cliente,
SUM(CASE WHEN p.pagamento is not null THEN p.valor ELSE 0 END) as 'PAGO',
SUM(CASE WHEN p.pagamento is null THEN p.valor ELSE 0 END) as 'ABERTO'
from cliente c
LEFT JOIN parcela p
ON c.id = p.id_cliente

Answer: Isso deve resolver, faltou você informar o group by
select c.nome_cliente
      ,SUM(CASE WHEN p.pagamento is not null THEN p.valor ELSE 0 END) as 'PAGO'
      ,SUM(CASE WHEN p.pagamento is null THEN p.valor ELSE 0 END)     as 'ABERTO'
  from      cliente c
  left join parcela p ON p.id_cliente = c.id
 group by c.nome_cliente

Somar parcelas em aberto com Join


Como adicionar um ícone mostrando que aquele item já foi lido, sendo salva as preferências usando SharedPreferences?

Question: Essa é uma parte do menu inicial do aplicativo:
Tela Inicial
A imagem abaixo representa a tela inicial do aplicativo, que possui os botões "como usar" e "Introdução a dinâmica", para o usuário escolher que tarefa vai fazer.

Tela "Como usar"
Clicando no ImagemButton (acima do texto "Como Usar") o usuário vai para um novo Layout no qual tem um botão voltar para tela principal para que possa seguir em frente para as próximas etapas do tutorial, como abaixo:

Dúvida
Depois que o usuário tenha entrado no layout do "como usar", ter lido e concluído clicando no botão voltar para tela principal queria que aparecesse um ícone no ImagemButton para notificar que ele já concluiu aquela tarefa. Assim, quando o usuário entrar no aplicativo novamente, ele poderá saber quais ele já fez e continuar de onde ele parou. Como representado abaixo:

Quais recursos/metodos do Android eu devo usar para que posso adicionar um ícone mostrando que aquele item já foi lido?
Comment: Cara, está meio confuso mais entendi um pouco do que você quer. Na media que vai respondendo as perguntas, o botão se altera certo?
Comment: Amigo, reformulei a pergunta... espero que esteja melhor
Comment: Não entendi, que respostas?
Comment: Ah ta! Dentro de "Como user" tem alguma interação com o usuário ou é simplesmente uma "layout"?
Comment: É simplesmente uma Layout com um botão para voltar para o menu... As outras tarefas tem uma interação maior do que essa "como usar", mas acredito que sabendo fazer essa mais simples, que só tem esse botão "Ir para tela principal", as outras darão certo também...
Comment: São muitas telas ou poucas? Dá pra fazer de várias formas.
Comment: Esse como usar só tem uma... só um detalhe que pode importar já que você acredita que possui varias formas de resolver... eu fiz o aplicativo inteiro com a mesma Activity, eu abro apenas layouts diferentes...
Comment: Se você estiver se referindo a interação com o usuário devido o nome Dinâmica, ele é nome do assunto tratado no aplicativo... é um aplicativo para auxiliar professores de Física no Ensino Médio...
Comment: Então teria que colocar a lógica a principio no clicar do botão para entrar no seu layout. Tipo, clicou e abriu o layout, já tornaria como lida. Seria a forma mais viável no momento por você está usando a mesma Activity. Se fosse algo mais rigoroso, daria pra fazer tipo além do usuário clicar e entrar no layout, poderia exigir que rolasse o app até no final etc.
Comment: Ótimo, clicando no botão e já adicionando é o suficiente... seria adicionado assim que ele entrasse no layout de como usar, certo?
Comment: Existem outras maneiras de fazer além da resposta que acabei de publicar. Caso tire totalmente sua dúvida, faça uma breve pesquisa sobre persistência de dados, porque pelo que percebemos, é o que você está precisando. Caso não persista os dados, toda vez que você abrir sua aplicação, vai ficar com valores padrões do desenvolvimento.
Comment: Amigo, muito obrigado por estar me ajudando, mas é que eu sou novo em programação... estou ainda tentando colocar o que vc propôs no app... apareceu alguns erros e estou tentando ver se da certo, vou ver uns vídeos e ler sobre persistência de dados e SharedPreferences... Assim que der certo ou se eu não conseguir dou um retorno... O primeiro erro que surgiu foi "boolean tela1..." talvez eu não tenha definido o botão como visualizado corretamente...
Comment: Tranquilo! Eu também estive ai no seu lugar e pedindo ajuda para outras pessoas. Nas horas vagas estou sempre tentando ajudar. Qualquer coisa, recorre aqui! abs
Answer: Como você mencionou, para casos de coleção relativamente pequena de valores-chave para salvar, use as APIs SharedPreferences. Um objeto SharedPreferences indica um arquivo que contém pares de valores-chave e fornece métodos simples para ler e gravar.

Cada arquivo SharedPreferences é gerenciado pela estrutura de trabalho
  e pode ser privado ou compartilhado.

Primeiramente pode definir uma string estática para dar o nome de sua configuração e declarar a imagem que vai surgir com o click do botão:
public static final String PREFS_NAME = "Preferences";
private ImageView img;

Depois criamos um método para ser adicionada a imagem quando o botão for clicado e ser salva uma preferência, desta forma:
private void onOff() {
    SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
    settings.edit().putBoolean("online", true).apply();

    boolean online = settings.getBoolean("online", false);
    if (online) {
        img.setImageResource(R.drawable.confirmacao);
    } else {
        img.setImageResource(R.drawable.fundo);
    }
}

Para resgatar o valor gravado basta você verificar desta forma, na tela em que a imagem se encontra:
img = (ImageView) findViewById(R.id.img);

SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
Boolean online = settings.getBoolean("online", false);

if (online)
    img.setImageResource(R.drawable.confirmacao);
else
    img.setImageResource(R.drawable.fundo);

Pro fim, você deve colocar esse método onOff(); no botão que desejar.
Sendo assim, você vai fazer essa verificação acima toda vez que entrar na sua aplicação. Lembrando que é uma maneira rápida de fazer e pode ser otimizada. Isso é só um exemplo básico para que tenha mais noção.
Observações:
1 - "img" é o id da imagem que não possui background definido no layout e é onde é inserida a imagem confirmação.
2 - "confrimacao" é o nome do arquivo da imagem que representa a notificação de visualizado.
3 - "fundo" é o nome de um arquivo de uma imagem com nada (transparente) salva em .png
4 - Talvez o método onOff(); possa ser acionado em qualquer botão do meu aplicativo devido eu usar apenas uma Activity em todo o app.
5 - Existe um vídeo na pagina do artigo "Muito além do SQLite" (proposto abaixo) que pode ajudar muito.
Existem outras técnicas de persistência como alternativa, simples e ágeis, que permitem a persistência de pequenas quantidades de dados. São elas:
• PreferenceActivity;
• Internal Storage;
• Armazenamento em Cache;
• External Storage.
Veja alguns artigos:

Persistência de dados no Android
Muito além do SQLite
Opções de Armazenamento
Persistência em Banco de Dados
Comment: Esse artigo que você propôs "Muito além do SQLite" parece que iria me mostrar exatamente o que falta para que eu consiga, mas ele é pago...
Comment: @TonyÁlaffe verdade, esqueci desse detalhe. Na verdade é assim, o SQLite é para quantidade muito grande de dados, nesse teu caso não precisaria. Este artigo mostra outras alternativas para quantidades pequenas de armazenamentos. Mas tem outros artigos bons na internet que você pode estar acessando. Tem dois gringos referência que gosto muito de seguir para aprender coisas novas, o [Vogella](http://www.vogella.com/) e [Ravi Tamada](http://www.androidhive.info/). Se quiser aprender de verdade, veja os tutoriais deles. Recomendo!
Comment: Ack Lay, deu certo! ficou muito bom! No artigo "Muito Além do SQLite" tem um vídeo que explica algo bem parecido com o que eu queria, daí aprendi a fazer o do vídeo e depois encaixei essa sua sugestão e acabou que deu certo! Muito Obrigado Novamente, me ajudou d+!
Comment: A questão é: eu devo editar sua respostas incrementando o que falta pra que dê certo ou devo criar uma resposta mostrando como ficou? Eu não entendo muito bem como aqui funciona... perdi 4 pontos de reputação por que coloquei essa pergunta como do Android Studio (Ainda não sei por que).
Comment: @TonyÁlaffe é muito complicado essa questão de negativar aqui no SO. Tem muita gente que não sabe ainda como usar esse botão do down. Talvez negativaram você por não tem um pouco de esforço pesquisa na sua pergunta. Geralmente tem que haver código, etc. e mais clareza, além de formatação. Leia aqui [como fazer uma boa pergunta](http://pt.stackoverflow.com/help/how-to-ask); e [tipos de perguntas devo evitar de fazer](http://pt.stackoverflow.com/help/dont-ask).
Comment: @TonyÁlaffe se minha resposta te ajudou e você tem um complemento para ela, sugiro fazer a edição da minha resposta incrementado o que você tem. Agora se for totalmente diferente, você pode adicionar uma nova resposta a sua pergunta. Fique a vontade! Como você não tem reputação suficiente, sua edição passara por uma ouvidoria que posteriormente será aprovada se for condizente. Sugiro também marcar a resposta como válida se caso for realmente valida.
Comment: @TonyÁlaffe vou editar sua pergunta um pouco. Veja.
Comment: @TonyÁlaffe editei tentando não sair do objetivo, porém foi custoso. hehe
Comment: Mas melhorou muito mesmo!!! Assim que tiver reputação suficiente, vou apenas colocar a imagem do antes, para que tenha o ante e o depois...
Comment: Eu editei a resposta, você pode ver como ficou?
Comment: @TonyÁlaffe perfeito. Eu aprovei. Agora você precisa apenas marcar a resposta como correta, e assim é finalizada a questão. Se precisar, dê um toque aqui. Abs.
Comment: Consegui reputação suficiente, editei e já marquei como correta. Abs... Sei que é difícil, mas se precisar, também to por aqui.


How can I send an instance over a socket connection?

Question: I'm attempting to write two Java programs.
One to simulate a server, and one to simulate a client.
How could I go about sending an instance of a Response class over a socket?
The Response class represents status codes of the server connection. e.g. 404 Not Found etc
I'm not allowed to use Serialisation unfortunately.
Any advice would be greatly appreciated.
Comment: You'll always need some sort of serialization. What is the constraint exactly?
Comment: What does "I'm not allowed to use serialization" mean?  SOAP?  XML?  JSON?  You can't write your own customer serializer?  To travel over the wire, the data *must* be serialized in *some* way.
Comment: You aren't allowed to use Java Serialization? Why? Could you use custom Serialization (say, JSON on a String stream)? Also, you should consider changing the title of the question (is misleading, should say instance, not class)
Comment: I've been told that Java serialization is not to be used as the client or server end should be able to be rewritten in another programming language where java serialization isnt supported.
Comment: @James both answers below are fine then, JSON, XML, ..., they're all cross-platform serialization.
Answer: At some level Serialization must occur in order to send an object across a connection. I can only assume your comment about being not allowed to use serialization refers to not being able to use Serializable instead of a blanket prohibition of serialization(which makes no sense).  A very simple method to accomplish this would be the use of a external serialization library such as gson. Gson serializes an object into a JSON string that you can transmit over your socket and then using the same library deserialize it back into an object on the other side.  You can of course use any of your preferred serialization libraries with your favorite format eg. XML, json, YAML,...
Comment: Just looked up Gson and I'm downloading the zip file now. It seems to do exactly what I want. Thank you
Answer: You wouldn't be sending an instance of the Response class itself. When sending things over a network, client and server machines understand bytes. Your application can understand more than bytes, it can understand specific representations. For example, your server might send a JSON representation of your Response class like:
{
   "response" : {
       "code":404
   }
}

Then your client must be able to understand what this sequence of bytes means. That's basically what a protocol is: how two machines can communicate.
Regardless of what language the server or clients are written in, the Response is an Entity. In Java you might use a Class to represent it, in C++ you might use a struct. However, both would need to know that when you are communicating with an external application.system, they would have to put it in a format that everyone understands, be it json, xml, or any other.
As for sending this through sockets, Oracle has a nice tutorial here. You get the OutputStream
from the socket and start writing your representation.


Error when reading strings from CSV (Core Dumped)

Question: I keep getting the same error, I'm new to programming so I'm not so sure if the Syntax is correct.
Every time I run it, it returns Segmentation Fault(core dumped), I'm not even sure If I can open a file with a string (address) instead of the filename in extense.
Also the files I'm reading from are CSV but in txt format.
I'm using C99
<code>#define BUFFER_SIZE 1024
#define TAM_PERGUNTAS 128
struct question{
    char category[TAM_PERGUNTAS];
    char question[TAM_PERGUNTAS];
    char option1[TAM_PERGUNTAS];
    char option2[TAM_PERGUNTAS];
    char option3[TAM_PERGUNTAS];
    char correct[TAM_PERGUNTAS];
};
struct question vec_question[BUFFER_SIZE];

void questions() {
    FILE *perguntas;
    int numaleat=0;
    int num_questions, counter = 0, index, temp_randomizer=0;
    char line[BUFFER_SIZE];
    char answer[32];
    char address[TAM_PERGUNTAS];
    address[0] = '\0';

    srand(time(NULL));

    printf("Digite agora o numero de perguntas desejadas.(MAX 20) : "); //Insert Number of questions
    scanf("%d", &num_questions);
    printf("\n");

    for (counter = 0; counter < num_questions; counter++) {
        temp_randomizer = rand() % j; //j Represents the number o CATEGORIES at play and acts as a marker in the SELECTION string
        sprintf(address, "%s.txt", SELECTION[temp_randomizer]);
        perguntas = fopen(address, "r");
        if (perguntas == NULL) {
            printf("ERROR OPENING FILE!");
        }
            index = 0;
            while (fgets(line, sizeof(line), perguntas) != NULL) {
                strcpy(vec_question[index].category, strtok(line, ";"));
                strcpy(vec_question[index].question, strtok(NULL, ";"));
                strcpy(vec_question[index].option1, strtok(NULL, ";"));
                strcpy(vec_question[index].option2, strtok(NULL, ";"));
                strcpy(vec_question[index].option3, strtok(NULL, ";"));
                strcpy(vec_question[index].correct, strtok(NULL, ";"));
                vec_question[index].correct[strlen(vec_question[index].correct) - 1] = '\0';
                index++;
            }
            fclose(perguntas);
            index = 20;
            numaleat = rand() % index;
            printf("%s : %s\n%s\n%s\n%s",vec_question[numaleat].category,vec_question[numaleat].question,vec_question[numaleat].option1,vec_question[numaleat].option2,vec_question[numaleat].option3);

            for (int i = 0; i < num_users; i++) {
                printf("\n%s: ", &users[i][20]);
                scanf("%s", &answer[32]);
                if (answer == vec_question[numaleat].correct)
                    userspoints[i] += 1;
            }
        }
    }
</code>
Comment: `char answer[32]; ... scanf("%s", &answer[32]);` makes no sense. When using %s, you need to pass the address of the beginning of a buffer large enough to hold the input string. (Which, in the case of %s, means you need to pass an infiinitely large buffer). Try: `char answer[32]; ... scanf("%s31s", answer);`
Comment: @WilliamPursell,  regarding: `scanf("%s31s"`  this is nonsense.  Suggest: `scanf("%31s"`
Comment: regarding: `temp_randomizer = rand() % j;`  the variable: `j` is never declared nor initialized in the posted code.
Comment: regarding: `vec_question[index].correct[strlen(vec_question[index].correct) - 1] = '\0';`  Are you trying to remove a trailing newline?  if so, then the first statement in that code block should be: line[ strspan( line, "\n" ) ] = '\0';` and remove that last line
Answer: In general one should assume that functions like strtok can fail.
Sometimes it fails and returns a NULL value.  A short record in your input is a likely cause.
Consider using it with a loop, and breaking out of the loop once strtok returns NULL.
I found a simple example here.
<code>#include <string.h>
#include <stdio.h>

int main () {
   char str[80] = "This is - www.tutorialspoint.com - website";
   const char s[2] = "-";
   char *token;

   /* get the first token */
   token = strtok(str, s);

   /* walk through other tokens */
   while( token != NULL ) {
      printf( " %s\n", token );

      token = strtok(NULL, s);
   }

   return(0);
}
</code>
Note that it does one strtok to get the first token.  That might return NULL in which case the loop doesn't run.   If it doesn't return NULL then it prints that token, and asks strtok for the next token.  It keeps doing that until strtok returns NULL.


Applescript - how to compare (in an if-clause) a bundle identifier?

Question: Something like this script
tell application "Safari"
    activate
end tell
tell application "System Events"
    set frontAppID to bundle identifier of first process whose frontmost is true
end tell

returns "com.apple.Safari"
However, if I try something like
if frontAppID of bundle identifier of first process whose frontmost is "com.apple.safari" then

then it doesn't work. Obviously a bundle identifier cannot be compared with a string. How do I create a bundle identfier object I can use in my comparison?
Answer: The bundle identifier is a string, so a string-to-string comparison is fine. The problems with your statement are: frontAppID of bundle identifier, which isn't valid because frontAppID isn't a property of bundle identifier; and frontmost is should be followed by a boolean, not a string.
Fixing these issues (and assuming you'll enclose this within the appropriate System Events command block):
    if the bundle identifier ¬
        of (the first process ¬
        whose frontmost is true) ¬
        is "com.apple.safari" then ¬
        return true

P.S. Are you aware you can also do this (without needing to call System Events):
    if application "Safari" is frontmost then return true

or, using the bundle identifier:
    if application id "com.apple.safari" is frontmost then return true

Answer: Your syntaxe is not correct. correct should be:
tell application "System Events"
    if (bundle identifier of first process whose frontmost is true) is "com.apple.Safari" then
        display dialog "Safari front most !"
    end if
end tell


Why doesn't NFS recognize a new UID?

Question: I have two servers running RHEL6. I have root access to both. The main server, which I will refer to as server, is a database server. The application server, which I will refer to as client, mounts a directory from server via NFS.
There is a user, appuser, on both client and server. However, appuser's UID on client is 502. appuser's UID on server is 506.
Both users need read and write capability on the NFS share. To facilitate this, I made the share owned by appuser on server.
Running id appuser on each yields: uid=506(appuser).
Of course, client does not recognize that ownership, since appuser has a different id on client. So I did the following:

Changed UID of user in /etc/passwd on client to be 506.
Changed ownership of appuser's $HOME on client to be appuser again so that I could log in.

Now, when I go to look at the NFS share from the client side, I see that it is owned by 502. 502 is the OLD id for appuser on client. I can't change ownership of the NFS share from client, since that is a volume that physically resides on server.
I need to make sure that the NFS share shows ownership of appuser from both server and client.
What step have I missed since changing the appuser id on client?
NOTE: I have not rebooted client (or anything else.)
Answer: id appuser will likely show you that the shell still sees the old UID for the user.  Logout and log back in.
Comment: They are both showing the same thing.
Answer: OK! I have got it. Found it on Bing after trying many times. Still not certain exactly WHICH thing fixed by problem, of two possibilities. But here they are.
There is "tell" on the internet that there can be client ownership permission problems with NFS v4. I don't know if that's true, and I don't care. Somebody had something they called a solution. So I followed the instructions to force the client to mount the drive as NFS version 3. So the first thing I did was change my mount line permissions in /etc/fstab from this:
rw,hard,intr

to this:
rw,hard,intr,vers=3

Also, I started the nfs daemon on the client, just because someone said to do it:
service nfs start

Then, because I was following some dated instructions, I checked to see if the portmap service was running on the client:
service portmap status

and was greeted with:
portmap: unrecognized service

Then I found that portmap is now rolled into rpcbind. So:
service rpcbind status

And I saw:
rpcbind dead but pid file exists

Then:
[root@myserver customers]# service rpcbind restart
Stopping rpcbind:                                          [FAILED]
Starting rpcbind:                                          [  OK  ]

Then I checked the ownership of the NFS share, and it was CORRECT!
Answer: File ownership is saved with user ids. When you were looking at those files and seeing them as owned by appuser before the 502 -> 506 change, they were actually owned by user id 502 (ls -n will confirm). This has not changed.
Therefore, if you want to see appuser as the owner, you will have to change the ownership of the files from 502 to 506. And you may have to do that on the server if you do not have permissions on the client.
How to change the permissions is a different topic. If you do not have access to the server you can try copying the files using your new user (assuming you have read only access) and removing them later. It may be easier if you temporarily create a user with id 502 which will be able to change the permissions (but not the ownership) of the files owned by 502, rename them, or remove them after you copy them.
Comment: This is not correct. The ownership of `506` on the `server` is correct, it is being mapped to `502` by NFS on the client. Restarting `client` fixed this problem for me, although there may be a less heavy-weight way of solving this problem.
Answer: I have the same issue on solaris 11.
systema : zfs filesystem shared to systemB - files owned by userid davida UID 305
systemb : filesystem mounted from systemA - created local user davida with UID 304
permissions on nfs shared directories was 755, files was 700. davida UID 304 on systemb could not open files.
changed UID of davida on systemB to 305
Umounted nfs filesystem and changed user id davida on systemB to UID to 305 to match systemA.
Remounted nfs filesystem. Files still shows owner as UID 304
why ???

Why doesn't NFS recognize a new UID?


How to `addQuantitiesFromSamples` in HealthKit?

Question: Building a HealthKit/WatchKit app based off WWDC 2015 - Session 203.
There is no source code so I am writing it on the fly. There is a method I am having difficulty with since they don't discuss it.
Luckily it's the same addQuantitiesFromSamples method for all the workout types that add sample quantities to the workout session.
Of course I have this error because that method does not exist in my code.

Value of type 'HKQuantity' has no member 'addQuantitiesFromSamples'

I am not sure how to write a method that adds sample quantities. The method must be relatively basic because it's being used on all three of the sample queries in the project.
The sumDistanceSamples function is where the mystery addQuantitiesFromSamples method is called.
This is one of the three blocks containing the same error so I just need to find a solution for one of them.
WorkoutSessionManager.swift
class WorkoutSessionManager: NSObject, HKWorkoutSessionDelegate {

var activeEnergySamples: [HKQuantitySample] = []
var distanceSamples: [HKQuantitySample] = []
var heartRateSamples: [HKQuantitySample] = []

// ... code

var distanceType: HKQuantityType {
    if self.workoutSession.activityType == .Cycling {
        return HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDistanceCycling)!
    } else {
        return HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDistanceWalkingRunning)!
    }
}

var currentActiveEnergyQuantity: HKQuantity
var currentDistanceQuantity: HKQuantity
var currentHeartRateSample: HKQuantitySample?

// ... code

// MARK: Data queries

// Create streaming query helper method.
func createStreamingDistanceQuery(workoutStartDate: NSDate) -> HKQuery? {
    guard let quantityType = HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDistanceWalkingRunning) else {return nil}

    // Instantiate a HKAnchoredObjectQuery object with a results handler.
    let distanceQuery = HKAnchoredObjectQuery(type: quantityType, predicate: nil, anchor: anchor, limit: Int(HKObjectQueryNoLimit)) { (query, samples, deletedObjects, newAnchor, error) -> Void in
        guard let newAnchor = newAnchor else {return}
        self.anchor = newAnchor
        self.sumDistanceSamples(samples)
    }

    // Results handler that calls sumDistanceSamples function.
    distanceQuery.updateHandler = {(query, samples, deletedObjects, newAnchor, error) -> Void in
        self.anchor = newAnchor!
        self.sumDistanceSamples(samples)
    }

    return distanceQuery
}

func sumDistanceSamples(samples: [HKSample]?) {
    guard let currentDistanceSamples = samples as? [HKQuantitySample] else { return }

    dispatch_async(dispatch_get_main_queue()) {

        // Error point - "no member 'addQuantitiesFromSamples'"
        self.currentDistanceQuantity = self.currentDistanceQuantity.addQuantitiesFromSamples(currentDistanceSamples, unit: self.distanceUnit)

        // Add sample to array of samples accumulated over the workout.
        self.distanceSamples += currentDistanceSamples

        self.delegate?.workoutSessionManager(self, didUpdateDistanceQuantity: self.currentDistanceQuantity)

    }
}

// MARK: HEART RATE STREAMING
func createHearRateStreamingQuery(workoutStartDate: NSDate) -> HKQuery? {

    // alternative method to creating a match samples predicate

    // Append the new quantities with the current heart rate quantity.
    guard let quantityType = HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate) else {return nil}

    // Instantiate a HKAnchoredObjectQuery object with a results handler that calls our sumHeartRateSamples function
    let heartRateQuery = HKAnchoredObjectQuery(type: quantityType, predicate: nil, anchor: anchor, limit: Int(HKObjectQueryNoLimit)) { (query, samples, deletedObjectts, newAnchor, error) -> Void in
        guard let newAnchor = newAnchor else {return}
        self.anchor = newAnchor
        self.updateHeartRateSamples(samples)
    }

    // Results handler that calls our addActiveEnergySamples function
    heartRateQuery.updateHandler = {(query, samples, deletedObjects, newAnchor, error) -> Void in
        self.anchor = newAnchor!
        self.updateHeartRateSamples(samples)
    }

    return heartRateQuery
}

func updateHeartRateSamples(samples: [HKSample]?) {
    guard let heartRateCountSamples = samples as? [HKQuantitySample] else { return }

    // updateHeartRateSamples method dispatches back to the main queue.
    dispatch_async(dispatch_get_main_queue()) {

       // Error: Value of type 'HKQuantitySample?' has no member 'addQuantitiesFromSamples
       self.currentHeartRateSample = self.currentHeartRateSample.addQuantitiesFromSamples(heartRateCountSamples, unit: self.countPerMinuteUnit)

        // appends/updates that sample to an array of samples accumulated over the workout.
        self.heartRateSamples += heartRateCountSamples

        self.delegate?.workoutSessionManager(self, didUpdateHeartRateSample: self.currentHeartRateSample!)
    }

}

Answer: I'm not sure if this is what you're looking for, but this appears to be your missing method from someone else who watched the same WWDC video:

extension HKQuantity {
    func addQuantitiesFromSamples(samples : [HKQuantitySample], unit: HKUnit) -> HKQuantity  {

        var currentValue = doubleValueForUnit(unit)

        for sample in samples {
            let value = sample.quantity.doubleValueForUnit(unit)
            currentValue += value
        }
        let result = HKQuantity(unit: unit, doubleValue: currentValue)
        return result
    }
}

Source: Calories and Distance data from query
Comment: It's funny. I obviously found that thread as well since I was searching everywhere. But I didn't realize that extension might work. Let me try it and get back to you. Thanks.
Comment: @tymac placing it at the end of your Swift file outside of the class should work.  Is your class private or internal?  Have you tried making the extension public?  Are you using multiple modules in your application?
Comment: Oh wait a second! I think I understand now. 2 out of the 3 summing blocks seem to be ok. The `addDistanceSamples` method and `addActiveEnergySamples` method appear to accept the extension. But the heart rate summing doesn't like the extension because the heart rate doesn't sum. It just updates right? Could I use duplicate the same extension to create a separate method for the heart rate? How do I work with `updateHeartRateSamples`?
Comment: @tymac Absolutely.  You could add an additional method to the extension, or change the extension and check for the heart rate sample type and do something else.
Comment: @tymac Not sure, there are no syntax errors.  I stepped away from my computer but will try to recreate your issue with a MCVE when I get back.
Comment: Found out why. `currentActiveEnergyQuantity` and `currentDistanceQuantity` are of type `HKQuantity`. But `currentHeartRateSample` is of type `HKQuantitySample`. Actually this `updateHeatRateSamples` method is not in the Apple WWDC project (I just assumed to copy it) so they are obviously not using the same `addQuantitiesFromSamples` method. I will create a `updateHeartRateValueFromSamples` function in the new extension. Would it be possible to briefly show me an adjusted version of the function you gave me that can work with my new `updateHeartRateValueFromSamples` function?
Comment: I found this. http://stackoverflow.com/questions/27268665/ios-healthkit-how-to-save-heart-rate-bpm-values-swift


Tone Color Changed after Replacing a Piano Bass String

Question: I have a very old piano. A few years ago, one of its bass strings broke. I removed that broken string and kept playing almost everyday for a few years. Last week my technician installed a new string made by its original producer for exactly the same type of piano, but it sounds quite differently. Why does the tone color change if the string is replaced by a new one? Is there any way to fix this problem?
Comment: You played without a string for years and now wonder why, with the string replaced, things sound different?   No surprise here - the piano was designed for multiple strings under each key!
Answer: Like Tom says, a new string, even made by the same manufacturer will sound much different, most likely brighter than strings that have been on there for years. I suggest talking to your tuner about maybe softening the felt on the hammer of the new string, a process called "voicing". This might help make the sound more consistent between the new and old strings.
Comment: Even though the sound is a little unbalanced now it's good he replaced the string because otherwise the hammer might eventually get misaligned or even damaged by the off center strike.  Hopefully your tech can even out the tone by voicing that note.
Comment: I learnt something today! Does voicing will also change the tone on the other strings of that note?
Comment: @Tom_C I'm assuming it might be an individual bass string, the OP didn't specify. The hammers are poked with needles to soften them depending on need to even out the tone from string to string. I suppose a tech could voice part of the hammer if there are two different strings on a note. There are plenty of articles about it, here's a good one: https://www.pianolifesaver.com/english/blog/so_what_is_voicing
Comment: @Tom_C I meant to say "from note to note", not string to string.
Comment: @John Belzaguy The key has two strings. One of them was replaced.
Answer: Guitarists are accustomed to the fact that new strings have a different sound, I would say brighter in a sense. As they have not been used (yet!), their vibrating properties are different, no oxidation and so on…
What probably disturbs you is that it does not have the same color as the surrounding strings, creating a contrast.
If you are playing enough, the string will age and get its color closer to its neighbors which are old already. Another solution would be the wire cutter, but that would be a pity…
Answer: The other answers are useful, but I think they missed the point.
Each piano key strikes 2 or 3 (depending on the pitch in question and the piano's design) strings.  These strings are deliberately detuned just a hair so as to increase cross-resonance and enhance the tonality and the lifetime of the note.
When you were playing with the wrong number of strings under that key,you weren't hearing the design tonality of the instrument.
Comment: That is an important point, but the new string's 'brightness' is probably more likely the sound difference OP picked up on. Maybe more so  with your point.
Comment: Pianos have several bass notes that use only one string as well.


Succesive random numbers in a range

Question: I have this following code:
#include <iostream>
#include <cstdlib>
#include <ctime>

int getRandomNumber(int min,int max)
{
    static const double fraction = 1.0/(static_cast<double>(RAND_MAX)+1.0);
    return static_cast<int>(rand()*fraction*(max-min+1)+min);
}

int main()
{
    srand(static_cast<int>(time(0)));
    std::cout<<getRandomNumber(1,6);
    return 0;
}

If I run this program in succesions, then i get the same number. But when i run this one with cout statement as:
std::cout<<getRandomNumber(1,6)<<getRandomNumber(1,6);

I get different numbers every time.
So how is this possible?? Am I missing something?
Comment: I run the above program with two cout. It gives the two same number as result.
Comment: I see you using an int number. It can be generated using rand() only. Why you going through much trouble. 'cout<<rand()<<" "<<rand();'
Comment: By the way; getRandomNumber() can generate at most RAND_MAX+1 different numbers, regardless of min and max. And it is relatively easy to predict the numbers that cannot be returned.
Answer: The time() function returns time in seconds so running the program two or more times within the same second will cause the random number system to be seeded with exactly the same number.
Comment: @denis on the contrary. The `time()` function is used in the call to `srand()` and it determines the sequence of random numbers that will be produced by the `rand()` function. If you call `srand()` with the same number you get exactly the same sequence of random numbers from the `rand()` function.
Comment: time() function is used in first srand function; is never used , hence have no relation with what we see as output.
Comment: Guys, I am using Codeblocks. Whenever i use single call to getRandomNumber(), i get same number,like 5. But when i call it two times, it generates two random number even during the same second every time i run,like 56 or 42.
Comment: @Hope It is calling `srand()` two times in the same second that causes the problem. You can call `rand()` as many times as you want it will give you random numbers **unless** you keep resetting it using `srand()` more than once per second.
Answer: When using function time() as seed and running program within short interval, the first result of rand() will be changed in a very small number comparing to RAND_MAX.
This explained why you got the same number, when using fraction to get a number from 1 - 6.
Here is another way to get random number from 1 to 6, which may do better.
rand() % 6 + 1

Succesive random numbers in a range


Probability Curiosity

Question: Let $X_{1},X_{2},\ldots$
  be i.i.d. random variables with $ E\left[X_{1}\right]=0$
  and $0<Var\left(X_{1}\right)=\sigma^{2}<\infty.$.
Let $ S_{n}=\sum_{j=1}^{n}X_{n}$. Consider now $\lim_{n\to\infty}E\Big[ \frac{|{S_{n}}|}{\sigma\sqrt{n}}\Big]$
To which theorem I have to appeal in order to bring the limit inside?
Comment: Inside of what? The expectation?
Comment: @Sasha. Yes, inside expectation
Answer: Let $T_n=|S_n|/(\sigma\sqrt{n})$, one knows that $T_n$ converges in distribution to the absolute value of a standard normal random variable hence, by Skorokhod's representation theorem, there exists some random variables $Z_n$ and $Z$ defined on a common probability space such that $Z$ is the absolute value of a standard normal, each $Z_n$ is distributed as $T_n$, and $Z_n\to Z$ almost surely.
Now, $(T_n)$ is bounded in $L^2$ hence $(Z_n)$ is bounded in $L^2$ hence $(Z_n)$ is uniformly integrable hence $Z_n\to Z$ in $L^1$, in particular $\mathbb E(T_n)=\mathbb E(Z_n)\to\mathbb E(Z)$.
Comment: do u use Skorohold's theorem in your proof, right? Great answer thanks. Thinker
Comment: [Yes](http://en.wikipedia.org/wiki/Skorokhod%27s_representation_theorem).

Probability Curiosity


How to make an alias of a command which accepts an argument and is executed on background?

Question: I want to make alias to open file with GUI editor on background from command line.

I tried:
alias new_command="editor_path &"
new_command file

But it just open editor without loading the file.
Answer: The & is ending the command, so it is not seeing your file argument.  You can't use alias if you want to substitute the filename string into the command with the ampersand on the end.
From the bash manpage:

   There  is no mechanism for using arguments in the replacement text.  If
   arguments are needed, a shell function should be  used  (see  FUNCTIONS
   below).

Consider creating a shell function:
function new_command
{
editor_path "$1" &
}

Answer: You can try something like this:
alias new_command="sudo -b editor_path"

Although you'd need to enter your password.


open all ports to specific IP with firewalld

Question: I'm on a red hat 7 machine, and I need to open all ports to a specific IP on the firewall.
I tried this command:
firewall-cmd --permanent --zone=public --add-rich-rule='   rule family="ipv4"   source address="126.96.36.199/20"   port protocol="tcp" port="*" accept'

But I'm getting an invalid port error for the *
Does anyone know and can tell me how to do this correctly?
Answer: Use a firewalld zone for this. Zones can be specified either by interface or by source IP address.
In fact, by default, a zone which accepts all traffic already exists, and it is named trusted. By default, though, nothing is in this zone. So, you don't even need to create a zone, just add the IP address to the trusted zone.
firewall-cmd --zone=trusted --add-source=126.96.36.199/20

In addition to CIDR ranges, you can specify single IP addresses or ipset names prefixed with ipset:.
After this, all traffic from the specified addresses will be allowed on any port. Remember to make it permanent, either by repeating the command with --permanent appended, or by running firewall-cmd --runtime-to-permanent.
Comment: I also used `xxx.xxx.xxx.xxx/32` to restrict to just my own Public IP address.
Answer: AFAIK the port can either be a single port number 123 or a port range 123-456 and * is not a valid input.
Not specifying any specific port number/range will match any port.


getting high resolution photos that were posted on a page wall/feed

Question: I'm getting my page wall with the open graph.
And when someone posted a photo, I get it on the JSON
{
     "id": "27888702146_10150369820322147",
     "from": {
        "name": "brocoli",
        "category": "Record label",
        "id": "27888702146"
     },
     "message": "Vincent Epplay / David Fenech / Jac Berrocal \u00e0 Beaubourg ce soir, 19h, gratos.",
     "picture": "http://photos-f.ak.fbcdn.net/hphotos-ak-snc7/305819_10150369820292147_27888702146_8255527_583491475_s.jpg",
     "link": "https://www.facebook.com/photo.php?fbid=10150369820292147&set=a.386279807146.165840.27888702146&type=1",
     "icon": "http://static.ak.fbcdn.net/rsrc.php/v1/yz/r/StEh3RhPvjk.gif",
     "type": "photo",
     "object_id": "10150369820292147",
     "created_time": "2011-10-16T08:22:21+0000",
     "updated_time": "2011-10-16T08:22:21+0000",
     "likes": {
        "data": [
           {
              "name": "brocoli",
              "category": "Record label",
              "id": "27888702146"
           },
           {
              "name": "Agathe Morier",
              "id": "601668526"
           }
        ],
        "count": 2
     },
     "comments": {
        "count": 0
     },
     "is_published": true
  }

The problem is that the picture link is a low resolution copy of the picture.
How can I get the URL of the full picture ?
Thanks!!
Best
Geoffroy
Comment: Have you got the solution , the below answer not working.
Answer: You can get different version of the photo by querying Graph API with its object_id (not photo post_id which is id in results you provided).
Once you'll request the photo by object id you'll get array of images with URLs and dimensions:
http://graph.facebook.com/10150369820292147?fields=images

If you're attempting to access posts on a Facebook Page (such as for a company) instead of typical user profile, you firstly need to fetch the feed like this:
https://graph.facebook.com/v15.0/YOUR_PAGE_ID_HERE/feed?fields=attachments&access_token=...

And then access data[0].attachments.data[0].subattachments.data[0].target.id to get the object ID (or "target ID" in this case) which you can then use to perform an additional query to obtain the higher resolution image. Increment the numbers to get additional posts and images inside each post.
Comment: @Juicy Scripter, Thanks for the great answer but for the feed type "Video" it is failing with below response. {"error":{"message":"Unsupported get request. Please read the Graph API documentation at https:\/\/developers.facebook.com\/docs\/graph-api","type":"GraphMethodException","code":100}}
Comment: @Juicy Scripter : not working ' Unsupported get request '  http://graph.facebook.com/397556853726341?fields=images
Comment: @Juicy Scripter What if i don't have an object_id in my feed.
Comment: @VineeshTP working for me, perhaps you're not using the correct object_id field?
Answer: All you need to do is :
http://graph.facebook.com/me?fields=picture.height(961)
// replace 961 with your required height which u want

Comment: This should be the accepted answer. Only thing working right now.
Comment: This only gets your profile pic, not all the photos in your feed.
Answer: You can do this from the main posts list now using
/v2.3/105753476132681/posts?limit=5&fields=likes.summary(true),comments.summary(true), attachments

If attachments doesn't work, try full_picture - but that just gave the 100x100 image for me as well.
Attachments returns a data hash with a 640x480 version of the image at least (not sure what my orig. photo size was)
Comment: This might work for a typical user feed, but not for a Facebook *Page*, which currently limits images to 720px. You instead need to use the [method mentioned above](https://stackoverflow.com/a/9821883/195835) by Juicy Scripter.
Answer: Use this Code. Its Work for me and get Clear Image
String PICTURE_URL;

String getPicture = hashMap.get("picture");
        if (getPicture.contains("_t.")) {
            PICTURE_URL = getPicture.replaceAll("_t.", "_n.");
        } else if (getPicture.contains("_a.")) {
            PICTURE_URL = getPicture.replaceAll("_a.", "_n.");
        } else if (getPicture.contains("_s.")) {
            PICTURE_URL = getPicture.replaceAll("_s.", "_n.");
        } else if (getPicture.contains("_q.")) {
            PICTURE_URL = getPicture.replaceAll("_q.", "_n.");
        }
        url=new URL(PICTURE_URL);
        Bitmap bitmap=BitmapFactory.decodeStream(url.openConnection().getInputStream());
        ((ImageView)view.findViewById(R.id.imageView_FullImage)).setImageBitmap(bitmap);

Comment: By me it works sometimes and sometimes not.... why did facebook made getting an image so stupid
Answer: Though requesting a photo by its object_id will return an array of images with different dimensions, in some cases this approach would require an additional call to the Facebook API.
A simpler approach is to add full_picture to your list of parameters, which will extract the highest resolution image associated with the post.
/v2.2/6275848869/posts?fields=full_picture

For example, if you want to extract all the posts from a Facebook page in the past X days, with the object_id approach you'd need to call the API 3 times:

To get the page info.
To extract the list of posts and obtain the object_id for each post.
For each object_id, to retrieve the list of higher resolution images.
Comment: Unfortunately this has two problems: it doesn't fetch the highest resolution when used on Facebook posts assigned to a "Page", and it only fetches a single image. Some posts can have multiple images attached.


Multiple regression: R splits Variable into multiple

Question: Hey there i want to explore the effect of Age and Gender on points of a test via mlr.
Yet when i type
model <- lm(punkte~ Age + Gender, data = df)

R gives me following results
(Intercept)   5.677369   0.176482  32.170  < 2e-16 ***
Age          -0.017953   0.004932  -3.640 0.000300 ***
GenderFemale  0.595369   0.154697   3.849 0.000134 ***
GenderDivers -1.416150   0.684191  -2.070 0.038964 *

But i dont want the Gender variable to be split into multiple, also GenderMale is missing and i dont know why. Help would be appreciated very much
Comment: This is not a programming question and hence it does not belong on this site. You should really do some research on `lm` because you are lacking very basic skills for interpreting this model.
Answer: "Male" is missing since your model chooses "male" as the reference, when you have categorical variables in gender.
You can always change the reference variable by something like:
df <- within(df, gender <- relevel(factor(gender), ref = "Female"))

You can only combine the "female" and "divers" if you change the data from the root (and normally we don't do that). For example, combine those two to "non-male" or "others".


What is an All-Pass Filter? What are its uses?

Question: Wikipedia says:

An all-pass filter is a signal processing filter that passes all frequencies equally in gain, but changes the phase relationship among various frequencies.

What does changes the phase relationship among various frequencies mean and what is its musical application?
Where is an All-Pass Filter used?
Are there any All-Pass filter plugins (AU, VST, AAX)?
Answer:

Are there any All-Pass filter plugins(AU, VST, AAX)?

The standard EQ plugin of Reaper (ReaEQ, you can also get this as a separate VST plugin) has different modes for the filters (a parametric EQ is nothing but a cascade of tweakable filters), including allpass.

What does changes the phase relationship among various frequencies mean and what is its musical application?

One way to look at it is that an all-pass filter is a short frequency-dependent delay. (In fact, an ordinary delay might also be considered an all-pass filter, though that's not usually what's meant by it.) See this example of a sweeping 1st-order all-pass applied to two different sinusoidals:

For very high filter frequencies, both signals are only delayed by the same small time, whereas for very low frequencies the delay approaches ½ or the signal period. (These exact details may vary between different kinds of APFs, but the principle is always similar.)

What does changes the phase relationship among various frequencies mean and what is its musical application?

As the other answer said, it is mostly relevant when you combine multiple signals that have a fixed phase relation – like one instrument recorded with two microphones. It may be that the microphones give in-phase signals below 300 Hz but out-of-phase for higher frequencies. In this case, neither direct mix nor phase-inverting one of the mics may give a good result, but an all-pass filter (and/or a short delay) on one of the channels might help.
Unlike a delay, an all-pass filter does also have an effect when applied to a single signal in isolation, though this is not evident on sinusoidals and almost inaudible because the ears are most sensitive to the Fourier amplitudes (i.e. sinusoidal components). However, in practice most signals are of course not sinusoidal. As the filters are linear, the result for a superposition is the same as a superposition of individually-filtered sinusoidals, however because those are delayed by different amounts, the resultant waveshape does actually change. In the example of those two sinusoidals, like this:

Again, the ear isn't very sensitive to phase, but the effect is quite significant in particular for signals with strong transients, such as this:

Notice how, although the APF does by definition not affect the power of the signal, it does in this case reduce the amplitude considerably, because the transient is smeared out a bit. This can be useful e.g. for drum tracks, to maximise loudness within a given headroom without needing compressor/limiter/softclipping.

Source code (Haskell with dynamic-plot):
import Graphics.Dynamic.Plot.R2
import Data.List
import Data.Function
import Text.Printf

type Signal = [Double]

lpf :: Double -> Signal -> Signal
lpf f = go 0
 where go s (y:ys) = s' : go s' ys
        where s' = s*(1-η) + y*η
       go _ [] = []
       η = 2*pi * f / sRate

allpass :: Double -> Signal -> Signal
allpass f ys = zipWith (\lfd orig -> 2*lfd - orig)
                  (lpf f ys) ys

signalPlot :: Signal -> DynamicPlottable
signalPlot ys = lineSegPlot $ zip [0, 1/sRate..] ys

functionSignal :: Double -> (Double -> Double) -> Signal
functionSignal l f = f <$> [0, 1/sRate .. l]

sRate :: Double
sRate = 44100

examples :: [ [DynamicPlottable] ]
examples = [ example ++ [forceXRange (0.01, 0.02), xAxisLabel ""]
           | example <- plots ]
 where plots
        = [ let [sig0, sig1] = functionSignal 0.02
                 <$> [(+1) . sin . (2*pi*440*), (+(-1)) . sin . (2*pi*675*)]
            in [ signalPlot sig0 & legendName "440 Hz"
               , signalPlot sig1 & legendName "675 Hz"
               , animatedAllpassPlot $ \apf -> plot $ signalPlot . apf
                                                 <$> [sig0, sig1]
               ]
          , let sig = functionSignal 0.02
                 $ \t -> sin (2*pi*440*t) + sin (2*pi*675*t)
            in [ signalPlot sig & legendName "440 Hz & 675 Hz"
               , animatedAllpassPlot $ \apf -> signalPlot $ apf sig
               ]
          , let sig = functionSignal 0.02
                 $ \t -> let φ = 2*pi*300*t in (sin φ/1.4 + 0.3)^9 - cos φ/3
            in [ signalPlot sig & legendName "Orig"
               , animatedAllpassPlot $ \apf -> signalPlot $ apf sig
               ]
          ]
       animatedAllpassPlot ftrUsr
               = plotLatest [ ftrUsr (allpass f)
                               & legendName (printf "APF @%.0g Hz" f)
                            | f <- (+50) . (*800) . (+1) . sin <$> [0,0.1..]
                            ]

main :: IO ()
main = mapM_ plotWindow examples

Comment: The last image and explanation here also demonstrates the idea behind a very popular use for phase rotation: processing for radio broadcast. Phase rotators are (or at least were - not sure if digital broadcast still does this) used in radio broadcast to reduce the peaks (called *modulation* in radio) without reducing the signal power.
Comment: Great answer! Cannot compete with Haskell!
Comment: I wish I understood any of that. Even the tiniest bit.
Answer: I am going to answer only your first two questions (or at least, I will try).
An audio signal can be seen as a sum of sinusoids. These sinusoids each have an amplitude and a phase. The amplitude is self-explaining but the phase actually tells you if all your sinusoids started together or not (in a very rough way).
Most of filters (standard low-pass, high-pass and bandpass) are modifying both the amplitude of these sinusoïds (for instance reducing the one of higher frequency for the low-pass), but also their phases. For the particular example of the low-pass, what you get after the filter will be in phase with the incoming signal below its cutting frequency and completely out of phase above. Completely out of phase actually means that the signal is reversed: A(t) becomes -A(t). Around the cutoff frequency, intermediate situations exist as the phase shift is continuous between 0 and pi (or minus pi, 2pi depending on the filter).
This can cause some issue, for instance leading to phase issues if you try to mix the original signal with the filtered signal: the phase relationship between these two signals will not be the same below and above the cutoff frequency. To prevent this, one can use an allpass to change the phase relationship between two signals to avoid this.
This kind of filters can also be used for instance in  phase distortion synthesis in order to modify the tone of a sound.
(A quick and dirty answer, I'll try to edit when I get a bit of time…)
Comment: Interestingly, many kinds of filters may be produced by taking an all-pass filter and mixing its output with the unmodified original signal.  Signals whose phase is unaffected or shifted by a whole manner of periods will double in strength; those whose phase was shifted by an odd number of half-periods will be eliminated.  Those whose phase is shifted by other amounts will be attenuated and phase-shifted to varying degrees.
Answer: I have tried to answere the questions to my understanding, but I would not consider myself very experienced in this topic. So feel free to correct or hint me if something is not totally correct or just plain wrong.

I have found the following information on this  site:
1. What does changes the phase relationship among various frequencies
mean and what is its musical application?

Allpass filters are filters that have what we call a flat frequency
response; they neither emphasize nor de-emphasize any part of the
spectrum. Rather, they displace signals in time as a function of
frequency. The time displacement accomplished by an allpass filter is
specified by its phase response. Allpass filters are used in circuit
design to perform various frequency-dependent time-alignment or
time-displacement functions.

So all pass filters are making changes to the phase of an audio source in specific frequencie ranges.
What is the phase?
Sound is just moving air and the phase is the way the air moves. For example if a string of a guitar is swinging with 500 Hz (swinging 500 times a second) you could show the air movement which is produced in this way:

(Of course it would not produce such a clean wave. The string would also swing on other frequenzies like 1000 Hz, would resonate with itself, the body of the guitar etc. Thats why you dont hear a sinus tone when you struc a string.).
You can now switch the phase and get this result:

An all pass filter can make such changes for specific frenquencies in an audio source.

2. Where is All-Pass Filter used?

Audio applications include filter banks,
speaker crossovers, and reverberators. Allpass filters appear in both
continuous- and discrete-time applications.

So all pass filters seems to be part of other audio transforming effects like reverbs.
Changing the phase of an audio source is often used to disable phase canccelation
Phase canccelation is when thwo phases, like the ones above, would cancel each other out. If you layer those two sine waves above another, you would hear no sound, since each wave valley would be canceld out by the wave crest of the other sine wave. So you would have no movement at all. This is a big factor in recording, aspecially when you use two mics to record the same source.

3. Are there any All-Pass filter plugins(AU, VST, AAX)?
As of my understanding of the article I linked, all pass filters most of the time are used internally inside other more complex vst's. There are some eq's and filters which provide an all pass filter functionality like the ReaEQ and the Fruity Love Philter
Comment: Fruity Love Philter is a standalone filter plugin with an all pass filter (available as VST or FL proprietary format)
Answer: I have answered these questions in full in a video and an article.
In summary:

What does changes the phase relationship among various frequencies mean and what is its musical application?

It means that different frequencies are delayed by different phase shifts in radians. The maximum negative phase delay occurs for the Nyquist frequency (half the sampling rate). For example, for a first-order all-pass filter, phase delay is 0 radians at 0 Hz and -PI radians at the Nyquist frequency. Again, visualization for the first-order all-pass filter and the second-order all-pass filter.

Where is an All-Pass Filter used?

Selected applications of all-pass filters are reverberation algorithms (Schroeder reverberator, Freeverb algorithm), parametric equalizers (musically useful high-pass, low-pass, shelving, notch, band-pass filters), the phaser effect, and phase equalization (e.g., when mixing signals from microphones with different phase responses).

Are there any All-Pass filter plugins (AU, VST, AAX)?

Yes, ReaEQ (as was mentioned), here I present an example anyone can play with.


Vagrant: Accessing host machine localhost from guest machine (Mac)

Question: I'm trying to access localhost (a Rails app) from Internet Exporer running on a VirtualBox (via Vagrant).
I've set up the following.
config.vm.network "forwarded_port", guest: 3100, host: 3000
Typing in the following into Internet Exporer running on the VM does not work:
<my host machines IP>:3100
0.0.0.0:3100
localhost:3100
Access to the guest machine from the host is does not work.
Lots of tutorials online covering setting up Vagrant to test IE, but not much on accessing hosts localhost from the guest machine browser.
Answer: This is an old question but for anyone else looking for an answer I found this solution

vb.customize ["modifyvm", :id, "--natdnsproxy1", "on"]
vb.customize ["modifyvm", :id, "--natdnshostresolver1", "on"]

By proxy and hostresolver to the vagrant box I can access same hosts as host-machine.
I also found this to be a good start config for Vagrant IE boxes https://gist.github.com/andreptb/57e388df5e881937e62a


índice do valor - como retornar a posição de um valor que se encontra na array (começando em 0 )

Question: preciso de uma ajuda! preciso implementar uma função que recebe uma array  e um valor e retorna a posição que esse valor se encontra na array?
tentei fazer assim!
porem preciso fazer também um retorno "0" ao invés do "2"
Comment: Por favor, edite a pergunta para limitá-la a um problema específico com detalhes suficientes para identificar uma resposta adequada.
Answer: Seu código está sempre procurando o valor 30. E sempre do mesmo array (scores). As variáveis 'array' e 'valor' são as que você deve usar no seu código para passar no teste.
substitua:
let posicao = scores.indexOf(30);

por:
let posicao = array.indexOf(valor);

Comment: shooooow, deu certinho, muito obrigado meu parceiro.. :)


Help understanding parameterization of gamma distribution in R's glm()

Question: I would like recover the gamma distribution parameters from a model fit in R using glm(..., family = Gamma). The first step is trying to figure out which parameterization R's glm function uses for the gamma distribution. Looking through ?glm, ?family, and ?Gamma didn't help me. This post was helpful in understanding the parameterization, but doesn't say much  about recovering the parameter estimates from the output. This post explains how to get the dispersion estimate from the fit model object, and I use that and the estimated mean values to calculate the shape and scale parameters.
# model from example in ?glm
clotting <- data.frame(
  u = c(5,10,15,20,30,40,60,80,100),
  lot1 = c(118,58,42,35,27,25,21,19,18),
  lot2 = c(69,35,26,21,18,16,13,12,12))
fit <- glm(lot1 ~ log(u), data = clotting, family = Gamma)

# mean = shape * scale (https://en.wikipedia.org/wiki/Gamma_distribution)
# mean can be directly obtained from model output
mu <- fit$fitted.values
# mu <- predict(fit, type = 'response')

# dispersion = residual deviance / residual degrees of freedom (https://stats.stackexchange.com/a/367563/45889)
dispersion <- (fit$deviance / fit$df.residual)
# and shape parameter is inverse of dispersion (https://stats.stackexchange.com/a/247631/45889)
shape <- 1 / dispersion
# scale = mu / shape (https://en.wikipedia.org/wiki/Gamma_distribution)
scale <- mu / shape

# variance = shape * scale^2 (https://en.wikipedia.org/wiki/Gamma_distribution)
var <- shape * scale^2

Is this correct? Because when I try to manually calculate Pearson residuals, my Pearson residuals differ from R's Pearson residuals by a factor of sqrt(shape).
# raw residuals
observed <- clotting$lot1
expected <- fit$fitted.values
raw_residuals <- observed - expected

# Pearson residuals = raw residuals / variance function (https://v8doc.sas.com/sashtml/insight/chap39/sect56.htm)
pearson_residuals <- raw_residuals / sqrt(var)

# but when I compare this to R's Pearson residuals, they're different
all.equal(resid(fit, 'pearson'), pearson_residuals)

# they're different by a factor of sqrt(shape)
pearson_residuals / resid(fit, 'pearson')
sqrt(shape)

var2 <- var * shape
pearson_residuals2 <- raw_residuals / sqrt(var2)
all.equal(resid(fit, 'pearson'), pearson_residuals2)
# TRUE

What am I missing? I have been assuming that I'm misunderstanding something with the parameterization of the gamma distribution, but perhaps am I doing something wrong with the Pearson residuals?
Answer: The Pearson residuals rescale using the variance function $V(\mu)$ but not using the estimated dispersion parameter. So if $\mathrm{var}[Y]=\sigma^2V(\mu)$,
$$r_P = \frac{y-\mu}{\sqrt{V(\mu)}}$$
not
$$r_P = \frac{y-\mu}{\hat\sigma\sqrt{V(\mu)}}$$
Obviously it doesn't matter for most graphical purposes whether the scale factor of $\hat\sigma$ is in there or not; it was at one point a free choice.  The implementation in R followed that in S, which followed people who defined Pearson residuals without the $\hat\sigma$ term.
It's convenient to leave it out for a few reasons. First, you can define $\hat\sigma^2$ as just the variance of the Pearson residuals.  Second, for linear/Gaussian glms you end up with the Pearson residuals being the same as the raw residuals (and the working residuals and the deviance residuals).
Comment: And since the variance function of the gamma distribution is `mu^2`, I divide the raw residuals by `mu` to get the Pearson residuals.


Copying from one dimensional vector vector starts to first element of two dimensional vector pair vector>matrix

Question: I have multiple 3 one dimensional vectors (vector<int> starts, vector<int> ends, vector<int> points). Each having specific number of elements.
I want to create a two dimensional vector vector<pair<int,int>>matrix in such a sequence :

from beginning of matrix to size of start first element of matrix is elements of vector<int> starts and second element is "-1"
Append now the elements of vector<int> ends to matrix such that first element of matrix is elements of vector<int> ends and second element is "-2"
Append now the elements of vector<int> points to matrix such that first element of matrix is elements of vector<int> points and second element is Index of points.
Visual Representation :-
Input:
starts: {1, 2, 3}
ends: {4, 5, 6}
points: (7, 8, 9}
Output:
matrix: { {1, -1}, {2, -1}, {3, -1}, {4, -2}, {5, -2}, {6, -2}, {7, 0}, {8, 1}, {9, 2} }

Currently I am using a push_back with for-loop function which works perfectly fine but when the input  size is big code is very slow.
Code I am using is as follows:
vector<pair<int,int>> fast_count_segments(
    vector<int> starts,
    vector<int> ends,
    vector<int> points)
{
   int i = 0;
   vector<pair<int,int>>matrix;

   for(i; i<starts.size(); i++) {
       matrix.push_back(make_pair(starts[i],-1));
   }
   for(i; i<starts.size()+ends.size(); i++) {
       matrix.push_back(make_pair(ends[i-starts.size()],-2));
   }
   for(i; i<starts.size()+ends.size()+points.size(); i++) {
        matrix.push_back(make_pair(
            points[i-starts.size()-ends.size()],
            i-(starts.size()+ends.size())
        ));
   }
   return matrix;
}

Can you please help on how to fill the 2D vector quickly with these requirements without iterating through each element. I am using C++11. Thanks in Advance !!
Comment: Don't tag a C++ question with the C tag.  It won't help you make friends and influence people.
Comment: `vector>` … uh, that's not how it works. That would create a 1D vector of pairs of int. Also https://www.boost.org/doc/libs/1_72_0/libs/multi_array/doc/user.html
Comment: @datenwolf: That could be a sparse representation of a matrix.
Comment: @epinpoklum Only 2-by-N matrices or N-by-2 matrices. Maybe you want `vector>`?
Comment: @einpoklum: Only if the elements of the sparse matrix you want to represent are members of the set `{False | True}`. Or if you want to represent a bidiagonal matrix. Either way, it'd be a very inefficient way to go about this.
Comment: @datenwolf: Yes, that would be a boolean matrix. Ok, point taken, I now also share your worry OP might be doing something wrong here.
Answer: Preliminary concern: As @datenwolf and others note - Your resulting data structure is not a 2D matrix (unless you mean a boolean matrix in sparse representation). Are you sure that's what you want to be populating?
Regardless, here are a few ideas to possibly improve speed:

Don't take the input vectors by value! That's useless copying... take their .data(), or their .cbegin() iterator, or take a span<int> parameter.
Use the reserve() method on the target vector to avoid multiple re-allocations.
Use .emplace_back() instead of .push_back() to construct the points in place, rather than constructing-then-moving every point. Although, to be honest, the compiler will probably optimize those constructions away, anyway.
Put the .size() values of the input vectors in local variables. This will only help if, for some reason, the compiler suspects that size will not be constant throughout the execution of the function.
Make sure you're passing optimization switches to the compiler (e.g. -O2 or -O3 to GCC and clang). This might seem obvious to you but sometimes it's so obvious you forget to check it's actually been done.

Some aesthetic comments:

No need to use the same counter for all vectors. for(int i = 0; i < whatever; i++) can be used multiple times.
No need for raw for loops, you can use for(const auto& my_element : my_vector) for the first two loops. The third loop is trickier, since you want the index. You can use std::difference() working with iterators, or go with Python-style enumeration described here.
You might consider using std::transform() with a back_emplacer output iterators instead of all three loops. No-loop code! That would mean using std::difference() in the transformer lambda instead of the third loop.
Comment: For 1. wouldn't a reference be the most natural option? 3. counts as aethetic, with integer values the generated code will be the same.
Comment: @MarcGlisse: 1. Nope, we work with iterators, ranges, or in some cases spans. Unless we're operating on the input vector _as_ a vector, which we aren.t 3. You're probably right.
Comment: A vector is a special case of range, so you can take a T const& (or sized_range const& in C++20) for instance.
Answer: This incorporates the suggestions from @einpoklum's answer, but also cleans up the code.
std::vector<std::pair<int,int>> fast_count_segments(
    std::vector<int> const & starts,
    std::vector<int> const & ends,
    std::vector<int> const & points)
{
   std::vector<std::pair<int,int>> matrix(starts.size() + ends.size() + points.size());

   auto out = std::transform(starts.cbegin(), starts.cend(),
                             matrix.begin(),
                             [](int i) { return std::pair<int,int>{i, -1}; });

   out = std::transform(ends.cbegin(), ends.cend(),
                        out,
                        [](int i) { return std::pair<int,int>{i, -2}; });

   int c = 0;
   std::transform(points.cbegin(), points.cend(),
                  out,
                  [&c](int i) { return std::pair<int,int>{i, c++}; });

   return matrix;
}

You could even write all the transforms as a single expression. Whether this is easier to read is highly subjective, so I'm not recommending it per se. (Try reading it like you would nested function calls.)

std::vector<std::pair<int,int>> fast_count_segments(
    std::vector<int> const & starts,
    std::vector<int> const & ends,
    std::vector<int> const & points)
{
   std::vector<std::pair<int,int>> matrix(starts.size() + ends.size() + points.size());
   int c = 0;

   std::transform(points.cbegin(), points.cend(),
        std::transform(ends.cbegin(), ends.cend(),
            std::transform(starts.cbegin(), starts.cend(),
                matrix.begin(),
            [](int i) { return std::pair<int,int>{i, -1}; }),
        [](int i) { return std::pair<int,int>{i, -2}; }),
    [&c](int i) { return std::pair<int,int>{i, c++}; });

   return matrix;
}

Comment: The [] indicates the start of a [lambda expression](https://en.cppreference.com/w/cpp/language/lambda). Updated the answer to work in c++11.
Comment: Doesn't each `transform` return the parameter for the next one?
Comment: Yeah, thanks for the suggestion. I realize I could nest the transforms as well, though I suspect that wouldn't make it easier to read.
Comment: Thank you @cigien. I am beginner in cpp. don't understand the significance of [] in transform. Also it is giving compilation error "returning initializer list". Also I am using C++11 hence for [c = 0], lambda capture initializers only available with -std+c++14
Comment: Thanks a ton @cigien. This really makes it clear. However if I use this method I am not able to read the matrix as I was reading it when I populate the matrix using the for-loop. `cout << matrix[i].first << " " << matrix[i].second << endl;`. Where i iterates through the size of the loop. What might be the reason ?
Comment: That's right. [reserve](https://en.cppreference.com/w/cpp/container/vector/reserve) only changes the capacity, not the size of the vector. I forgot that. I've edited the answer.


"Back up" join option in R full_join

Question: We're in the process of merging two very large online databases, and there's going to be a lot of manual data cleaning we're going to have to do.  For now, we're just using R to visually put the columns next to each other and eyeball the differences.
Say one of the databases looks like this:
df <- tibble::tribble(
  ~IRB_NO,       ~Oncore_NCT_Number, ~Oncore_Protocol_No,
  NA_character_, "NCT03150693",      "A041501",
  "0002-20",     NA_character_,      "NHPCC",
  NA_character_, "NCT05091567",      "LS-P-GO43104",
  "0003-21",     "NCT04546399",      "AALL1821",
  "0005-14",     "NCT01824836",      "CTSU-E1Z11",
  "0005-21",     NA_character_,      "LS-P-ONC-1879",
)

and the other looks like this:
df2 <- tibble::tribble(
  ~IRB_NO,       ~Epic_NCT_Number, ~Epic_Protocol_No,
  "0001-21",     "NCT03150693",    "A041501",
  "0002-20",     NA_character_,    "NHPCC",
  NA_character_, "NCT05091567",    "LS-P-GO43104",
  NA_character_, "NCT04546399",    "AALL1821",
  "0005-14",     "NCT01824836",    "CTSU-E1Z11",
  "0005-21",     NA_character_,    "LS-P-ONC-1879",
)

And I want to join them on "IRB_No".  Well when I do that like so:
Merged<-df%>%full_join(df2, by="IRB_NO")

The problem is, sure that joins them on IRB_No, but if the IRB_No was blank, it still joins them, like so:

Now, SOMETIMES thats ok.  In the row I marked blue, you can tell thats probably a match because they have the same protocol_no and nct_number, but obviously a lot of the time its incorrect.
I saw the warning in R about multiple matches and handling it with "all", "any", "first", etc...  but I was thinking there's probably a better way.
Is there a way to do a "backup" column?  I.e. if irb_no is blank, then try to join by nct_number?
Update based on comments:
after using na_matches = "never"  I was able to help dial in my results a little more.  But for instance, these two rows (which now dont match because they have blank IRB_NO's)  are pretty obviously the same study, and it'd b great if I could "squish" the rows into one row:
Comment: What would you want your desired output to look like with these example data? Something like, `full_join(df, df2, by = c("IRB_NO", "Oncore_NCT_Number" = "Epic_NCT_Number"))`?
Comment: I'll update the question to elaborate on what a desired output could be
Answer: By default, NA will match another NA. To prevent these kinds of matches, specify na_matches = "never":
full_join(df, df2, join_by(IRB_NO), na_matches = "never")
#> # A tibble: 9 × 5
#>   IRB_NO  Oncore_NCT_Number Oncore_Protocol_No Epic_NCT_Number Epic_Protocol_No
#>   <chr>   <chr>             <chr>              <chr>           <chr>
#> 1 <NA>    NCT03150693       A041501            <NA>            <NA>
#> 2 0002-20 <NA>              NHPCC              <NA>            NHPCC
#> 3 <NA>    NCT05091567       LS-P-GO43104       <NA>            <NA>
#> 4 0003-21 NCT04546399       AALL1821           <NA>            <NA>
#> 5 0005-14 NCT01824836       CTSU-E1Z11         NCT01824836     CTSU-E1Z11
#> 6 0005-21 <NA>              LS-P-ONC-1879      <NA>            LS-P-ONC-1879
#> 7 0001-21 <NA>              <NA>               NCT03150693     A041501
#> 8 <NA>    <NA>              <NA>               NCT05091567     LS-P-GO43104
#> 9 <NA>    <NA>              <NA>               NCT04546399     AALL1821

Comment: Sure, take your time to pause and ponder ;) I don't think there's a way to do this sort of secondary merge key though. You might want to manually find the entries that could not be matched with `anti_join()` and merge them using your second key, and so on.
Comment: Ah!  Did not know about that.  I'll give this question a little bit and then possibly accept this as an answer.  I'm interested to see if anyone can show me how to use a 'backup', but at the very least this will be useful for preventing incorrect joins
Answer: Using {powerjoin} I'm getting a different output from the accepted answer but I think this is the correct one :
library(powerjoin)
power_full_join(df, df2, ~ .x$IRB_NO == .y$IRB_NO | .x$Oncore_NCT_Number == .y$Epic_NCT_Number, conflict = coalesce_xy)
#> # A tibble: 6 × 5
#>   Oncore_NCT_Number Oncore_Protocol_No Epic_NCT_Number Epic_Protocol_No IRB_NO
#>   <chr>             <chr>              <chr>           <chr>            <chr>
#> 1 NCT03150693       A041501            NCT03150693     A041501          0001-21
#> 2 <NA>              NHPCC              <NA>            NHPCC            0002-20
#> 3 NCT05091567       LS-P-GO43104       NCT05091567     LS-P-GO43104     <NA>
#> 4 NCT04546399       AALL1821           NCT04546399     AALL1821         0003-21
#> 5 NCT01824836       CTSU-E1Z11         NCT01824836     CTSU-E1Z11       0005-14
#> 6 <NA>              LS-P-ONC-1879      <NA>            LS-P-ONC-1879    0005-21

Created on 2023-03-22 with reprex v2.0.2
You'll get the development version for this :
devtools::install_github("moodymudskipper/powerjoin")

Comment: I spent 5 minutes trying to figure out what was different between your answer and the one I accepted, finally noticed that for row 7 in zephryl's answer, the NCT03150693 study was duplicated because the key was different.  So yes, I like your answer a lot.  I had already accepted theirs so I'll leave it, but thank you! Works great
Answer: To get something like your "backup," you can compute a key in each dataframe by dplyr::coalesce()ing IRB_NO and *_NCT_Number. This will yield a key with the value of IRB_NO if not NA and *_NCT_Number if IRB_NO is NA. (And you'll want to use na_matches = "never" as pointed out by @dufei.)
library(dplyr)

full_join(
    mutate(df, key = coalesce(IRB_NO, Oncore_NCT_Number)),
    mutate(df2, key = coalesce(IRB_NO, Epic_NCT_Number)),
    by = "key",
    na_matches = "never"
  ) %>%
  relocate(key, Oncore_IRB_NO = IRB_NO.x, Epic_IRB_NO = IRB_NO.y)

# A tibble: 8 × 7
  key         Oncore_IRB_NO Epic_IRB_NO Oncore_NCT_Number Oncore_Protocol_No Epic_NCT_Number Epic_Protocol_No
  <chr>       <chr>         <chr>       <chr>             <chr>              <chr>           <chr>
1 NCT03150693 NA            NA          NCT03150693       A041501            NA              NA
2 0002-20     0002-20       0002-20     NA                NHPCC              NA              NHPCC
3 NCT05091567 NA            NA          NCT05091567       LS-P-GO43104       NCT05091567     LS-P-GO43104
4 0003-21     0003-21       NA          NCT04546399       AALL1821           NA              NA
5 0005-14     0005-14       0005-14     NCT01824836       CTSU-E1Z11         NCT01824836     CTSU-E1Z11
6 0005-21     0005-21       0005-21     NA                LS-P-ONC-1879      NA              LS-P-ONC-1879
7 0001-21     NA            0001-21     NA                NA                 NCT03150693     A041501
8 NCT04546399 NA            NA          NA                NA                 NCT04546399     AALL1821

"Back up" join option in R full_join


Passing list of values as parameters in reactJS

Question: I am new to react js and I need help..
I am trying to create a page which shows details of a team
import React from "react";

import "../styles/team.css";
import bs from "../images/girl.jpg";
import { membercard } from "./teamcard";

export const Team = () => {
  const user = {
    name: "sowmi",
    email: "sddsd",
    src: { bs },
    designation: "sgsfgsfg",
  };
  return (

MEET OUR AMAZING TEAM

          This the paragraph where you can write more details about your team

          <membercard {...user} />

  );
};

This is my Team.js file
import React from "react";
import "../styles/team.css";

export const membercard = ({ user }) => {
  const [src, name, email, designation] = this.user;
  return (

{name}

      {designation}

            Email : {email}

  );
};

and this is teamcard.js file
So say I want to display 3 members with their details .I want to reuse teamcard.js component,I need to know how I can pass the values as parameters from team.js to teamcard.js
THANK YOU IN ADVANCE
Comment: I think there is a **user** has an array of object then you can pass the whole array in the teamcard.js after that you have done the **map** in the teamcard.js So your issue has been solved
Comment: no it doesnt work thats y i have asked for help!!!
Answer: You can loop through a list of users and pass each one to the component.  One note though, by spreading the user values with ...user your props are going to come in as ({ name, email, src, designation }).  They way it's set up now you'll want to pass the full user as a prop.
export const Team = () => {
  const users = [
{
    name: "sowmi",
    email: "sddsd",
    src: { bs },
    designation: "sgsfgsfg",
  },
{
    name: "user2",
    email: "sassdf",
    src: { sdfsdf },
    designation: "vbnvbnvbn",
  },

]
  return (

MEET OUR AMAZING TEAM

          This the paragraph where you can write more details about your team

        {users.map(u =>

           <member  user={u} />|

         )}

  );
};

Answer: I think you're using some of the class methods to access props when you're using Functional Components.
Click the "Run Code Snipper" button below to see it working.

// Notice the spread operators ({ }) here that are extracting the key from the object user passed
const MemberCard = ({ src, name, email, designation }) => {

  // Alternatively you could do:
  // MemberCard = (props) => {
  // const { src } = props;

  return (

{name}

      {designation}

            Email : {email}

)
 };

const Team = () => {
  // Notice the change too for the 'src' for the image as well
  const user = {
    name: "sowmi",
    email: "sddsd",
    src: 'https://loremflickr.com/320/240',
    designation: "sgsfgsfg",
  };
  return (

MEET OUR AMAZING TEAM

          This the paragraph where you can write more details about your team

          <MemberCard {...user} />

  );
};

ReactDOM.render(<Team />, document.querySelector('#root'));


Can we see shape of normal curve somewhere in nature?

Question: I do not want to know if some phenomena in nature have normal distribution, but whether we can somewhere see shape of normal curve as we can see it for example in Galton box. See this figure from Wikipedia.

Note that many mathematical shapes or curves are directly seen in nature, for example golden mean and logarithmic spiral can be found in snails.
First naive answer is whether nonskewed hills would often "fit" normal distribution :-).
Comment: Many years ago, the East Wing of the National Gallery of Art in Washington DC had a beautiful (and unintentional) example of a normal distribution showing on an exterior wall where two exterior walls met at a 45-degree angle instead of the usual 90-degree angle. People presumably had _touched_ the edge to see if it felt sharp, and the smudges from their fingers left a stain on the wall which showed as a bell curve (rotated 90 degrees clockwise) at about chest height. On a more recent visit, I found that the exterior walls had been cleaned and the smudges had disappeared.
Comment: [This example](http://math.stackexchange.com/a/38828/7003) is a favorite of mine.
Comment: @cardinal That's an intriguing example, but wear on steps is highly unlikely to be at all Normal.  In fact, it would be a puzzle if it were.  The CLT might possibly be invoked to describe horizontal variation in where people walk, but that will not lead to a Gaussian shape in the wear on the step.
Comment: [This blog post](http://mathtourist.blogspot.ca/2010/05/irresistible-edge.html) shows the example that @Dilip mentions as well as one example of wearing patterns on stone steps (with links to other pictures of wear patterns). Some might find it interesting.
Comment: I have not seen wear like that, @cardinal. In your model the wear would be much flatter near the peak than a Gaussian and--of course--would be confined within natural limits, unlike any Gaussian. (The latter is not such a big deal because we cannot demand that the Gaussian fit *perfectly*.) The wear on steps I have examined is *far* flatter than a Gaussian.  (Often it is bimodal, too, because most long-lived stairs have been used in both the up and down directions.) A better model would be a convolution of a fairly narrow Gaussian with a uniform distribution.
Comment: @Cardinal Nice! It may only be in the eye of the beholder, but the cathedral steps image appears to validate my expectation of a flat curve and multimodality. Moreover, the handprint pattern clearly is non-Gaussian in outline. The density (of dirt) very well could be Gaussian, but that is hard to determine from this image. That blog exemplifies http://stats.stackexchange.com/a/4301: **"Everybody believes in the [the Normal distribution]: the experimenters, because they think it can be proved by mathematics; and the mathematicians, because they believe it has been established by observation."**
Comment: @whuber: I agree on all points. I really find that picture alluring; I believe the lighting actually *accentuates* the apparent troughs in the steps, i.e., they are flatter than they appear in the shot. The convolution model is certainly more faithful if for no other reason than that a point force is a rather poor approximation to that produced by a typical shoe. :-)
Comment: I'd argue that the Galton box is _not_ an example of the Normal distribution, but instead, an example of a binomial distribution (with $p \approx 0.5$). After all, "discrete" is a closer description of the distribution than "continuous", and the distribution is bounded. Instead, the Galton box demonstrates the appropriateness of Normal approximation to a binomial distribution (or, equivalently, the Central Limit Theorem applied to the total of a sample from a Bernoulli distribution).
Comment: This has already been discussed elsewhere on the site: http://stats.stackexchange.com/questions/33776/real-life-examples-of-common-distributions
Comment: But not about the shape of distribution, it is only question where we can find some types of distributions.
Comment: Often my students in statistics course ask me, where can they see it in nature. If I answer that normal curve is everywhere, but you cannot directly see it, then they are not satisfied. :-)
Comment: @whuber: I agree it is still a bit of an idealization, but not altogether implausible, and I have seen some realistic examples. The material should be (originally) uniform in both construction and density, not prone to chipping and relatively unaffected by other environmental factors such as water runoff. Also, depending on the step height, some people will tend to step on the edge of the step and so, in these cases, the indentations will not be vertical, but somewhat diagonal. But, if the pressure exerted by each passerby is relatively constant, the wear could take the stated form. :)
Comment: Our (wooden) steps in the institute show distinct bimodal wear. I'd have said not because of up and down, but because people keep their legs beside each other (not like foxes). In addition, it is clearly visible that most people enter with the same foot. In terms of up/down I'd guess that there may be more down traffic than up traffic as we have elevators as well (there's a trade-off between climbing speed and waiting time for the elevator) but I don't know how one could see this.
Comment: @cardinal Thanks for the link to an actual picture! I guess the 19-degree angle at which the walls meet is far sharper than the 45-degree angle that I talked about in my comment, and more likely to create the urge to touch.
Answer: I wouldn't think any pattern of erosion or deposition on Earth would fit because skewing factors including gravity and Coriolis are always involved (rivers meander more as they age, for example, and valley floors are sort of the average of rivers).  Maybe the cross section of a stalagmite, assuming the drip remained in one fairly exact central location? I would think the drips would deposit the most precipitate right where they are moving slowest, which would be at the point of impact.
Answer: I thought a lot about my question and probably I found something. U-shape of many valleys imitates "reversed" normal curve. Are there any reasons why this should not be gaussian (note that water makes the valleys smooth)?
Here is an example.
Comment: There seems to be a strong tendency for people to hope than any unimodal curve is normal. I see no reason why such a valley would be closely approximated by an inverted normal curve, and many factors such as the erosion from water which may be unimodal, but where any accurate physical model predicts something other than a normal curve.
Comment: This is an interesting empirical question - how closely the shape can be approximated as normal would depend on the age of the various features.  A valley probably begins more poisson shaped, becomes normal-ish, and as the tops of the hills wear heads back in a poisson direction.


What's the topological dimension of Sierpiński's Triangle?

Question: I am aware that Sierpiński's Triangle is a fractal, with Hausdorff dimension $1.5850$. Therefore my intuition leads me to believe it's topological dimension is 1 (as the topological dimension must be less than the Hausdorff dimension). However, since it's area is 0 this makes me believe it has topological dimension 0 since it's a collection of infinitely many points. Some clarification on this would be fantastic. Thank you.
Answer: The Sierpinski triangle contains a lot of line segments so I would think its dimension would be at least 1.
There's more than one definition of topological dimension but, generally, these are inductive definitions. Loosely, we might say that a set has dimension $n$, if there is a basis for its open sets whose boundaries have dimension $n-1$. The boundaries of the open balls in $\mathbb R^3$ are spheres and the surface of a shpere has dimension 2, for example.
Of course, we need a place to start so we might define $\dim(\varnothing)=-1$. This implies that the zero dimensional sets are exactly the totally disconnected sets. In particular, any finite set in Euclidean space has dimension zero.
Now, let $T$ denote the open triangle in the plane with vertices
$$(0,0), \: (1,0), \text{ and } (1/2,\sqrt{3}/2).$$
We can obtain a basis for the open sets in the Sierpinski triangle by intersecting the Sierpinski triangle with images of $T$ under the application of functions generated by the IFS. Two such open triangles are shown in the figure below. Note that the boundary of these sets in the Sierpinski triangle are exactly the vertices of the smaller triangles. Thus, the basis sets have boundaries with dimension zero. So the Sierpinski triangle has dimension 1.
Comment: An excellent response. Thank you.


Como pesquisar numa collection de JSON um determinado registro com Angular 2x?

Question: Tenho um JSON neste formato:
[
    {
        "agencia": "2342342",
        "digito_agencia": "2342",
        "numero_conta": "234234",
        "digito_conta": "23423",
        "_id": "5bff1a63a617f53414766c27",
        "createdAt": "2018-11-28T22:44:51.567Z",
        "updatedAt": "2018-11-28T22:44:51.574Z",
        "__v": 0,
        "bancos": {
            "nome_banco": "001 - BANCO DO BRASIL S/A",
            "_id": "5bf2eb4bc3910712f4604847",
            "id": "5bf2eb4bc3910712f4604847",
            "updatedAt": "2018-11-28T22:42:11.276Z",
            "contasJogador": "5bff0c013efde3235465a39f",
            "nome_do_banco": "5bff0dc1d40d01202418df4b",
            "contasjogador": [
                "5bff18eed8d38e1e7c99e83a"
            ]
        },
        "id": "5bff1a63a617f53414766c27",
        "jogador": {
            "nome": "Ramos Janones",
            "email": "firstname.lastname@example.com",
            "cpf": "03472925698",
            "celular": "34996320391",
            "telefone": "",
            "cep": "38300070",
            "endereco": "DEZESSEIS",
            "cidade": "Ituiutaba",
            "estado": "Minas Gerais",
            "bairro": "",
            "complemento": "",
            "usuario": "ramos",
            "senha": "teste123",
            "idppoker": "",
            "nickppocker": "ramosinfo",
            "numero": "",
            "_id": "5bf18c512af2e61ab879d2f7",
            "createdAt": "2018-11-18T15:59:13.735Z",
            "updatedAt": "2018-11-26T15:41:00.806Z",
            "__v": 0,
            "id": "5bf18c512af2e61ab879d2f7",
            "foto": null,
            "contasJogadors": null
        },
        "tipocontas": {
            "tipo_conta": "Conta Poupança",
            "_id": "5bff19328ff184285c7131df",
            "createdAt": "2018-11-28T22:39:46.676Z",
            "updatedAt": "2018-11-28T22:42:11.275Z",
            "__v": 0,
            "id": "5bff19328ff184285c7131df",
            "contasjogador": [
                "5bff18eed8d38e1e7c99e83a"
            ]
        }
    }
]

Preciso pegar esses dados quando o id do "jogador" for igual ao passado, neste caso do JSON a cima seria "id": "5bff19328ff184285c7131df".
Meu service tenho:
query(): Observable<any> {
  const id = localStorage.getItem('ref');
  return this.http.get(this.baseUrl, ${id});
}

Onde localStorage.getItem('ref') é o id do jogador armazenado no localStorage.
Como faço para pegar apenas pelo id do "jogador" como filtro neste array para jogar no *ngFor da View?
Comment: Aqui no site existem varias perguntas: https://pt.stackoverflow.com/questions/81713 https://pt.stackoverflow.com/questions/261168 https://pt.stackoverflow.com/questions/330819 https://pt.stackoverflow.com/questions/185806 https://pt.stackoverflow.com/questions/292455
Comment: Para mais, basta acessar [essa pesquisa no Google](https://www.google.com.br/search?q=javascript+filtrar+array+site:pt.stackoverflow.com)
Comment: Minha pergunta conseguiu te ajudar? Caso não me fale mais como posso ajuda-lo :D
Answer: Opa, tudo bem?
Você pode usar o filter, ele retorna o item do Array que satisfaz uma condição, você pode ver mais aqui
Segue a forma que fiz

const jogadores = [
  {
    id: '1',
    jogador: {
      nome: 'Eduardo',
      email: 'email@example.com'
    }
  },
  {
    id: '2',
    jogador: {
      nome: 'Jose',
      email: 'firstname.lastname@example.com'
    }
  },
  {
    id: '3',
    jogador: {
      nome: 'Ribeiro',
      email: 'email@example.com'
    }
  }
]

const filtraJogadores = (id, jogadores) => {
  return jogadores.filter(jogador => jogador.id === id)
}

let jogadorFiltrado = filtraJogadores('1', jogadores)

console.log(jogadorFiltrado)

Claro, o meu exemplo está bem mais simples que o seu, mas a lógica é essa, porém como você está usando o padrão Observable, você terá de usar o subscribe, algo do tipo;
this.query()
  .subscribe(data => {
    this.jogador = this.filtraJogadores(ID_A_SER_FILTRADO, data)
  }, error => {
    console.error(error)
  })

Se ficou alguma dúvida deixa seu comentário aqui abaixo, se for preciso eu edito e faço uma resposta mais completa.


Application is consuming power in the background if I set listener for Firebase Realtime Database in Android

Question: I use Firebase Realtime Database in my android application. When I try to read from database overriding method onDataChange(DataSnapshot dataSnapshot)
myRef.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot)
        String value = dataSnapshot.getValue(String.class);
        Log.d(TAG, "Value is: " + value);
    }

    @Override
    public void onCancelled(DatabaseError error)
        Log.w(TAG, "Failed to read value.", error.toException());
    }
});

it is working nice, but in morning my device (with Android 7.0) give me warning that my app is consuming power in the background. I don't find in documentation how unset listener if activity is paused/destroyed.
Comment: Can you share the code you're using to add the listener?
Comment: If you're application is executing code, whether in the foreground or the the background, you will always be consuming power.
Comment: I use standart code from hint: myRef.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        String value = dataSnapshot.getValue(String.class);
        Log.d(TAG, "Value is: " + value);
    }
});
Comment: @WadeWilson:when I use Firebase Cloud Messaging I don't got same warning although FCM events are occurs with more frequency
Answer: In order to stop this from happening, you need to remove the listener accordingly to the life-cycle of your activity. So, please use the following line of code:
databaseReference.removeEventListener(valueEventListener);

So, if you have added the listener in onStart you have to remove it in onStop. If you have added the listener in onResume you have to remove it in onPause. If you have added the listener in onCreate you have to remove it in onDestroy.
But remember onDestroy is not always called!
Here is a graphic representation:
Comment: Thanks for your answer, I think that it is what I search, but I want to check that warning will not appear, I'll test for a day and if not, I accept your answer as right.


Com quais bancos de dados o Apache Atlas é compatível?

Question: O apache Atlas tem compatibilidade com quais bancos de dados noSQL e SQL
estou fazendo um trabalho, e não consegui achar nada sobre
Answer: Pelo o que entendi, o Apache Atlas usa o HBase e apenas ele, uma vez que o Apache Atlas usa Hadoop e o banco de dados do Hadoop é o HBase. Você pode escolher entre usar um HBase externo ou usar um HBase embedded:

Above will build Atlas for an environment having functional HBase and Solr instances.

E:

To create Apache Atlas package that includes HBase and Solr, build with the embedded-hbase-solr profile