left/right bitwise shifts - why do we shift by byte length

Question: I have been reading this blog about bit manipulation in networking packages. I have this code and I am seeing that its reading in an integer which is typically 4 bytes long (32 bits)
public int readInt() {
    return (pData[caret++] & 0xff) << 24 | (pData[caret++] & 0xff) << 16
            | (pData[caret++] & 0xff) << 8 | pData[caret++] & 0xff;
}

Why are we moving by 8, 16 and 24 when reading in an integer value? What is the goal and what does it achieve?
Comment: What tutorial are you following and why does it not explain that part? Have you tried this code with a given input and looked at what it actually produces? What is `pData`?
Comment: It sets the correct [Endianness](https://en.wikipedia.org/wiki/Endianness). It seems like pData contains the most significant byte on the lowest index.
Comment: ^^ Be aware that there is no "unsigned" in java, so sometimes you may come across `long` being used for an unsigned int from network.
Comment: @Fildor `char` is unsigned in Java
Comment: @phuclv that's a special case, but yes. On the other hand, I haven't seen char being used for unsigned numbers ...
Answer: That is because pData is a byte array. What readInt() does is pack 4 bytes into an integer then return the result. Because an integer is 4 bytes, by ((value & 0xFF) << 24) will set for the 1'st slot, ((value & 0xFF) << 16) for the 2'nd slot, ((value & 0xFF) << 8)  for the 3'rd slot and (value & 0xFF) for the last slot. And to merge these four values into one (that in this case is an integer), bitwise OR ( |) must be performed between each value. If pData is indeed an integer array, thats probably because it wants to use unsigned integers (0 - 255). So what readInt() does is pack 8 LSB (least significant bits) for each int (up to 4 integers) into an integer then return the result.


Numerical Methods for ODE

Question: I have been working through Iserles books A first course in Numerical Analysis of Ordinary Differential Equations.
I am trying to figure out how to prove that the error constant for an s-step BDF is -beta/(s+1)
I have tried using the characteristic polynomials to no avail.
does anyone have any ideas?
Answer: Multistep methods in general follow the scheme
$$
\sum a_k y(x-kh)\approx h\sum b_k f(x-kh, y(x-kh))
$$
For an exact solution we have that $f(x,y(x))=y'(x)$ and the order condition can be then written as
$$
\sum a_k y(x-kh)=h\sum b_k y'(x-kh) + O(h^{p+1})
$$
The coefficients inside this formula have to be valid for all differentiable functions. It is sufficient to explore it for all analytical functions. Then one can write the shift operator for $y(x-h)$ as $e^{-hD}$ with $D=\frac{d}{dx}$, so that the order condition translates to
$$
\sum a_k e^{-khD} = hD\sum b_k e^{-khD} + O(h^{p+1})
$$
Now write $e^{-hD}=1-Z$, $hD=-\ln(1-Z)$ and we get an equation in truncated power series
$$
\sum a_k(1-Z)^k=-\ln(1-Z)\sum b_k(1-Z)^k + O(Z^{p+1})
$$

For BDF methods one uses (for the moment) $b_0=1$ and $b_k=0$ for $k>1$ so that
$$
a(1-Z)=Z+\frac12Z^2+…+\frac1pZ^p
$$
and the error terms is $\frac1{p+1}Z^{p+1}+O(Z^{p+2})$. Since $Z=1-e^{-hD}=hD+O(h^2)$ one gets $Z^{p+1}y=h^{p+1}y^{(p+1)}(x)+O(h^{p+2})$. In the coefficients $a_k$ we get
$$
\sum_{k=0}^p a_kq^k = (1-q)+\frac12(1-q)^2+…+\frac1p(1-q)^p\\
=\sum_{k=0}^p q^k\sum_{j=k}^p\binom{j}{k}\frac1j
$$
Obviously, the constant coefficient is $a_0=1+\frac12+…+\frac1p$ and by multiplying all coefficients with $β=(1+\frac12+…+\frac1p)^{-1}$ one gets a method with $a_0=1$, $b_0=β$ and leading error term
$$
\frac{β}{p+1}h^{p+1}y^{(p+1)}(x)+O(h^{p+2}).
$$
Comment: Thanks for the response. I actually ended up figuring it out using taylor series on sum(alphas*y(t+hj)-h*beta*y'(t+hs)
 and then recognizing that the sum(alphas*j^(s+1)) is equal to s*beta*s^s
It is nice to see another way of doing it!
Comment: Note that $(e^{hD}y)(x)=\sum\frac{h^k}{k!}(D^ky)(x)$ is just a compact notation for the Taylor series.

Numerical Methods for ODE


Run unit tests for two Django applications in PyCharm

Question: I've Django project with two applications with added unit tests (django.test.TestCase). In PyCharm I have created two Django test launchers (one for every app). In this configuration everything works correctly. Now I want to create one test launcher, which will be able to start unit test for both applications at once.
Is it possible?
Answer: OK, I've found solution.
If you want to launch many test suits with one test launcher in PyCharm, you should add names of your applications separated by a space to Target field of your Django tests Run/Debug configuration.


Penalty for interfering with the path of the cue ball?

Question: In snooker, what is the penalty for interfering with the path of the cue ball?
I assume it must be more than 7 points because let's say a player hits a shot and he sees the cue ball heading for the black which is not on, then it is a seven point foul if he hits it, so let's say he sticks his cue in front of the cue ball and deflects it, what is the penalty?
I guess the same question could apply in any situation where the frame is in jeopardy if the cue ball gets into position. In other words, let's say that if the cue ball lands in favorable position for the other player, then you will lose the frame. No penalty is big enough, because you will lose the frame anyway, so you might as well foul to prevent it.
Answer: Section 4 of the Official Rules allows the referee a lot of discretion in this kind of matter:

In the event of [...] any conduct by a Player which in the opinion of the referee is wilfully or persistently unfair [...] the referee shall either:
(v) warn the Player that in the event of any such further conduct the
frame will be awarded to his opponent; or
(vi) award the frame to his opponent; or
(vii) in the event that the conduct is sufficiently serious, award the game
to his opponent.

For any professional players, I'd imagine that this kind of behaviour would also result in sanctions from the WPBSA.


Defining $A \in \mathcal{P}(\Bbb N \times\Bbb N)$ such that it is not any member of a countable subset $M \subseteq \mathcal{P}(\Bbb N \times \Bbb N)$

Question: $
\newcommand{\N}{\mathbb{N}}
\newcommand{\P}{\mathcal{P}(\N \times \N)}
\newcommand{\set}[1]{\left\{ #1 \right\}}
\newcommand{\i}{^{(i)}}
\newcommand{\x}{^{[x]}}
\newcommand{\y}{^{[y]}}
\newcommand{\I}{\mathcal{I}}
\newcommand{\J}{\mathcal{J}}
$
The Problem: Define $M := \set{A_i}_{i \in \N} \subseteq \P$ to be a countable susbset of $\P$. How would we define some $A \in \P$ such that $A \ne A_i$ for every $i \in \N$?
Context: The context for the problem is this unanswered MSE question from $2018$ that has not been answered yet. I've been trying to answer it for a few days, but I'm not certain of the approach I'm taking. I would like a sort of constructivist approach to the problem, in the sense of an explicit or direct way to define the set $A$ in question (as opposed to, say, just handwaving things away by saying a certain element of $A$ is just in a complement of some $A_i$).
The original problem also specifies the condition $(0,0) \not \in A$, though it's not clear if this is an important restriction in my eyes. (Of course this also means we're adopting the convention $\N := \set{0,1,2,3,\cdots}$.)
My Approach So Far: My goal is sort of in the vein of a diagonalization argument. Since $M$ is countable and $A,A_i$ are at most countable themselves (as $|\N \times \N| = \aleph_0$ per, e.g. here), we may write:
$$M = \set{A_i}_{i=0}^\infty \qquad A = \set{a\i}_{i \in \I} \qquad A_i = \set{a_{i,j}}_{j \in \J}$$
as a means of indexing the members of each set. $\I$ and $\J$ are index sets such that $|\I|,|\J| \le \aleph_0$. We may likewise order the elements of each. Finally, define $a_{i,j} \x$ to be the first coordinate of $a_{i,j}$, and $a_{i,j} \y$ the second. That is,
$$a_{i,j} = \left( a_{i,j} \x \; , \; a_{i,j} \y \right)$$
Then, to ensure $A \ne A_i$, I want to ensure $A$ contains an element different from each $A_i$. We can break this into cases for every possible $A_i$:

Suppose $A_i = \varnothing$. Then let $a\i :=  (1,1)$.
Suppose $A_i$ is finite and nonempty. Then take
$$a^{(i)} := \left( 1+ \max_{0 \le j \le |A_i|} a_{i,j} \x \; , \; 1+ \max_{0 \le j \le |A_i|} a_{i,j} \y \right)$$
In short: $a \i$ is $1$ bigger (or more) in each component than any of $A_i$'s elements.
Suppose $A_i$ is infinite, but not equal to $\N \times \N$. Then ... ?
Suppose $A_i = \N \times \N$. Then ... ?

I'm pretty confident in my first three cases, but handling the cases of $A_i$ infinite are proving to be sticking points for my approach - in particular the case of $A_i = \N \times \N$, I'm really not sure how to handle that one. I guess we could just say $a\i \in A_i^c$, but that feels a little hand-wavey (especially for, again, $A_i = \N \times \N$), and I'm more interested in defining the elements of $A$ directly in some fashion, if at all possible.
Someone brought up, in the comments of the original question, about using the axiom of choice and ZFC set theory. If strictly necessary, I'm fine with the use of axiom of choice or alternative set theories (e.g. NBG), though the less we have to invoke those, the better in my opinion, since I'm not particularly well-versed in these sorts of decisions and their ramifications.
Anyhow - does anyone have some bright ideas as to how I might be able to finish this approach? And how does the restriction of $(0,0) \not \in A$ affect the original problem?
Answer: It's possible to do something along the lines that you have in mind, but you can also (and much more easily) do it all at once: let
$$A=\{\langle n,n\rangle\in\Bbb N\times\Bbb N:\langle n,n\rangle\notin A_n\}\,.$$
For each $n\in\Bbb N$ the sets $A$ and $A_n$ disagree on $\langle n,n\rangle$: one contains it, and the other doesn't.
If you want to ensure that $\langle 0,0\rangle\notin A$, change the definition: let
$$A=\{\langle 1,n\rangle\in\Bbb N\times\Bbb N:\langle 1,n\rangle\notin A_n\}\,.$$


Comparar letra 'E' em python

Question: Tenho este código que basicamente percorre a lista new_users e verifica se já existe alguns usuário dentro de current_users.
Quando meu if faz a conversão dos nomes de new_users para maiúsculas, minúsculas e etc, ele falha em uma possibilidade, que é quando o nome 'ze' esta assim: 'zE'. Ou qualquer outro nome com final 'E' na lista current_users.
Coloquei outros nomes na lista current_users com a letra 'E' no final e meu código falha em verificar. O que posso fazer para converter as duas listas em lower() e verificar se existe algum usuário repetido?
current_users = ['ze', 'carmo', 'sofia', 'jeff', 'isa']
new_users = ['ze', 'didao', 'edi', 'taria', 'sofia']

for new_user in new_users:

    if new_user.lower() not in current_users \
            and new_user.upper() not in current_users\
            and new_user.title() not in current_users\
            and new_user.lower() not in current_users:
        print('O nome "' + new_user.title() + '" está disponível.')
    else:
       print('Forneça outro nome.')

Answer: O problema não é só a letra "E", e sim o fato de que o código falha quando a lista current_users possui nomes que misturam letras maiúsculas e minúsculas. Afinal, somente no new_user que você transforma tudo em maiúsculas ou minúsculas (no seu caso, você está comparando ze, Ze e ZE com zE, e aí não vai funcionar mesmo).
Se quer fazer comparações case insensitive, pode usar o método casefold(). Este método é similar a lower(), mas segundo a documentação, ele é mais "agressivo" e trata casos especiais, como por exemplo o caractere ß, que quando transformado para maiúsculo, se torna "SS" (então 'ß'.upper().lower() retorna "ss"):
print('ß'.lower() == 'SS'.lower()) # False
print('ß'.casefold() == 'SS'.casefold()) # True

Claro que para letras de a a z não acentuadas, não vai fazer tanta diferença assim usar lower() ou casefold(), mas enfim.
Sendo assim, basta aplicar casefold() na lista de usuários atuais, e também em cada usuário que você está verificando:
current_users = ['ZE', 'carmo', 'SofiA', 'jeff', 'isa']
new_users = ['ze', 'didao', 'edi', 'taria', 'sofia']

current_users_fold = list(map(lambda user: user.casefold(), current_users))
for new_user in new_users:
    if new_user.casefold() not in current_users_fold:
        print('O nome "' + new_user.title() + '" está disponível.')
    else:
       print('Forneça outro nome.')

Primeiro eu uso map para criar outra lista, contendo a versão casefolded dos usuários atuais. Depois eu aplico o casefold() para cada novo usuário que estou verificando.
A saída é:
Forneça outro nome.
O nome "Didao" está disponível.
O nome "Edi" está disponível.
O nome "Taria" está disponível.
Forneça outro nome.

Outra alternativa é usar set para encontrar a intersecção entre as duas listas (ou seja, os usuários já existentes), e usar esta lista para verificar os não-existentes:
def ajusta(s):
    return s.casefold()

existentes = list( set(map(ajusta, current_users)) & set(map(ajusta, new_users)) )
nao_existentes = [ new_user for new_user in new_users if new_user.casefold() not in existentes]
print(existentes) # ['sofia', 'ze']
print(nao_existentes) # ['didao', 'edi', 'taria']

Uma vez tendo as duas listas (usuários já existentes e que ainda não existem), você pode usá-las da maneira que quiser.
Comment: Obrigado, estou aprendendo python cada ajuda é bem vinda. Editei o código com base no seu e deu certinho :)
Answer: No seu código, o que está acontecendo é que você só está fazendo transformações no new_user e não no current_users, uma maneira de resolver isso seria normalizando as duas listas e só depois comparar, por exemplo:
current_users = ['zE', 'carmo', 'sofia', 'jeff', 'isa']
new_users = ['ze', 'didao', 'edi', 'taria', 'sofia']

current_users_lower = [current_user.lower() for current_user in current_users]
new_users_lower = [new_user.lower() for new_user in new_users ]

for new_user in new_users_lower:

    if new_user not in current_users_lower:
        print('O nome "' + new_user + '" está disponível.')
    else:
       print('"' + new_user + '" não está disponível, forneça outro nome.')

Outra maneira seria utilizando o set, por exemplo:
current_users = ['zE', 'carmo', 'sofia', 'jeff', 'isa']
new_users = ['ze', 'didao', 'edi', 'taria', 'sofia']

current_users_lower = {current_user.lower() for current_user in current_users}
new_users_lower = {new_user.lower() for new_user in new_users }
duplicated = current_users_lower.intersection(new_users_lower)

print('Nomes já utilizados: {}'.format(', '.join(duplicated)))
print('Nomes disponíveis: {}'.format(', '.join(new_users_lower - duplicated)))

Comment: Sua versão com `set` ficou melhor que a minha, esqueci que dá para subtrair... :-)
Answer: Bem, você basicamente precisa converter todos os nomes da lista current_users para minúsculo. Veja o código abaixo:
current_users = ['zE', 'carmo', 'sofia', 'jeff', 'isa']
new_users = ['ze', 'didao', 'edi', 'taria', 'sofia']

# Converte todos os nomes da lista current_users para minúsculo.
c_users = []
for user in current_users:
    c_users.append(user.lower())
current_users = c_users

for new_user in new_users:

    if new_user.lower() not in current_users:
        print('O nome "' + new_user.title() + '" está disponível.')
    else:
       print('Forneça outro nome.')

Comparar letra 'E' em python


Two factor ANOVA with blocking

Question: I am conducting an RCBD experiment in which I have Treatment A (with 5 levels) and Treatment B (two levels). It is also being done in 3 separate locations (3 blocks). My question is, how can I do the ANOVA? Do I just treat it like a three-way ANOVA? And how should I code it in R?
Comment: You have three categorical variables and all of the (three-way) interactions, right?
Answer: Just add block as an extra (factorial) covariate to the linear model.
Simple R code (presuming the DV is a continous variable):
anova(model<-lm(DV~block+A*B,data=mydata))

You might also want to do post-hoc tests. The emmeans package in R is pretty good for this.
library(emmeans)
emmeans(model,pairwise~A|B)

The A|B can be replaced with one of B|A or A:B, which will all answer slightly different questions, and of course just A or B (drop the interaction from the model first before doing these though).
Comment: thank you very much!

Two factor ANOVA with blocking


Postar na Fanpage do facebook com PHP

Question: Boa tarde. Gostaria de realizar a seguinte ação: quando alguém cadastrar um produto no meu site, gostaria que o mesmo produto fosse cadastrado na minha Fanpage do facebook. Já criei o aplicativo, peguei o id e a senha,
mas ainda sim não consigo fazer funcionar. Ele retorna um erro de autenticação e
o código que estou usando é similar ao do link abaixo:
Como fazer postagem numa página do facebook utilizando PHP
O erro apresentado é esse:
<code>Graph returned an error: Invalid OAuth access token.
</code>
Alguém pode me orientar?
Answer: Vi algumas soluções no stackoverflow em inglês, veja se é útil para você:
Facebook PHP SDK - Graph returned an error: Invalid OAuth access token
Facebook SDK v5 Graph returned an error: Invalid OAuth access token
Facebook PHP SDK access token issue when retrieve User Profile via the Graph API
Comment: eu li mas não faço ideia de como gerar este token ainda ;(
Comment: sua aplicação já está publica? quando eu fiz algo envolvendo api do facebook tive que publica-la primeiro, da uma lida aqui:
Comment: https://developers.facebook.com/docs/facebook-login/access-tokens
Comment: sim já publiquei e foi aprovada tbm tenho o id e a senha ok. so falta esse token de acesso que não sei onde gera nem como.

Postar na Fanpage do facebook com PHP


Quicksort C - contest.c:16:50: error: request for member 'nome' in something not a structure or union

Question: Estou tentando fazer essa questão do URI:

Tetris
A sua turma do colégio resolveu organizar um campeonato de tetris.
  Após discussão sobre as regras, ficou definido que cada aluno jogaria
  um total de 12 partidas. Das 12 pontuações obtidas por um aluno, a
  maior e a menor são descartadas, e as demais são somadas, resultando
  na pontuação final do aluno.
Como você possui conhecimentos de programação, acabou sendo designado
  pela turma para escrever um programa para imprimir a classificação
  final do campeonato, a partir das pontuações de cada jogador. Entrada
A entrada é composta de vários conjuntos de teste. A primeira linha de
  um conjunto de testes contém um número inteiro J (0 ≤ J ≤ 1000), que
  indica o número de jogadores que participaram do campeonato. A seguir,
  para cada jogador há duas linhas na entrada: a primeira possui o nome
  do jogador (formado apenas por letras, sendo apenas a inicial em
  maiúscula, e com no máximo 15 letras), e a segunda possui as 12
  pontuações que o jogador obteve, separadas por espaço. As pontuações
  são inteiros entre 0 e 1000. O final da entrada é indicado por um
  conjunto de teste com J = 0. Saída
Para cada conjunto de teste, o seu programa deve escrever uma linha
  contendo o identificador do conjunto de teste, no formato "Teste n",
  onde n é numerado seqüencialmente a partir de 1. A seguir, o seu
  programa deve escrever a classificação final no campeonato, utilizando
  uma linha para cada participante. Cada linha deve conter três
  informações, separadas por um espaço em branco: a classificação do
  jogador, a sua pontuação final, e o seu nome. A classificação de um
  jogador é igual a 1 mais o número de jogadores que obtiveram pontuação
  maior do que a sua. Em caso de empate, os jogadores devem ser
  ordenados em ordem alfabética. Depois de toda a classificação, deve
  ser deixada uma linha em branco. O formato do exemplo de saída abaixo
  deve ser seguido rigorosamente.

https://www.urionlinejudge.com.br/judge/pt/problems/view/2250
Estou na parte de organizar por ordem alfabética os que têm a mesma quantidade de pontos. Tentei fazer uma condição no quicksort pra quando os pontos forem iguais, ordenar por nome e estou tendo o seguinte erro:

contest.c: In function 'compare': contest.c:16:30: error: request for
  member 'nome' in something not a structure or union    return
  strcmp(((Jogador*)a).nome, ((Jogador*)b).nome);
                                ^ contest.c:16:50: error: request for member 'nome' in something not a structure or union    return
  strcmp(((Jogador*)a).nome, ((Jogador*)b).nome);

Alguém pode me explicar o que é? "Aprendi" isso hoje e to meio que fazendo às cegas. O meu código é esse:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct{
    char nome[16];
    int pontuacao;
}Jogador;

int compare(const void * a, const void * b){
    if((*(Jogador *)a).pontuacao > (*(Jogador *)b).pontuacao){
        return -1;
    }else if((*(Jogador *)a).pontuacao < (*(Jogador *)b).pontuacao){
        return 1;
    }else if((*(Jogador *)a).pontuacao == (*(Jogador *)b).pontuacao){
        return strcmp(((Jogador*)a).nome, ((Jogador*)b).nome);
    }

    return 0;
}

int achaMaior(int *pontos){
    int maior = pontos[0];
    int i, j;

    for(i = 1; i < 12; i++){
        if(pontos[i] > maior){
            maior = pontos[i];
        }
    }

    return maior;
}

int achaMenor(int *pontos){
    int menor = pontos[0];
    int i, j;

    for(i = 1; i < 12; i++){
        if(pontos[i] < menor){
            menor = pontos[i];
        }
    }

    return menor;
}

Jogador jogador[100];

int main(){
    int j, i, k , pontos[12], maior, menor, teste = 0;;

    scanf("%d", &j);

    while(j != 0){
        teste++;
        for(i = 0; i < j; i++){
            scanf("%s", jogador[i].nome);
            for(k = 0; k < 12; k++){
                scanf("%d", &pontos[k]);
                jogador[i].pontuacao += pontos[k];
            }

            maior = achaMaior(pontos);
            menor = achaMenor(pontos);

            jogador[i].pontuacao -= (maior + menor);
        }

        qsort(jogador, j, sizeof(jogador[0]), compare);

        printf("Teste %d\n", teste);
        for(i = 0; i < j; i++){
            printf("%d %d %s\n", i + 1, jogador[i].pontuacao, jogador[i].nome);
        }

        printf("\n");

        for(i = 0; i < j; i++){
            jogador[i].pontuacao = 0;
        }

        scanf("%d", &j);
    }

    return 0;
}

Answer: Consegui resolver isso. Estava faltando um ponteiro na seguinte linha:
return strcmp(((Jogador*)a).nome, ((Jogador*)b).nome);

Linha corrigida:
return strcmp((*(Jogador*)a).nome, (*(Jogador*)b).nome);

Quicksort C - contest.c:16:50: error: request for member ‘nome’ in something not a structure or union


Can enabling load balancing on a cluster jeopardise high availability?

Question: I'm considering enabling load balancing on our data gateway clusters for Power BI, where we have two servers in a cluster, and the secondary is configured as a failover for the primary (only operational when the primary is offline). I was wondering how likely in the real world it is that using load balancing to push traffic through both servers would end up reducing high availability compared to only using the one, considering the following scenario:

Assume a constant stream of traffic generated by application
While there is no load balancing, one server does all the work and defines the capacity limits for the operation. If it fails, the other server picks up the work and because of identical specs, can handle the traffic as expected. Monitoring is configured so that an alert is triggered when either server hits 80% capacity, so scaling can take place before bottlenecks are hit.
Load balancing is switched on, both servers are now processing traffic, and traffic increases to >50% capacity on both servers. One fails, and now the remaining server has to process >100% of its capacity, resulting in request delays or failures. At no point with either server were monitoring alerts triggered.

I suppose I could rephrase my question as 'does using load balancing to handle increased traffic instead of scaling the servers up reduce the redundancy required for high-availability?'
Answer: Load balancing doesn't decrease availability; failing to measure load does. In all cases, you should have load monitoring set to thresholds that will allow for a single server failure.
You have good monitoring in your first scenario but for some reason you removed it in your second scenario. Rather, you're not monitoring the whole system. Measure load at the load balancer.
Comment: Thanks, that confirms my suspicions, that with load balancing enabled I would want to build in resilience for the eventuality we're down to one server. So in the second scenario, we'd want alerts to trigger at 40% capacity
Comment: Well kind of. Monitor the whole system, including your LB not just the servers.


How to define my own block regions for original, custom front page layout?

Question: I want to define my own block regions for the front page
I want to have a grid of blocks, each block containing a list of recent media (pictures, youtube, audio) with a certain tag. See example wireframe as ascii art below
A rule with the blocks is that if an item has already appeared in one block, then it doesn't appear in the others (media items can have multiple tags obviously).
Questions after the drawing.
<code>+-----------------------------------+
! main menu                         !
+-----------------------------------+
! rolling display                   !
!                                   !
!                                   !
+-----------+-----------+-----------+
! tag a     ! tag b     ! tag c     !
! heading   ! heading   ! heading   !
+-----------+-----------+-----------+
! list      ! list      ! list      !
! of media  ! of media  ! of media  !
! with tag a! with tag a! with tag c!
! & thumb   ! & thumb   ! & thumb   !
! nail for  ! nail for  !nail for   !
! each item ! each item ! each item !
+-----------+-----------+-----------+
! tag d     ! tag e     ! tag f     !
! heading   ! heading   ! heading   !
+-----------+-----------+-----------+
! list      ! list      ! list      !
! of media  ! of media  ! of media  !
! with tag d! with tag e! with tag f!
! & thumb   ! & thumb   ! & thumb   !
! nail for  ! nail for  !nail for   !
! each item ! each item ! each item !
+-----------+-----------+-----------+
! tag g     ! tag h     ! tag i     !
! heading   ! heading   ! heading   !
+-----------+-----------+-----------+
! list      ! list      ! list      !
! of media  ! of media  ! of media  !
! with tag g! with tag h! with tag i!
! & thumb   ! & thumb   ! & thumb   !
! nail for  ! nail for  !nail for   !
! each item ! each item ! each item !
+-----------+-----------+-----------+
</code>
Please outline specifically how I would go about doing this. I'm looking for a fairly definitive answer -
i.e. something that won't break something else, and is robust in itself.
Specific questions:

Would I use PHPTemplate and if so how? Would I use this to declare
the regions, and how?
What would the roles of Panels, Views and Blocks be in creating this
layout?
Can I create the layout in panels without writing any PHP code?
Presumably the Views module would provide the content within the
blocks.
How do I tell Views and Blocks where to put the content, i.e. in a particular block?
Comment: I made it by hand. No program used. I used the  tag to enable fixed width font.
Answer:
If you just need it on your front page, doing it in page template is wrong.
You can do in in Panel - create new panel for logged and not logged users; use there blocks; and views' display 'panel pane' for using views which need argument from context.
Yes you can
It can, but sending view argument this way is really painful. I recommend use panels panes.
You set it in panel.
Comment: +1 Thanks @Marcin Wosinek - I'll look into Panels further and report back. Once I have a solution I may add further comments to your answer and accept your answer as panels being the basis of my solution.
Comment: Accepted answer. Because it gives me the right guidance about the best steps to take. That is exactly what I need, before I invest time in learning and developing the solution based on that.


Why is my canvas fill pattern repeating/overlapping itself?

Question: I've drawn a grid of rounded rectangles, and I need to fill them with an image background. Eventually I'll have many image backgrounds, but for now, I'm trying to get it to work with one. I'm close, my rectangles draw but the fill does something a little whacky - it overlaps itself and kills my pattern (except on the edges) basically filling the whole canvas with the image. I've tried to 'clip' my path but that just causes only one rectangle to fill. I'm not sure what I'm doing wrong, and I'm hoping a canvas expert can spot it?
/* build rounded rectangle */
var roundedRect=function(ctx,x,y,width,height,radius,fill,stroke)
{

 ctx.save(); // save the context so we don't mess up others ctx.beginPath();

// draw top and top right corner ctx.moveTo(x+radius,y);
ctx.arcTo(x+width,y,x+width,y+radius,radius);

// draw right side and bottom right corner
ctx.arcTo(x+width,y+height,x+width-radius,y+height,radius);

// draw bottom and bottom left corner
ctx.arcTo(x,y+height,x,y+height-radius,radius);

// draw left and top left corner
ctx.arcTo(x,y,x+radius,y,radius);
ctx.clip();

if(fill){ ctx.fill(); }

if(stroke){ ctx.stroke(); }

 ctx.restore(); // restore context to what it was on entry
}

/* onload, fill canvas with pattern of rounded rectangles separated by 2px */
window.onload = function() {
var canvas = document.getElementById("canvas");
/* rounded filled rectangle pattern */
var canvasWidth=530;
    var canvasHeight=530;
    var recWidth=42;
    var recHeight=42;
    var grout=2;
    var radius=2;
    var cols=canvasWidth/(recWidth+grout);
    var rows=canvasWidth/(recHeight+grout);

    /* loop through each row/column to build pattern */
    alert("rows" + rows + " & cols " + cols);
    for (i=1; i<rows; i++){
        for (j=1; j<cols; j++){
            var ctx = canvas.getContext("2d");
            /* fill pattern */
            var img=document.getElementById("poppy");
            var pat=ctx.createPattern(img,"repeat");
            ctx.fillStyle=pat;
            roundedRect(ctx,(j*grout + (j-1)*recWidth),(i*grout + (i-1)*recHeight),recWidth,recHeight,radius,true,false);

                }
             }
};

Answer: Let's assume that your problem is reproduced in this JSFiddle: http://jsfiddle.net/hBEwr/. (If this is not the case, the rest of this answer is ~bunk; please edit to match your exact problem.)

If we remove the pattern from the equation altogether, we can see that it is not directly to blame.
http://jsfiddle.net/hBEwr/1/
Instead, the rounded rects are not leaving the grout necessary between them.
Since everything is running over each other, we then change the fill color to a low-opacity blue. Interesting!
http://jsfiddle.net/hBEwr/2/
We see that many of the paths are getting drawn again and again. This insight leads us to look at the implementation of roundedRect() more closely and notice that we never call beginPath(). Indeed, in your code from the question above it seems to have gotten eaten by a comment. Without this call, each invocation of roundedRect() adds additional rectangles to an ever-growing path, instead of starting over.
Adding the call to beginPath() back in, we see that we are on the path to success:
http://jsfiddle.net/hBEwr/3/
Now we can add back in the pattern (with some slight changes) and achieve glorious victory:
http://jsfiddle.net/hBEwr/4/

Some notes on other small tweaks I made:

Make sure you always var your local variables:
for (i=0; i<10; i++)     // Oops! i is a global variable
for (var i=0; i<10; i++) // Much better

It's inefficient to re-get the ctx, img, and create the pattern for each tile. In the final code above I've moved these outside the loops for simplicity and speed.
Using console.log instead of alert for debugging is often far easier. (Open the developer console to see the output.)
I added the final outer row/col of grout the the column calculations to ensure that there is space for it to be included. Use or not as you like.
Comment: you are so above and beyond awesome, i don't know what to say except a very hearty thank-you. i appreciate the extra special response to set this straight. the eaten beginpath was just lame, need my eyes checked!


Eclipse: Apache Spark 2.1.1, org.apache.spark.logging couldn't be resolved

Question: The error statement:
<code>org.apache.spark.logging couldn't be resolved. It is indirectly referenced from required .class files
</code>
I read about the error here (general to such errors). Further I found that org.apache.spark.logging is in fact not available for Spark versions > 1.5.2 here.
I am able to run the code by setting the spark version to 1.5.2. Is there any way to run the same code (with some changes, if required) using Spark version 2.1.1 ? I am specifically trying this code.
I am new to maven, eclipse and spark, therefore a detailed answer explaining the stuff would be highly appreciated.
Answer: It seems you are using the Spark 2.1.1 so please use the below depedency to resolve the issue.
<code>   <dependency>
        <groupId>org.apache.spark</groupId>
        <artifactId>spark-streaming-kafka-0-8_2.11</artifactId>
        <version>2.1.1</version>
    </dependency>
</code>
Comment: Hi, I added this dependency to the POM file, also set the spark version to 2.1.1. Have a at the ([pom](https://pastebin.com/xirXYgvN)) file. The problem persists.


Use string in subprocess

Question: I've written Python code to compute an IP  programmatically, that I then want to use in an external connection program.
I don't know how to pass it to the subprocess:
import subprocess
from subprocess import call

some_ip = "192.0.2.0"  # Actually the result of some computation,
                       # so I can't just paste it into the call below.

subprocess.call("given.exe -connect  host (some_ip)::5631 -Password")

I've read what I could and found similar questions but I truly cannot understand this step, to use the value of some_ip in the subprocess. If someone could explain this to me it would be greatly appreciated.
Comment: I've edited both the question and my answer. As my previous comments were now obsolete, I've deleted them. Feel free to delete your comments, too. (They might be confusing without context.)
Answer: If you don't use it with shell=True (and I don't recommend shell=True unless you really know what you're doing, as shell mode can have security implications) subprocess.call takes the command as an sequence (e.g. a list) of its components: First the executable name, then the arguments you want to pass to it. All of those should be strings, but whether they are string literals, variables holding a string or function calls returning a string doesn't matter.
Thus, the following should work:
import subprocess

some_ip = "192.0.2.0"  # Actually the result of some computation.

subprocess.call(
    ["given.exe", "-connect",  "host", "{}::5631".format(some_ip), "-Password"])

I'm using str's format method to replace the {} placeholder in "{}::5631" with the string in some_ip.
If you invoke it as subprocess.call(...), then
import subprocess

is sufficient and
from subprocess import call

is unnecessary. The latter would be needed if you want to invoke the function as just call(...). In that case the former import would be unneeded.
Comment: I may have speak too soon,I tried the code at work (access to VPN) and I've been unable to do the same for the password, if I put it before the IP, it isn't used and after it is used as the host. I noticed that the last time you posted something about the password but then the comments were deleted. Would you be so kind to help me with this issue? Thank you in advance.

Use string in subprocess


Isn't pitch memorization almost as valuable as absolute pitch?

Question: I think a high majority of people are capable of singing songs in the original key and singing the correct notes. Taking it a step further, wouldn't paying attention to the name of notes that we remember be almost similar to having absolute pitch?
I am not currently capable of hearing a note and naming what pitch it is, but I am capable of remembering the correct notes of many songs. I haven't personally taken the time to start paying attention to what the names of the notes are but I am going to now. That is what pitch memorization is correct?
I really want to be able to recall certain pitches, mainly to aid in tuning instruments by ear.
Comment: devils advocate: who says absolute pitches worthwhile? ;) but seriously, many people make far too much of it, as if it has anything to do with talent or even intonational ability. And most who have it don't have it to the degree that you could tune accurately with it. I can identify A, but can't tell you whether it's 338 or 440.
Comment: So you're asking, "Can I develop absolute pitch if I start be memorizing pitch names of songs"?
Comment: @Aaron eh no not exactly, because perfect pitch is hearing a note and being able to differentiate them correct? I'm only able to memorize songs. So what I mean is, if I start attaching the note names to the pitches, won't I be able to recall an E whenever for example, or other notes?
Comment: That would be the equivalent, more or less, of absolute pitch
Comment: You would only benefit for the first string you tune. The others you tune by consonance with the first string. (When the wobbly sounds flatten out they are consonant.). Unless you need a specific dissonance I guess.... but that is probably identifiable by the wobble sound as well... (the wobbling is like a mini sine riding on top of the general sine shape I think, it is because the sum of two sines can be written as the product of two sines)
Comment: Sorry it might be the other way around, the envelope being the wobbling. See https://www.wolframalpha.com/input?i=sin%28440t%29%2Bsin%28%28y%2B440%283%2F2%29%29t%29+%2C++t+between+-30+and+30%2C+y+between+-5+and+5
Comment: Here is a better image, the amount of bumps in the envelope depend on how many Hertz off you are https://www.wolframalpha.com/input?i=sin%28440+2+pi+t%29%2Bsin%28%280.5%2B440%283%2F2%29%29+2+pi+t%29+%2C+plot+t+between+0+and+10 .
Comment: Some years ago I attended some Kodaly courses, following a renown Hungarian teacher of that method. In case you don't know it, two of the fundamental aspects of the Kodaly methods are: 1. singing; 2. awareness of relative pitch (no matter the "tuning"). One of the members of that course had absolute pitch, and singing with him was an absolute nightmare: for obvious reasons, we sometimes "adjusted" common pitch by listening to each other while performing, but he *had* to keep the absolute pitch he was sure about. Our tuning was almost always off as an ensemble, but just because of him.
Answer: If you can consistently sing a song in the original key, you have something very akin to absolute pitch.   But maybe you have it at a physical level rather than an intellectual one.  You have physical memory of what it feels like to sing those notes rather than aural memory.
This isn't uncommon.  When I used to play keyboard for talent contests - now a dead art, EVERYONE brings backing tracks - I would often play a song introduction as printed only for the singer to set off in the (different) 'key of the record'.   In fact, part of my craft was knowing what keys many popular numbers were recorded in so that I could immediately adjust when required!
Unfortunately, this type of absolute pitch generally came along with an un-tutored approach to music in which reading notation and even knowing note names had no part.  It can be difficult to transfer the skill across to a more structured way of looking at music.
Absolute pitch comes in many forms.  I'm a pretty well-trained musician. I don't consider myself as having absolute pitch.  But play me A on a piano, I can usually tell if it's 'out'. To some degree, I 'know A'.   But I wouldn't rely on it if tuning the piano (another skill that I've never developed).
I can't offer any definite answer to your question.  Maybe you can 'learn' E, A, D etc. and so be able to tune a guitar without any reference. Maybe this will never be reliable.  But what you CAN do is work on your Relative Pitch.  'This note is C, so sing me F♯?'  A very useful musical skill, and completely learnable.
And, heck, who needs absolute pitch when it's so easy to load a tuning app onto your phone?
Answer: "Pitch memorisation" would more or less be the equivalent of "absolute pitch".
Note, however, that "absolute pitch" is mostly a fallacy anyways, since most people with this "ability" have only been exposed to music played in A = 440 Hz and 12-tone equal temperament. "Absolute pitch" is actually a great benefit if you define it as the ability to recall frequencies, but not if you think of it as the ability to recall notes, since music where A is significantly different from 440 Hz or music that uses alternative or historical tunings can easily throw you off.
It's a one-trick pony—something that allows someone to function very well under very specific conditions, while preventing them from being able to function well outside those conditions
I know this from experience, since I have been told that I have "perfect pitch", and when I didn't know any better I even used to brag about it. But since I was only ever taught 12-TET, the early age at which I started my musical training and gained the ability to identify notes led to me thinking of notes as absolute frequencies and intervals as fixed mathematical constants. In late 2022, I re-gained interest in classical music again and discovered alternative and historical tunings on my own. I'm glad that I finally broke out of the 12-TET walled garden, but by absolutely no means whatsoever should this have taken 18 years.
Nowadays, my favourite alternative tunings for Western music that doesn't require 12-TET's enharmonic equivalences are 31-TET and 43-TET, and I already know of many Western non-classical songs that I think would sound much more expressive in 31 and 43 than in 12. Additionally, I absolutely hate the term "perfect pitch" and have since grown increasingly disdainful towards the heavily stripped-down nature of the current state of Western music education (at least in the US).
Comment: Ok, but but how many cents off does a frequency have to be for you to hear it as a different pitch?  If you hear 352 Hz, do you think, "that's too high to be F4" because it's not 349.228 Hz?
Comment: By any chance, is the piano your only instrument? (Alternately, are your only other instruments unpitched percussion ones, keyboard instruments, and/or ones in the xylophone family?) I would have thought the traumatic experience of needing to tune your instrument would teach you that notes are ranges instead of absolute frequencies, even with 12TET as your only true tuning system.
Comment: @phoog The difference, if I recall correctly, has at least 5-10 cents. I'm actually glad you asked because I've asked many people to see if they can hear the difference between an A major triad in 12-TET and an A major triad in 31-TET at A = 440 Hz, and half of the people think that the 31-TET triad sounded too flat. I used to think 352 Hz was too high to be F4, but now that I've broken out of the 12-TET hegemony I know better.
Comment: @Dekkadeci I've played piano for most of my life, and cello for about 8 years, and I sing now. I don't know why the thought of notes being ranges of frequencies never came across to me for most of my life. I guess that's because I had only ever been exposed to 12-TET most of my life, and I discovered alternative tunings only recently and on my own (not in a classroom setting). This is why I think it is important to teach the harmonic series and just intonation BEFORE going into scales and chords.
Comment: I suppose I was fortunate enough to be in an elementary school with a concert band and a great desire to tune the band and say my clarinet is "5 cents flat" and a sax is "7 cents sharp" before I started formal ear training. The part where I only found I sight-sing in Grade 7 and started gaining absolute pitch in Grade 8, thus giving me time to get used to transposing instruments (though never any tuning systems other than 12TET and arguably just intonation thanks to my school choir), also probably helped.
Comment: Lol when I read your and others abilities I'm pretty much speechless. Why does absolute pitch only work in 12 tet and 440hz? I've never thought of pitches as being fixed but rather, there's a certain space for each note in an octave. That's why I don't 100% understand what a microtone would be. What I mean is, if an octave is broken up in 12, then say 339-359 hz is F4 territory. An analogy with colors, between red and yellow is orange territory.
Comment: @Lecifer The reason I say "absolute pitch only works at 440 Hz and 12-TET" is because most people (at least Western musicians) who have "absolute pitch" have only been exposed to music in 440 Hz A, 12-TET music. They become used to hearing only very specific, relatively narrow ranges of frequencies.
Comment: Would that really be absolute pitch though? In my mind someone who knows absolute pitch would be able to say the exact hertz with a bit of training. I can sometimes "feel" when it is the pitch I want (something like a tingle in my head and down my spine and skin) but I can't remember its name... but a number is just a name for a number...
Comment: @Emil Yes. Since the second is truly absolute as a unit of time, I would say "true perfect pitch" would be the ability to state the exact or almost exact frequency without a reference. Defining "perfect pitch" as the ability to identify notes is misleading, since there are too many variables that go into defining where notes sit for this to be accurate at all.
Answer:
I am not currently capable of hearing a note and naming what pitch it is, but I am capable of remembering the correct notes of many songs. I haven't personally taken the time to start paying attention to what the names of the notes are but I am going to now. That is what pitch memorization is correct?

Maybe.  The thing is, though, if you know that a certain song starts with "F," do you always actually hear it in your mind with a frequency of 349.228 Hz?  Try an experiment: choose a recording you know well, identify the pitch of the opening by comparing it with a fixed pitch reference, and every morning, as soon as you wake up, think of that recording and check the pitch you're hearing in your mind against the pitch reference.  That is what absolute pitch is really about; the names of the notes are just a mechanism of communication.

I really want to be able to recall certain pitches, mainly to aid in tuning instruments by ear.

I think most people with absolute pitch will tell you that they can only tune instruments approximately without a pitch reference.  They too are only human.  Their sense of pitch also fluctuates, just far less than it does for someone who doesn't have absolute pitch.  And again, the names of the notes are not critical, just as you may (or may not) be able to tell whether a piece of paper someone hands you is larger or smaller than the bank cards in your wallet without knowing the size of a bank card in millimeters or inches and without knowing that this size is called "ID-1" in the ISO/IEC 7810 standard.
Comment: I always hear the songs exactly as they are sung or the way that they were recorded. Like whatever those exact pitches were. The thing is I've never practiced remembering just a single pitch by itself, so I'm not sure if I can do that. I doubt it though. That's why I don't think what I'm describing is absolute pitch whatsoever. And by using the names of the notes, that would just be for me to be able to differentiate what I'm remembering from the songs. I can't really tell the difference between pitches without them being in relation to another pitch (Relative pitch?).
Comment: The way the instruments were recorded*
Comment: @Lecifer "I always hear the songs exactly as they are sung or the way that they were recorded": are you saying this because you've actually measured?  I find that I'm often but not always right on pitch, but sometimes I'm off by a third or more.  Just now, for example, I tried with Blondie's Heart of Glass and I was a half step flat. At one point I tried to train myself by predicting the pitch of a tuning fork.  I did improve, but I was never consistently correct.  I did however develop a sightly pavlovian ability to be closer to 440 Hz if I pretended to strike the tuning fork before guessing.
Answer: Answer to the lead question -  yes, probably more so. Absolute pitch is often seen as a curse, but recall of pitches is far more useful. That's if the recalls are spot-on for tuning, which I, and I guess most others, would be sceptical about.
So, unless you can be 100% certainly accurate, 100% of the time, don't even consider it. It may be a party trick, but as an accurate tuning mechanism, it most likely won't do the job. I've been practising just that for many years now, and my 90%-95% wouldn't be good enough.
If you can do an acid test for 100 times, with different notes, and be spot-on every time, then I'm wrong. But I doubt it. Other factors will come into play, like the key of the last tune that went through your mind (proved that!). I've been tuning guitars/basses by ear for 60 odd yrs, and whilst I get pretty close - sometimes spot-on, I wouldn't guarantee it.
Comment: Pitch recall and detection is still very useful if you mainly use them to write music (compositions/arrangements/transcriptions). I agree absolute pitch doesn't help you completely nail tuning, though (clarinet ends up only within 15 cents of accurate, and that's because I assembled it correctly).

Isn’t pitch memorization almost as valuable as absolute pitch?


How to update the Shopify CLI on Node.js?

Question: I'm trying to update my Shopify CLI to its latest version but when I run npm run shopify upgrade Node.js gives me this error...

Do you know what it means?
Answer: The confusions seems to be that the 2.xx Shopify CLI is for themes only and runs via the terminal fine and what I understand are core ruby calls. 3.0 is trying to run via NPM purely so in your package.json you would need :

 "scripts": {
    "shopify": "shopify",
    "build": "shopify app build",
    "dev": "shopify app dev",
    "push": "shopify app push",
    "scaffold": "shopify app scaffold",
    "deploy": "shopify app deploy",
    "info": "shopify app info"
  },
  "dependencies": {
    "@shopify/app": "3.10.1",
    "@shopify/cli": "3.10.1"
  },

in order to run what youve mentioned
Comment: Thanks for the answer @Darren Mc, in the end I found that the problem was I was  trying to update the cli via npm and not via Ruby. The right command is `gem update shopify-cli`


geofield map theme markers

Question: I wonder if (and how) it is possible to have dynamic markers on a geofield map created by views. I'd like to have different colors of markers depending on a field value, and also a count of matches from a proximity filter direktly printed into the markers (not the popup). I'm using the google map layer and cannot find an option to even have (e.g.) green instead of the default red markers. Google search on this topic didn't wield any solutions.
I'm using the following modules: address field, geofield, geophp & geofield maps for map display.
Has anyone done this already? Thanks!
Comment: Do you mean e.g. something like this http://ithaka.im/nl/route
Comment: @Justme more like so: http://www.leerstandsmelder.de/
Comment: I see, yes it is possible with openlayers 2.x. I did not got it working with openlayers 3.x.
Answer: An instruction how to do this can be found on:
http://purewebmedia.biz/article/2014/08/01/create-multi-layer-map-drupal-7-openlayers-2x

geofield map theme markers


Push notification to all the users subscribed to the topic except login user using FCM Firebase

Question: Now i have a group which have more than ten thousand members and for a group i have created a topic(Notification topic) where all the users in the group subscribed to that topic. Now inside the group any user can add post like image or file or video. When user add the post i need to send notification to all the users subscribed to that topic but except one, that is person who add the post. How can i achieve this??
Now notification is going to all the users including the person who add the post.
Answer: There is currently no parameter of any sort to exclude a specific user from receiving a message from a topic they are subscribed to. However, as a workaround, you could simply have a custom implementation on building the payload and handling the message to receive it.
Depending on how you build your payload, you could just add a custom key-value pair that includes the user id of the one who posted the data (something like posterId or simply userId).
Then on your client side, when handling the push notification, just check if the id is the user's or not. If it is the same user, don't show the notification, else show it. e.g.:
if (userId == currentUserId) {
    // if user is the one that sent the message, don't show the notification
    return;
}

Comment: Like this can we avoid to show the notification in notification tray itself for that user??
Comment: If you're using a `data`-*only* message payload, it's possible. But if you have the `notification` parameter, then no (when your app is in background, the Android system automatically handles the `notification` message). What I mentioned is just a sample to provide the idea on how to go around it. I think there are still other ways to get around this.
Comment: You're welcome. Also have a look at [Cloud Functions for Firebase](https://firebase.google.com/docs/functions/). Depending on this use-case, it might be useful. :)
Comment: I am wondering how to send the "most read article" to a topic but exclude those users who already seen / read it ? Do I need to keep list of read articles on the client side ? If thats the case it might not work when the app is not launched.
Comment: @abiieez I think that is solved better by having a filter on the ids prior to adding them to the topic. Check if userId has read the topic before (I assume you have a list per user), true = don't add, false = add. Then unsubscribe as necessary.
Comment: Looks like unsubsribe and subcribe back is way of tackling This issue. Thank you for the confirmation.
Answer: Even though this question is already answered and a bit old, there's a workaround. So therefore I will still add the answer for future reference. What you can do is unsubscribe the user from the topic, send the message to the topic and subscribe the user once again. Sure that is a bit more work and calls to Firebase, but then you've got what you want.
Just a thought
Comment: Works for me: Just don't forget to add some few seconds before you subscribe back incase of slow networks

    Timer(Duration(seconds: 5), (){
        firebaseMesseging.subscribeToTopic("POST");
      });
Comment: @Erik Dohmen For unscribing the user, we need registration token of the app instance and for example if the user is using multiple devices then we need to get all the registration tokens of the user and then call unssubscribeTopic() on all tokens. so for this we need to store all the tokens in a database. Then it might be very difficult to manage tokens(stored in database). Is there anyway to do it without managing this token on application server?
Comment: Is it guaranteed that the "unsubscribe" has time to work before the message is sent...? Or would I need to add a few seconds there as well? Coz that'd be annoying...


sas cumulative return multiple variables

Question: I've been running a datastep for computing the cumulutive product of a variable X1, giving it a starting value of 1. However, I'm unable to run it for several variables using a %do loop. I provide both codes below. Help appreciated.
DATA HAVE;
INFILE DATALINES DSD;
INPUT X1 X2 X3 YEAR;
DATALINES;
0.99,0.98, 0.97,2005
0.975,0.96, 0.923,2006
0.983,0.934, 0.93,2007
0.978,0.93, 0.887,2008
;

data working;
set have;
retain R1 1;
S1=R1*X1;
output;
R1=S1;
drop S1;
run;

%macro macro5(j);
data notworking;
set have;
%DO i=1 %to &j;
retain R&i 1;
S&i=R&i*X&i;
output;
R&i=S&i;
drop S&i;
%end;
run;
%mend;
%macro5(3);

Comment: I think this is more designed for an array not a macro do loop.
Answer: Use an array, not a macro loop here.
DATA HAVE;
INFILE DATALINES DSD;
INPUT X1 X2 X3 YEAR;
DATALINES;
0.99,0.98, 0.97,2005
0.975,0.96, 0.923,2006
0.983,0.934, 0.93,2007
0.978,0.93, 0.887,2008
;

data want;
set have;
array x(3) x1-x3;
array r(3) r1-r3;

retain r1-r3 1;

output;

do i=1 to 3;
r(i)=x(i)*r(i);
end;

drop i;
run;


Need to invoke same controller method for different api's

Question: I have 2 APIs
1. localhost:8080/myservice/foo/1/0/updatesStatus
2. localhost:8080/myservice/bar/1/0/updatesStatus

I am not allowed to have different controllers for each API. So both the APIs are pointing to the same controller method where I have if-else check, but the code looks very bad in that, is there any better way to handle this.
@PostMapping(value = UPDATE_STATUS_API_PATH)
public Response updateStatus(@PathVariable("group") String group , @RequestBody UpdateStatusRequest updateStatusRequest, HttpServletRequest request) {
        try {
            if(APIUrl.FOO_GROUP.equals(group)){
               //code spefic to foo
            }
            else{
              //code spefic to bar
            }
            //common code
}

The same conditional checks also have to be performed on the service layer as well.
Is there any way I can avoid this conditional checks without having separate controller methods.
Comment: What do you mean not allowed? By who? Is it homework?
Comment: its an bad idea, what you actually trying to do is ` sort of api gateway` for internal layer, If you really want to do this (without any design) use `Object` as request body, then update entries based on condition `list vs single` will save you lot in **hot fix** but won't recommend
Answer: I can think of this.
Create an interface for service.
public interface UpdateService {
    void updateStatus(UpdateStatusRequest updateStatusRequest);
}

Then you create different implementations.
public class FooUpdateService implements UpdateService  {
    void updateStatus(UpdateStatusRequest updateStatusRequest) {
        // foo specific logic
    }
}

public class BarUpdateService implements UpdateService  {
    void updateStatus(UpdateStatusRequest updateStatusRequest) {
        // Bar specific logic
    }
}

Create a UpdateServiceFactory
public class UpdateServiceFactory {
    @Autowired
    private UpdateService fooUpdateService;

    @Autowired
    private UpdateService fooUpdateService;

    public UpdateService getUpdateService(String group) {
        // Move the if-else logic here
        if(APIUrl.FOO_GROUP.equals(group)){
               return fooUpdateService;
            }
            else{
              //code spefic to bar
              return barUpdateService;
            }
    }
}

Controller:
@PostMapping(value = UPDATE_STATUS_API_PATH)
public Response updateStatus(@PathVariable("group") String group , @RequestBody UpdateStatusRequest updateStatusRequest, HttpServletRequest request) {
        updateServiceFactory.getUpdateService(group).updateStatus(updateStatusRequest);
            //common code
}


Beach tennis rackets with most control?

Question: I am trying to keep my tennis level high.
Sometimes, I do not find any field to play tennis in Riga.
So I think the good thing is to play beach tennis on badminton fields.
I have now tested about 5 rackets of the brands King and MBT.
I will post here soon the specific rackets which I have tested.
Which are the beach tennis rackets with most control?
Answer: Each racket is distinguished by the following characteristics:

weight
balance
hardness

Weight
  A lighter racquet allows greater ease and speed of movement. However, for hitting the shots, a light racquet requires greater effort on the the arm. Otherwise, a heavier racquet offers more power on the ball, without affecting the arm as much as a light racquet. A good choice should be to choose the racket with the maximum weight the player can manage.
Balancing
  The more the racket is balanced on his head, the more this will promote the power of the shot (think especially smash and service). Nevertheless, this type of racket bears more intensely on the wrist. A balanced racquet towards the handle, however, allows a very accurate control of the ball and easier on the wrist.
Hardness of the frame
  A racquet with a more elastic frame favors the offensive game, giving more power to the shots and the best defense on smash. However, a stiffer racquet is characterized by a better control of the ball and more accurate hit. Moreover, the choice of the racket frame, it should also be considered the type of ball to be used: if the ball is hard, we advise you to use a rigid plate. Conversely, if the ball is soft or as much used, we recommend using a softer racquet.

The racket should be chosen thinking of the characteristics of the player

Beach tennis rackets with most control?


Wordpress admin bar not showing on frontend when logged in

Question: The thing is that I found a lot article on the internet that briefs like this,

check footer.php for <?php wp_footer(); ?>
check header.php for <?php wp_head(); ?>
check function.php for

    function my_function_admin_bar() {
        return false;
    }

    add_filter('show_admin_bar', 'my_function_admin_bar');

Check if in user profile show toolbar ticked on.

I checked all of that and everything is fine and in order. It seems it creating a white space before the header but it is actually not showing up with quick access buttons on the frontend.
N.B: Previously it was displaying the admin bar but all of a sudden it just disappeared.
Please help to fix this...
Answer: Do you still have the code you listed as #3 of your question (the function in function.php) included? If yes, delete that - return false hides the admin bar....
Answer: first put this:<?php wp_footer(); ?>  after this
<?php get_header(); /*Template Name: Debut Party*/ ?>


Testing current location in Iphone simulator

Question: I have integrated the myAnnotationview custiomed api in to my project.And i have added some address on it.I want to test it from iphone simulator.Is it possible?How can i achieve it?Do i need to ON anything in Simulator?
Thanks
Answer: I'm not sure what the problem is or what you hope to achieve. You can add a custom annotation to a specific location specifying the coordinate using CLLocationCoordinate2DMake( , );
If you are interested in your current address, use CLLocationManager for the specific location. On the simulator on a MKMapView your current location is always Infinite Loop at San Jose, California.


mod_rewrite to 302 a blank query string

Question: I'm currently working with:
RewriteEngine On
RewriteBase /somepath

RewriteRule ^/$ home [R]

I'd like to have requests of GET /somepath to redirect via 302 to /somepath/home. What am I missing here?
Comment: This is working on a subdirectory of the web server.
Answer: When using mod_rewrite in an .htaccess file, the base path is removed from the requested URL path before testing the patterns. That means /somepath (or rather /somepath/, since you're actually in /somepath/) is removed so that the remaining path is empty. So:
RewriteRule ^$ home [R]

mod_rewrite to 302 a blank query string


Doubt in connected and path connected s

Question: My teacher taught me that a set of points is connected if and only if it is path connected. However,the Topologist's sine curve is connected but not path connected. Am i missing something here?
Comment: This is only true if we put extra conditions on the space in question. For instance, a locally path connected space is connected iff it is path connected. Generally though there are connected spaces that are not path connected as you point out.
Comment: Please elaborate
Comment: If the set is open then it is path connected
Comment: @AdityaDwivedi yes, for **open** subsets of the plane because these are locally path-connected. And the Topologist's sine curve is closed and not-open.
Comment: @HennoBrandsma does open connected subset of $ \mathbb{R}^n$ is not neccesarily path connected
Comment: @AdityaDwivedi for an open subset of $\Bbb R^n$ we have that it's connected iff it's path-connected. That might be the fact your teacher was referring to.
Answer: No, your teacher is wrong. Even for planar subsets connected does not imply path-connected. In $\Bbb R$ this equivalence does hold, maybe you misheard him and did he mean that instead. Otherwise just plain wrong. Within the class of locally path-connected spaces the equivalence does hold, though. So e.g. in $\Bbb C$, the regions/domains (open connected subsets) are also path-connected (even with piecewise linear paths) which becomes important for path-integration theory.
Answer: In general, path-connected implies connected. The converse is not true as you point out with the topologist's sine curve. As Henno is correctly pointing out, the notion is equivalent in $\mathbb{R}$ since the topology in $\mathbb{R}$ is "so poor" that it is impossible to find a non-path-connected set that is connected. To be able to find one, you need to go on "bigger" topological spaces, in some sense.
I suggest that you go here to see how far you can generalize the equivalence, where it is noticed that in a locally path-connected space, connected open sets are path-connected. Every topological vector space over $\mathbb{R}$ or $\mathbb{C}$ is locally path-connected since the balanced neighbourhoods form a local base at 0.

Doubt in connected and path connected s


How to combine two data sets (level-1 and level-2 data sets) for multilevel analysis in R

Question: I want to analyze data from TIMSS on mathematics. Data contains two data sets one for student level information (i.e. level-1) and another one for school level information (i.e. level-2). Data sets are provided in two different files and each file contains school ID variable.
As far as I know, I can't do multilevel analysis with these two data sets and these have to be combined into one data set.Am I right?
I tried to use reshape and reshape2 for combining the two data set but it didn't work. In level-1 data I have SchoolID,motivation, confidence, learningApproach and math scores. Data looks like:
SchoolID studentID motivation confidence learningApproach math
100123  10012301    23  10  12        45
100123  10012302    32  5   16        67
100123  10012303    14  7   21        89
.
.
.
110223  11023301    13  7   18        77
110223  11023302    24  7   11        98
110223  11023303    16  8   12        56

In level-2 data I have SchoolID and resources. Data looks like:
SchoolID    resources
100123      45.5
100223      66.7
1106303     34
110223      22.3

Could you please guide me on how to combine these two data sets in an appropriate way for using with lme4 package?
Thanks.
Answer: Try using merge():
combined <- merge(x=level1data, y=level2data, by="SchoolID")

Comment: this is what I was looking for.Is there any reverse method?
Comment: @Amin what do you mean by reverse? do you mean getting back to your level-2 data? I think what I would do would be this: `level2data <- combined[duplicated(combined$SchoolID) == FALSE, c("SchoolID", "resources")]`. The bit `duplicated(combined$SchoolID) == FALSE` selects rows for the first occurrence of each SchoolID, then `c("SchoolID", "resources")` only keep the SchoolID and resources columns.


Setup right field type and widget for field

Question: I'm using Drupal 7.23 to build an online catalog for a shop. I made an "articles" content type and I've built all the required fields.
I need to setup the Price field in a way that it's a list, and each row of the list will show something like "buy x at yx", like "buy 1 at 5, buy 2 at 9, buy 3 at 12" and so on, and I need it to be treated as numbers (5,9,12). How can I accomplish this?
I have also the image field, I need to have up to 10 images for the same article, and I want to show a gallery (more or less like Amazon does), where you click on the photo and it enlarges. It is handled by Drupal already? Do I have to setup something special to do this?
Answer: For the first issue you can actually add it as a key|label pair.
Where the key would be the number and the Label would be what is displayed. for example 5|buy 1 at 5
this would show "buy 1 at 5" in the dropdown but the value would be five. you want to work with numbers you might want to select List(integer) as your field type.
For the second problem you might want to take a look at the Cloud Zoom Module.

This addon provides a small, thumbnail sized image, with an on-hover
  popup, zoomed and centred on a larger version of the image.

OR
jQZoom

The jQZoom module is a wrapper for the jQuery plugin jQZoom. The
  module provides a javascript magnification effect for images. When a
  user mouses over an image, a larger version of the area under the
  cursor will be displayed beside the image.


Parseval's theorem.

Question: We consider two signal $h(t)$ and $g(t)$ such that
$$\int_{-\infty}^\infty |g(t)|^2dt<+\infty$$
$$\int_{-\infty}^\infty |f(t)|^2dt<+\infty$$
Parseval's theorem states that:
$$\int_{-\infty}^\infty{h(t)g(t)^*dt}=\int_{-\infty}^\infty{H(\omega)G(\omega)^*d\omega}$$
where $^*$ is the conjugate and $H(\omega),G(\omega)$ are the Fourier Transforms.
This result is also valid if, instead of the integrals, there are the series and instead of the transforms there are the Fourier series?
Comment: Yes, http://en.wikipedia.org/wiki/Discrete_Fourier_transform#The_Plancherel_theorem_and_Parseval.27s_theorem
Answer: You question follows from properties of the complex numbers. I'm assuming you're used to $j=\sqrt{-1}$ instead of $i=\sqrt{-1}$; so that's what I'll use. Let $z$ and $w$ be complex numbers. Then
$$
          z w^{\star} = \frac{1}{4}\sum_{n=0}^{3}j^{n}|z+j^{n}w|^{2}
$$

Parseval's theorem.


jQuery.html() returns invalid IMG

Question:
Possible Duplicates:
Jquery html() and self closing tags
Is it expected that jQuery $('span').html() turns XHTML br tag to html syntax?

I have a document like this
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

I want to retrive html for some nodes to do something. But I see one problem with IMG.
$('#content').html();

This returns invalid XHTML

jQuery version is 1.4.2.
Comment: That's an interesting problem. I suspect this is because jQuery doesn't query the HTML, but rather the DOM, which is a model that the browser builds up using the HTML. When you ask for .html(), it's not looking the source, but rather generating new HTML from the DOM. Out of curiosity, why do you need it to return valid xHTML?
Comment: The first answer here seems relevant. http://stackoverflow.com/questions/1490909/is-it-expected-that-jquery-span-html-turns-xhtml-br-tag-to-html-syntax
Comment: @Anton Well, there's no `xhtml()` method. :-) See @Nathan's linked question
Comment: Have you tried this with jQuery 1.4.3?
Comment: @Surreal Deeams jQuery 1.4.3 returns the same string
Answer: This is a duplicate, but none of the answers in the original question gives an actual  workaround. (Probably rightly so. I can't but agree with what @Cletus says in his - as always excellent - answer.)
But if you're stuck with XHTML: there is a jQuery plugin providing a innerXHTML() function (poorly maintained though, last updated 2007, and never made it from Beta) and a JavaScript tool named innerXHTML that promises to do what you need. If you need this, that may be your best bet.
Answer: innerHTML/html() won't give you an XHTML serialisation unless you've actually served the page as XHTML, under the application/xhtml+xml media type. (And that doesn't work on IE<9.) If you are serving your page as text/html, then your self-closing tags are nothing but ignored clutter to the browser when it's parsing your source into a DOM. You cannot expect to get the same format HTML out of the DOM serialised from that as you put in.
In fact in some cases in IE innerHTML won't even give you a valid HTML serialisation: it omits quotes around attr in some cases where it shouldn't. In short, you cannot rely on innerHTML giving you any particular format of markup. It might re-order attributes, it might HTML-escape different characters, it might normalise attribute values, it might change whitespace. So doing string operations on the html() return value is a non-starter. All you can rely on is that you can assign the serialised markup back to the innerHTML of another element and the browser will be able to parse it.
What's your purpose in trying to retrieve XHTML? You may be able to achieve more using normal DOM-style manipulations.
ETA re comment:
Then XHTML validity is the least of your worries. It doesn't matter if the HTML isn't well-formed, you will still be able to write it back to html(). But:
What you can't reliably do with the html() is tell what sentences are in text content and what are in attribute values. For example  is markup and if you start putting s inside the title attribute, you're obviously going to have difficulties.
This is a text-processing task, so you should do it on text nodes, not markup. This is a bit tricky and jQuery doesn't give you any special tools to do it. But see the findText function from this answer and you could use it like:
// Split each text node into things that look like sentences and wrap
// each in a span.
//
var element= $('#content')[0];
findText(element, /.*?[.?!]\s+?/g, function(node, match) {
    var wrap= document.createElement('span');
    node.splitText(match.index+match[0].length);
    wrap.appendChild(node.splitText(match.index));
    node.parentNode.insertBefore(span, node.nextSibling);
});

Comment: I want to split my paragraphs by sentences and wrap then into SPANs. It is to allow users manipulate with each sentence.
Answer: .html() doesn't return the HTML or XHTML markup that was provided to make the nodes, it returns the browser's internal representation of the relevant nodes.  This internal representation is not XHTML compliant and is not made to be--it's technically an internal implementation detail.
You can throw any HTML or XHTML at a browser and it will parse it into an internal DOM.  The internal DOM does not differ if the original source was crappy HTML, good HTML, or perfect XHTML.  The resulting DOM for equivalent source documents will be the same, but generating a new HTML document from that will not necessarily be exactly the same as the source.

jQuery.html() returns invalid IMG


Clarifications on Poisson Regression

Question: I am watching this Bloomberg course on machine learning, and i need help on understanding the application of Poisson Regression. So it goes like this
Let $Y=\{1,2,3,...\}$ and let $X$ be a vector in $\mathbb{R}^d.$
We can then model $Pr(Y_i|X_i) = e^{W^TX}.$ The vector $W$ can then be found using an optimization algorithm. But, $e^{W^TX}$ is not always an integer. So, my question is how do we predict a particular $Y_i$ given $X_i.$
Answer: In Poisson regression we use exponential link function. This means that
$$
\mathbb{E}[Y | X] = e^{W^TX}.
$$
Note that the expression above contains the expectation, not a probability. The expression is known as intensity and is usually denoted with $\lambda(X)$. Conditional on $X$, variable $Y$ has Poisson distribution with parameter $\lambda(X)$. This means that
$$
P(Y = k | X) = \frac{\lambda(X)^k}{k!} e^{-\lambda(X)} = \frac{e^{kW^TX}}{k!} e^{-e^{W^TX}},\ \ \ k = 0, 1, 2, ...
$$
As you can see, $Y$ takes only non-negative integer values.
Comment: I see. This cleared it up. I appreciate your help sir!

Clarifications on Poisson Regression


Symfony2 RESTful API + AngularJS

Question: I've been working on an e-commerce project built on Symfony2 (for the backend) and AngularJS for the frontend. Currently the Symfony part is used only as an API, which has three different user levels (guest, customer & admin). Different actions that can be done within the system (like add/remove data) are secured by:

Symfony2 firewall with user roles/access control
JMS security extra (@PreAuthorize expressions)

For the parts that are secure everything works as intended and I'm very happy with the way things work.
Problem:
There are parts of the API which are public (like retrieving product information, categories, etc.). I'm retrieving such data in Angular with Ajax calls to my API that returns the data in JSON format. One example would be:

/api/product/get-all/?page=1&count=10&sorting[id]=asc

The problem is that anyone could look at the requests in browser and copy the path and have access to all the data (such as all the products) and could just download a JSON of all the information. Although this data is "public", I don't want to give others such an easy way of "stealing" my data.
Ideas & possible solutions:

I was looking at the JWT (Json Web Token) standard to try and secure the public calls to my API and implement it in such a way that I generate a token for "real" users that are on the website, and such limit direct access to public API links.

What do you think? Would this be a possible solution?

I was also reading in some other question on StackOverflow that I could check the HTTP_X_REQUESTED_WITH header from the request, but we all know this can be easily spoofed by an attacker.

Finally, I read a similar approach to "solution" 1) here : http://engineering.talis.com/articles/elegant-api-auth-angular-js/ but I'm not entirely sure that this fits my purpose.

Additional notes:

I don't want to make this bullet-proof, but I also don't want to give people the option to click 2 buttons and get all my data. I know that eventually all the information can be "stolen" (e.g.: by using a web scraper ), but "securing" the system in such a way that people would have to make a bit of an effort is what I have in mind.
I can't really re-model my API too much at this stage, but any ideas would be appreciated

Thanks for taking the time to read my question and I'm looking forward for any feedback.
Comment: You cant really protect public data, because you _want_ the public to be able to see that data. You can try to make it more difficult to get all of the data, but thats all. Just accept that public data is public, _and invest your power in better, productive things_.
Answer: You can limit the abuse of your system in a number of ways, including:

Limit the total number of requests that API will return before requiring CAPTCHA or some other validation method. This can be limited by IP, browser fingerprint, authentication token, etc.
Make it difficult for abuser to guess IDs of products, categories, etc. by using GUIDs or other randomly generated IDs.
Use API management proxy such as Azure API Management for more enterprise level management of the APIs (http://justazure.com/azure-api-management-part-one-introduction/)
Answer: You could try something like:

To access the site anonymous users first need to fill in the captcha to get temporary token.
Add referrer check on.
Limit amount of data anonymous users can view. For instance, first 50 products.

This way everyone who wants to steal your data first need to get anonymous temporary token by filling in the captcha and change referrer.
Answer: Try with DunglasAngularCsrfBundle

Symfony2 RESTful API + AngularJS


Why acoustic-guitar often use direct output instead of amp miking while on-stage?

Question: When I'm performing a song (well, any) on stage, with an acoustic-electric guitar, the soundman tells me that I should use direct output into the mixer, but when I ask for it to be plugged into an amp first (which is a Roland JC-120), he says that it can't lift up the signal.
Why is it? Why does he tell me to go direct output instead of plugging in to an amp?
Answer: Amp miking is basically a ridiculous thing to do: a speaker is, in principle, a device to make an electric signal audible. A microphone is a device to do the opposite. Neither does its job perfectly, in particular it's very hard to design a speaker with truely even frequency response. A purely electrical transmission is obviously much better, cleaner, from a technical point of view: the signal you want comes through virtually unaltered, and interference (AC hum etc.) is much less of an issue as well compared to mic bleed.
There are basically two reasons why it is nevertheless often a good idea to mike an electric-guitar amp:

An electric guitar's signal is not itself "meant to sound well". Back in the day when these were invented, there wasn't even really a notion of how an electric signal "sounded"; sound was always an acoustic thing and if some particular system used electric transmission then the meaning of this signal was defined by what you would plug the guitar into. And because electronics were clunky in the day, it was kept to a minimum in the guitar (from a modern point of view, an absolutely archaic and rather badly-designed minimum) and the sound was adjusted mostly by altering the amp's characteristics. You could say, an electric guitarist is playing two instruments simultaneously: the guitar that is largely a "control device", like an organ manual. The real instrument being – the amp, or organ pipes. So, taking away the "imperfections" of the amp's response is problematic; if you do that you probably need to compensate in some way (e.g. amp modelling).
Electric guitarists tend to make a lot of extra sound adjustments as part of their performance, almost a third instrument. To have proper control about pedal etc. FX, they need to be sure what the audience hears is comparable to what they hear themselves from the amp, including stuff like controlled feedback. The easiest way to ensure this is to have the audience hear the very output of the amp cabinet, via a microphone.

Neither of these points really apply to acoustic guitars:

An acoustic guitar is, well, an acoustic instrument! Under ideal circumstances (studio), it's largely agreed that "correct" sound is always the direct sound from the guitar, as you can only capture with your ears or a microphone. Pickup systems generally strive to approximate this as closely as possible (not in some vague "so-it-sounds-well-through-some-particular-amp" sense, but in the modern sense of: the electric signal is similar to what a microphone might emit, and when you plug into a good (almost-linear) PA / monitors / headphones, it'll sound similar to the original guitar itself).
Most acoustic guitarists don't use a great lot of effects, only gentle "thickeners" like reverb and chorus, set up more or less always the same way. You thus don't really need fine-control over these effects during the performance; indeed, IMO the best thing is if the engineer sets them up from the FOH.

So really, the main purpose of an acoustic guitar amp is as a monitor for your playing on the guitar. Now, that's in fact not a trivial task, mostly because acoustic guitar has to deal with uncontrolled-feedback problems much more than in the electric. Acoustic-guitar amps tend to focus on surpressing feedback quite a lot, and that means

You want a frequency response without peaks that might resonate too strongly. Colourations like electric amps do are basically out simply for that reason. This point can also make the designers put less focus on response in the time domain. Time unsharpness, even if it's ok through a single localised amp, can become more of a problem when combined with a PA and lots of extra reflections, in particular for a wide-band signal like acoustic guitar (compared to more midrange-focused electric guitar).
Feedback-problematic ranges are often cut away rigourously. That's ok if you only need a sound that tells you how to play best, but for the audience it can sound more natural if these ranges are actually kept.

In summary: the reasons why you'd mic an electric amp don't apply (or indeed apply negatively!) for acoustic guitars. Therefore, I too would very much hesitate to mike an acoustic-guitar amp, and instead opt for either a good DI box, or the amp's built-in direct out.
Answer: Feedback, bleed, clarity in the mix. All these apply to both miking an amp and miking the guitar directly without using an amp. These apply to using microphones in general, in any instrument, with or without amps involved.
It depends on the venue (dimensions, materials, shape), the equipment (mics, amps, PA, monitors), and the performance (# of instruments, type of instruments, the mix). In many scenarios, there is a very big potential of feedback. It doesn't need to be a complex scenario. One guitar alone can have problems in a small and reflective venue (both standing waves and reflections being an issue).
Mixing engineers know this, and they often recommend to use direct out in all or some instruments. It also makes mixing simpler, since you don't have to worry about bleeding (which again, depending on the scenario, can be a big issue).
When he said that "it can't lift up the signal", I'm sure he meant that he can't bring the guitar to the amplitude levels he wants because it would induce feedback. This is why feedback can impact your performance even if it's not manifested as feedback, it will be manifested as a limitation of volume (which will vary among mics and instruments), this will be reflected in the mix. Some instruments won't be able to sound loud enough to clearly be heard (this is because feedback will be triggered at the same volume as the instrument needs to be heard through the mix).
What might have happened there is that the soundman noticed that he wouldn't be able to capture the guitar correctly with a mic (volume, tone, dynamic, whatever), and he considered that by using line out he could achieve a better individual sound and/or mix as a whole. It's a pros and cons game. You lose the guitar amp, but you gain in other areas. How good is miking your amp if the audience won't be able to hear it? At that point it really doesn't matter how beautiful it sounds, all the details will be lost since it won't be able to sound loud enough, or the details are being masked by other things going on around the mic (as good isolation is not always possible).
If you find yourself in this situation a lot, and you don't like the sound of raw line out or whatever process the soundman chooses, do yourself a favor and have amp or speaker-mic modeling as an option, as a plan B, in your performance. There are a lot of options out there, in both hardware and software form. This way if amp miking can't be done, you will still be able to have the amp sound.
The most popular sepeaker-mic simulator (that will simulate the speakers and mic combo, but not the amp), is Hughes & Kettner's Redbox. You feed it with your amp's output, and it simulates being the speakers and mic. I see this one the most often since it's inexpensive, easy to use, and it's hardware (doesn't require you to carry a laptop around).
For amp-speaker-mic simulator there are a lot of options. The most populars are Native Instrument's Guitar Rig, Waves' GTR, and IK Multimedia's Amplitube.
Answer: Get an LR Baggs Para-Acoustic DI and never haul your amp again. Ever! We usually do our own sound system in our acoustic duo. I DI both my keyboard and my acoustic Breedlove Atlas Black Magic. It has a built in LR Baggs Piezo pickup and the Para-Acoustic DI box uses Phantom power from the mixer. It's an active DI and that is what you want. I can color the sound as there are EQ's on the DI as well. I also run a Godin A6 ultra through it as my second guitar. I pump both my keyboard and guitar back through our monitor along with vocals. Works slick! Dump the amp man! You don't need it!
Comment: That's actually what I do too: my cello runs through a Para-Acoustic DI. No amp on stage. **But** I rely completely on in-ear monitoring, if it weren't for that then I _would_ use an acoustic amp. Wedge monitors are unbeatable for vocals; but for acoustic instruments they're at best _ok_, often much more prone to feedback problems than a good acoustic amp. — Aside... how does this post actually answer the question?


Spring Not Initializing - App not starting

Question: java.lang.IllegalArgumentException: Could not find class [org.springframework.cloud.netflix.feign.FeignAutoConfiguration]
Getting this error while running the Spring boot app. I have added the pom and the error log here.
Tried changing from feign to openfeign but still won't work.
I have a dependency on sleuth for using 1.3.4.RELEASE version since I am trying to use SpanAccessor which has been deprecated after 2.0.0X
This is my pom
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://maven.apache.org/POM/4.0.0"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <packaging>pom</packaging>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.5.RELEASE</version>
        <relativePath/>
    </parent>

    <groupId>com.gdn.gamification</groupId>
    <artifactId>blibli-gamification-parent</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>blibli-gamification</name>

    <properties>
        <common-module-version>0.0.1-SNAPSHOT</common-module-version>
        <java.version>1.8</java.version>
        <commons-lang3-version>3.3.2</commons-lang3-version>
        <spring-sleuth-version>1.3.2.RELEASE</spring-sleuth-version>
    </properties>

    <modules>
        <module>model</module>
        <module>service-api</module>
        <module>service-impl</module>
        <module>dao-api</module>
        <module>dao-mongodb</module>
        <module>feign-client</module>
        <module>outbound-api</module>
        <module>outbound-impl</module>
        <module>rest-web</module>
        <module>rest-web-model</module>
    </modules>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Hoxton.SR3</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-sleuth-core</artifactId>
            <version>${spring-sleuth-version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb-reactive</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-webflux</artifactId>
            <version>2.2.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
            <version>2.2.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.12</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>${commons-lang3-version}</version>
        </dependency>

    </dependencies>

    <repositories>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
        </repository>
        <repository>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
            <id>bintray-bliblidotcom-maven</id>
            <name>bintray</name>
            <url>https://dl.bintray.com/bliblidotcom/maven</url>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
        </pluginRepository>
    </pluginRepositories>

</project>

This is the error I am facing
java.lang.IllegalArgumentException: Could not find class [org.springframework.cloud.netflix.feign.FeignAutoConfiguration]
    at org.springframework.util.ClassUtils.resolveClassName(ClassUtils.java:332) ~[spring-core-5.2.4.RELEASE.jar:5.2.4.RELEASE]
    at org.springframework.core.annotation.TypeMappedAnnotation.adapt(TypeMappedAnnotation.java:481) ~[spring-core-5.2.4.RELEASE.jar:5.2.4.RELEASE]
    at org.springframework.core.annotation.TypeMappedAnnotation.getValue(TypeMappedAnnotation.java:401) ~[spring-core-5.2.4.RELEASE.jar:5.2.4.RELEASE]
    at org.springframework.core.annotation.TypeMappedAnnotation.asMap(TypeMappedAnnotation.java:286) ~[spring-core-5.2.4.RELEASE.jar:5.2.4.RELEASE]
    at org.springframework.core.annotation.AbstractMergedAnnotation.asAnnotationAttributes(AbstractMergedAnnotation.java:193) ~[spring-core-5.2.4.RELEASE.jar:5.2.4.RELEASE]
    at org.springframework.core.type.AnnotatedTypeMetadata.getAnnotationAttributes(AnnotatedTypeMetadata.java:106) ~[spring-core-5.2.4.RELEASE.jar:5.2.4.RELEASE]
    at org.springframework.context.annotation.AnnotationConfigUtils.attributesFor(AnnotationConfigUtils.java:285) ~[spring-context-5.2.4.RELEASE.jar:5.2.4.RELEASE]
    at org.springframework.context.annotation.AnnotationBeanNameGenerator.determineBeanNameFromAnnotation(AnnotationBeanNameGenerator.java:98) ~[spring-context-5.2.4.RELEASE.jar:5.2.4.RELEASE]
    at org.springframework.context.annotation.AnnotationBeanNameGenerator.generateBeanName(AnnotationBeanNameGenerator.java:77) ~[spring-context-5.2.4.RELEASE.jar:5.2.4.RELEASE]
    at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.registerBeanDefinitionForImportedConfigurationClass(ConfigurationClassBeanDefinitionReader.java:160) ~[spring-context-5.2.4.RELEASE.jar:5.2.4.RELEASE]
    at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitionsForConfigurationClass(ConfigurationClassBeanDefinitionReader.java:141) ~[spring-context-5.2.4.RELEASE.jar:5.2.4.RELEASE]
    at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitions(ConfigurationClassBeanDefinitionReader.java:120) ~[spring-context-5.2.4.RELEASE.jar:5.2.4.RELEASE]
    at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:331) ~[spring-context-5.2.4.RELEASE.jar:5.2.4.RELEASE]
    at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:236) ~[spring-context-5.2.4.RELEASE.jar:5.2.4.RELEASE]
    at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanDefinitionRegistryPostProcessors(PostProcessorRegistrationDelegate.java:275) ~[spring-context-5.2.4.RELEASE.jar:5.2.4.RELEASE]
    at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:95) ~[spring-context-5.2.4.RELEASE.jar:5.2.4.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:706) ~[spring-context-5.2.4.RELEASE.jar:5.2.4.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:532) ~[spring-context-5.2.4.RELEASE.jar:5.2.4.RELEASE]
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:141) ~[spring-boot-2.2.5.RELEASE.jar:2.2.5.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:747) [spring-boot-2.2.5.RELEASE.jar:2.2.5.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) [spring-boot-2.2.5.RELEASE.jar:2.2.5.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:315) [spring-boot-2.2.5.RELEASE.jar:2.2.5.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226) [spring-boot-2.2.5.RELEASE.jar:2.2.5.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1215) [spring-boot-2.2.5.RELEASE.jar:2.2.5.RELEASE]
    at com.gdn.gamification.rest.web.GamificationApplication.main(GamificationApplication.java:14) [classes/:na]
Caused by: java.lang.ClassNotFoundException: org.springframework.cloud.netflix.feign.FeignAutoConfiguration
    at java.net.URLClassLoader.findClass(URLClassLoader.java:382) ~[na:1.8.0_231]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:418) ~[na:1.8.0_231]
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:355) ~[na:1.8.0_231]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:351) ~[na:1.8.0_231]
    at java.lang.Class.forName0(Native Method) ~[na:1.8.0_231]
    at java.lang.Class.forName(Class.java:348) ~[na:1.8.0_231]
    at org.springframework.util.ClassUtils.forName(ClassUtils.java:282) ~[spring-core-5.2.4.RELEASE.jar:5.2.4.RELEASE]
    at org.springframework.util.ClassUtils.resolveClassName(ClassUtils.java:322) ~[spring-core-5.2.4.RELEASE.jar:5.2.4.RELEASE]
    ... 24 common frames omitted

Process finished with exit code 1

Answer: If you use spring-sleuth-version 1.3.2.RELEASE you should include this dependency:
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-feign</artifactId>
    </dependency>

However, this has no sense if you want to use openfeign (spring-cloud-starter-openfeign).
So... my advice is use spring-sleuth-version 2.x.x.RELEASE and follow https://github.com/spring-cloud/spring-cloud-sleuth/wiki/Spring-Cloud-Sleuth-2.0-Migration-Guide
It seems that the problem is spring-sleuth-version 1.3.2.RELEASE needs org.springframework.cloud.netflix.feign.FeignAutoConfiguration which is available in the dependency I've mentioned before.
Greetings.