Stretching for a guitar intro

Question: I'm having a really hard time trying to play the intro to Ballroom Blitz by Sweet on guitar.
The intro riff looks like this:

    D 9 11 12 11 9
    A 7  7  7  7 7

While I can definitely hit the first two, stretching for the 7/12 difference is incredibly difficult. Are there exercises or stretches I can do to make this easier, or is that considered a physically difficult stretch for smaller hands?
Comment: You can do stretching exercises, but please don't ever overdo them. I had quit playing for 3 months after doing stretching exercises to the point where I had a constant ache in my hand
Comment: To add to @DaveHalsall, If it hurts even the slightest little bit, then stop. There are not allot of nerves surrounding those tendons and muscles, from what I have been told. That implies that anything you feel in your hand muscles is something to take seriously.
Answer: That is in fact a stretch but perhaps not impossible - even for small hands.
One thing you must be sure you are doing is correctly positioning your fretting hand on the neck for that type progression involving a maximum stretch.  You will probably find it easier to make the stretch if you position your thumb near the center of the back of the neck and shift it closer to the body of the guitar so that when you are playing the 7th fret on the A string your thumb is actually under the 8th or 9th fret.  This will cause your hand to pivot or rotate in the direction of the distant 12th fret and make it easier to reach with your pinkie (yes you will have to use your pinkie).
To help develop more flexibility you can do some simple stretching exercises that you can do before every practice session.  Here is a good video on YouTube that has been highly rated and will give you some ideas about a safe stretching routine.  Be sure you warm up the muscles in your hands before you stretch.

After doing some warm up exercises and going through your stretching routine, you should practice playing the intro riff.  Until you improve your flexibility it might be all you can do to reach the 9 - 12 fret stretch.  But it should become easier over time.  It might take weeks of intentional stretching prior to  every practice session before you see noticeable gains.  Be patient.
Once you are able to make the stretch more comfortably - practice playing the riff - starting at a tempo that allows you to play it fluidly with the correct timing between notes.  Gradually speed up the tempo as you master the riff at each successive speed.
The good news is, if you use a desire to play this riff on the A and D string as a goal, and work towards accomplishing it - your efforts will be rewarded with an ability to play many more riffs with similar stretches.
On the other hand, if after doing your best to increase your flexibility and ability to make the stretch - you still come up short (no pun intended), you might have to find a different place on the fretboard to play the riff where the stretch is not quite so great (as Dom suggested in his excellent answer).
But I believe you will be able to master the stretch - and in so doing - open up a world of other riffs you will be able to do.
Good luck improving your skills.  It's a journey that never ends - enjoy the journey!
Comment: There's a blank space where the video needs to be!
Comment: @Tim  I see the video and clicked on it and it plays.  Not sure what browser you are using.  If anyone else is having problems seeing the video I hope they will let me know so I can see what the problem is.  Unfortunately I can't duplicate the issue.
Comment: Magic - today it's on!
Answer: In general on guitar you have a lot of options about where you can play something. Take advantage of being able to play the same thing on other strings. Instead of just using the A and D string like you are currently doing, you can do this:

    G -  8  9  8  -
    D 9  x  x  x  9
    A 7  7  7  7  7

You also have the option of instead of playing it on the A and D string play it on the E and A string instead where you would play:

    A 14 16 17 16 14
    E 12 12 12 12 12

This high on the neck the stretch is much easier. The tone however this high on the neck may not be what you want. Try both see what feels and sounds best.
Comment: This is right and good to know, but both of these options are probably not optimal in terms of sound and groove. It's certainly a good skill, being able to play that typical Rock'nRoll pattern as the OP has it in the tab; I thing that version is best in particular for playing with a lot of overdrive.
Answer: I have three tips for you, and the third one works for most people with smaller hands:

As a final goal, try to play that riff in the seventh position, as you've tabbed it out. All other theoretically possible options won't give you the right sound. This is an important standard riff that is worth to learn well.
As an exercise, play the same riff a few frets higher where it feels more comfortable and work your way down to the seventh position. This may take some time.
If you have small hands it will help to play the note b on the d-string (9th fret) with you second finger instead of with your third finger. In this way you will distribute the stretch between your index finger and your pinky. Your index finger should touch the high e-string around the 8th fret (not the 7th!), so slant your index finger instead of trying to keep it parallel to the frets. You can figure out the hand position that works best for you by just pressing the A-string with your index finger at the 7th fret, and the d-string with your pinky at the 12th fret. I'm pretty sure that your second finger will hover above the 9th fret, and your thumb will be more or less behind your second finger in the middle of the neck. If you put down the second finger on the 9th fret of the d-string you will finally be able to play that riff with fingers 1, 2, and 4.
Answer: I don't have time for a long careful answer, but...
If you do most of your "stretching" between your first and second finger you will find a larger reach than if you worried about making space between each finger.
Further, if you place your pinkie (fourth finger) in a comfortable position and reach back with your first finger (stretch with your first finger instead of your pinkie) you will find you are able to reach farther.
Note that with such a stretch your first finger will end up landing more on the side of your finger.
Spend some time practicing scales with extra space between the first and second finger to get used to (controlling) it.
Answer: Why stretch?  Instead use an alternating tuning.  There is no realistic way a musician on stage would do something like that; it takes a lot of effort to do and sounds awful if it doesn't work.  I used this tuning instead
E A D G B E
becomes
E A E G B E
The intro would be something like this:

D 9 11 12 11  9
A 7  7  7  7  7

becomes

E 7 9 10 9 7
A 7 7  7 7 7

The verses also have an even more exceptionally insane stretch such as

D 7 7 9 9
A 5 5 5 5

becomes

E 5 5 7 7
A 5 5 5 5

This makes the chords no more than double stops.
The pre-chorus might seem wonky at first but isn't asking something ridiculous:

D   7
A 7 7 7 7
E 5 5 5 5

becomes

E   5
A 5 7 5
E 5 5 5

IMHO, This makes it seem a little easier to digest and play. And the string tones are close because they are played on the same string as it is tabbed.

Stretching for a guitar intro


Problems with Shaders in OpenGL

Question: I'm trying to use stuff like glShaderSource in C++.
Visual Studio says that functions like glCompileShader or glCreateProgram dont exist.
I use FreeGLUT to include OpenGL. Does anybody have an idea how I can fix this?
Answer: On windows, anything beyond GL1.1 must be loaded via the extension mechansim. The most convenient way to do so is by using a GL loader like glew.

Problems with Shaders in OpenGL


Entity Framework 6: método de remoção não funciona

Question: Estou tentando excluir um objeto utilizando o repository pattern, mas o problema é que ao chamar o método para a remoção não acontece nada, nem lança exceção.
FinanceiroController.cs:
<code>[HttpPost]
public ActionResult DeleteConfirmed(int id)
{
    var financa = _financeiroApp.ObterFinanca(id); // Aqui retorna o objeto sem nenhuma exceção.
    _financeiroApp.Remover(financa);

    return RedirectToAction("Index");
}
</code>
RepositoryBase.cs:
<code>public void Remover(T obj)
{
    banco.Set<T>().Remove(obj); // Não remove, mas também não lança nenhuma exceção.
    banco.SaveChanges();
}
</code>
Não consigo entender, pois ao obter o objeto ele fica dentro do contexto e, sendo assim, deveria ser removido sem nenhum problema.
Comment: Já tentou dar um `contexto.SaveChanges();` após remover o objeto?
Comment: pode mostrar como está a declaração da sua Classe RepositoryBase ?
Comment: Tentei sim Diego, tinha esquecido de colocar aqui. Já editei.
Answer: Se seu objetivo é excluir, você pode altera o seu Remove por DeleteObject
ObjectContext.DeleteObject(entity) marca a entidade como excluídos no contexto. (EntityState é excluído depois disso.) Se você chamar SaveChanges depois o Entity Framework envia uma instrução SQL DELETE para o banco de dados. Se não há restrições de referência no banco de dados a entidade será excluído, caso contrário, uma exceção é lançada.
Seu EntityCollection.Remove(childEntity), marca o relacionamento entre pai e filho Entity como eliminados. Se o relacionamento tem uma restrição de integridade referencial, chamando o método Remove em um dependentes marcas objeto tanto o relacionamento e o objeto dependente para exclusão. Isto ocorre porque a restrição indica que o objecto dependente não pode existir sem um relacionamento ao pai.
Remover retorna falso quando o objeto especificado não está na coleção.
Raferencia


node:menu tokens not working in Pathauto

Question: I can't get any node:menu-based tokens to work in my Pathauto replacement patterns.  Other tokens, such as [current-user:name] or [node:language], work fine.  But the token I am trying to use, a menu-based token, specifically [node:menu-link:parents:join:/] does not. I've tried a slew of the node:menu-link tokens, such as [node:menu-link:parent:url:path], and they're all being skipped.
When I bulk delete all Content aliases, then bulk update them, I do not get any error messages.  The resulting aliases from my pattern [node:menu-link:parents:join:/]/[node:title] just ends up being the node title.
git status
I've been banging my head against this for days, and in trying to fix it have:

installed Token Tweaks and set the depth to 2
run drush @test ev "token_clear_cache(); incessantly
disabled Menu Firstchild, then when that didn't help...
updated Menu Firstchild to the dev version and applied this patch
applied this Token patch
applied this core (!) patch

Now I'm running:

Pathauto 7.x-1.2+21-dev
Token 7.x-1.5+4-dev
Token Tweaks 7.x-1.x-dev
Menu Firstchild  7.x-1.1+1-dev

An additional detail:
Going to node/[nid]/devel/token for any given page hangs for a while, then displays a blank screen.  It produces three errors like this:
Notice: Undefined property: stdClass::$field_studio_location in addressfield_tokens() (line 219 of /var/www/html/test/sites/all/modules/contrib/addressfield/addressfield.tokens.inc).

This doesn't seem particularly serious, but maybe relevant.
Any ideas? Even pointers on how to debug would be great.
Answer: Just encountered that, after a full debug, it seems that menu_tokens() is not called at all.
  // There is a huge bug with menu tokens not being detected, to fix that, load
  // token include file and force repicking the menu_tokens() function as
  // implementation of hook_tokens()
  module_load_include('inc', 'token', 'token.tokens');
  module_implements('tokens', FALSE, TRUE);

That crappy hack fixed my problem but Why... just WHY ?
So yeah, after a deeper investigation, in module_implements():
  $include_file = isset($hook_info[$hook]['group']) && module_load_include('inc', $module, $module . '.' . $hook_info[$hook]['group']);
  // Since module_hook() may needlessly try to load the include file again,
  // function_exists() is used directly here.
  if (function_exists($module . '_' . $hook)) {
    $implementations[$hook][$module] = $include_file ? $hook_info[$hook]['group'] : FALSE;
  }

Okay, so the only thing that is preventing menu from being picked is the sorting:

if menu is processed before token in this module_implements(), the menu.tokens.inc include file will not be picked as it doesn't exist
if token is before menu, the token.tokens.inc thus menu_tokens() function will be discovered and picked up after

So if you don't want any code, just alter the weight of token and menu so that menu's is higher than token's.
But NO, there is a token_module_implements_alter() that just does that, but it is not called, and that is the thing I couldn't figure out. So the final hack was:
  // Rebuild implementation cache
  cache_set('module_implements', array(), 'cache_bootstrap');
  cache_clear_all('hook_info', 'cache_bootstrap');

Comment: Thanks for the awesome & thorough debugging — I'll have time to implement/test next week.
Answer: FWIW, this was actually caused by the menu not being selected in the Menu Settings of this particular content type. Thanks for the help!


Como criptografar GET e copiar o parametro

Question: Tenho um e-mail de feedback que é enviado para um usuário após o serviço ser completado. Esse email tem 5 links, onde cada um é a nota respectiva do serviço (de 1 a 5).
Quero ao direcionar para a página atualizar no banco de dados, a avaliação do serviço, usando o id do cliente, do prestador, do pedido e a nota.
Para isso usei link como.. /avaliacao.php?prestador=1&cliente=2&pedido=3&avaliacao=4
No PHP, estou usando $_GET['prestador'] pra pegar os parâmetros e defino a variável que será inserida em um banco de dados MySQL, mas não quero que o cliente veja essa url, para ele não alterar da forma que ele quiser.
Como posso fazer? Criptografar? Há outra forma?
Comment: Ja pensou em utilizar `POST`?
Comment: Mas como o @RafaelAugusto disse, seria melhor utilizar o verbo `POST` para este cenário.
Comment: POST não vai garantir segurança, o ideal para evitar a manipulação creio eu, seria um TOKEN unico e exclusivo que já conteria os dados prestador e cliente e pedido e depois de usado, o tal TOKEN não poderia mais ser reutilizado.
Comment: mas daí cada link seria um formulario?
vou usar assim, link1 avaliacao=1, link2 avaliacao=2...etc. Esses links estarão no email enviado
Comment: Não entendi, poderia postar o codigo do seu back end tambem, assim fica mais facil ajudar
Comment: @LeandroMarzullo se vc quiser ofuscar os parâmetros vc pode usar as funções `urlencode()` e `base64_encode()`, depois é só decodificar.
Comment: consegui. fazendo o post igual vc falou, vou postar aqui como ficou, BRIGADÃO!!
Answer: Você pode usar um simples HMAC para verificar se o id permanece inalterado, isso será seguro enquanto ninguém souber a chave utilizada por você, lógico ela deve ser forte e gerada de forma segura, explicarei isto também.
Além disso você deve ter certeza que não se pode obter HMACs de outras contas, caso contrário seria o mesmo que ele ter a chave.

/!\ Não utilize as chaves mencionadas nos exemplos.

Em geral, ficará algo do tipo:
$id = '1234';
// Este é o id do usuário, que deve estar associado de alguma forma segura.

$chave = pack('H*', '07e8796b87caa27d793dbe2ecfa7c85f753a9c920cb5d1394fbc36c20f1755b818c9afe37fb453ebf42724c8670d365ca9f0d12d49e31ea843023126f3174df9');
// Esta sua chave secreta e segura que foi gerada por você.

$hmac = hash_hmac('sha512', $id, $chave);
// Este é o resultado do HMAC de SHA-512.

<form action="avaliacao.php" method="post">

<input name="id" type="hidden" value="<?= $id ?>" />
<input name="hmac" type="hidden" value="<?= $hmac ?>" />

<input type="submit" name="avaliacao" value="1" />

</form>

Depois para verificar se houve alteração:
$chave = pack('H*', '07e8796b87caa27d793dbe2ecfa7c85f753a9c920cb5d1394fbc36c20f1755b818c9afe37fb453ebf42724c8670d365ca9f0d12d49e31ea843023126f3174df9');

if(!isset($_POST['hmac'], $_POST['id'])) {
    echo 'Erro: faltam dados';
    exit;
}

$isHMACValido = hash_equals(
    hash_hmac('sha512', $_POST['id'], $chave),
    $_POST['hmac']
);
// Comparamos de maneira segura e em tempo contante o HMAC enviado pelo usuário e o computado agora.

if(!$isHMACValido){
    echo 'Erro: Dados foram manipulados';
    exit;
}

// Chegou até aqui está tudo certo!
// ...

Qual proteção que isso trás?

Contra alteração do id por um usuário que desconhece a chave.

Como essa proteção é alcançada?

O HMAC é uma opção do tipo H(K⊕opad||H((K⊕ipad)||m), portanto duas mensagens (m, neste caso o id) diferentes resultam em um HMAC diferente. Um usuário malicioso poderá modificar ambos (exemplo, enviar: id=99&hmac=aaaa), mas isto será comparado com o novo HMAC (nós faremos o hmac(id, chave)), óbvio que será diferente da hash enviada pelo usuário.

Isto não tem risco?
Do HMAC...

Ataques de CPA não funcionam, mesmo que o atacante crie milhares de contas (assim tendo vários HMACs válidos para cada conta) ele não terá nenhuma indicio de qual é a chave utilizada.
Ataques de busca exaustiva sempre vão funcionar, porém são 512 bits, isso resulta em mais de 2^512 possibilidades, o que inviabiliza o ataque, ao menos até este momento.
Ataques de busca exaustiva contra a chave também funcionam. Para isso a chave deve ser segura e gerada de um CSPRNG seguro e forte o suficiente, caso contrário ataques de força bruta serão rápidos, utilize também 512 bits de chave.
Ataques de MiTM são válidos. Se não utilizar HTTPS uma pessoa monitorando a rede poderá obter o HMAC do outro usuário, isto não afetaria somente o HMAC, mas todo o sistema.

Da aplicação...

Não deve ser possível o usuário ter acesso aos HMACs outros usuários. O id deve ser unicamente dele. Sua aplicação não deve dizer qual é o HMAC de um X, sendo X enviado pelo usuário, permitir isto anulará toda segurança.
A chave deve ser mantida em segredo e não deve ser conhecido pelo cliente, se a chave for exposta será possível computar HMACs válidos.

Para gerar uma chave segura utilize:
echo unpack('H*', random_bytes(32))[1];

Answer: Conforme o Rafael Augusto Falou, alterei usando o POST, aí ficou assim:
email:
<form action="avaliacao.php" method="post">
<input name="id" type="hidden" value="1" />
<input type="submit" name="avaliacao" value="1" />
<input type="submit" name="avaliacao" value="2" />
<input type="submit" name="avaliacao" value="3" />
<input type="submit" name="avaliacao" value="4" />
<input type="submit" name="avaliacao" value="5" />
</form>

avaliacao.php
<?php

$id = $_POST['id'];
$avaliacao = $_POST['avaliacao'];
echo 'id: '.$id.' - Avaliação: '.$avaliacao.'
';

$conn = new mysqli('localhost', 'user', 'password', 'db');
$sqlverifica = '
SELECT avaliacao
FROM prestadores_avaliacao
WHERE id = '.$id;
$result = $conn->query($sqlverifica);
while($row = $result->fetch_assoc()) {
    $avaliacaoatual = $row["avaliacao"];
    echo "Avaliação Original: ".$avaliacaoatual;
}

if($avaliacaoatual==''){
$sql = '
UPDATE prestadores_avaliacao
SET avaliacao = '.$avaliacao.'
WHERE id = '.$id;
$conn->query($sql);
}

?>

Comment: O POST não muda em nada, continua sendo possível alterar os dados.


Python 3.5.2 FileNotFoundError: [Errno 2] No such file or directory: 'test.txt'

Question: Here is a sample of the code that's causing my issue:
import string

letters = string.ascii_lowercase

offset = ord('a')

def countFrequency(file_handle):
"""Traverse a file and compute the number of occurences of each letter
return results as a simple 26 element list of integers."""
results = [0] * len(letters)
for line in file_handle:   #read line from file
    for char in line:      #read char by char from above line
        char = char.lower()    #cnverting char in lowercase
        if char in letters:    #checking if char exist i letters
            results[ord(char) - offset] += 1

return results

#sorting the both lists frequency and letter list
def sort(ltr,frequency):
for x in xrange(len(frequency)):
    for y in xrange(len(frequency)-1):
        if frequency[y]<frequency[y+1]: # on true swap values
            t=frequency[y+1]
            frequency[y+1]=frequency[y]
            frequency[y]=t
            t=ltr[y+1]
            ltr[y+1]=ltr[y]
            ltr[y]=t

#print the sorted results
for i in xrange(len(ltr)):
    if(frequency[i]==0):
        break;
    print "%s=%d" % (ltr[i], frequency[i])

if __name__ == "__main__":
filename = str(input('Enter file name(e.g. test.txt):'))
#file path
sourcedata = open(filename)
#fucntion return frequency of letters
frequency = countFrequency(sourcedata)
#creating list of letters (a-z)
ltrs= [0] * len(letters)
for i in xrange(len(frequency)):
   ltrs[i]=chr(i + ord('a'))
#sorting the result in descending order
sort(ltrs,frequency)

I am supposed to write a Python program that prompts for an input filename.  The program should open the named file and calculate the frequency of each letter in it, ignoring case. The resulting table should be output to the screen in sorted order.  By "sorted order" I mean that the most frequent letter should be displayed first, followed by the second most frequent letter, and so on.
This is what I got so far but when I try running it and inputting the filename I receive:
sourcedata = open(filename)     #file path
FileNotFoundError: [Errno 2] No such file or directory: 'filename'
What could be casing this error? How do I resolve this issue?
Comment: FileNotFoundError is self-explanatory. Check your filepath.
Comment: You are probably running the program in a different directory than your test file. Try specifying the whole file path.
Comment: You state you are using Python 3 but your code is Python 2. Both versions differ in how they handle input. So which version di you run?
Comment: I am using Python 3
Answer: Use the absolute path (use /Path/to/your/file.txt instead of file.txt).
Using the absolute path is much better than using the relative path because you will not get the FileNotFoundError and it will work in Python 2 and in Python 3.
As @Trenton_m has said,
print "%s=%d" % (ltr[i], frequency[i])

will not work in python 3. You should use:
print('{}={}'.format(ltr[i], frequency[i]))


Stuck in understanding PCA objective function

Question: I am trying to understand the objective function of PCA. Intuitively I understand that we are trying to find the direction where the variance of the projected data points on that direction is maximum.
The formulation of objective function is stated here: https://stats.stackexchange.com/a/10256/176418
But I don't understand the first equation itself. Which is as following:
$$\frac{1}{n}\sum_{i=1}^{n} x_i x_i^T = \frac{X^TX}{n}$$
where each $_$ is a vector of $p$ features and $$ is the matrix such that the th row is $x^T_i$ (data matrix).
How summation of variance of data points ($\sum_{i=1}^{n} x_i x_i^T$) is same as the covariance matrix of the entire data matrix ($X^TX/n$)?
Isn't this summation a scalar? Whereas the covariance matrix would be of size $p*p$, where $p$ is number of features as mentioned in the above reference?
The same thing is also mentioned in here: http://cs229.stanford.edu/notes/cs229-notes10.pdf (page 5), where this summation is called empirical covariance matrix.
Comment: $x_i^Tx_i$ is a scalar, whereas $x_ix_i^T$ is a $p \times p$ matrix
Comment: @DhanviSreenivasan Hmm..is that why they are calling it empirical covariance matrix? It's estimated using average of individual data points. Then the first equation should not have strict equality...
Answer: I suppose, you've made a mistake: $\sum\limits_{i=1}^n x_{i} x_{i}^T = X^T X$  (without $\frac{1}{n}$ term) (below is python example)


Sheaves in Grothendieck Topologies

Question: Let $S$ be a scheme and the category of $S$-schemes be equipped with one of the standard Grothendieck topologies, say étale or fppf.
Let $G \rightarrow H$ be a morphism of abelian sheaves on this site and assume that $H$ is actually an $S$-scheme. But $G$ is only a sheaf.
Now define on the category of $H$-schemes the presheaf
$T \mapsto Hom_H(T,G)$.
This should be a sheaf on the category of $H$-schemes, but why is this?
Answer: Your claim is basically the internal version of the well-known fact that the presheaf
$$U \mapsto \textbf{Top}_B (U, E)$$
where $U$ varies over the open sets of $B$ and $E \to B$ is any continuous map, is a sheaf on $B$ in the traditional sense of algebraic topology.
Now, let $\mathcal{S}$ be an (infinitary) pretopos (i.e. a category satisfying all the exactness requirements in Giraud's theorem but without a small generating family). Let $B$ be an object in $\mathcal{S}$ and let $\mathcal{B} = (\mathcal{S} \downarrow B)$. Let $Y$ be an object in $\mathcal{B}$, and consider the presheaf
$$X \mapsto \mathcal{B}(X, Y)$$
on $\mathcal{B}$. I claim this is a sheaf in the canonical topology for $\mathcal{B}$. Indeed, suppose we have an epimorphism $U \to X$ in $\mathcal{B}$, and $f : U \to Y$ is a morphism in $\mathcal{B}$ with the property $f \circ p_1 = f \circ p_2$, where $p_1, p_2 : U \times_X U \to U$ are the projections of the fibre product over $X$. Now, fibre products in $\mathcal{B}$ agree with fibre products in $\mathcal{S}$, so it doesn't matter too much which category we work in. However, because $\mathcal{S}$ is a pretopos, every epimorphism in $\mathcal{S}$ is the coequaliser of its kernel pair, i.e. the canonical diagram
$$U \times_X U \rightrightarrows U \to X$$
is a coequaliser in $\mathcal{S}$ whenever $U \to X$ is an epimorphism in $\mathcal{S}$. (In other words, every epimorphism in $\mathcal{S}$ is effective.) It is not hard to show that epimorphisms and coequalisers in $\mathcal{B}$ agree with epimorphisms and coequalisers in $\mathcal{S}$; hence, $f : U \to Y$ factors through $U \to X$ in $\mathcal{B}$ in a unique way. A more complicated version of this argument shows that $\mathcal{B}(-, Y)$ satisfies the sheaf condition with respect to general jointly epimorphic families. Thus $\mathcal{B}(-, Y)$ is indeed a sheaf on $\mathcal{B}$.
Now, to get the claim for sheaves of abelian groups, we must show that when all of the objects in question are internal abelian groups, then a homomorphism $f : U \to Y$ descends to a homomorphism $X \to Y$, but this is straightforward enough.
Addendum. I forgot to explain what this has to do with sheaves on a site. Let $\mathcal{C}$ be a subcanonical site, and let $\mathcal{S}$ be the category of sheaves on $\mathcal{C}$. By definition of subcanonical, $\mathcal{C}$ embeds as a full subcategory of $\mathcal{S}$, and it can be shown that the category of sheaves on the slice site $(\mathcal{C} \downarrow B)$ is equivalent to the slice category $(\mathcal{S} \downarrow B)$. (See [Johnstone, Sketches of an elephant, Part C, Lemma 2.2.17].)

Sheaves in Grothendieck Topologies


Operator in $\mathbb R^2$

Question: I am a bit confused, can someone help me with the following?
Is there an operator $T$ in $\mathbb{R}^2$ such that:
$\parallel u \parallel +\parallel v\parallel = \parallel T(u+v)\parallel$ for every $u,v\in \mathbb{R}^2$
Answer: There is no such linear mapping: Take $u=-v\ne0$, then $\|u\|+\|v\|>0$,
but $T(u+v)=0$ be linearity.

Operator in $\mathbb R^2$


How are backup vocals notated in sheet music (score order)?

Question: Many pop songs have a lead singer singing over instrumentals. However, on certain phrases, the singer may be joined by a backup singer who sings the same words and rhythm but harmonizing above. How would this typically be notated in sheet music? For example,

backup vocals on a separate staff...

above the lead vocal's staff (because they are harmonizing above)
below the lead vocal's staff (because they are secondary to the lead vocal), or

backup vocals on the same staff as the lead vocal.

I am not very familiar with vocal music and how it is notated in sheet music. Apologies if I've used incorrect terminology.
Comment: Sheet music for pop notating the original background vocals in the song isn't all that common, in my experience, in no small part because sheet music and the pop genre don't mix very often! That, and I would guess bgv tend to be dubbed in post rather than as discrete voice parts. Still, nice question, and I'm very interested to see how it's notated for popular music in general!
Answer: This is very anecdotal, & I of course can't speak for all productions, but way back in the mists of time [the 80's] I used to do session BVs on occasion. Usually rock rather than pure pop bands, when people wanted what they would at the time call "Queen blocks" - huge vertical cliffs of vocals, from as low to as high as anyone could reach. I had a 3 1/2 octave useful range without falsetto, so it was a good time to be a singer for me.
I never saw a dot written, ever.
You walk in, they play the track, twice if you're lucky. then as that's going, someone will be saying - 'Yeah, right about here we need a bit af doubling on the lyrics, then you get an ooooh, oooeeoooh, to bridge that to the next line. Wanna give it a go?'
…and then you're on. Make it up as you go. The Producer will pull you up if there are better ideas or changes of mind in the control room.
Once you've got the basic structure down, you'll get instructions such as, "Let's get another couple over that, then one under. When we get to the big stuff in the chorus we're gonna block it up all the way' This will involve stacking maybe 6 or 8 different parts, depending on the complexity, with 2, 3 or four tracks of each to keep it smooth.
in some cases you start with 'the obvious' lines, the notes that make up the chord & transition with the melody. Then often after that, you get some 'squeeze & thicken'. This is the tough one sometimes. You try to find every possible note in the extended chord that hasn't been used yet;) Adding 4ths, 6ths & 9ths etc to otherwise solid majors to create 'cornflour'… thickener.
People don't really notice these notes, they tend to be buried back in the mix. But they generate a smooth 'wall' of vocals, very useful in many genres to 'thicken & glue' the BVs into a solid block.
All of this comes through 'skill & judgement', casual conversation, ideas from the producer &/or artist & a lot of trial & error.
I can't link to anything I did back then, but this is a snippet of something along those lines I did maybe 15 years ago, which I own copyright on, as an example of this 'fill every hole/cornflour' approach. It's just two simple choruses, one with & one without instrumentation. The block isn't quite as wide as we would be doing back then, but it gives you an idea.
https://soundcloud.com/graham-lee-15/norton-disney-weightless-excerpt
Answer: Standard score order is that solo voice(s) are placed above the choral (or, in this case, backup) voices. By that standard, the lead vocals would be on the top staff, and the backup vocals would be on one or more staves below that. It would be your choice whether to combine two or more of the backup voices on a single staff (e.g., one staff for high voices; one staff for low voices).
Example from an orchestral score: Beethoven Symphony #9, Movement 4, Measure 83.

(IMAGE SOURCE: IMSLP)
Example from a choral score with soloists: Eric Whitacre, Alleluia, Measure 1.

(IMAGE SOURCE)
Example from a reduced (piano) score: Lin-Manuel Miranda, "Alexander Hamilton" from Hamilton, Measure 32.

(IMAGE SOURCE: Lin-Manuel Miranda, Hamilton: An Americal Musical — Vocal Selections [Hal Leonard, 2015].)


error : The method parse() is undefined for the type HttpResponse

Question: When I try to run some code, I am getting the following error:
The method parse() is undefined for the type HttpResponse

Here is my code:
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = client.execute(post);
strResp = EntityUtils.toString(response.getEntity());
Document document = response.parse();

Comment: Are you trying to do [this](http://stackoverflow.com/questions/11206127/convert-http-response-to-xml-document-in-java)?
Answer: There is no such method parse() for HttpResponse
Answer: Why do you want to parse an HttpResponse ?
It doesn't exist... Parse exist for a String
Maybe you wanted to do :
Document document = strResp.parse();

Which would work if strResp is a String. But maybe that's not what you want.
I do it like this (I found it on the web and it works perfectly for me) :
    public String getXmlFromUrlHttp(String url)
{
    String xml = null;

    try {
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpGet httpPost = new HttpGet(url);
        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        xml = EntityUtils.toString(httpEntity);

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return xml;
}

Then you parse the result of the function ;)
Answer: I think you should get a few solutions from: How to parse a xml type HTTPResponse in Android
Probably something like:
...
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = client.execute(post);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
InputStream is = response.getEntity().getContent();
Document doc = db.parse(is);


Keep Footer at the Bottom of the Page w/ Andromeda Theme

Question: I recently setup a site using the Andromeda theme and love it! However the only issue I have is that when a page doesn't have much content in it the footer does not stick to the bottom of the page. I have tried to implement some of the css answers I have seen on this site with no luck. Does anyone else know how to implement this?
Comment: Which css answers on this site?  Please provide links.
Answer: You should be able to do this with CSS using
<code>position: fixed;
</code>
On the footer and placing it on the bottom of the screen.


matriz [l][c] The local Variable c may not have been initialized

Question: bom dia, sou iniciante em java e estou estudando sobre matrizes, estou fazendo uma aplicação simples onde devo preencher uma matriz e depois somar seus elementos, porem estou tendo um erro na hora mostrar a matriz depois de preenchida. Abaixo segue o inicio do código
import javax.swing.JOptionPane;

public class somaMatriz {
    public static void main(String[] args) throws Exception {

        int[][] mat = new int[5][5];
        int l,c,soma;

        JOptionPane.showMessageDialog(null, "Bem vindo ao software somaMatriz v_1.0");
        JOptionPane.showMessageDialog(null, "Inicializando a Matriz..");

        for (l=0; l<5; l++){
            for (c=0; c<5; c++){
               mat[l][c] = Integer.parseInt(JOptionPane.showInputDialog("Entre com o valor da posição [" + l +"][" + c +"]"));
            }//fim-para-c
        }//fim-para-l

        JOptionPane.showMessageDialog(null, "Matriz finalizada");
        JOptionPane.showMessageDialog(null, mat[l][c]);
    }
}

nessa ultima linha esta dando o erro "The local variable c may not have been initialized"
ja tentei na declaração inicializar com valor 0 e o erro continua
alguem poderia me explicar o porque?
Comment: Mas por que vc quer imprimir `mat[l][c]` fora do loop? Não faz sentido, porque depois que o `for` termina, o valor de `l` e `c` é `5`, então vc estará acessando uma posição inválida de `mat`.
Answer: Para quem ver este post, consegui descobrir o problema
para mostrar a matriz em questao não basta apenas utilizar o comando
JOptionPane.showMessageDialog(null, mat[l][c]);

é preciso criar uma estrutura de repetição para poder pegar todos os valores da matriz e assim poder imprimir
meu código ficou assim
import javax.swing.JOptionPane;

public class somaMatriz {
    public static void main(String[] args) throws Exception {

        int[][] mat = new int[5][5];
        int l,c,soma;
        String exibir = "";

        JOptionPane.showMessageDialog(null, "Bem vindo ao software somaMatriz v_1.0");
        JOptionPane.showMessageDialog(null, "Inicializando a Matriz..");

        for (l=0; l<5; l++){
            for (c=0; c<5; c++){
               mat[l][c] = Integer.parseInt(JOptionPane.showInputDialog("Entre com o valor da posição [" + l +"][" + c +"]"));
            }//fim-para-c
        }//fim-para-l

        JOptionPane.showMessageDialog(null, "Matriz finalizada");
        for (l=0; l<5; l++){
            exibir += "[ ";
            for (c=0; c<4; c++){
                exibir += mat[l][c] + " | ";
            }//fim-para-c
            exibir += mat[l][c];
            exibir += " ]";
            exibir += "\n";
        }//fim-para-l
        JOptionPane.showMessageDialog(null, exibir);

    }
}


Downloads from Bamboo server are slow, how can I debug this?

Question: I have a Windows box running Bamboo, a continuous integration server. I can download files from it over HTTP, but they're really slow, like 80 kbps slow. I don't have any speed issues copying files between the machine and network shares.
What are some steps I can take to debug this problem? I really don't know where to start.
Answer: We migrated Bamboo to run under Tomcat on Windows Server 2008 and the problem went away.


Failed to execute 'createPattern' on 'CanvasRenderingContext2D': Source image is in the 'broken' state

Question: I want to use canvas in react and typescript, there is my code:
it's render html:
public render() {
    return (

            <input type="radio" id={'repeatRadio'}/>sdf
            <canvas id={'canvas'} width={600} height={300}>
                canvas not supported
            </canvas>

    );
}

It's componentDidMount function:
 public componentDidMount() {
        this.initCanvas();
    }

    private initCanvas = () => {
        const canvas = document.getElementById('canvas') as HTMLCanvasElement;
        const ctx = canvas.getContext('2d') as CanvasRenderingContext2D;
        const repeatRadio = document.getElementById('repeatRadio') as HTMLElement;
        const image = new Image();

        image.src = 'test.jpg';
        repeatRadio.onclick = () => {
          this.fill(image,'repeat');
        };

        ctx.lineJoin = 'round';
        image.onload = () => {
            this.fill(image, 'repeat');
        }

    };
    private fill = (image: any, str: string) => {
        const canvas = document.getElementById('canvas') as HTMLCanvasElement;
        const ctx = canvas.getContext('2d') as CanvasRenderingContext2D;
        debugger;
        const pattern = ctx.createPattern(image,str);

        ctx.clearRect(0,0,canvas.width,canvas.height);
        ctx.fillRect(0,0,canvas.width,canvas.height);
        ctx.fillStyle = pattern;
        ctx.fill();

    };

It's can run before I click input radio, but It's appear err like title when i click.
I add onerror code:
image.onerror = (message) => {
    console.error(message);
}

I get info as fallow:

But I can't find something useful.
Comment: check your dev tools' network panel, it will probably tell you in which way it failed to load your resource.
Comment: my image is well, and I test another image is same error, others, image's path is right.
Comment: I see the network panel, and the image resource is 304, I don't know what lead this.
Comment: I disable caching and get 200. But also get same error when I click.
Comment: Are you able to load this same image by directly setting its url in the address bar? What if you add `image.onerror = console.error`?
Answer: Image will have to be imported in react using import clause.
import TEXTURE_IMG1 from '../textures/honey_im_subtle.png'

Once imported you can assign it 'src' property.
    var img = new Image();
    img.src = TEXTURE_IMG1;
    var texturePatternBrush = new fabric.PatternBrush(this.canvas);


Use DrawText to update label

Question: I am currently writing a program in c++ (no MFC) and want to update a label (win32 static control) using the win32 DrawText function. However when i call the function nothing is written to the label. I use the following code:
    HDC devCon = ::GetDC(GetDlgItem(IDC_TITLE).m_hWnd);
    RECT rect = {10, 10, 100, 15};
    ::DrawText(devCon, _T("TEST DC TEXT!!!"), -1, &rect, DT_NOCLIP);
    ::ReleaseDC(GetDlgItem(IDC_TITLE).m_hWnd, devCon);

As you see with the GetDlgItem(...) I am using ATL but that should not be a problem in my opinion. When I specify NULL in the GetDC method the text is drawn in the upper left corner of the screen as it is supossed to be since the method return the DC to the entire screen.
Why doesn't this work with the DC of the label?
Hope you folks can help me.
Answer: If you want to draw the text manually because setting the control text doesn't do what you want, then you need to tell Windows that you're doing that. Otherwise the control will draw itself over whatever you do whenever it needs to be redrawn.
To draw it yourself, mark your control as owner draw by setting the SS_OWNERDRAW style, and then handle the WM_DRAWITEM message to draw it in the window procedure of the parent window, or subclass the window and handle the WM_PAINT message in your new window procedure.
Answer: I guess that the text is drawn but at the next window message is set to the default text.
Try to set the text with SendMessage(..,WM_SETTEXT,...);
Comment: WM_SETTEXT does not work for me because for some reason the label does not show ellipsis if the text is to long like it is supposed to do.
Comment: Forget what I just said, it works perfectly!
I just have the problem that I want to display two line text with end ellipsis and MSDN says you have to use DrawText for that.
Answer: Use SetDlgItemText() to set the text for the control.
You are trying to paint directly onto the static control's device context.
This is not going to be so simple, because:

the control will repaint itself whenever it's update region is invalidated
usually the controls share the device context with the parent window, so what you are getting in GetDC(...) is actually your dialog's device context.

So, use SetDlgItemText, or SetWindowText to set the text of the window.
To use a custom font (or set the text/background color), handle the WM_CTLCOLORSTATIC message in your WindowProc.

Use DrawText to update label


mod_fcgid, perl script output going to apache error_log

Question: I'm trying to get an old Perl script running again after installing mod_fcgid.  I had to install mod_fcgid for a new client, but it seems to have broken some of my other cgi scripts.
When going to the page, its now a 500 error.  I checked the error log, and the output from the script is in the error log... so the script is running but for some reason it still delivers a 500 Internal Server Error to the browser...
HTML headers are the first thing printed... so I'm not really sure why this error is occurring.
The Error Log:

[omitted:html output]
[Wed Dec 08 08:59:18 2010] [warn] (104)Connection reset by peer: mod_fcgid: read data from fastcgi server error.
[Wed Dec 08 08:59:18 2010] [error] [client x.x.x.x] Premature end of script headers: www_protect.cgi, referer: http://www.mywebsite.net/
[Wed Dec 08 08:59:21 2010] [notice] mod_fcgid: process /www/sites/somescript.cgi(6747) exit(communication error), terminated by calling exit(), return code: 0

fcgi.conf:

  AddHandler fcgid-script .fcgi .cgi
  #SocketPath /var/lib/apache2/fcgid/sock
  IPCConnectTimeout 45
  IPCCommTimeout 20
  OutputBufferSize 0
  MaxRequestsPerProcess 500
  IdleTimeout 3600
  ProcessLifeTime 7200
  MaxProcessCount 8
  DefaultMaxClassProcessCount 2

# Sane place to put sockets and shared memory file
SocketPath /var/run/mod_fcgid
SharememPath /var/run/mod_fcgid/fcgid_shm
Answer: Your configuration is telling Apache to serve all CGI scripts under FastCGI, which isn't possible. FastCGI isn't directly compatible with CGI scripts.
You should move the AddHandler directive into your client's VirtualHost, so it doesn't apply to the whole configuration, e.g.
<VirtualHost *:80>
    ServerName clienthost.com
    ...
    AddHandler fcgid-script .fcgi .cgi
</VirtualHost>

If your client's scripts are on the same VirtualHost as your other cgi scripts, you can restrict the FastCGI handling to a specific Location or Directory, e.g.
<Location /clientarea>
    AddHandler fcgid-script .fcgi .cgi
</Location>


Existe alguma forma de inserir trechos de códigos pré-definidos no Visual Studio?

Question: Gostaria de saber se o Visual Studio possibilita gerir trechos de código para fácil inserção em arquivos durante uma edição. Ou se existe algum add-on que faça isso.
Exemplo:
Tenho esse trecho de código que sempre utilizo:

A ideia seria gravar esse trecho de código e inseri-lo facilmente sempre que necessário, com poucos cliques.
Answer: Sim, é possível!
O Visual Studio permite a criação de trechos de código personalizados. Para isso é necessário criar um arquivo XML usando a estrutura pré-definida pelo Visual Studio.
Veja todos os detalhes no MSDN.
Aqui vai um pequeno passo-a-passo de como criar um snippet de código personalizado.

Abra o menu Tools e entre em Code Snippet Manager ou acesse o gerenciador direto pelo atalho Ctrl + K + B
Crie um arquivo XML com esta estrutura
<?xml version="1.0" encoding="utf-8"?>
<CodeSnippets
    xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
    <CodeSnippet Format="1.0.0">

            <Title></Title>

        <Snippet>

                <![CDATA[]]>

        </Snippet>
    </CodeSnippet>
</CodeSnippets>

No atributo Language da tag Code coloque a linguagem
Dentro dos colchetes de CDATA coloque o código do snippet
Salve o arquivo com a extensão .snippet
Abra o gerenciador (do passo 1) e clique em Import
Answer: Sim, é possível. Isto chama-se Code Snippet e tem extensiva documentação.
Se não for suficiente existem plugins no marketplace do VS.


How to resample friendships when bootstrapping by individuals

Question: Sheesh, I'm really confused.
So, I have a dataset of individuals, and a dataset of their friendships. I want to test whether a particular (numeric) variable is correlated among friends. To do this,
I am bootstrap resampling individuals.
My original data looks like:
NAME  VARIABLE
Joe   1
Sam   3
Pete  2
...   ...

with a friendship network like:
FRIEND1   FRIEND2
Joe       Pete
Joe       Sam
Sam       Jill
...       ...

My basic statistic is created by correlating friend 1's variable with friend 2's variable. That is, I join my tables to create:
VARIABLE1 FRIEND1 FRIEND2 VARIABLE2
1         Joe     Pete     2
1         Joe     Sam      3
3         Sam     Jill     4

Standard errors will be wrong, of course, because each friend may appear many times in the data.
So, I resample individuals with replacement. When I do this, I might get Joe's name 2 times and Pete's name 3 times. I then want to recreate the friendship network and rerun my correlation. By doing this many times, I will get the
sampling distribution of my statistic.
But, how many times should the Joe-Pete friendship appear in the new data? I guess 2*3 = 6 times... is that right?
Examples in R would be welcome, but mostly I want to know how to think about this. (I'm even confused... is it legitimate to resample at individual level, given that by assumption friends' data is correlated... argh!!!)
Comment: It is not clear for me what and why do you want to resample..? Your second question: "But, how many times should the Joe-Pete friendship appear in the new data?" is even more unclear -- bootstrap will give you random number of pairs so what are you counting here..?
Comment: Could you be more specific about what you mean by "correlated among friends"? One possible interpretation--which assumes you didn't really mean "correlated," but meant "dependent"--is that the distribution of unordered pairs of the variables among the friends somehow differs from the distribution of such pairs among non-friends. I suspect you implicitly have in mind some metric to compare values of those variables and that you might mean that the variables tend to be closer between friends than between non-friends.  But I'm just guessing... .  If I'm correct, what is the metric?
Comment: @dash2 "correlation" has a precise meaning in statistics, it implies that a mathematical relation (by default linear) describes well their dependence. Is it really what you look for ? Is the reformulation suggested by whuber acceptable to you ? If not, why?
Comment: Although you might get some useful answers here, what you are trying to do is probably very difficult. I see that "Bootstrap a network, non-parametrically" is one of the items on Cosma Shalizi's list of "Things I wish I knew how to do" in his notebook pages (and he is one of the world's leading statisticians at the moment.)
Comment: To avoid any ambiguity, can you precise if your variable is numerical, categorical or ordinal ?
Comment: @Tim: I am bootstrapping individuals, not pairs. Let's assume that I get Joe's name twice, and Pete's name 3 times. Then, how many times should the Joe-Pete friendship appear?
Comment: @brumar : the variable is numeric.
Comment: @whuber : I simply mean that friends' values are correlated. So, if you made a dataset of friend 1's value, and friend 2's value, with one row for every pair of friends in the _population_, then those values would be correlated. I'll clarify this in the text.
Comment: @brumar I am indeed looking for a linear correlation. I appreciate that there are other forms of dependence, but I am relaxed about that. In this particular case, as often in applied research, more complex forms of dependence, that did not also cause a non-zero correlation, would be implausible.
Comment: @dash2 I fail to see how a linear correlation is imaginable here. I ll suggest to take a mathematical standpoint here. V1 and V2 are symetric (to not say the same variable). Whatever the resampling you are doing you arbitraly organize your friend pairs by choosing which guy has V1 and which guy has V2. Whatever the relation you are looking for between the two, it must respect f(V1)=V2 and V1=f(V2). Among bijective functions, only the identity function can work.
Comment: @brumar: I do not agree. Suppose Pete is friends with Jim Sam is friends with Al; and Tim is friends with Zac. If Pete and Jim are both 6 feet tall, while Sam and Al are 5 feet tall, and Tim and Zac are both 4 feet tall, then there is a positive linear correlation between friends' height. Yes, if height was a deterministic function of friends' height then only the identity function would work, but the relationship is statistical, not deterministic.
Comment: @dash2 the backbone of linear correlation is still a mathematical function. You won't find any suitable $a,b$ where both $X2=aX1+b$ and $X1=aX2+b$ reach statistical significance. From your example, I realized that maybe the friendship relationship you are considering is asymetric. If this is not the case,because I can order the pair as I want and not getting the linear correlation mentioned. Is it the case ?
Comment: @brumar. Here is some R code. `tmp <- data.frame(name = LETTERS, hairlength = 1:26 + rnorm(26));   tmp$friend = LETTERS[c(2:26,1)];   frs <- left_join(tmp, tmp, by = c('friend'='name'));   plot(frs$hairlength.x, frs$hairlength.y); cor.test(frs$hairlength.x, frs$hairlength.y); s <- sample(1:26, 13); frs[s,] <- frs[s, c(3,4,1,2,5)];  plot(frs$hairlength.x, frs$hairlength.y); cor.test(frs$hairlength.x, frs$hairlength.y)` A significant correlation survives randomly permuting friends. That said, the issue you address does have important ramifications - see Manski (1993).
Answer: I don't feel ultra confident on my answer, but I would be interested to be reviewed if necessary. If I were you, I would go for a permutation test because it does not suffer from the non-independence you are pointing. Pick a good statistic that represents the effect you are studying. Something like $$S=\sum_{i,j} |V(i)-V(j)|*I_{i,j}$$ with $I_{i,j}=1$ if $i$ and $j$ are connected (0 otherwise). After computing this statistic for your data-set, do it for each permutation of your data by shuffling the VARIABLE column.
NAME  VAR             NAME  VAR    NAME  VAR    NAME  VAR
Joe   1               Joe   2      Joe   5      Joe   5
Sam   3               Sam   3      Sam   3      Sam   3       ....
Pete  2               Pete  1      Pete  2      Pete  1
John  5               John  5      John  1      John  2
...   ...             ...   ...    ...   ...    ...   ...
Original data-set     data-set1    data-set2    data-set3      ....

In r this can be done with the built-in function sample on the column you wish to shuffle. As we do a permutation test (not a bootstrap procedure) there is no replacement.
For each new data-set, compute your $S_k$ score. If your hypothesis is true, your $S_k$ scores must be most of the time higher than $S$.
Your p-value is the number of times your permuted set get better or equal $S_k$ score than your original S.
Comment: This looks like a good idea--but could you be more explicit about what you mean by "breaking and redistributing"?  The validity of the result appears to rely on exactly how that is carried out.
Comment: This is a good idea and I might well do it. But, I think the original question (how to resample a network?) still deserves a specific answer, because I've seen it done a fair bit.
Comment: I think you are right. But I personally think that there is no general answer. It depends on your goal. You can chose to preserve the structure and only resampling the values (as I did in my answer). This is in line with the sole interpretation of your goal I can come up with. Another goal being given, I guess you can come up with procedures could maybe involve resampling the network itself.


How do I evaluate this summation?

Question: I was wondering how do I solve the summation?
$$\frac{1}{n}\sum_{j=1}^nja_{m,j-1}a_{m-1,j-1}$$
I found it in this link on power towers
http://mathworld.wolfram.com/PowerTower.html
Comment: ??. There is a complete formula around there - what are you missing? (It's nothing to "be solved", it's a computation-recipe)
Comment: @GottfriedHelms what I'm confused about is what the terms in the summation mean.  How do I use these terms to get actual numerical values?
Comment: I would proceed with software Pari/GP to define a function `a(m,n)=if(n==0,return(1));if(m==1,return(1/n!));  ...`. Then I would practically compute a matrix "A" as `A=matrix(16,16,r,c,a(r,c))` or the like (while I'm typing here I cannot see the formula) and after that the next formula in MW shows how to compute an actual value for th powertower of height m as sum using that coefficients of `a(m,n)` which are stored in the matrix plus the other sum. (I hope I didn't confuse you even more...)
Answer: The actual definition is
$$a_{m,n}=
\begin{cases}
1 & \text{if }n=0\\
\frac{1}{n!}& \text{if }m=1 \\
\frac{1}{n}\sum_{j=1}^n j a_{m,n-j} a_{m-1,j-1} & \text{otherwise}
\end{cases}
$$
So to construct this array you can think of $a_{m,n}$ as a function $f(m,n)$ defined recursively as
$$f(m,n)=
\begin{cases}
1 & \text{if }n=0\\
\frac{1}{n!}& \text{if }m=1 \\
\frac{1}{n}\sum_{j=1}^n j\times f(m,n-j)\times f(m-1,j-1) & \text{otherwise}
\end{cases}
$$
with $m,n\in\mathbb{N}$. Evaluating the summation simply requires you to find the values of $f(m,n)$ at $(m,n-j)$ and $(m-1,j-1)$ for every value of $j$.
Comment: Thank You!  I think understand it now.

How do I evaluate this summation?


Key signatures with Quarter Tones

Question: I know how to write the key signatures for any note within the 12-note chromatic scale. I know this doesn't come up very often, but what are some ways to write out key signatures for passages of music in a key center based off of a quarter tone?
For example, I know A major has 3 sharps. What would a key signature look like for A half-sharp major?

I considered simply notating something like "A=453hz" and writing in A, but shifting between tuning systems can get a bit unwieldy (especially if performing on a real instrument) and I'd rather avoid that.
I considered having three "3/2 sharp" glyphs on F, C, and G, and placing a "1/2 sharp" glyph on D, A, E, and B. I noticed, though, that under this system, every microtonal key signature has seven accidentals in it, and a lot of them have "1/2 sharp" and "1/2 flat" signs in the same key signature (example: G 1/2 flat major).
I also considered shorthanding them, writing "3/2 sharp" glyphs on F, C, and G, and leaving the other notes with nothing. One advantage of this is that the visual look of A major is preserved, with the three sharp-ish accidentals, and the performer would know that all the other notes logically must be 1/2 sharp. It would be like reading a normal key signature, then seeing the altered accidental and deducing that everything is a quarter tone flatter than A major.
I'm open to other suggestions (as long as they use some form of microtonal key signatures) as well - there's probably a better system out there that I haven't discovered.
Comment: duplicate of [How are key signatures for quarter tones denoted?](https://music.stackexchange.com/questions/90832/how-are-key-signatures-for-quarter-tones-denoted)
Comment: In particular, the question linked above does not get into quarter tone key signatures at all, instead sidestepping and giving more practical advice. I'm interested specifically in actually representing these keys using a key signature with microtones. I hope this gets reopened.
Comment: I saw that, but I don't think the answers to that question apply to my question.
Answer: In most cases, I'd use A=453.
There are a few reasons for this:
1. As you said, it is easier to notate and keeps it nice and clean
2. Any performer with enough skill to comfortably handle quarter tone notation won't be intimidated by an alternate tuning
3. Many instruments require frequent re-tuning back to A=440 anyway. Unless the musician has perfect pitch, you could just play A=453 as the tuning pitch and they probably wouldn't even notice!
4. If alternate tuning (and quarter tones themselves) are not possible, like on a piano, it is much easier for someone to quickly adapt and make playable (unless, of course, you make extensive use of quarter tone accidentals
Conversely, here are a few reasons you might consider another option:
1. Sheet music packed with lots of quarter tone accidentals can look freaking awesome! :)
2. If much of the song is in a standard key and tuning and you modulate to a half sharp key at some point
Comment: Re the first point #2:  Conversely, many performers who *wouldn't* be comfortable with quarter-tone notation would be able to perform in "A = 453 Hz".  This is because writing "A = 453 Hz" at the top and then writing in your piece in A just makes all of your instruments transposing instruments rather than writing in concert pitch.  This means that the fingerings and such won't change;  the performer just has to "set it and forget it", and it won't bother them unless they have perfect pitch.
Comment: Re the second point #2:  As the flipside of my previous comment, the number of Western-trained performers who would be able to accurately modulate between quarter-tone tunings is probably rather limited, so writing a piece this way may make it harder to get it performed.
Comment: Quarter tones are pretty noticeable, even to laymen. The video game theme "Rude Buster" from *Deltarune* is in F#-G quarter-tone minor or a tuning close to it, and I've read multiple *arrangers* complain about how difficult it was to get the tuning right in their arrangements. (Transcriptions are split between F# minor and G minor.)
Answer: In this video, the semisharps are simply written out completely in the same order as the sharps would be. Later on he uses a combination of semiflats and semisharps while still sticking to the circle of fifths. Although it's in the context of 31 edo, it should still be applicable (and you probably won't need the key signatures with both sharps and flats because in 24edo, the two 12edo chains aren't linked). The description of the video has some resources as well, such as a list of 31edo key signatures and some of the sources that he used.
I don't think there's any existing convention, so you're free to make your own as long as you explain it.
Answer: If you want normal intervals and notes but EVERYTHING out a quarter-tone, yes 'A=253' seems sensible.
Quarter-tones more often occur as accidentals within a normal chromatic A=440 framework.  And there currently seems more interest in alternative tuning schemes producing 'pure' intervals than in quarter-tones as such.
Either way, they are outside the scope of standard key signatures. If you want to invent a custom notation, be sure to explain it!
Answer: If writing sheet music for A half sharp major, I would personally put a half sharp motif on all 7 notes at the beginning of the clef as well as the 3 sharps on F, C and G, as these 3 notes need to be sharpened by three quarters of a tone. I don't know if this is correct, but at least I would understand it?

Key signatures with Quarter Tones


Migrate error: Call to a member function count() on a non-object

Question: I am trying to implement a user migration with the migration module but am getting this error:

Fatal error: Call to a member function count() on a non-object in
  E:\wamp\www\website\sites\all\modules\migrate\includes\migration.inc
  on line 946

here is my migrate class:
abstract class CakeBaseMigration extends Migration {
  public function __construct($arguments) {
    parent::__construct($arguments);

    $this->team = array(
      new MigrateTeamMember('Chris', 'firstname.lastname@example.com',
          t('developer')),
    );

    Database::addConnectionInfo('for_migration', 'default', array(
      'driver' => 'mysql',
      'database' => 'databasename',
      'username' => 'username',
      'password' => 'password',
      'host' => 'localhost',
      'prefix' => '',
    ));

  }
}

class CakeUserMigration extends CakeBaseMigration {
  public function __construct($arguments) {

    parent::__construct($arguments);
    $this->description = t('Lagacy cakePHP system customers');

    $query = Database::getConnection('default', 'for_migration')
    ->select('customers', 'c')
    ->fields('c');

    $this->source = new MigrateSourceSQL($query);
    $this->destination = new MigrateDestinationUser();

    $this->map = new MigrateSQLMap($this->machineName,
        array('id' => array(
          'type' => 'int',
          'not null' => TRUE,
          'description' => 'Account ID.'
        )
        ),
        MigrateDestinationUser::getKeySchema()
    );

    $this->addFieldMapping('username', 'name');
    $this->addFieldMapping('pass', 'password');
    $this->addFieldMapping('mail', 'email');
    $this->addFieldMapping('created', 'modified');
    $this->addFieldMapping('roles')
    ->separator(',')
    ->defaultValue(DRUPAL_AUTHENTICATED_RID.',4');

  }
}

running the drush command drush migrate-audit --allsays that that cakeUser is missing a source and destination.
I don't get it, Setting the database and running the query at devel/php returns the expected rows from the database.
Any help on this would be fantastic :)
Answer: It seems the problem was the files not saving properly after I updated them, The code I posed above seems to be working ok now.


hypothetical measure of variability similar to entropy

Question: Variance has the following properties:

$Var(cX)=c^2Var(X)$
For independent variables $Var(X+Y)=Var(X)+Var(Y)$.

Range of a rv has the following properties:

$Range(cX)=|c| Range(X)$
For independent variables $Range(X+Y)=Range(X)+Range(Y)$.

Entropy has the following properties:

$H(cX)=H(X)$
For independent variables $H(X,Y)=H(X)+H(Y)$.

My main question: Does there exist a characteristic of a random variable such that:

$New(cX)=New(X)$
For independent variables $New(X+Y)=New(X)+New(Y)$.

?
(the only difference is "plus" instead of a vector random variable)
Maybe something can be said if the first property is replaced by $New(cX)=|c|^3New(X)$?
Comment: Almost by definition, "variability" reflects the value of $c$ (it's a scale factor). Therefore *no* measure that has your property (1) has any claim to be related to variability.
Comment: I agree, maybe the variability is the wrong word.
Comment: What, then, is your question?
Comment: I've replaced the word "variability" by "characteristic"
Comment: So you are looking for any scale "invariant" (not really the right wording) characteristic, which is also a measure (ie. with Countable additivity) ?
Answer: A characteristic with the desired properties (almost)
Variance is the second central moment: $$Var(x)=E(X-\mu)^2.$$
So when trying to find a characteristic that satisfies conditions 1 and 2, a natural first guess could be the third central moment:$$\mu_3(X)=E(X-\mu)^3.$$
By expanding the cube, it can be verified (I recommend that you try it!) that $\mu_3$ has the following properties, which are close to what you were hoping for:

Homogeneity: $\mu_3(cX)=c^3\mu_3(X)$
Additivity: $\mu_3(X+Y)=\mu_3(X)+\mu_3(Y)$ when $X$ and $Y$ are independent.

Beyond the third moment
At this point you would perhaps guess that for the $k$:th central moment $$\mu_k(X)=E(X-\mu)^k$$ it holds that

$\mu_k(cX)=c^k\mu_k(X)$
$\mu_k(X+Y)=\mu_k(X)+\mu_k(Y)$ when $X$ and $Y$ are independent.

This is however not the case. There is however a characteristic $\kappa_k$, of which the variance and the third central moments are special cases, that has both the homogeneity and additivity properties. This $\kappa_k$ is called the $k$:th cumulant. It is derived from the logarithm of the moment-generating function $E(e^{Xt})$:
$$ \mbox{log}(E(e^{Xt}))=\sum_{k=1}^\infty \kappa_k\frac{t^n}{n!}. $$
As an example, the above formula can be used to see that
$$\kappa_2(X)=Var(X)\\\kappa_3(X)=\mu_3(X)\\\mbox{and}\\\kappa_4(X)=\mu_4(X)-3Var(X)^2.$$
The Wikipedia page for cumulants contains a lot more information about them.


LilyPond - change tuplet bracket to a small bow

Question: I have a Cello piece from Sebastian Lee, that uses quite a lot of tuplets.
My snippet with the default LilyPond setting looks like this:

this looks pretty nice, the problem is that a beginner could easaly think this was the fingering, especially in this example where as the b would be actually played with a third finger on the G string.
So I used \override TupletBracket.bracket-visibility = ##t to print the tuplet spanner/bracket that results in a very ugly print:

One edition, that is available on IMSLP looks like this:

which I personally find somewhat nicer (not to be misunderstood, I'm only talking about the tuplet spanner, not about the whole print)
Does anyone on here know for a possible tweak of the spanner, to make it rather look like this small bow in the third example?
Sebastian Lee, Op.70 in LilyPond format on GitHub
Comment: See: http://lilypond.1069038.n5.nabble.com/Tuplets-curved-brackets-td207326.html
Answer: A first approach would be to change the text of the tuplet number and append a small slur:
bow-up = \markup { \with-dimensions #'(0 . 3) #'(0 . 0)
    \override #'(filled . #t)
    \path #.1 #'((moveto 0 0)
                 (curveto 1 1.2 2 1.2 3 0)
                 (curveto 2 0.9 1 0.9 0 0)
                 (closepath)) }

bow-down = \markup { \with-dimensions #'(0 . 3) #'(0 . 0)
    \override #'(filled . #t)
    \path #.1 #'((moveto 0 0)
                 (curveto 1 -1.2 2 -1.2 3 0)
                 (curveto 2 -0.9 1 -0.9 0 0)
                 (closepath)) }

#(define-markup-command (tuplet-bow-up layout props tuplet-number) (markup?)
  (interpret-markup layout props
    (markup #:center-column(#:vspace -.2 bow-up #:vspace -.6 #:line(tuplet-number)))))

#(define-markup-command (tuplet-bow-down layout props tuplet-number) (markup?)
  (interpret-markup layout props
    (markup #:center-column(#:vspace .2 tuplet-number #:vspace -1 #:line(bow-down)))))

tupletBowUp = #(define-scheme-function (parser location tuplet-number) (string?)
     #{\override TupletNumber.text = \markup \tuplet-bow-up #tuplet-number #})

tupletBowDown = #(define-scheme-function (parser location tuplet-number) (string?)
     #{\override TupletNumber.text = \markup \tuplet-bow-down #tuplet-number #})

\score {
  {
    \clef bass
    \time 3/4
    \tupletBowUp "3" \tuplet 3/2 { c8 b, c } \tupletBowDown "3" \tuplet 3/2 { e8 g e } \tuplet 3/2 { e8 g e } c'4
  }

  \layout{}
}

With \tupletBowUp "3" you set the number of all following tuplets to a 3 with a small bow above. With \tupletBowDown "3" you set it to a 3 with a small bow below. You can put other numbers as you like.
Result:

But I am sure, this can also be achieved in a much more sophisticated manner. However, I don't know the internals of LilyPond that well. For example, it would be great to have the small bow automatically switch above or below the number according to its position.

Edit: Another way would be to change the tuplet bracket like this proposal and one comment suggest (sorry, I only saw the comment after having edited my answer). I changed the code from the linked proposal a bit to simplify it and to make the slurs smaller:
printTupletBow = {
  \override TupletBracket #'stencil = #ly:slur::print

  \override TupletBracket #'thickness = #1.2

  \override TupletBracket #'control-points =
    #(lambda (grob)
      (let* ((x-pos (ly:grob-property grob 'X-positions))
             (pos (ly:grob-property grob 'positions))
             (x-ln (interval-length x-pos))
             (dir (ly:grob-property grob 'direction))
             (height (- (cdr pos) (car pos)))
             (height-corr (* 0.3 dir height))
             (edge-height (ly:grob-property grob 'edge-height '(0.7 . 0.7))))

        (list
          (cons
            (+ (car x-pos) (* x-ln 1/4))
            (+ (car pos) (* 1 dir (car edge-height))))
          (cons
            (+ (car x-pos) (* x-ln 3/8))
            (+ (car pos) (* dir (+ 1.5 height-corr))))
          (cons
            (+ (car x-pos) (* x-ln 5/8))
            (+ (cdr pos) (* dir (- 1.5 height-corr))))
          (cons
            (+ (car x-pos) (* x-ln 3/4))
            (+ (cdr pos) (* 1 dir (cdr edge-height)))))))
}

\score {
  {
    \clef bass
    \time 3/4
    \tuplet 3/2 { c8 b, c } \tuplet 3/2 { e8 g e } \tuplet 3/2 { e8 g e } c'4
  }
}

\layout {
  \printTupletBow
}

Result:

If you want to temporarily omit the bows, you can use \once \override TupletBracket.stencil = ##f just before the relevant tuplet.
One problem with this approach is that the slur will be slanted quite a lot if the notes span bigger intervals. But it might be a nice solution if your piece includes mainly tuplets with beams.
Comment: No need to do that, because I also took inspiration from there. So, the basic code may already be there as well.
Comment: For the second example, you can use `\once \override TupletBracket.stencil = ##f`.
Comment: I'll post your link in [LilyPonds official IRC on Freenode](https://webchat.freenode.net/#lilypond), maybe they are inspired... :-) as I am! (ot looks so much nicer then the bracket!)
Comment: is there a way to omit the bows further on in the piece, as you do with `\omit TupletNumber`?
Comment: you should definitely add this to the [LSR - Snippet Repository](http://lsr.di.unimi.it/)


How do I render a custom form on a view page?

Question: In my module's routing.yml file I set the form path to a path which also shows a view page. But on that path the form does not get displayed, only the view.
When I change the path in the routing.yml it works, so I guess views somehow overrides/ ignores my form.
How can I do that?
Comment: Yes, a route required by a page view and a custom route will always conflict because there can only be one route. Does the custom form affect the view or do you want to display different types of content in a custom layout (using blocks, panels, etc...)?
Comment: Maybe you could do the reverse, create a view block and place it on your form page.
Comment: @mradcliffe i think its best when i provide a custom block with my form and just add it to the view page via block overview :)
Answer: It's only possible to display one "page" on a url, so you can't both display a view and a form or any other "page" for that matter.
You have a few options:

Insert the form into the view (can be done with a global views handler)
Insert the form on the view page by exposing it as a block.
Insert the view on the form page by exposing it as a block.

Probably the easiest solution for you is to convert the view page to a view block and insert it on the form page. Views already has support for this, so you only need a few clicks in the interface to achieve this.


Tremolo on ukulele pick or fingers?

Question: I saw a few vids on tremolo on ukulele. I like tremolo on uke because the strings are so spread out. But from the videos I watched, some use one finger, some use two fingers, and some use a pick. I'm confused on what to use.
This video was interesting, but he seems to use the two fingers on the highest string. Do people use a pick if they want to tremolo on all strings? or can you tremolo with your fingers on all strings? And if so, why's a pick necessary? I mainly do fingerstyle. So should I use a pick or one or two fingers. I'd also like to be able to tremolo on all strings.
Comment: There are many different tremolo techniques - fast with a pick, one finger, two fingers, even three or four fingers, a sort of rasguedo. Use what you find best or easiest. There's more than one way to kill a cat, as the saying goes. (I think!).
Comment: @Ramillies - using a pick certainly works well on guitar. I see no reason why it shouldn't work on uke. Leave only the tip of the pick to play with.
Comment: @user45266 - skinning it is just one way to kill it...
Comment: I don't think using a pick for tremolo would work (however I have no experience with a pick!). If it helps, in classical guitar, you would use three fingers ("p-a-m-i", i. e. thumb strikes a bass string, then the ring, middle and index fingers strike the same string), and I personally like it the most (it's reasonably easy and gives a reasonably "full" sound). If you have longer fingernails, you can also "slide" the fingers across the strings during the tremolo (though I don't like the resulting sound too much). But ultimately, it's just about what you like the most.
Comment: When you ask 'all strings', do you mean each string individually - any one of the four, or all strings simultaneously?
Comment: @Tim each string individually (any one of the four)
Comment: @Tim I've always heard that expression as *"There's more than one way to **skin** a cat"*. That doesn't make it any less apalling, though.
Answer: The video you linked to showed a guy using two fingers for tremolo on the top string as you noticed. I can't (haven't learned to) do tremolo that way, but I have a couple of alternative methods:

Fingernail-as-pick. You mentioned that you play mostly fingerstyle, and I think this method is worth learning if you don't really use a pick. Basically, it's as though you are strumming one string as quickly as possible. I like to turn my finger such that the curved edge of the nail is oriented perpendicularly to the strings, sort of "scraping" rather than picking. I find that that gives me a quieter, more consistent tone, and it can easily be performed on all four strings. It's all in the wrist; I sort of imagine I'm strumming funk guitar as fast as I can, but with much smaller movement. Also, I find that sort of pinching my index (the one actually strumming) and thumb together helps me be faster and have more control, almost as though I were using my nail as a real pick. By the way, fingernail length doesn't seem to matter for me; I can do this and all my other nail-based technique on ukulele both before and after trimming them. Some are quite particular about their nails, especially fingerstyle guitarists, but for ukulele it's never been a concern for me.
Two strings. I know you said that you wanted to be able to do it on all strings, but this is also a cool method that I think you should try. Basically, fret the G string such that it produces the exact same note that the A string is playing (G string should be two frets higher), then pluck the A string with the middle finger, then the A string with the index finger, then the G string with the thumb. When done at high speeds, it should feel like a roll-type pattern (actually,the order of the strokes doesn't matter, since they're all the same note). It sounds a lot like the classical technique that uses three fingers on only one string, but I find it easier to do at great speed because while the thumb is picking, the other two fingers can reset and be in position for their next strokes. Plus, the thumb plucking a different string means that you get a kind of natural reverb, since at least one note is ringing out at any given moment. The thumb can also reach over to other strings to hit other notes and fill out the harmony a little more.
Using a pick. Again, I know you said you like fingerstyle, but I'll just throw this out there for the benefit of others. Most electric guitarists I know that also dabble in ukulele already know how to use a pick, and they do their trem-picking with a pick in the exact same manner that is used in metal/rock music; it's just like my fingernail method, but I don't think they "scrape" the string, I think they actually alternate picking it from both sides like normal. As User Tim pounted out in the comments, only the tip of the pick should emerge from the hand, and that goes for either instrument.
Rasgueado-style (three finger classical/Spanish Flamenco tremolo). There's hundreds upon hundreds of resources on how to do that, so I won't go over it (and also because I can't do it yet). I imagine it absolutely works on ukulele, and someday I'll actually motivate myself enough to work on that technique. I'm pretty sure most famous ukulele players who do this technique do it in a similar manner to the classical/Spanish guitarists. And it leaves the thumb free to hit a bass note (but on ukulele, there might not be much of a bass sound to do this with).

Tremolo on ukulele pick or fingers?


How to plot GAMs on the scale of the response with univariate smooths, interactions and random effects

Question: This is a very similar question to Plotting GAMs on Response Scale with Multiple Smooth and Linear Terms, but I am specifically interested in the answer from @gavinsimpson.
I am using the code provided in the answer to the above question to plot individual smooths on the scale of the response but the plots it produces seem "off" and I can't figure out why.
Model:
model <- gam(count ~
                   s(x1, k = 40) +
                   s(x2, k = 40) +
                   s(x3, k = 40) +
                   s(x4, k = 40) +
                   s(x5, k = 40) +
                   s(x6, bs = "re") +
                   s(Latitude, Longitude, bs = "sos", k = 230),
                 gamma = 1.4, family = nb(), method = "REML",
                 data = dat)

All predictors are scaled, and I am only interested in plotting the individual smooths of x1, x2, x3, x4, the rest are "nuisance" variables.
Plot of smooth x1:

Two issues:

Fitted trend is much higher than expected,

Credible interval has "jagged" edges.

Both issues are present in all plots of the individual smooths I am interested in.
Code used for above plot:
new_data <- with(dat, expand.grid(x1 = seq(min(x1), max(x1),
                length = 200),
                    x2 = median(x2),
                    x3 = median(x3),
                    x4 = median(x4),
                    x5 = median(x5),
                    x6 = x6,
                    Latitude = median(Latitude),
                    Longitude = median(Longitude)))

ilink <- family(model)$linkinv
pred  <- predict(model, new_data, newdata.guaranteed=TRUE,
           type = "link", se.fit = TRUE, unconditional = T)
pred  <- cbind(pred, new_data)
pred  <- transform(pred, lwr_ci = ilink(fit - (2 * se.fit)),
                         upr_ci = ilink(fit + (2 * se.fit)),
                         fitted = ilink(fit))

ggplot(pred, aes(x = x1 , y = fitted)) +
  geom_point(dat, aes(x = x1, y = count)) +
  geom_ribbon(aes(ymin = lwr_ci, ymax = upr_ci), alpha = 0.2) +
  geom_line(colour = "red", lwd = 1.1) +
  theme_classic() +
  xlab("x1") +
  ylab("Count")

Ps First stack post so please let me know if you require more details or the format of the post is wrong.
Comment: The "jagged edges"  probably result from the random effects smoother. You should predict for the population mean (but consider carefully what you confidence interval is conditioned on).
Comment: What does "Fitted trend is much higher than expected" mean here? On what basis do you claim this?
Comment: From visual inspection and other models of a similar sort using the same predictors. Furthermore, when I plot using base R commands the fitted trend is more where you would expect it to be given the data.
Comment: What do you inspect visually? The plot in your question? You set four predictors to their median values. You should inspect the distribution of these values in your data. E.g., one of them could be mostly in a narrow range of values with a few more extreme values. I think potting smooths on the predictor scale like this shouldn't be done if your model includes more than one smoother.
Comment: what about using `plot(model)` ?
Answer: As @Roland surmised, the jagged edges are due to you predicting multiple values of the response at each value of x1. You get multiple predictions because you plugged in all the values of x6 when you created new_data. That you didn't get a spaghetti plot is likely down to the ordering of the values in the expand.grid call; if x1 were your random effect variable then the plot could have been a visual mess and highlighted the problem more easily.
When predicting from models like this you typically need to provide a data frame of new values for all covariates used to fit the model. You can provide a single value for the covariates you are not interested in, in which case the predicted values are conditioned on those values. You could do this for the random effect also by selecting a single level of the random effect variable to predict for:
new_data <- with(dat,
                 expand.grid(x1 = seq(min(x1), max(x1), length = 200),
                             x2 = median(x2),
                             x3 = median(x3),
                             x4 = median(x4),
                             x5 = median(x5),
                             x6 = factor(x6[1], levels = levels(x6)), # <- here
                             Latitude = median(Latitude),
                             Longitude = median(Longitude)))

In the example I'm choosing a single level from x6 but making sure that new_data$x6 is still a factor with the right levels.
This would condition the predictions on that subject, which may not be what you want.
An alternative is to exclude certain terms from the predictions. Basically this is like setting or forcing the effect of $f(\mathsf{Lon}, \mathsf{Lat}) = 0$, which given how the smooths are set up means the average spatial effect. In terms of the random effects, because these are mean 0 i.i.d. Gaussian random effects, setting the effect of the random effect smooth to 0 is the same as generating population level predictions.
Note: The smooths are centred about the model constant term, so if you have factor terms, then this will mean the predictions are conditioned on the reference level(s) for that/those factor(s); changing the contrasts for those factors will change the interpretation of the model constant term so you should bear that in mind as you might prefer a different set of contrasts.
Regardless, we can exclude those terms that we might consider superfluous or nuisance using the terms or exclude arguments to predict.gam, which have the following description:

terms: if type=="terms" or type="iterms" then only results for the terms (smooth or parametric) named in this array will be returned. Otherwise any smooth terms not named in this array will be set to zero. If NULL then all terms are included.

exclude: if type=="terms" or type="iterms" then terms (smooth or parametric) named in this array will not be returned. Otherwise any smooth terms named in this array will be set to zero. If NULL then no terms are excluded. Note that this is the term names as it appears in the model summary, see example. You can avoid providing the covariates for the excluded terms by setting newdata.guaranteed=TRUE, which will avoid all checks on newdata.

(emphasis added) In your case it is easier perhaps to exclude the terms you want excluding.
Note the bit in italics above. You have to name the smooths in this vector you pass to terms or exclude exactly as {mgcv} knows them. So read them off the summary() output if you are unsure.
If you want to exclude the effects of s(x5), s(x6), and s(Latitude, Longitude) from your predictions then you would do:
excl <- c("s(x5)", "s(x6)", "s(Latitude,Longitude)")
pred  <- predict(model, new_data, exclude = excl,
                 type = "link", se.fit = TRUE, unconditional = TRUE)

Note how I removed spaces in the label for the spatial smooth.
You probably don't want to use newdata.guaranteed=TRUE here unless you are very sure you have everything perfectly correct in the definition of your new_data; it's very easy to mess up factor coding etc.
As a double check, you should confirm that your new_data has as many rows as you planned to plot. Here you wanted to show how the predicted value of your response changed over the range of x1 and generated 200 values of x1 at which you wanted predictions. Hence your new_data should have 200 rows: if it doesn't then you messed something up and need to check how you are creating new_data and invariably you have an issue in the expand.grid call.
Note also here that you will get different predictions if you predict at the median latitude and longitude than if you exclude those effects with exclude as sum to zero constraint imposed on each smooth will centre the smooths at the mean, and hence the 0 represents the mean spatial effect, not the effect on Y at the median location. I may be glossing over some minor implementation details there, but just bear that in mind when choosing values to predict at if you are conditioning on them as you did in your example.
Comment: Apologies for the delay this was right before my masters submission, I have accepted your answer which was very useful and gave me much to consider. Thank you.


Showing that an algebraic number is not a root of a real

Question: While answering this question on mathoverflow, I stumbled across a question that I expect may be easily answered by someone knowing a bit more algebra than me.
Let's make it really specific.
Consider the polynomial equation $X^4-X^3-X^2-X-1=0$. It has two real roots and a pair of complex roots.

How can one show that the complex roots are not roots of a real number?
Comment: From the context, it means that $(\text{Arg }z) / \pi$ is irrational.
Answer: I'd like to see an elegant way to do this, but here's a reasonably concrete way:
If $z$ is either complex root, then since $z$ is algebraic, so is $|z| = \sqrt{z\bar{z}}$, and so is $z/|z|$.  We can thus find the minimal polynomial of $z/|z|$ and then the question reduces to whether it is an $n$th root of unity (which amounts to comparing it against a finite list of cyclotomic polynomials).
For this particular case it looks like the minimal polynomial is $X^{10} - X^9 + 2X^7 + 7X^6 + 8X^5 + 7X^4 + 2X^3 - X + 1$, which does not match $\Phi_{11}(X)$ or $\Phi_{22}(X)$, the only cyclotomics of degree 10.
Comment: Thanks Erick. It's nice to see *a* solution, but as you say one feels there should be an elegant solution.
Answer: Let $p(x)$ be a fixed monic polynomial with integer coefficients and degree $d$. If $r$ is one of its roots and $r^n = b$ is real and non-negative (and $n$ is minimal with this property), then $b$ is a product of algebraic integers, hence an algebraic integer. We therefore have
$$r = \zeta_n \sqrt[n]{b}$$
for some primitive $n^{th}$ root of unity $\zeta_n$. Since $\sqrt[n]{b}$ is real, $\bar{r} = \zeta_n^{-1} \sqrt[n]{b}$ is also a root of $p$, and so it follows that
$$\frac{r}{\bar{r}} = \zeta_n^2$$
lies in the splitting field $F$ of $p$. But $\zeta_n^2$ generates a cyclotomic field of degree $\varphi \left( \frac{n}{\gcd(2, n)} \right)$, and so this must divide the degree of $F$, which divides $d!$. It is known that there are only finitely many numbers with a given totient, so there are only finitely many possibilities for $n$, and so for fixed $p$ this indeed reduces to a finite problem as Gerry says.
When $p(x) = x^4 - x^3 - x^2 - x - 1$, we compute that $\bmod 2$ we have $p(x) \equiv \frac{x^5 - 1}{x - 1}$, which is irreducible (the smallest finite field over $\mathbb{F}_2$ which has elements of order $5$ is $\mathbb{F}_{2^4}$), so $p$ is irreducible and its splitting field has degree dividing $4! = 24$. So $\zeta_n^2$ lies in its splitting field only if
$$\varphi \left( \frac{n}{\gcd(2, n)} \right) | 24.$$
If $q$ is a prime dividing $n$, then $q - 1 | 24$, so we can only have $q = 2, 3, 5, 7, 13$. Of these, the only odd prime which also divides $24$ is $3$ and it only does so once, so $3$ can occur with multiplicity at most $2$ and the other odd primes occur with multiplicity at most $1$. Since $2^3 | 24$, the prime $2$ occurs with multiplicity at most $5$.
Summarizing, to prove that $p(x)$ does not have a root which is the root of a real number, it suffices to prove that $r^{2^5 \cdot 3^2 \cdot 5 \cdot 7 \cdot 13}$ is not real for any of the roots $r$, and this can be done by a finite calculation. Of course this is a large exponent, and the actual size of the possible values of $n$ is smaller, but the possible values of $n$ are somewhat tedious to list out.

Here's another idea for ruling out values of $n$. Recall that if $K \subset L$ is an inclusion of number fields, then the discriminant $\Delta_K$ of $K$ divides $\Delta_L$. The discriminants of the cyclotomic fields $\mathbb{Q}(\zeta_n)$ are known (see Wikipedia, although the general formula is somewhat complicated), and in particular every odd prime divisor of $n$ divides them, so by computing the discriminant of $p$ we can rule out some prime factors.
WolframAlpha tells me that the discriminant of $x^4 - x^3 - x^2 - x - 1$ is $-563$. This is prime so it must be the discriminant of the splitting field, and this already rules out all of the possible values of $n$ above.
Comment: Also, I don't think it's true that a transposition and a 4-cycle necessarily generate $S_4$. I know it's true for $S_p$ for $p$ prime, but $(1\ 3)$ and $(1\ 2\ 3\ 4)$ generate a dihedral group.
Comment: There's something wrong with the first display equation. $r$ is a primitive root of unity times a real root of $b$.
Comment: Whoops. Thanks for catching that.
Comment: Whoops again! Ignore that part then. I mostly need that $p$ is irreducible.
Comment: ok... thanks a lot Qiaochu. This is quite helpful...
Comment: I don't know anything about discriminants of number fields, but it is very nice to know that there are elegant high-tech solutions to the question.
Answer: If $f(x)$ has a root that is $\root n\of b$ for some real $b$, then it will have an irreducible factor in common with the minimal polynomial for $\root n\of b$. This places very strong restrictions on $n$ and should reduce it to a finite problem in all cases.
I am assuming that, as in the example, the polynomial is monic with integer coefficients, making its roots algebraic integers, which restricts the possibilities for $b$, as it, too, must be an algebraic integer.


Hypothesis testing with the geometric distribution

Question:
A single observation of a random variable having a geometric distribution is used to test the null hypothesis $\theta=\theta_0$ against the alternative hypothesis $\theta=\theta_1 > \theta_0$.
If the null hypothesis is rejected if and only if the observed value of the random variable is greater than or equal to the positive integer $k$ , find expressions for the probabilities of type I and type II errors.

My idea:
Type I error equals $\alpha$, which is the probability that we reject $H_0$ while it is true. Probability of type II error is $\beta$, which is the probability that we accept $H_0$ while $H_0$ is false.
Let's say the Null Hypothetis is rejected, this means that $X\ge k$ ?
I know that that $P(X\ge k ; \theta_0)= 1- \theta_0(1-\theta_0)^{k-1}$. Is this value equal to $\alpha$?
How can I calculate $\beta$?  $P(X\ge k ; \theta_1)= \theta_1(1-\theta_1)^{k-1}$.
Who can help me making this clear ? :-)
Thank you for your trouble :-)
Answer: You have the definitions of Type I and Type II errors correct. However, the probability statement you use to represent the Type I error is incorrect. You want $P(X\geq k;\theta_0)=1-F_X(k-1;\theta_0)$, where $F_X(x;\theta_0)$ is the cumulative distribution function of a geometric random variable with parameter $\theta_0$. For the Type II error, the probability statement you've given is also incorrect. You want the probability of failing to reject the null hypothesis given that the alternative is true. This can be written as $P(X<k;\theta_1)=F_X(k-1;\theta_1)$.
When you write that $P(X\geq k;\theta_0)=1-\theta_0(1-\theta_0)^{k-1}$, you're actually saying that the Type I error is the probability of $X\neq k$ rather than $X\geq k$. Similarly, when you write that $P(X\geq k;\theta_1)=\theta_1(1-\theta_1)^{k-1}$, the inequality is incorrect (it should be $<$) and you've written that it is the probability of $X=k$ rather than $X<k$.


How to remove latitude and longitude from Google Maps ACF field in Wordpress?

Question: In Wordpress, there's an Advanced Custom Fields Google Map option. I'm using that to refer to the address as text at one point. Code used:
<?php the_field('address');?>

Address is the custom variable for the Google Map.
This displays the street, city, state, zip code, country and latitude and longitude.
I don't need the country, lat or long. I've been trying to find an array I can edit, but no luck so far.
Thanks!
Answer: If you use get_field() instead of the_field() it will give you an array of 3 elements: address, lat and lng.
Unfortunately address is a string with the full address, country name included.
But if it's always the last voice separated by a comma, you can retrieve just the address string until the last comma, something like this:
$location = get_field('address');
if(isset($location['address'])) {
    $address = substr($location['address'], 0, strrpos($location['address'], ','));
    echo $address;
}

Comment: Good, I'm glad :). Please consider [accepting the answer](http://meta.stackexchange.com/q/5234/179419) by clicking the check-mark. This indicates to the wider community that you've found a solution and gives some reputation to both the answerer and yourself. There is no obligation to do this.
Comment: Ah, thank you. I just started here, so I didn't know of that option yet.


Macbook pro Manjaro bluetooth not working

Question: I'm not sure if this is the write place to write my question, but here it is.
Before a week i updated my macbook pro early 2015 with manjaro gnom.
All good, but the bluetooth is not working.
I tried with bluetooth-manager but it's not opening and inside the journalctl -f it's showing
 Oct 15 20:08:59 PPeev systemd[1095]: Started Application launched by gnome-shell.
Oct 15 20:09:00 PPeev blueman-manager.desktop[5014]: blueman-manager 20.09.00 ERROR    Manager:118 on_dbus_name_appeared: Default adapter not found, trying first available.
Oct 15 20:09:00 PPeev blueman-manager.desktop[5014]: blueman-manager 20.09.00 ERROR    Manager:122 on_dbus_name_appeared: No adapter(s) found, exiting
Oct 15 20:09:00 PPeev blueman-manager.desktop[5014]: blueman-manager version 2.1.3 starting
Oct 15 20:09:00 PPeev systemd[1095]: gnome-launched-blueman-manager.desktop-5014.scope: Succeeded.
Oct 15 20:09:04 PPeev systemd[1095]: gnome-terminal-server.service: Succeeded.

Also when i check the status systemctl status bluetooth
    ● bluetooth.service - Bluetooth service
     Loaded: loaded (/usr/lib/systemd/system/bluetooth.service; enabled; vendor preset: disabled)
     Active: active (running) since Thu 2020-10-15 19:52:23 EEST; 19min ago
       Docs: man:bluetoothd(8)
   Main PID: 1083 (bluetoothd)
     Status: "Running"
      Tasks: 1 (limit: 9413)
     Memory: 2.3M
     CGroup: /system.slice/bluetooth.service
             └─1083 /usr/lib/bluetooth/bluetoothd

Oct 15 19:52:23 PPeev bluetoothd[1083]: src/main.c:parse_controller_config() Key file does not have key "LEScanIntervalConnect" in group "Controller"
Oct 15 19:52:23 PPeev bluetoothd[1083]: src/main.c:parse_controller_config() Key file does not have key "LEScanWindowConnect" in group "Controller"
Oct 15 19:52:23 PPeev bluetoothd[1083]: src/main.c:parse_controller_config() Key file does not have key "LEMinConnectionInterval" in group "Controller"
Oct 15 19:52:23 PPeev bluetoothd[1083]: src/main.c:parse_controller_config() Key file does not have key "LEMaxConnectionInterval" in group "Controller"
Oct 15 19:52:23 PPeev bluetoothd[1083]: src/main.c:parse_controller_config() Key file does not have key "LEConnectionLatency" in group "Controller"
Oct 15 19:52:23 PPeev bluetoothd[1083]: src/main.c:parse_controller_config() Key file does not have key "LEConnectionSupervisionTimeout" in group "Controller"
Oct 15 19:52:23 PPeev bluetoothd[1083]: src/main.c:parse_controller_config() Key file does not have key "LEAutoconnecttimeout" in group "Controller"
Oct 15 19:52:23 PPeev systemd[1]: Started Bluetooth service.
Oct 15 19:52:23 PPeev bluetoothd[1083]: Starting SDP server
Oct 15 19:52:23 PPeev bluetoothd[1083]: Bluetooth management interface 1.17 initialized

Is running.
Answer: try disabling and re-enabling the bluetooth from the bios menu.
I checked some threads, and the only working option i got is this.
You may try this. I guess it will work for you too.