Why do we need to determine the distribution of $\textbf{Y}$ in the multiple linear regression problem?

Question: Once again, here I am. Given the multiple linear regression model
\begin{align*}
\textbf{Y} = \textbf{X}\beta + \epsilon
\end{align*}
where $\epsilon\sim\mathcal{N}(\textbf{0},\sigma^{2}\textbf{I})$ and $\mu = \textbf{X}\beta$, why do we need to determine the distribution of $\textbf{Y}$? If we apply the least square method to obtain $\hat{\beta}$, we get the explicit relation
\begin{align*}
Y_{i} = \hat{\beta}_{0} + \hat{\beta}_{1}x_{i1} + \ldots + \hat{\beta}_{p-1}x_{i,p-1} + \epsilon_{i}
\end{align*}
from whence we are able to obtain the value of the response variable $Y$ in terms of the explanatory variables. My second question is: how do we interpret each component of $\textbf{Y} = (Y_{1},Y_{2},\ldots,Y_{n})$? Does each $Y_{i}$ represent the outcome from a different sample? Otherwise, if they belong to the same sample, why do they have different means?
Answer: Linear regression makes no assumptions on the distribution of the marginal outcome (That is, $\bf{Y}$).  However, there is an assumption on the distribution of the elements of $\bf{Y}$.
Each element of $\bf{Y}$ should have a normal distribution.  Given the covariates, the distribution should be
$$y \vert \beta,x \sim \mathcal{N}(x^T\beta, \sigma)$$
To your specific questions:

why do we need to determine the distribution of ?

We don't.  We make assumptions about the conditional distribution of $\bf{Y}$, not the marginal.

how do we interpret each component of =(1,2,…,)?

As a draw from $$y \vert \beta,x \sim \mathcal{N}(x^T\beta, \sigma)$$

Does each  represent the outcome from a different sample?

Yes
Comment: I think you are hung up on the difference between conditional and marginal means.  Focus on a single element of $\bf{Y}$.  It has associated covariates $x$.  I were to sample the phenomenon again and again, linear regression assumes that those samples would be normally distributed with mean $x^T\beta$.  Linear regression doesn't care about the distribution or sample mean of $\bf{Y}$
Comment: The problem which concerns me is the distribution $\textbf{Y}\sim\mathcal{N}(\textbf{X}\beta,\sigma^{2}\textbf{I})$. How do we interpret it? According to such distribution, each component $Y_{i}$ could have a different mean.
Comment: @user1337 That is correct.  Each element of the response vector should come from a normal with distinct mean, namely $x^T\beta$.
Comment: Sorry for insisting, but I still did not understand why they have different means. In simple linear regression, we colect the pairs of data $(x_{i},y_{i})$ and estimate the parameter $\beta$. In this case, all the information is collected from a single sample, which has an unique sample mean. When we extend the study to the multiple linear regression case, why do we get different means? Don't the data come from the same sample?
Comment: I think I get it now. If we are given $n$ observations $Y_{i}$ and the model matrix $\textbf{X}$, we determine $\hat{\beta}$, where $x^{T}\hat{\beta}$ is an estimator for the mean $\mu$. Such procedure results into the distribution $\mathcal{N}(x^{T}\hat{\beta},\sigma^{2})$ for $y$. Am I on the right track? Anyway, there still remains one question: does it have any purpose on obtaining the distribution of $\textbf{Y}$?
Comment: @user1337 Yes, you're on the right track.  To your other question, the distribution of $\bf{Y}$ (that is, the distribution of the elements in that vector) is of no consequence.  I can easily construct an example where the distribution is strongly bimodal and linear regression produces an almost perfect fit.
Comment: "

Linear regression makes no assumptions on the distribution of the marginal outcome. However, there is an assumption on the distribution of the elements of Y. " This is backwards - the variable Y can have any unspecified distribution, but the marginal distribution (conditional on XB, i.e. the distribution of the error term) must be Gaussian. You correctly represent it later in your post.
Comment: @JoeyF., *but the marginal distribution (conditional on XB, i.e. the distribution of the error term)* sounds a little confusing to me. Actually, there is is the conditional distribution $Y|X$ and there is the (unconditional) distribution of $\varepsilon$. These are different because they have different means, but the functional form and the variance are the same.
Comment: After some thought, I came into the following problem: which $x^{T}$ do we choose to estimate the mean $\mu = x^{T}\hat{\beta}$?
Comment: @RichardHardy Yes, you are correct - my notation was sloppy. It is not exactly the the same distribution, but rather shifted from $\mu=0$ (distribution of $\epsilon$) to $\mu=X\beta$ (marginal distribution of $Y | X\beta$. It is "equal" in terms of variance and type of distribution (i.e. both are Gaussian). Good clarification.
Comment: @user1337 your question doesn't make much sense. The correct interpretation would be, "for any given $X$, the corresponding distribution of $Y$ has mean $\mu = X\beta$".


Baixar Plugin Genymotion no Eclipse

Question: Galera, não consigo instalar o plugin do Genymotion no meu Eclipse, ele não aparece pra fazer a opção de download, me ajudem por favor]1
Comment: Recomendo baixar ele separedamente  e rodar via linha de comando.
Answer: A princípio você está fazendo certo. Adicionando o link de download e apertando em 'Add' para procurar o plugin. Você poderia dar mais detalhes sobre o passo a passo que você está fazendo e quais mensagens você está recebendo da IDE?
Outra coisa, recomendo que você baixe o Android Studio para programar apps Android, não só porque o Android Studio é feito completamente para programação Android, com todas as ferramentas que você possa imaginar e por ser mais rápido e ter um sistema de build bem mlhr (Gradle), mas principalmente pq o Google já falou que não irá mais dar suporte ao plugin pra Eclipse
Comment: Nenhuma mensagem, não acontece nada, é que o curso que estou fazendo é no eclipse e sou iniciante nisso
Comment: @DaniloAlbergardi recomendo trocar de curso
Answer: Basta desmarcar os check box abaixo.
<code>Show only latest versions of available software
Group items by category
</code>
Depois disso vai aparecer o Genymotion Eclipse Tools.

Baixar Plugin Genymotion no Eclipse


What is a piezo pickup and how does it differ to a common pickup?

Question: I have heard of a piezo pickup used in some guitars, like John Petrucci's signature Music Man.
What is a piezo pickup and how does it differ to a common pickup?
Answer: A piezo pickup is a type of microphone. It picks up the physical vibration of the the instrument and converts it to a voltage. It is usually used on acoustic guitars/instruments.
A "common" pickup - generates a signal by disturbing a magnetic field generated, you must have metal strings for this to work.
There's a very good page covering pickups on WikiP : Wikipedia


Problema Query server has gone away

Question: Ocorreu-me um erro na parte da Query
mysql_query(): MySQL server has gone away

Que tipo de erro é este?
Query:
$sqlinsert = "INSERT INTO tb_trabalhador  VALUES(0,'".$Nome."','".$Morada."','".$Tipo."','".$Email."','".$AlvaraNumero."','".$AlvaraValidade."','".$AlvaraAnexo."', '".$AcidenteNumero."',
'".$AcidenteValidade."','".$AcidenteAnexo."','".$SeguroNumero."','".$SeguroValidade."','".$SeguroAnexo."','".$FinancasValidade."','".$FinancasAnexo."','".$SocialValidade."',
'".$SocialAnexo."','".$RemuneracaoValidade."','".$RemuneracaoAnexo."','".$InstaladorNumero."','".$InstaladorValidade."','".$InstaladorAnexo."','".$MontadorNumero."','".$MontadorValidade."','".$MontadorAnexo."')";

Estrutura
'tb_trabalhador', 'CREATE TABLE `tb_trabalhador` (\n  `id` int(11) NOT NULL AUTO_INCREMENT,\n  `Nome` varchar(200) DEFAULT NULL,\n  `Morada` text,\n  `Tipo` varchar(45)
 DEFAULT NULL,\n  `Email` text,\n  `AlvaraNumero` int(11) DEFAULT NULL,\n  `AlvaraValidade` date DEFAULT NULL,\n  `AlvaraAnexo` longblob,\n  `AcidenteNumero` int(11)
 DEFAULT NULL,\n  `AcidenteValidade` date DEFAULT NULL,\n  `AcidenteAnexo` longblob,
\n  `SeguroNumero` int(11) DEFAULT NULL,\n  `SeguroValidade` date DEFAULT NULL,\n  `SeguroAnexo` longblob,\n  `FinancasValidade` date DEFAULT NULL,\n  `FinancasAnexo` longblob,\n  `SocialValidade` date DEFAULT NULL,\n  `SocialAnexo` longblob,\n  `RemuneracaoValidade` date DEFAULT NULL,\n  `RemuneracaoAnexo` longblob,\n  `InstaladorNumero` int(11) DEFAULT NULL,\n  `InstaladorValidade` date DEFAULT NULL,\n  `InstaladorAnexo` longblob,\n  `MontadorNumero` int(11) DEFAULT NULL,\n  `MontadorValidade` date DEFAULT NULL,\n  `MontadorAnexo` longblob,\n  PRIMARY KEY (`id`)\n) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8'

Comment: Por favor evitem longas discussões nos comentários; a conversa de vocês foi [movida para o chat](http://chat.stackexchange.com/rooms/54293/discussion-on-question-by-chrisadler-problema-query-server-has-gone-away)
Answer: Regra geral o erro que estás a ver é devido a três problemas:

mysql_query(): MySQL server has gone away

Operações realizadas no PHP
Se entre o tempo em que abres a ligação à base-de-dados e a altura em que efectivamente vais interagir com a mesma estás a realizar operações que demoram até estarem concluídas, a ligação à base-de-dados pode ser perdida.
A recomendação aqui é que faças as operações que tens a fazer e abras ligação à base-de-dados quando efectivamente precisas dela.
Em alternativa, podes verificar se a mesma está activa antes de a tentares usar fazendo uso do mysql_ping() (Inglês) onde podemos ler:

Ping a server connection or reconnect if there is no connection

Que traduzido:

Realiza um ping à ligação ao servidor ou restabelece a mesma se não for encontrada.

Para usar dado que o mysql_ping() não restabelece a ligação automaticamente:
$conn = mysql_connect('localhost', 'utilizador', 'password');
mysql_select_db('db',$conn);

// blá blá blá

// antes de correres a consulta de inserção
if (!mysql_ping($conn)) {

  // fecha ligação anterior (mesmo que já não exista, tem que ser fechada)
  mysql_close($conn);

  // volta a ligar
  $conn = mysql_connect('localhost', 'utilizador', 'password');

  // escolhe base de dados
  mysql_select_db('db',$conn);
}

// a tua consulta para inserir aqui...

Inserção de dados (blob's e afins)
Ao procederes à consultas de inserção, particularmente as que contém BLOB's, estás sujeito a ultrapassar os limites máximos impostos ao pacote que é enviado para o MySQL.
Os limites são definidos em max_allowed_packet (Inglês) onde podemos ler na documentação:

You must increase this value if you are using large BLOB columns or long strings.

Que traduzido:

Deve aumentar este valor se estiver a utilizar grandes colunas BLOB ou strings longas.

O referido valor pode ser alterados de duas maneiras:

Executar uma consulta para alterar o limite até que o servidor seja reiniciado:
SET GLOBAL max_allowed_packet=1073741824;

Alterar o ficheiro de configurações para manter a alteração para sempre:
No ficheiro my.ini, incluir uma linha após [mysqld] com:
max_allowed_packet=500M

Recolha de dados
Se for o caso de aparecer este erro quando estamos a realizar consultas à base-de-dados para recolher dados, o problema poderá estar na quantidade de informação e/ou no tempo que a mesma demora até chegar.
Para estes cenários, é preciso aumentar o tempo da ligação no PHP de forma a garantirmos que as operações correm como esperado.
No início do nosso ficheiro PHP, podemos definir dois valores superiores ao normal de 60 segundos:
ini_set('mysql.connect_timeout', 300);
ini_set('default_socket_timeout', 300);

Comment: @user3253195 Se a alteração foi a partir do ficheiro de configuração, deverás reiniciar os serviços para que a alteração tenha efeito.
Comment: Continuo com o mesmo problema.:
Mysql_query(): MySql server has gone away.
Mysql_query():Error Reading Set's header.

e é ao inserir os dados na BD
Comment: Mas tem haver com o tamanho. porque se preencher menos campos funciona.
Comment: @user3253195 Sim, é o tamanho do pacote enviado para a base de dados, tinhamos concluído isso ontem, mas alteraste o `max_allowed_packet` para valores elevados?
Comment: Sim alterei. coloquei 500M
Comment: @user3253195 Alteraste então a partir do ficheiro de configuração, é isso?

Problema Query server has gone away


Can't import product names/descriptions with special characters

Question: I'm trying to import a product CSV which has Bulgarian product names/descriptions (using the standard import under import/export->import)
The only way I've been able to import any so far is by wrapping them in quotes or by putting roman characters in front of the Bulgarian.
e.g. 'Ламинирани ПДЧ' or xxx Ламинирани ПДЧ
without adding these characters it outputs the error: Required attribute 'name' has an empty value in rows: 1
It seems like the Bulgarian is being stripped out completely? My file is encoded as UTF-8 and I've also set the default charset as UTF-8 in the htaccess file.
Is it possible to import the Bulgarian without quotes/roman characters?
Comment: Are you looking for a programmatic solution? Or just how to make the import work using Magento?
Comment: Ideally I'd like it to work with magento out of the box as you'd think it would, but If there's a programmatic solution to this that'll work for me too.
Comment: Stack Overflow is a programming-related Q&A site. Questions asked here should be specifically about programming. If you want a general Magento question answered you should post on http://magento.stackexchange.com/ instead.
Comment: Ok, I'll post there, but if anyone has experienced this before and has a  programmatic solution then i'm all ears..
Answer: I haven't personally tried it, but I have seen this answer that seems to work.
Try saving your csv file through Libre Office Calc with UTF-8 and try import again.
Comment: Try this link for more details. [Solution Link] (https://magento.stackexchange.com/questions/131078/importing-product-names-with-special-characters-using-magmi)


Can Google Maps show 3D KML objects?

Question: Unable to let Google Maps show my imported 3D KML objects in 3D
I can import a KML file to "My Maps", but when I go to Google Maps, My maps, to view the KML file, I only get to see a "flattened" version where everything is projected onto the ground.
Can anybody tell me if (and how?) it is possible to convince Google Maps to show my imported 3D objects in 3D?
Answer: Google Maps can not show 3D KML objects, nor 3D Models, like Earth can. The Google Maps Platform documentation has a page on using KML and GeoRSS Layers in Maps, with a list of Supported KML elements.  In there, you'll see that both the  and  elements are not supported, so no 3D in Maps, unfortunately.

Can Google Maps show 3D KML objects?


Queries não devem ser executadas em uma view?

Question: Acabei lendo isso agora pouco "É importante ressaltar que queries não devem ser executadas em uma view. O correto é que você aplique um pattern MVC( Model View Controller) e separe as coisas. Um bom exemplo, utilizando o Framework Code Igniter" Alguém pode me explicar melhor, e qual a diferença de executar a query na view? E se devo mudar meu projeto por conta disso
Comment: voce executa querie na suas views ?
Answer: Conforme o padrão MVC suas queries devem ser executadas pela camada Model. O MVC é um padrão muito popular e largamente aplicado nos dias de hoje. Ele é um padrão e pode ser substituído por outros.
Contudo é fortemente recomendado que se siga algum padrão, dessa forma caso outra pessoa dê manutenção no seu código terá um pouco menos de dificuldade de entende-lô, e até você mesmo.
Alinhado ao MVC é interessante que se siga outras boas práticas de programação, como: DRY, SOLID e outros.
As boas práticas servem para tornar-mos os nossos códigos mais legíveis para humanos, facilitando assim a manutenção e aumentando o ciclo de vida do projeto.
A grande diferença  no lugar onde a query é executada está na organização do projeto.
Quanto a questão de alterar o projeto, creio que apenas você pode responder isso.
Se você tem liberdade para recomeçar o projeto, recomendo a você olhar o Laravel, que é um framework php que aplica o MVC. Recomendo ele pela larga adesão da comunidade e facilidade de encontrar material.


How to sort a Java ArrayList in Descending Order?

Question: I have to sort out 15 numbers that are given by a user in descending order. I can write how to sort them in ascending order but I don't know how to turn them. To use for-loop or something else?
Comment: Show us your code please.
Comment: possible duplicate of [Sort List in reverse order](https://stackoverflow.com/questions/18073590/sort-list-in-reverse-in-order)
Comment: See [a link] https://stackoverflow.com/questions/5894818/how-to-sort-arraylistlong-in-decreasing-order/5894862
Answer: If you use Java 8 or above you can use this:
yourList.sort(Comparator.reverseOrder());

If you want to keep the initial ordering of the list, you can:

create a copy:
List<YourType> copy = new ArrayList<>(yourList);

And then sort the copy.
use streams:
List<YourType> sorted = yourList.stream()
                                .sorted(Comparator.reverseOrder())
                                .collect(Collectors.toList());

Answer: You can use that example
List<Integer> list = Arrays.asList(10, 5, 7, 8, 6, 9);
Collections.sort(list, Collections.reverseOrder());
System.out.println(list);

Show: 10, 9, 8, 7, 6, 5
Answer: Sort the arraylist first then reverse it, like this:
Collections.sort(arraylist);
Collections.reverse(arraylist);
System.out.println(arraylist);

Answer: You can just call Comparator.reverseOrder() for that.


Automatically import fontyourface fonts

Question: Is is possible to automatically import selected fontyourface fonts via config? Ideally, this would be just the fonts I've selected, not all from the source API.
I'm in the middle of a D7 -> D9 migration, and I keep having to manually press that 'Import from fontsquirrel_api' button each time I test the migration from scratch. And that entails downloading all 1021 FontSquirrel fonts, rather than just the 4 I'm using.
Answer: A few minutes after posing the question, I found a potential solution:
dump the entire fontyourface_font table, and then import it during deployment.
It's not quite as elegant as I had hoped, but it'll work if there's nothing better.
(https://www.drupal.org/project/fontyourface/issues/2978933#comment-13847846)

Automatically import fontyourface fonts


Farseer/Box2D - constrain rotation of Revolute Joint (or other) to one direction?

Question: I am trying to create a machine in Farseer (based on Box2D) which requires the use of one-way bearings so that a weight pivots around a point in an anti-clockwise only direction.
I have the weights attached using Revolute joints and everything is working apart from this issue.  I need the force of gravity on the weight to still affect the machine.  So it should swing out and not be able to swing back with the physics of the movement still there.
If anyone has any ideas as to how I could accomplish this I would be very grateful.
Answer: Unfortunately Box2D doesn't come with this feature 'out of the box'. You could enable limits for the revolute joint, and adjust one of the limits to the current rotation every time step.
Comment: Yup. This technique can simulate the action of a ratcheting mechanism.
Comment: Thanks for the replies guys, unfortunately this is not working for me.  There is a lot of inertia involved in the model and it seems as though this may be the reason for it not working.  I see other, slower models working, but still with some "flex" when limits are applied against inertia.  edit: specifically with applying limits, the objects with the limits applied to them go out of control when force is applied.  I am including the zero angle value in the range.


Creating custom settings/variables for site

Question: I created a custom Form from a module in Drupal 8. Here is the code:
class SocialSettingsForm extends FormBase {

    public function buildForm(array $form, FormStateInterface $form_state){
        $form['facebook'] = [
            '#type' => 'textfield',
            '#title' => $this->t('Facebook Username'),
            '#description' => $this->t('Enter your facebook username.'),
            'required' => FALSE,
        ];

        $form['actions']= [
            '#type' => 'actions',
        ];

        $form['actions']['submit'] = [
            '#type' => 'submit',
            '#value' => $this->t('Submit'),
        ];

        return $form;
    }

        public function getFormId(){
            return 'social_socialsettingsform';
        }

         public function validateForm(array &$form, FormStateInterface $form_state){
            $facebook = $form_state->getValue('facebook');
            if (strlen($facebook) < 5){
                // Set an error for the form element with a key of "title".
                $form_state->setErrorByName('facebook', $this->t('The username must be at least 5 characters long.'));
            }
         }

         public function submitForm(array &$form, FormStateInterface $form_state) {

            $title =$form_state->getValue('facebook');
            drupal_set_message(t('You specified a title of %title', ['%title' => $title]));
         }

    }

The form works fine. But I'm not sure which direction and conventions to follow in order to make use of the user's input.
I would like to make use of the username the user enters, but I'm not sure how to store that input from the form. Ideally I would use these settings in a Twig template or a module.
UPDATE:
I have figured out how to add custom variables to my theme but I'm not sure how to get my form to access them. I was able to add
function mytheme_preprocess_page(&$vars){
    $vars['facebook'] = 'default';
}

But I'm not sure how to get my form to alter this variable.
Answer: To save custom configuration you probably want to use ConfigFormBase, the code would look something like this.
class SocialSettingsForm extends ConfigFormBase {
  ...

  /**
   * {@inheritdoc}
   */
  protected function getEditableConfigNames() {
    return [
      'social.settings', // The name of the config you want to edit
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $this->config('social.settings')
      ->set('facebook', $form_state->getValue('facebook'));
  }
}

Then everywhere, you can use the config factory of the Drupal global object to get the config like this.
function some_preprocess_function(&$variables) {
  $facebook = \Drupal::config('social.settings')->get('facebook', 'default_value_if_no_value_is_set');
}

Note the above approach is centered around how you would do it in a module, saving and getting configuration. You should also note that it's best practice to define the configuration a module provides in a yml file located in module_folder/config/schema/module_name.schema.yml. I'm not 100% sure what the file is actually used for, as it's possible to save configuration not defined in the config file and all other features seem to "work" just fine without it.
Comment: I added your code but \Drupal::config('social.settings')->get('facebook', 'defaultvalue'); is still empty
Comment: I was able to get it to work by adding ->save() to $this->config('social.settings')->set('facebook', $form_state->getValue('facebook'))->save();


Como faço para um array através de uma de função?

Question: Estou escrevendo um código no Unity é preciso passar vários valores através de uma função, resolvi utilizar o array na declaração da função, no entanto quando eu tento recuperar os valores do array todos eles são definidos como 0, o código esta da seguinte forma
public class ArrayTest : MonoBehaviour{

private int[] number;

void Start(){
    number = new int[] { 2, 3, 5 };
    Numbers(number);
}

void Numbers(int[] numb) {
    numb = new int[3];

    Debug.Log("Este é o primeiro valor: " + numb[0]);
    Debug.Log("Este é o segundo valor: " + numb[1]);
    Debug.Log("Este é o terceiro valor: " + numb[2]);
  }
}

Comment: A resposta resolveu sua dúvida? Acha que pode aceitá-la? Veja o [tour] se não souber como faz. Isso ajudaria muito indicar que a solução foi útil para você. Também pode votar em qualquer pergunta ou resposta que achar útil no site todo (quando tiver 15 pontos).
Answer: O que está fazendo não tem o menor sentido. Você recebe um parâmetro e a primeira coisa que faz com ele é jogar fora seu valor e criar outro valor. Ou faz algo com o parâmetro ou faz algo com a variável local que deseja.
Só retire a linha que reinicializa o parâmetro numb (péssimo nome) dentro de Numbers() que funcionará.
O código parece ter outros problemas, ainda que funcione, mas não posso falar nada porque não sei o que está tentando fazer.


Formula for the integration and differentiation of Levy process

Question: Ito lemma works for Wiener process only. What is the Ito lemma (or a generalized calculus rule) for the more general Levy process?
Could you please provide me some references?
I have checked something like http://www.applebaum.staff.shef.ac.uk/ovron1.pdf but it does not give the general equation.
Sorry if the problem is too beginner-ish.
Comment: Itô's formula holds more generally for semimartingales; you'll find it in (almost) any book on stochastic calculus.
Answer: Please refer to Th.4.4.7, p.251 of the book: D. Applebaum, Lévy Processes and Stochastic Calculus, 2nd Ed, Cambridge University Press, 2005.
Comment: Thanks!!! I will def take a look


How do I change the site name in the .theme file?

Question: I'm looking for a solution to change the site name in a .theme file in Drupal 8. I'm using the Group module and want to display a different site name when the current user navigate inside each group. How can I achieve this ?
Comment: General site name, you can change it here "admin/config/system/site-information" in drupal administration
Comment: Do you mean you want to change the site_name variable for an existing template? Which template?
Comment: I'm using the group module and when I'm in a specific group, I want to change the site name. For exemple on front page I have the default site name, on group 1 page, I would have another site name.
Comment: What do you mean by "site name" though? The page title? h1? Something else?
Answer: In a *.theme file this would be difficult to find all places where the site name may end up. This is much easier to do it in settings.php right at the start:
settings.php:
if ($_SERVER['REQUEST_URI'] == '/abc/def') {
  $config['system.site']['name'] = 'abc-def';
}

Comment: Ugh, this isnt really ideal in settings.php for Nodes related to Groups.  How can this be done in a way that the `[site:name]` token is altered to swap it out with the Group name early enough for metatag module to update the Window Title (ie `` tag) on nodes related to the Group so they display `[node:title] | [site:name]` and the site name is swapped for the Group label.
Answer: You can override the site title based on the group name by implementing a Config Factory Override class inside a custom module, and passing a '@current_route_match' argument and a few other arguments noted below to help get the information you need out of the entity represented at the current route.
In my case, I needed to limit the site name change to a specific group bundle type called division that has a specific field value. The code below is currently working for me inside a custom module called: mysite_group. There are two helper methods that contain the logic for finding the group entity and deciding whether or not to change the site name.  The logic should work both on the group page itself, as well as on any other entity or node that is related to the group.
Note: the site we built is leveraging entity_reference fields to maintain the mapping between nodes->groups, if this is not the case for your site, you can take the example below and modify the logic contained in the getSiteNameFromEntityReference() method and customize it to your needs.
# in mysite_group.services.yml
services:
  mysite_group.group_site_name_config_override:
    class: \Drupal\mysite_group\GroupSiteNameConfigOverride
    arguments: ['@current_route_match', '@entity_type.manager', '@entity_field.manager']
    tags:
      - {name: config.factory.override, priority: 5}

<?php
// in mysite_group/src/GroupSiteNameConfigOverride.php

namespace Drupal\mysite_group;

use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Config\ConfigFactoryOverrideInterface;
use Drupal\Core\Config\StorageInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityFieldManagerInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\field\Entity\FieldConfig;

/**
 * Override the site name config variable on groups and nodes that relate to
 * groups.
 */
class GroupSiteNameConfigOverride implements ConfigFactoryOverrideInterface {

  /**
   * {@inheritdoc}
   */
  public function __construct(RouteMatchInterface $route_match, EntityTypeManagerInterface $entity_type_manager,EntityFieldManagerInterface $entity_field_manager) {
    $this->routeMatch = $route_match;
    $this->entityTypeManager = $entity_type_manager;
    $this->entityFieldManager = $entity_field_manager;
  }

  /**
   * {@inheritdoc}
   */
  public function loadOverrides($names) {
    $overrides = [];
    if (!in_array('system.site', $names)) {
      return $overrides;
    }

    $site_name = NULL;
    if ($entity = $this->getViewedEntity()) {
      if ($entity->getEntityTypeId() == 'group') {
        $site_name = $this->getSiteNameFromGroup($entity);
      }
      else {
        $site_name = $this->getSiteNameFromEntityReference($entity);
      }
    }

    if ($site_name) {
      $overrides['system.site'] = ['name' => $site_name];
    }

    return $overrides;
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheSuffix() {
    return 'GroupSiteNameConfigOverride';
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheableMetadata($name) {
    return new CacheableMetadata();
  }

  /**
   * {@inheritdoc}
   */
  public function createConfigObject($name, $collection = StorageInterface::DEFAULT_COLLECTION) {
    return NULL;
  }

  /**
   * Helper method loads the viewed entity from the current route.
   *
   * Adapted from https://www.drupal.org/node/2309797#comment-12752478
   *
   * @return an entity object, when it exists; otherwise null.
   */
  protected function getViewedEntity() {
    foreach ($this->routeMatch->getParameters() as $param) {
      if ($param instanceof EntityInterface) {
        $page_entity = $param;
        break;
      }
    }
    if (!isset($page_entity)) {
      // Some routes don't properly define entity parameters.
      // Thus, try to load them by its raw Id, if given.
      $types = $this->entityTypeManager->getDefinitions();
      foreach ($this->routeMatch->getParameters()->keys() as $param_key) {
        if (!isset($types[$param_key])) {
          continue;
        }
        if ($param = $this->routeMatch->getParameter($param_key)) {
          if (is_string($param) || is_numeric($param)) {
            try {
              $page_entity = $this->entityTypeManager->getStorage($param_key)->load($param);
            }
            catch (\Exception $e) {
            }
          }
          break;
        }
      }
    }
    if (!isset($page_entity) || !$page_entity->access('view')) {
      $page_entity = FALSE;
      return NULL;
    }
    return $page_entity;
  }

  /**
   * Helper method determines the site name based on the specified group
   * entity.
   *
   * @return (string) site name value based on the specified group; null if the group
   */
  protected function getSiteNameFromGroup(EntityInterface $group) {
    $site_name = NULL;

    // In our application only groups in the 'division' bundle that have a
    // 'library' specified in their field_division_type should provide an
    // alternate site name.
    if ($group->bundle() == 'division' && $group->field_division_type->getString() == 'library') {
      $site_name = $group->label();
    }
    return $site_name;
  }

  /**
   * Helper method loads the site name from an entity reference field.
   *
   * @return (string) site name value based on the first group found in the
   *   entity reference field on the specified entity.
   */
  protected function getSiteNameFromEntityReference(EntityInterface $entity) {
    $site_name = NULL;
    $bundle = $entity->bundle();
    $type = $entity->getEntityTypeId();
    $valid_group_type = 'division';

    // Gather a list of all entity reference fields.
    $map = $this->entityFieldManager->getFieldMapByFieldType('entity_reference');

    // We only care about entity reference fields on the current entity.
    $reference_field_ids = [];
    if (!empty($map[$type])) {
      foreach ($map[$type] as $name => $data) {
        if (!empty($data['bundles'][$bundle])) {
          // TODO: Improve logic to determine which reference fields may be
          // used to determine the site name, for improved performance. The
          // order in which we process reference fields is currently
          // arbitrary, based on the order returned by
          // EntityFieldManager::getFieldMapByFieldType()
          $reference_field_ids[] = "$type.$bundle.$name";
        }
      }
    }

    // Determine if any of the reference fields on the current entity point
    // to a group.
    foreach (FieldConfig::loadMultiple($reference_field_ids) as $field_config) {
      $field_name = $field_config->getName();
      $target_type = $field_config->getSetting('target_type');
      if (!empty($target_type)) {
        $handler_settings = $field_config->getSetting('handler_settings');
        if (isset($handler_settings['target_bundles'][$valid_group_type])) {
          if ($referenced_entities = $entity->{$field_name}->referencedEntities()) {
            // If multiple entities are referenced, the first one with a
            // custom site name takes precedence.
            foreach($referenced_entities as $referenced_entity) {
              if ($site_name = $this->getSiteNameFromGroup($referenced_entity)) {
                break 2;
              }
            }
          }
        }
      }
    }

    return $site_name;
  }

}


Indentação de código C

Question: Eu e mais duas pessoas estamos desenvolvendo um código em C, e cada um fez a sua parte do código, porém ficou muito "bagunçado", existe algum comando para o codeblocks, a IDE que estamos usando, ou algum site que alinhe o código automaticamente?
Desde já, grato.
Answer: Indentação
Pode indentar no CodeBlocks acedendo a:
Plugins > Source code formatter(AStyle)

Atalhos
Pode também associar uma atalho à indentação através de:
Settings > Editor > Keyboard shortcuts > Source code formatter(AStyle)
Depois em New Shortcut configura o atalho que quer e faz Add

Configurações da indentação
É até possível de configurar a forma como o indentação é aplicada em:
Settings > Editor > Source formatter

Quer ao nível do estilo, indentação em tabs ou em espaços, keywords a não indentar, etc...
Answer: Utilize o Notpad++ usando TextFX> TextFX Edit> Reindent C++ code.
Ou utilizar o Sublime Text.
http://substanciando.blogspot.com.br/2014/02/indentacao-no-sublime-text.html

Indentação de código C


Why Grid Search is not performed for Naive Bayes Classifier?

Question: I was looking at sklearn gridsearchcv but i see no gridsearch for GaussianNB. I am very beginner in this field.
Edit: Gaussian Naive Bayes may not have any hyperparameters but I know Bernoulli Naive Bayes has the hyperparameter of alpha. Can we potentially do grid search with this?
Comment: Why should it be used and what for?
Answer: There isn't a hyper-parameter to tune, so you have nothing to grid search over.
Comment: Argument "prior" is present. It tells the Prior probabilities of the classes. If specified the priors are not adjusted according to the data.
Comment: Just a thought, I've used NB almost exclusively for NLP tasks. Consider sentiment analysis, the distribution over the word "fast" might be `{pos:0.8, neg:0.2}`. this design is often called "unigram" (just one word), however, n-grams (2 or more) will improve accuracy. In general, perplexity is used to evaluate if added model complexity is worth the effort. All that to say, grid search might be useful, if you were trying to optimize the number of n-grams (though this would no longer be "Naive Bayes" but rather a conceptual extension.) But outside of NLP, there might be no use for this idea.


Best method to clean guitar?

Question: After a month or two of playing, the strings will often have grime and skin oil stuck to the underside, and the frets will eventually start building up dirt. Add to that all the dust that accumulates on the guitar, since I have it on a wall mount, and you end up with a relatively nasty instrument that is not quite as enjoyable to play.
When and how often is it best to clean your guitar? And what are some techniques and cleaning products that will help the instrument look good as new?
Answer: Cleaning guitars comes in two flavours: everyday maintenance and the occasional full-on scrub-down.
As Dave says, prevention is the first thing you should be doing. Keep a cleaning cloth handy and give the whole guitar a good wipe every time you finish playing. Slip the cloth under the strings (I find it's best to do this one string at a time) and run it across the full length of the string, bridge to nut, a couple of times. Wipe the body and the neck as well. You may want to use separate cloths for the strings and the body, because cleaning strings will make holes in the cloth pretty quickly. Plus, that's where most of the grime accumulates when playing. A painting brush is also useful, for getting dust particles out of hard-to-reach places, such as bridge saddles.
Every once in a while, however, you'll want to give your guitar a good cleaning and the best time to do this is when changing strings. To do this, you'll have to remove the whole set (a pain with floating-bridge tremolos, but worth the extra effort) and have some cleaning agents handy for the various parts of the guitar.
What you use to clean the body will depend on the finish. Most electric guitars have synthetic finishes, which are fairly robust and resistant to environmental insults, but some higher-priced guitars - Gibsons for example - have nitrocelulose finishes that require a little more care in choosing what you clean them with. French-polished classical guitars are even more demanding in this respect, since the finish is so delicate. When in doubt, get a purpose-made cleaner/polish from a music store.
Unless the manufacturer specifies otherwise, apply a small amount of the cleaning agent (which may be as simple as water with a bit detergent, if the finish has no special requirements) and wipe down the body and all other finished parts (which will probably include the headstock and maybe the neck). Pay special attention to the cutaways, since that's where grime tends to accumulate, and work into the light to see whether you've missed anything. Once you're satisfied that the guitar is clean, dry and buff the finish with a clean cloth.
Fingerboards deserve separate attention, which will depend on whether they've been lacquered or not. Rosewood or ebony fingerboards tend to be unfinished and should be cleaned either with a purpose-made fretboard cleaner or with a small quantity of lemon oil. Again, apply a bit to your cleaning cloth (a different one than the one you used for the body - obviously) and rub down the whole fretboard, taking special care to remove any dirt that has accumulated around the frets. If you have trouble removing this, try wrapping the cloth around a fingernail or pick. Having done that, wipe off any excess cleaner or oil and leave the wood to soak it in for a bit.
Lacquered fingerboards can be cleaned in a similar way as other finished guitar parts, but check the manufacturer's recommendations just in case. For unfinished necks, it would probably be best to simply use a moist cloth.
Any dust can be removed with either a cloth or a painting brush (as mentioned above). Chrome parts may be cleaned with a purpose-made cleaning agent, but this is seldom necessary. Remember to remove them from the guitar, if you intend to do so.
Always remember to read the instructions from the manufacturer of the guitar and any cleaning agents you use. When in doubt, keep cleaning agents away from exposed wood (including any chips in the finish) and use small amounts of cleaner.
Answer: The excellent Frets.com site:
http://www.frets.com/FretsPages/pagelist.html#Musician
has a wealth of information.  Check out the "general maintenance" section.
Answer: Prevention is the best approach for this.  Slip a microfibre cloth between the strings and fretboard and run it up and down the neck a few times after you're finished playing. Dust and grime aren't going to accumulate on the string when you aren't playing, and if you've wiped your sweat off corrosion won't happen as fast either.
If you've got really corrosive sweat, you might find that something like "Fast Fret" is useful, it's just mineral oil but it should provide some defence against corrosion.  It also lessens the effects once it's happened.
Answer: Seconding Dave's comment, recommending suggestion.  Wiping down with a microfiber cloth following each playing will significantly increase the life of the strings.  Take a look at The String Cleaner (http://thestringcleaner.com).  Affordable microfiber cloth unit that gets all 6 strings at once.  Quicker and more effective than a cloth alone.

Best method to clean guitar?


Webform custom submit handler rebuild

Question: I am acutally trying to build a custom webform submit handler to force the form to be rebuilded. I know that this is possible with the integrated webform settings, but I need to do it programmatically.
Here is what my code looks like at the moment:
function he_helper_form_alter(&$form, &$form_state, $form_id) {
    dsm($form);
    dsm($form_state);
    dsm($form_id);

    if(strpos(current_path(), 'print') !== false && $form['#node']->type == 'genericforms') {
        $form['actions']['submit'] = array (
            '#type' => 'submit',
            '#value' => 'submit',
            '#submit' => 'he_helper_custom_redirect'
        );
    }
}

function he_helper_custom_redirect($form, &$form_state) {

    $form_state['rebuild'] = TRUE;

}

The problem now is, that the rebuild works as expected, but the form data does not get submitted. I tried it with $form_state['redirect'] as well, but ran into the same problem.
Anyone got an idea how to solve that?
UPDATE:
function he_helper_form_alter(&$form, &$form_state, $form_id) {
  // dsm($form);
  // dsm($form_state);
  // dsm($form_id);
  if(strpos(current_path(), 'print') !== false && $form['#node']->type == 'genericforms') {
    // $form['#after_build'][] = 'he_helper_after_build';
    $form['actions']['submit'] = array (
      '#type' => 'submit',
      '#value' => '2hello',
      '#submit' => array('_he_helper_custom_submit'),
    );
  }
}

function _he_helper_custom_submit(&$form, &$form_state) {
  $form_state['redirect'] = 'print';
  $form_state['rebuild'] = TRUE;
}

This is what my code now actualy looks like. The redirect now works fine, but the data wont get submitted. I tried the after_build function as well, but when i am using this, even my redirect wont work. This is what my code looked like with the after_build
function he_helper_form_alter(&$form, &$form_state, $form_id) {
  // dsm($form);
  // dsm($form_state);
  // dsm($form_id);
  if(strpos(current_path(), 'print') !== false && $form['#node']->type == 'genericforms') {
    $form['#after_build'][] = 'he_helper_after_build';
  }
}

function he_helper_after_build(&$form, &$form_state) {
  $form['actions']['submit'] = array (
    '#type' => 'submit',
    '#value' => '2hello',
    '#submit' => array('_he_helper_custom_submit'),
  );
  return $form;
}

function _he_helper_custom_submit(&$form, &$form_state) {
  print 'hello';
  dsm('hello');
  $form_state['redirect'] = 'print';
  $form_state['rebuild'] = TRUE;
}

Comment: If you want to submit the data what is the purpose of re-builidng the form?
Comment: I just want to get redirected to the form itself, but as I wrote, i ran into the same problem with $form_state['redirect'].
Answer: I think I've just used $form_state['redirect'] in the submit handler in the past.
However I'm not sure what order your submit handlers are firing in, maybe it would work if you added the after_build function to the form array as opposed to the button array. (If your custom submit handler is firing first then your redirect could get overwritten.)
E.g: $form['#submit'][] = 'he_helper_custom_redirect';

If that doesn't work then this post suggests using rebuild with redirect:
$form_state['redirect'] = 'where-do-you-want-to-go-today';
$form_state['rebuild'] = TRUE;

This code shows how to add a new custom submit handler without overwriting the original one:
function he_helper_after_build(&$form, &$form_state) {

  // add to the existing submit array to not override the default submit handler
  $form['actions']['submit']['#submit'][] = '_he_helper_custom_submit';

  // change the button text
  $form['actions']['submit']['#value'] = '2hello';

  return $form;
}

Comment: Thanks for your reply. I was wrong with my adoption that the "redirect" was working, cause it was not.
I dont know why, but the redirect wont work whatever I try...

I now tryied as well the after_build function, but it seems like that webforms is using that as well and when I use it, the form disappears :-/
Comment: You need to put return $form at the end of your after build function or the form will disappear!
Comment: Updated my top post
Comment: Your data isn't getting submitted because you are overwriting the default submit handler attached to the submit button (and that is where the data gets saved). Inspect the form array before making any changes to the form and see what the submit handler attached to the submit button is. Then when you make you changes make sure to call the default submit handler as well as your custom one.
Comment: I've also updated my answer to show how to add a submit handler without overwriting the existing one.

Webform custom submit handler rebuild


Pegar o valor de uma variável em SeekBar - Java / Android

Question: Sou iniciante em Java / Android e estou desenvolvendo uma aplicação com processamento de imagem. No momento já tenho a aplicação funcionando com os filtros necessários.
No caso tenho:
Canny(edges, edges, thresholdCanny, thresholdCanny2);

Gostaria de aplicar uma SeekBar para alterar os valores das variaveis thresholdCanny e thresholdCanny2 diretamente no aplicativo em execução, ou seja, ajustar a intensidade dos filtros.
Segue minha função já com a SeekBar implementada:
    public Mat onCameraFrame(final CameraBridgeViewBase.CvCameraViewFrame inputFrame) {

    // Image Processing
    Mat rgba = inputFrame.rgba();
    Mat edges = new Mat(rgba.size(), CV_8UC1);
    final int thresholdCanny = 80, thresholdCanny2 = 100;

    // SeekBar change value
    seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }
    });

    try {
        Imgproc.cvtColor(rgba, edges, Imgproc.COLOR_RGB2GRAY, 4);
        Imgproc.GaussianBlur(edges, edges, new Size(5,5), 30, 50);
        Canny(edges, edges, thresholdCanny, thresholdCanny2);
    } catch (Exception e) {
        Log.i(TAG, e.toString());
        e.printStackTrace();
    }

    return edges;
}

É possível capturar o atual valor de thresholdCanny e thresholdCanny2 dentro da onProgressChanged e ir substituindo os valores dessas variáveis de acordo com o movimento da SeekBar? Como posso fazer isso?
Agradeço desde já!
Answer: Para você obter o valor do SeekBar:
seekBar.getProgress();

E dentro do método onProgressChanged(SeekBar seekBar, int progress, boolean b) o progresso é o segundo parâmetro int progress
E para trocar os valores de final int thresholdCanny = 80, thresholdCanny2 = 100; você pode criar essas variáveis no escopo de classe:
private int thresholdCanny = 80;
private int thresholdCanny2 = 100;

Comment: Devo utilizar thresholdCanny = seekBar.getProgress(); ?
Uma outra duvida, é possível fazer com que essa variável assuma um valor com algum outro calculo?  exemplo:  thresholdCanny - 20 //
Obrigado
Comment: Pode fazer thresholdCanny = progress;
Comment: Nesse caso você pode criar um método `setThresholdCanny(int thresholdCanny)` e fazer o cálculo no método. E em vez de usar `thresholdCanny = progress;` você faz `setThresholdCanny(progress)`;. Assim fica mais flexível para criar cálculos etc.
Comment: Consegui, obrigado pela ajuda!


Failed to resolve: com.hbb20:ccp:2.4.5

Question: I have added this dependency in my app from github. I tried changing the version but it keeps giving the error "Failed to resolve: com.hbb20:ccp:2.4.5".
implementation 'com.hbb20:ccp:2.4.5'

This is the error in the build.
Failed to resolve: com.hbb20:ccp:2.4.5
Show in Project Structure dialog
Affected Modules: app

Answer: I also faced the same problem.
You need to update X Y and Z with the latest version. In my case it was 2.6.0.
You can find the latest version here

Failed to resolve: com.hbb20:ccp:2.4.5


Hearing overlapping sound

Question: When I sing/hum lets say C note and then play on a piano a C note too, the sound I hear overlap so that I can immediately know if its the same note or not.
I want to know if everyone can do this and why does the sound overlap?? if it does overlap because its the same note, why cant I hear that overlap when I play the same notes on piano, but only when I sing/hum the notes.
Comment: How do you play two of the same notes on the piano? There's only ever one of each, unless you involve octaves, which are the same name, not the same pitch.
Comment: What is the 'overlapping' effect in terms of sound?
Comment: @Tim it sounds like your voice and the notes you played become one.
Comment: @Tim yes the octaves
Comment: This may actually be a question about beat frequencies from additive/destructive interference of nearly identical notes, or binaural beat frequencies. Hard to tell.
Comment: richard - it is very difficult to understand what you are asking. Do you know the difference between the pitch of a note and the timbre?
Answer: Playing a note and simultaneously singing the same note is something most people can do, although there are some who are tone deaf and cannot sing the same note they hear.
Your question, though, is about something else. When you play two notes of the same name, on a piano, they must be at least an octave apart; pianos don't have the propensity to play two separate notes in unison, only in octaves. So, you're not hearing the same thing as you do when you play a certain note and sing it, at exactly that pitch, at the same time. Thus, the two effects won't be the same.
Answer: No, not everyone can do this (although those who can often have a hard time imagining that anyone might not be able to).
For instance, one of the tests often given to prospects for military recruiting is how well they can distinguish tones of grossly or slightly different pitch. This is supposed to indicate how well they would do e.g. at signal communications jobs. (Needless to say, musicians are also almost exclusively recruited from people who are good at it.)

Hearing overlapping sound


Find position knowing 2 points and distances to those points

Question: I have a problem that I am trying to solve and I don't know how to approach it.
I am trying to position myself in 2d space using Bluetooth Beacons.
Basically i have my 2 beacons:

BEACON 1 at coordinates (50, 638)
BEACON 2 at coordinates (586, 10)

I can calculate the distance to these beacons and for example I get:

Distance to BEACON 1 = 188 cm
Distance to BEACON 2 = 646 cm

And I need to find the coordinates of where I am.
It would have been easier to do if I had 3 beacons, but I think it may be possible with 2 as well. As I thought about it there can be 2 positions where I could possibly be, so that the distances that I found to be correct.
We can see here in this drawing that I made:

I'm sure there should be some kind of formula in order to find these 2 possible coordinates. I have though about how should I calculate them but I didn't come up with anything. Can someone help me with finding this coordinates?
Comment: What are the equations you would get if you were standing at point $(x,y)$?
Comment: What do you mean
Comment: Look at the method to find the intersection of two circles.
Comment: For example, The distance from $(x,y)$ to beacon 1 would be $\sqrt{(x-50)^2+(y-638)^2}=188$. Do that for the other beacon and you have two equations in two variables
Answer: You can use this formula:
$$\begin{align}
x&=\frac{l}{d}(x_2-x_1) \pm \frac{h}{d}(y_2-y_1) + x_1,\\
y&=\frac{l}{d}(y_2-y_1) \mp \frac{h}{d}(x_2-x_1) + y_1.\\
\end{align}$$
Where:
$$\begin{align}
d&=\sqrt{(x_1-x_2)^2+(y_1-y_2)^2}\\
l&=\frac{r_1^2-r_2^2+d^2}{2d}\\
h&=\sqrt{r_1^2-l^2}
\end{align}$$
$r_1=$ distance to BEACON 1,$r_2=$ distance to BEACON 2
This will give you the 2 possible coordinates $(x_1,y_1)$ $(x_2,y_2)$ where you may be standing.


Add main/java classes to my test/java directory in intellij

Question: I am new to intellij. I am switching from eclispe Kepler.
I do not have a maven project, but I do have a maven directory structure. My classes are in src/main/java with my tests in src/test/java.
My unit tests are complaining because they can't find the classes from src/main/java. What is the proper way to add this to the build path so that my unit tests can find the source?
Comment: I don't think it's a duplicate because adding the junit jar file did not fix this problem.
Comment: Appologies, I should read the question more carefully.
Comment: The directories structures for tests and tested classes must fit. Here is how to do it easily: stackoverflow.com/a/36057080/715269
Answer:
Right click the "src/main/java" directory and select "Mark directory
as > Sources root".
Right click the "src/test/java" directory and select "Mark directory
as > Test Sources root"

Also, make sure you use packages underneath your source folders.
Comment: @TheThom ok, are you using packages?
Comment: Yes. Both the original class and the unit test are in the same package, although in different directories.
Comment: Does IntelliJ have any suggestions for what classes that it's indicating are in error in the tests?
Comment: @NickHolt Not sure i follow your question. I'm getting cannot find symbol: class ConnectHistory location ConnectHistoryTest. I'm getting no further advice. I tried using Ctrl+Alt+O to see if it would straighten things out, but no luck.
Comment: Before you compile, if you look at `ConnectHistoryTest` the IDE will highlight the errors - I'd expect to see an error on the import of `ConnectionHistory` and an error where it's used.  If you put the cursor on the point that it's used IntelliJ will suggest a class to import or nothing if there's no obvious choices - does that happen?
Comment: @NickHolt Because they are in the same package, no import is necessary. The error is in the first reference to ConnectHistory. It simply indicates Cannot resolve symbol.
Comment: The IDE doesn't seem to think they're in the same package, otherwise it would work.  Are there errors in `ConnectionHistory`?
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/45298/discussion-between-the-thom-and-nick-holt)
Answer: Jetbrains directed me to here: http://www.jetbrains.com/idea/webhelp/configuring-module-dependencies-and-libraries.html. I added the main/java directory as a module dependency under the test module and everything started working.


Should adapters in Android be static inner classes or non-static inner classes

Question: I have a ListView in an Activity and I am setting a custom adapter to the ListView.
Should my adapter class be:
private static class MyAdapter extends ArrayAdapter

or
private class MyAdapter extends ArrayAdapter

I guess it should make no difference as long as the adapter is enclosed within the activity reference but wanted to confirm that.
Comment: (For future readers) The last question is backwards. If you have a static inner class, and need access to the activity/context, you should use a WeakReference (if there is anything that could outlive the activity). If the class is not static and inner, it has an implicit strong reference to the outer class. In that case, you'd also still need to be careful about how the adapter is used. Using static can help find implicit leaks, but adds overhead in passing around a context/weakreference.
Comment: Also, in any of the calls into an adapter that take a View object, the context is available (View.getContext()). You can use instanceof to make sure it's your activity.
Answer: Holding onto the context is fine from within an adapter if you are careful about how you use the adapter. Adapters are usually tied to the lifecycle of their Context (an Activity) so it's fine. Use a WeakReference only if it makes sense.
Comment: No, because onDestroy() isn't a guaranteed call, from what I understand.
Comment: Don't keep the adapter in a static field that lives longer than your activities for instance.
Comment: Could you elaborate more on "being careful how to use the adapter" part? So it seems it shouldn't matter which of the two since the adapter is tied to the Activity life cycle.
Comment: @RomainGuy what about if we explicitly `null` the static adapter object in `onDestroy()`? is it a good approach?


Distribution of ranges of normally distributed variables

Question: I have four independent variables $x_i$, each of them normally distributed with $\mu = 0$ and $\sigma = 1$. What is the distribution of the range of the four variables, i.e., $\max(x_i) - \min(x_i)$?
For example, I draw a random sample of $n=10000$ of each variable and calculate the $\Delta x  = \max(x_i) - \min(x_i)$, which gives $10000$ range values. I am interested in the expected distribution of this range value $\Delta x$ under the condition that each $x_i$ is normally distributed as explained above.
Comment: The phrase "peak-to-valley," which apparently has nothing to do with the *range* of the sample you describe, suggests you might have a different setting in mind: are you sure you have asked a question relevant to your underlying statistical problem?
Comment: @whuber is correct. With "Peak-to-Valley" in finance we denote the distance between the local minimum (maximum) and the next local maximum (minimum) with the term "Maximum Drawdown". Maybe you want to derive the distribution of the maximum drawdown. A quick google search will give you some paper addressing your question (if you are concerned with this measure)
Answer: The range of a sample $X = x_1, x_2, \ldots, x_n$ is the difference between its maximum $x_{(n)}=\max(X)$ and minimum $x_{(1)}=\min(X):$
$$\operatorname{range}(X) = x_{(n)} - x_{(1)}.$$
When $X$ is a simple random sample of size $n\ge 2$ from a continuous distribution with distribution function $F$ and density function (PDF) $f=F^\prime,$ the joint distribution of the minimum and maximum is also continuous and, following the analysis at https://stats.stackexchange.com/a/78559/919, has a density function
$$f_{(X_{(1)}, X_{(n)})}(x,y) = n(n-1) f(x)f(y)\left(F(y)-F(x)\right)^{n-2}\, \mathcal{I}(y\ge x).$$
(The indicator $\mathcal{I}(y\ge x)$ means this function is zero when $y \lt x.$)
Upon changing variables from $(x,y)$ to $(x,r)$ with $r=y-x\ge 0$ representing possible values of the range, it follows that $$\mathrm{d}x\mathrm{d}y = \mathrm{d}x\mathrm{d}(x+r) = \mathrm{d}x\mathrm{d}r$$ and you can then integrate out the variable $x$ to obtain the PDF for the range,

$$f_{\operatorname{range}(n)}(r) = n(n-1)\mathcal{I}(r\ge 0)\,  \int_{\mathbb R} f(x)f(x+r)\left(F(x+r)-F(x)\right)^{n-2}\mathrm{d}x.$$

I understand $f_{\operatorname{range}(4)}$ responds to the question's request for an "expected distribution."
In general--and particularly for Normal distributions--there is no closed form expression for the integral: it needs to be evaluated numerically.  Neither is there generally a closed form expression for its expectation; that too requires numerical evaluation.  But for modest values of $n$--less than $10^{36},$ approximately, when working in double precision--these integrals can be accurately evaluated.
As an example, the following plots show (from left to right)

A histogram of the results of 100,000 simulated ranges of standard Normal samples of $n=4$ observations on which a plot of $f_{\operatorname{range}(4)}$ is superimposed to show how closely the numerical integral adheres to the simulated frequencies;

Plots of $f_{\operatorname{range}(n)}$ for $n=3$ (red) through $n=6$ (blue), with that for $n=4$ outlined in black, to show how the range distribution changes with sample size;

A plot of $f_{\operatorname{range}(10^{36})}$ to show what the range distribution looks like for large $n.$

The following R code produced the figure.  It shows how to compute $f_{\operatorname{range}(n)}$ numerically and how to simulate ranges.
#
# Compute the density of the Normal range distribution at value `r` for a
# sample of size `n`.
#
f <- Vectorize(function(r, n, mu=0, sigma=1, ...) {
  q <- qnorm(1e-4/n)
  f <- function(x) dnorm(x, mu, sigma, log=TRUE)
  ff <- function(x) pnorm(x, mu, sigma, log=TRUE)
  logdiff <- function(y, x, k) {
    u <- x-y
    ifelse(2*u < log(.Machine$double.eps), y-exp(u), y+log(1-exp(u))) * k
  }
  h <- function(x,y) {
    log(n) + log(n-1) + f(x) + f(y) + logdiff(ff(y), ff(x), n-2)
  }
  integrate(function(x) exp(h(x,x+r)), mu+q*sigma, mu-q*sigma, ...)$value
}, "r")
#
# Simulate a large number of ranges of samples of size `n`.
# This takes about a second for n=10^5.
#
n.sim <- 1e5
n <- 4
set.seed(17)
x <- apply(matrix(rnorm(n.sim*n), ncol=n.sim), 2, function(y) diff(range(y)))
#
# Create the figure.
#
par(mfrow=c(1,3))
#
# Histogram of the simulation.
#
hist(x, freq=FALSE, breaks=50, cex.main=1,
     xlab="Range",
     main=expression(paste("Histogram of ", 10^{5}, " Standard Normals"))
)
curve(f(x, n), add=TRUE, lwd=2, n=201)
#
# Plots of `f` for small `n`.
#
range.plot <- function(n, add=FALSE, n.pts=201, color="Gray", outline="Black", ...) {
  x <- seq(max(0, -2*qnorm(1/n)-3), -2*qnorm(1/n)+5, length.out=n.pts)
  y <- f(x, n, stop.on.error=FALSE, rel.tol=1e-8)
  i <- y > 1e-3
  if(!isTRUE(add))
    plot(x[i], y[i], type="n", xlab="Range", ylab="Density",
         main=expression(paste("PDF for Range of ", 10^{36}, " Standard Normals")),
         ...)
  polygon(x, y, col=color, border=NA)
  lines(x, y, lwd=2, col=outline)
}
plot(c(0,6), c(0,.5), type="n", cex.main=1,
     main=expression(paste("PDFs for Ranges of ", 3-6, " Standard Normals")),
     xlab="Range", ylab="Density")
invisible(sapply(3:6, function(i) {
  a <- sapply(c(.4, .9), function(a) rainbow(5, 0.7, 0.9, alpha=a)[i-2])
  range.plot(i, add=TRUE, color=a[1], outline=a[2])
}))
curve(f(x, 4), add=TRUE, lwd=2, n=201)
#
# Plot `f` for very large `n`.
#
range.plot(1e36, n.pts=501, cex.main=1)
par(mfrow=c(1,1))

Comment: Why the `log=TRUE` in the calls to `dnorm` and `pnorm`? I mean, how did you get to the conclusion that it was better to use logarithms...?
Comment: @Vicent This reduces loss of precision when working in finite precision arithmetic.  It's part of the art of scientific computation.


Learning the piano and theory without a teacher?

Question: I recently ordered a keyboard, and I plan to buy online courses to learn the piano and theory. I can afford a teacher, however, due to some circumstances in my life, it's hard to attend the lessons at a specific time during the day. I do plan to get a piano teacher somewhere at the end of the next year.
Would it be a good idea to learn the piano and the theory online? Can I get decent at it by learning on my own? I do assume a teacher would be able to point out mistakes earlier, whereas on my own it would take more time to find out my mistakes and I might then have to unlearn those. However, since I do plan to get a teacher next year, would learning the piano and theory on my own right now still benefit me?
Some more information about me:

I'm 26 years old

I can practice the piano daily 45-60 minutes

I have almost no prior knowledge of music theory, other than I do know what notes, accidentals, octaves are.
Comment: Does this answer your question? [Learning Piano without a teacher](https://music.stackexchange.com/questions/14130/learning-piano-without-a-teacher)
Comment: Not knowing anything about you, the best responses will be personal opinions, which won't be too helpful. This will possibly be closed.
Answer: Yes and no.
If you know nothing about music theory, then the theory that you'd be learning while simultaneously learning how to play the piano is relatively basic (doesn't mean it's not important, but it'll be the "addition" and "multiplication" and not the "algebra", so to speak). Because of that, I think that it'd be hard to learn wrong things. On a personal note, I HIGHLY recommend the Faber and Faber adult piano method.
That being said, DO start eventually learning with a teacher, and sooner is better than later. Also, if you have the opportunity, take ONE lesson with a teacher, and make sure that they understand that this is a "what should I do/not do starting out?".


Module with extensive list of RGB colors to create dictionary

Question: I'd like to create a long dictionary of RGB colors, e.g.,
{'blue': (0, 0, 150), 'black': (0, 0, 0), 'green': (0, 150, 0), 'red': (150, 0, 0)}

However, I'd like a extensive dictionary containing many color. I have been unable to find a module that contains information like this.
I am aware I could crawl a website that has this information, but I would prefer to simply import it from a module.
Does such a module resource exist? If not, are there other easy solutions to this problem?
Comment: Or this? https://pypi.python.org/pypi/webcolors/1.3
Answer: Depending on what set of colors you're looking for the web colors might be a good set. There are libraries others have written for these, like webcolors.
Answer: Recently I have found module which can give a dictionary of colors with names (real color name in css) and hex values. Here I have post the code and you can see the result.
import matplotlib

rgb_colors = {}
for name, hex in matplotlib.colors.cnames.items():
    rgb_colors[name] = matplotlib.colors.to_rgb(hex)

print(rgb_colors)

You asked this question 3 years before, anyway I think my answer may be useful for future readers.
Answer: Refer: https://pypi.org/project/colordict/
You can get a dictionary  of RGB Colors like this:
from colordict import ColorDict
colors = ColorDict()
print(colors)

You will get almost all the colors you will ever need.
Output: {'aliceblue': (240.0, 248.0, 255.0, 255.0), 'antiquewhite': (250.0, 235.0, 215.0, 255.0), 'aqua': (0.0, 255.0, 255.0, 255.0), 'aquamarine': (127.0, 255.0, 212.0, 255.0)... }

You can access color values using their names as key:
red = colors['red']


How do I contrast code for a factor where one level is the application of both of two others?

Question: I have a factor 'Music' that has four levels: none, piano, guitar, and mixed. Subjects gave a response hearing no music, piano only, guitar only, or piano and guitar, so I want to create an lmer model Response ~ Music + (1 | PersonID).
contrasts(Music)

gives me:
         Piano Guitar Mixed
None      0     0    0
Piano     1     0    0
Guitar    0     1    0
Mixed     0     0    1

but I feel there should be some indication that Mixed is actually the application  of both piano and guitar.
My question is:
Should I indicate the link between the levels? Do I do it by contrast coding? How?
I tried contrasts(Music) <- cbind( 1, c(0,1,0,1), c(0,0,1,1), c(0,0,0,1) ) as @Greg Snow suggested and got
contrasts(Music)
      [,1] [,2] [,3]
None    1    0    0
Piano   1    1    0
Guitar  1    0    1
Mixed   1    1    1
But this gives an error fixed-effect model matrix is rank deficient so dropping 1 column / coefficient
Comment: Where you write "is actually the sum of," does that mean you expect the coefficient of `Mixed` in this model to be the sum of the coefficients of `Piano` and `Guitar`?
Comment: whuber, I've amended the question. I expect Mixed to have a greater effect than the sum of its parts. Thank you.
Comment: If I correctly understand what you intend, you can either have a "no-piano/piano" and a "no-guitar/guitar" factor, and pick up "mixed" via an interaction term, *or* you can have a single factor with "none/piano/guitar/mixed".
Comment: Thanks Glen_b. What are the advantages/disadvantages of each?
Answer: With the current/default contrasts the coefficients will represent the difference between the baseline of "None" with each of the other levels.
There are a couple of options, the first is to recode as 2 factors with Piano being Yes/No and Guitar being Yes/No, then fit the 2 factors and their interaction.
Another option is to set a different set of contrasts (really a dummy variable encoding).  You can use the assignment form of the contrasts function to do this:
contrasts(Music) <- cbind( 1, c(0,1,0,1), c(0,0,1,1), c(0,0,0,1) )

and then the coefficients will represent the same idea as splitting and including the interaction, i.e. the 3rd coefficient will represent the difference from the additive model.


Can't load a background image using Pygame

Question: I just started programming my first game with Pygame and Pycharm. I'm trying to load the background image in the following code, but an error occurs.
import os
import pygame
import pygame.locals
#objects        (classes, functions)

#setup          (run-once code)
worldx = 960
worldy = 720
fps = 40
ani = 4          #animation cycles
clock = pygame.time.Clock()
pygame.init()
world = pygame.display.set_mode([worldx,worldy])
current_path = os.path.dirname(__file__)
image_path = os.path.join(current_path, 'images')
backdrop = pygame.image.load(os.path.join(image_path, 'stage.png'))
backdropbox = world.get_rect()
BLUE = (25,25,200)
BLACK = (23,23,23)
WHITE = (254,254,254)

#main loop      (game loop)

And this is the error message:
pygame.error: Couldn't open C:/Users/Justus/PycharmProjects/Vulcanoreal_game.py\images\stage.png

Can somebody please help me? And by the way, my English is not the best, sorry ;)
Comment: Look at the image path. You mixed slashes "/" and "\"
Comment: I'd recommend using [`pathlib`](https://docs.python.org/3/library/pathlib.html) instead of `os.path`. It's generally more intuitive for building paths.
Comment: @Dmitry I don't know how to change this. Can you give me the finished code?
Comment: @Dmitry A mix of slashes and backslashes as path delimiters will work without problems  on Windows. The question is: does the path `C:/Users/Justus/PycharmProjects/Vulcanoreal_game.py\images\stage.png` exist?
Comment: Use `os.path.isfile()` to check if the file path is correct before using it. Post the full error message. A part of it is not much of a help.
Answer: Import:
import pathlib

Your current path should be:
current_path = pathlib.Path().absolute()

image_path = os.path.join(current_path, 'images')

backdrop = pygame.image.load(os.path.join(image_path, 'stage.png'))

Comment: Thank you so much, it worked : ) My motivation is back!
Comment: Did this help you?
Comment: First of all, thank you very much for the many answers from you. Only backslashes appear in the file path now. But it still doesn't work. I have tried a little bit and now no more errors appear. But the image is still not loaded. I don't get an error message anymore, but the screen that appears is just black and you can't see a picture. Is the picture too big? It is 1,90 MB big and Full HD.
Comment: You are welcome =) I'm not an expert in pygame but I tested this solution and it worked. In main game loop: `world.fill(BLUE)` `world.blit(backdrop, backdropbox)` `pygame.display.flip()` Please try it.


How to overwrite modules by default with DRUSH?

Question: I am using a module list from Drupal 7 to populate a Drupal 8 site.
Some modules are now included in core, so there are a lot of confirm overwrite messages like this:
<code> Install location C:\drupal-8.0.1//modules/imagecache_actions already exists. Do
you want to overwrite it? (y/n):
</code>
What is the command for default Y or N ?
Now I use this command:
<code> drush en module -y
</code>
But I would like to set default answer to "overwrite yes" if module is already enabled or already exists and downloaded so I don't have to manually enter Y everytime
Answer: Overwrite
Allows the project to be installed in a directory that is not empty. If not specified this is treated as FALSE, Drush make sets an error when the directory is not empty. If specified TRUE, Drush make will continue and use the existing directory. Useful when adding extra files and folders to existing folders in libraries or module extensions.
<code>projects:
  myproject:
    overwrite: TRUE
</code>
Comment: This answer is for Drush make. The question was for Drush pm-enable.
Comment: Yes indeed, this is for simple drush command to install modules, looking for the equivalent of overwrite options in FTP


WPF VB.NET Binding Image Source From String in Data Template

Question: My first WPF application (please be gentle!), and I'm making an app based on events during a football match. So I've set up a Player class, and one of the properties is Nationality eg: Scotland. Then I have a DataTemplate, but rather than the string "Scotland" showing up, I would like an image of the national flag to show up instead. All my images are in Images/Countries then are named Scotland.png etc...
The line of code in my data template which I need the binding is:
<Image x:Name="Player_Nationality_Image" Margin="0,0,0,0" Grid.Column="4"Source="Images/Countries/Scotland.png" Height="14" Width="14"/>

Is there an easy way to change my class slightly and bind the image source based on this Nationality property alone? Do I need something in between to convert this?
Here is my Player.vb class:
Imports System.Collections.ObjectModel
Imports System.ComponentModel

Public Class Player
Implements INotifyPropertyChanged

Private playerFirstNameValue As String
Private playerSurnameValue As String
Private playerShirtNameValue As String
Private playerSquadNumberValue As Integer
Private playerDOBValue As Date
Private playerPlaceOfBirthValue As String
Private playerNationalityValue As String

Private playerCategoryValue As Position
Private specialFeaturesValue As SpecialFeatures

Private teamValue As ObservableCollection(Of Team)

Public Event PropertyChanged As PropertyChangedEventHandler Implements INotifyPropertyChanged.PropertyChanged

Public Property FirstName() As String
    Get
        Return Me.playerFirstNameValue
    End Get
    Set(ByVal value As String)
        Me.playerFirstNameValue = value
        OnPropertyChanged("FirstName")
    End Set
End Property

Public Property Surname() As String
    Get
        Return Me.playerSurnameValue
    End Get
    Set(ByVal value As String)
        Me.playerSurnameValue = value
        OnPropertyChanged("Surname")
    End Set
End Property

Public Property ShirtName() As String
    Get
        Return Me.playerShirtNameValue
    End Get
    Set(ByVal value As String)
        Me.playerShirtNameValue = value
        OnPropertyChanged("ShirtName")
    End Set
End Property

Public Property SquadNumber() As Integer
    Get
        Return Me.playerSquadNumberValue
    End Get
    Set(ByVal value As Integer)
        Me.playerSquadNumberValue = value
        OnPropertyChanged("SquadNumber")
    End Set
End Property

Public Property StartDate() As Date
    Get
        Return Me.playerDOBValue
    End Get
    Set(ByVal value As Date)
        Me.playerDOBValue = value
        OnPropertyChanged("DateofBirth")
    End Set
End Property

Public Property PlaceOfBirth() As String
    Get
        Return Me.playerPlaceOfBirthValue
    End Get
    Set(ByVal value As String)
        Me.playerPlaceOfBirthValue = value
        OnPropertyChanged("Surname")
    End Set
End Property

Public Property Nationality() As String
    Get
        Return Me.playerNationalityValue
    End Get
    Set(ByVal value As String)
        Me.playerNationalityValue = value
        OnPropertyChanged("Nationality")
    End Set
End Property

Public Property Position() As Position
    Get
        Return Me.playerCategoryValue
    End Get
    Set(ByVal value As Position)
        Me.playerCategoryValue = value
        OnPropertyChanged("Position")
    End Set
End Property

Public Property SpecialFeatures() As SpecialFeatures
    Get
        Return Me.specialFeaturesValue
    End Get
    Set(ByVal value As SpecialFeatures)
        Me.specialFeaturesValue = value
        OnPropertyChanged("SpecialFeatures")
    End Set
End Property

Public ReadOnly Property Team() As ReadOnlyObservableCollection(Of Team)
    Get
        Return New ReadOnlyObservableCollection(Of Team)(Me.teamValue)
    End Get
End Property

Public Sub New(ByVal FirstName As String, ByVal Surname As String, ByVal ShirtName As String, ByVal PlaceOfBirth As String, ByVal NationalityImageSourceString As String, ByVal Category As Position, ByVal squadNumber As Integer, ByVal DOB As Date, ByVal specialFeatures As SpecialFeatures)
    Me.playerFirstNameValue = FirstName
    Me.playerSurnameValue = Surname
    Me.playerShirtNameValue = ShirtName
    Me.playerPlaceOfBirthValue = PlaceOfBirth
    Me.playerNationalityValue = Nationality
    Me.playerDOBValue = DOB
    Me.playerSquadNumberValue = squadNumber

    Me.playerCategoryValue = Category
    Me.specialFeaturesValue = specialFeatures
    Me.teamValue = New ObservableCollection(Of Team)()
End Sub

Protected Sub OnPropertyChanged(ByVal name As String)
    RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(name))
End Sub
End Class

Public Enum Position
    GK
    DF
    MF
    FW
End Enum

Public Enum SpecialFeatures
    None
    Yellow
    Red
    SubbedOff
    SubbedOn
    Highlight
End Enum

Data Template in Application.xaml:
<DataTemplate DataType="{x:Type src:Player}">

        <Button Name="Player_Button" Style="{StaticResource Player}" Height="24" Width="320" Margin="0,2,0,0">
            <Grid HorizontalAlignment="Center" Width="300">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="20"></ColumnDefinition>
                    <ColumnDefinition Width="210"></ColumnDefinition>
                    <ColumnDefinition Width="10"></ColumnDefinition>
                    <ColumnDefinition Width="30"></ColumnDefinition>
                    <ColumnDefinition Width="30"></ColumnDefinition>

                </Grid.ColumnDefinitions>

                <TextBlock Name="Player_Number_Text" Grid.Column="0" FontFamily="Font/#Gotham Narrow Bold" Text="{Binding Path=SquadNumber}" Margin="0,0,0,0" HorizontalAlignment="Left" />
                <StackPanel Orientation="Horizontal" Grid.Column="1">
                    <TextBlock Name="Player_FirstName_Text" FontFamily="Font/#Gotham Narrow Bold" Text="{Binding Path=FirstName}" Margin="5,0,0,0" HorizontalAlignment="Left" />
                    <TextBlock Name="Player_Surname_Text" FontFamily="Font/#Gotham Narrow Bold" Text="{Binding Path=Surname}" Margin="5,0,0,0" HorizontalAlignment="Left" />
                </StackPanel>
                <Rectangle Name="Player_Card" Grid.Column="2"></Rectangle>
                <TextBlock Name="Player_Position_Text" Grid.Column="3" FontFamily="Font/#Gotham Narrow Bold" Text="{Binding Path=Position}" Margin="5,0,0,0" />
                <Image x:Name="Player_Nationality_Image" Margin="0,0,0,0" Grid.Column="4" Source="Images/Countries/Scotland.png" Height="14" Width="14" />

            </Grid>
        </Button>

        <DataTemplate.Triggers>
            <DataTrigger Binding="{Binding Path=SpecialFeatures}">
                <DataTrigger.Value>
                    <src:SpecialFeatures>Yellow</src:SpecialFeatures>
                </DataTrigger.Value>
                <DataTrigger.Setters>

                    <Setter Property="Fill" Value="Yellow" TargetName="Player_Card" />

                </DataTrigger.Setters>
            </DataTrigger>
            <DataTrigger Binding="{Binding Path=SpecialFeatures}">
                <DataTrigger.Value>
                    <src:SpecialFeatures>Highlight</src:SpecialFeatures>
                </DataTrigger.Value>

                <Setter Property="Fill" Value="Blue" TargetName="Player_Card" />

            </DataTrigger>
        </DataTemplate.Triggers>
    </DataTemplate>

Comment: Couldn't your player class just expose a property that returns an ImageSource? Player would be responsible for returning the correct image.
Comment: Yes, but I'm unsure how. Especially as it should be as simple as adding the path and .png to whatever Nationality. I've tried a few things, but I keep getting 'Cannot convert String to ImageSource' errors when I try and add a New test Player.
Answer: You'll need to implement an IValueConverter.
Somewhere in your solution add the following class. (I highly recommend making a converter folder and dumping all converters to be used throughout the application in this folder so you can find and modify them easily down the track.)
Imports System.ComponentModel
Imports System.Windows.Data
Imports System.Windows.Media

Public Class StringToImageConverter
    Implements IValueConverter

    Public Sub New()
    End Sub

    Public Function Convert(value As Object, targetType As Type, parameter As Object,        culture As System.Globalization.CultureInfo) As Object _
    Implements IValueConverter.Convert

             Select Case value
            Case "Scotland"
                '
                Return New ImageSourceConverter().ConvertFromString("/YOURSOLUTION;component/Images/Countries/Scotland.png")
                '
           Case "Australia"
                '
                Return New ImageSourceConverter().ConvertFromString("/YOURSOLUTION;component/Images/Countries/Australia.png")
                '
        Case Else
                Return Nothing
        End Select

    End Function

    Public Function ConvertBack(value As Object, targetType As Type, parameter As Object, culture As System.Globalization.CultureInfo) As Object _
    Implements IValueConverter.ConvertBack

    End Function
End Class

In Application.xaml place the following code.
 <Form.Resources>
        <my:StringToImageConverter x:Key="StringToImageConverter" />
  <Form.Resources>

 <Button Name="Player_Button" Style="{StaticResource Player}" Height="24" Width="320" Margin="0,2,0,0">
            <Grid HorizontalAlignment="Center" Width="300">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="20"></ColumnDefinition>
                    <ColumnDefinition Width="210"></ColumnDefinition>
                    <ColumnDefinition Width="10"></ColumnDefinition>
                    <ColumnDefinition Width="30"></ColumnDefinition>
                    <ColumnDefinition Width="30"></ColumnDefinition>

                </Grid.ColumnDefinitions>

                <TextBlock Name="Player_Number_Text" Grid.Column="0" FontFamily="Font/#Gotham Narrow Bold" Text="{Binding Path=SquadNumber}" Margin="0,0,0,0" HorizontalAlignment="Left" />
                <StackPanel Orientation="Horizontal" Grid.Column="1">
                    <TextBlock Name="Player_FirstName_Text" FontFamily="Font/#Gotham Narrow Bold" Text="{Binding Path=FirstName}" Margin="5,0,0,0" HorizontalAlignment="Left" />
                    <TextBlock Name="Player_Surname_Text" FontFamily="Font/#Gotham Narrow Bold" Text="{Binding Path=Surname}" Margin="5,0,0,0" HorizontalAlignment="Left" />
                </StackPanel>
                <Rectangle Name="Player_Card" Grid.Column="2"></Rectangle>
                <TextBlock Name="Player_Position_Text" Grid.Column="3" FontFamily="Font/#Gotham Narrow Bold" Text="{Binding Path=Position}" Margin="5,0,0,0" />
        <Image Source="{Binding Path=Nationality, Converter={StaticResource StringToImageConverter}}" Stretch="None" />

            </Grid>

Hope this helps.
Comment: Could I do this a bit more dynamically?                                                          Return New ImageSourceConverter().ConvertFromString("/YOURSOLUTION;component/Images/Countries/" & value & ".png")


Use dynamic number of hooks in React

Question: Let's say I have a hook, useX() that returns some states and functions. I do an API request that returns some (dynamic amount of) strings (for example, "a" and "b").
I want to have a dictionary mapping these strings to instances of useX(), something like: x = {a: useX(), b: useX()}, so I can do actions like x.a.someFunction() or x.a.someState.
I know React doesn't let you call hooks inside loops, so I wonder whether this is even possible at all. Please help!
Comment: Not sure what's your exact use case. But if I understand it correctly you could create one hook that is handling your events. Something like in the following [Codesandbox](https://codesandbox.io/s/epic-brahmagupta-sddx3w?file=/src/App.js).
Answer: I think what you're facing is XY problem, you've found a problem and figured out that this is the solution, and you asked your question about the solution, not the original question..
Your problem is that you want to use "Dynamic number of hook calls.
Is this possible? No.
However, is this the solution? still a No
Your solution is basically to use one big hook or multiple hooks to solve your problem.
What's I've understood from your problem though is that you want something like events, in this case, see Redux

Use dynamic number of hooks in React


Estimating separate smooths for a factor with hundreds of levels using GAMs

Question: I am fitting a smooth-factor interaction term to a longitudinal microbiome abundance data set using GAMs.
model <- gam(Abundance ~ s(Time, by = Genus) +
             Batch + s(AnimalId, bs = "re"))

I am interested in estimating separate smooths for each level of the Genus factor.  The factor includes hundreds of levels, but I am unsure whether or not this is the right approach for a dataset with sparseness.
Now, there are specific genera that I am interested in based on previous exploratory analysis, but I noticed that when I ran separate models on subsets of the Genus factor, the effective degrees of freedom tended to decrease as a function of the number of levels I was looking at.
My main question(s) are:

Why do the effective degrees of freedom decrease as a function of nlevels(Genus)?
What are the pros/cons of removing features with low sample prevalence or abundance?
Is this a reasonable approach for estimating separate smoothing functions for this type of dataset?
Comment: Couple of things: 1. Can you clarify your model as `s(numeric, factor)` if that's literally what you used makes no sense and won't work - you're missing something to specify the `bs`. 2. Can you show how the EDF changes as you add more data and increase the number of levels in `Genus`?
Comment: That's your problem... you probably don't want to use the `by` mechanism for this but any time you do use a factor `by` smooth you *must* include the factor as a parametric term. I suspect what's happening is that in order to model the different means, the smooths are changing shape and becoming less wiggly (using fewer EDFs) in order to simply model the differences in mean abundance between the genera.
Comment: @GavinSimpson I updated the model in the post.  See [link](https://gist.github.com/cdeanj/be7e95329c12ba28fbf2b061b67f2568) to gist with model output.  Let me know if additional clarification is needed.
Answer: Q1
You probably don't want to use the by mechanism for this many factor levels but any time you do use a factor by smooth you must include in the model as a parametric term the factor. I suspect what's happening is that in order to model the different means, the smooths are changing shape and becoming less wiggly (using fewer EDFs) in order to simply model the differences in mean abundance between the genera.
Your model then should be:
model <- gam(Abundance ~ Genus +
               Batch +
               s(Time, by = Genus) +
               s(AnimalId, bs = "re"),
             family = something,
             method = "REML")

Q2
A big con is that you can no longer get estimates for the genera you left out. A pro is that it might not be possible to model (easily) those low prevalence genera or modelling them might require a much more complex model to capture the differences in abundance and varying mean-variance relationships than if you just modelled the most abundant genera.
Whether either of these is a big deal depends on the questions you are trying to answer.
Q3
I would suggest that for something where you have 10s or more levels of a factor, you might want to rethink using the factor by approach. Instead I would gravitate towards the fs basis type which treats the collection of smooths more like true random effects to give a "random smooth" which includes random intercepts and slopes for each genera plus random wiggly terms. The constraint on the fs that makes it feasible for data of this sort is that we only have one set of smoothing parameters to estimate instead of a separate smoothing parameter for each genera. The implication of this is that we are explicitly assuming that the smooth for each genera has the same overall wiggliness, but potentially different shapes. With the factor by smooth formulation you are explicitly accepting that the smooth for each genera could have a different wiggliness.
As described above, a starting model using the fs basis would be:
model <- gam(Abundance ~ Batch +
               s(Time, Genus, bs = "fs") +
               s(AnimalId, bs = "re"),
             family = something,
             method = "REML")

noting that we have dropped the parametric term Genus as the s(Time, Genus, bs = "fs") includes a random intercept for each level of Genus.
If you have such large amounts of data you should be looking at the mgcv::gamm() function or better gamm4::gamm4() to do the modelling as the fs basis is designed to be more efficient there, or even more likely mgcv::bam() if the model and data are large enough.


Cannot access local domain

Question: I have setup a DNS server in a LAN. the BIND9 DNS server sits on 192.168.1.65
after setting my computer(macbook)'s dns server to 192.168.1.65, i am able to access the local domain setted up using bind, http://xyz.local/.
But when I access the url on the ubuntu server itself, it tells me that the url cannot be found. I can dig the link without problem, but the nslookup failed.
Any idea on how can I fix it so that the dns ubuntu box itself can also resolve the url?
Comment: What's in /etc/resolv.conf on the server? It is probably pointing to wrong dns server.
Comment: @rvs this is the content of /etc/resolv.conf: nameserver 192.168.1.65
Answer: Could be mDNS/DNS-SD.
The symptoms would be that name-resolution that goes through nss/libc fails (i.e. when you use applications like a browser, ping, etc.) but name-resolution with applications that query dns directly themselves (i.e. host, dig, etc.) succeeds in resolving the name.
If this is the case, on ubuntu you could try changing the hosts-entry in the file /etc/nsswitch.conf (remove mdns4_minimal [NOTFOUND=return]) to say something like:
hosts:          files dns mdns4

Comment: another problem is that the ubuntu keeps overwriting the dns ip in resolv.conf after reboot, how can i add 192.168.1.65 to it permly
Answer: Point your server's dns to 127.0.0.1 (/etc/resolv.conf) and configure bind to forward the rest to your original isp dns-es.
Btw. Do you have reverse dns configured for your network addresses?
Comment: hi, yes i do have the reverse dns zone, the problem now is the other computer can access the local domains without problem, only the machine host the dns cannot resolve the domain, i also tried adding nameserver 127.0.0.1 to /etc/resolv.conf, but no luck..
Comment: do i need to restart the server ?
Answer: Have you tried restart the system, in order to flush any caches.
Also when you start nslookup and give the command server, what nameserver it writes.
Ex:
> server
Default server: 192.168.1.8
Address: 192.168.1.8#53

Comment: > server
Default server: 192.168.1.65
Address: 192.168.1.65#53

Cannot access local domain


Meaning of $\sin^{-1}()$ and $\sin^{(-1)}()$

Question: Which of $\sin^{-1}()$ and $\sin^{(-1)}()$ refers to $\arcsin(\sin(x)) = x$ and $\csc(x) = \frac{1}{\sin(x)}$?
Comment: Welcome to Math.SE! ... This question has been asked numerous times here, so you are in good company. :)  See, for instance, ["What is the authoritative consensus on ambiguous notation of $\sin^{−1}()=\arcsin()$ vs. $\sin^{−1}()=\csc()$?"](https://math.stackexchange.com/q/3542563/409). For more examples, look through the results of [a site search for "arcsin csc"](https://math.stackexchange.com/search?q=arcsin+csc).
Comment: Your post doesn't mention calculus but $\sin^{(-1)}x$ could be construed as the $-1$-th derivative of $\sin x$, i.e. its "first" antiderivative. $\dfrac{d^n f(x)}{dx^n}\equiv f^{(n)}(x)$ is a fairly common notation.
Comment: Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer.
Answer: To the best of my knowledge, there is no agreed upon applicable universal convention.
So, if you are the reader, you have to try to guess the intent from the surrounding context.
If you are the writer, it is best to specify what convention that you are using.  In the alternative, you can use the unambiguous arcsin$(x)~$ and $~\left[ ~\sin(x) ~\right]^{-1}.$


Why is $T(X) = X_{1} + ... + X_{n}$ a sufficient statistics for Poisson $\lambda$ instead of $\frac{1}{n}\sum{X_{i}}$

Question: From Wikipedia:

If $X_{1},\dots, X_{n}$ are independent and have a Poisson distribution with parameter $\lambda$, then the sum $T(X) = X_{1} + ... + X_{n}$ is a sufficient statistic for $\lambda$.

Why the sufficient statistics for $\lambda$ is not $\frac{1}{n}\sum{X_{i}}$ instead?
I struggle to understand how the sum of the observations can say anything about the mean ($\lambda$) of the distribution that generated the observations. The vectors of observations 3 6 2 2 and 3 6 2 2 0 2 2 0 7 2 have different sums but they are generated from the same distribution with $\lambda = 3$.
I suspect my question is a duplicate of Sufficient statistic for Poisson in wiki? by I'm afraid I still don't get it.
Comment: One is a bijective transform of the other, hence they are equivalent.
Answer: If $n$ is known, both are sufficient. More generally, any statistic which is in 1-1 correspondence with a sufficient statistic, is sufficient. What matters is the partition different values of the statistic induce in the sample space, not the particular values of the sufficient statistic.
Comment: *What matters is the partition different values of the statistic induce in the sample space, not the particular values of the sufficient statistic.* But then a sufficient statistics for the mean $\theta$ of a normal distribution could also be $\sum{X_{i}}$ instead of $\frac{1}{n}\sum{X_{i}}$ as reported on Wikipedia? I surmise the answer is no... but why?
Comment: Right. If $n$ is known, both are sufficient for the mean of a normal. (Both give the same information, you can always obtain one from the other.)
Comment: (Thanks for your patience) You say *If n is known*. My understanding is/was that a sufficient statistic gives you everything you need to know to estimate the parameter of interest. For me, this means the $n$ cannot be assumed to be known. Or is $n$  "allowed" because it's a property of the sample rather than a statistic about the population?
Comment: If $n$ is not known, then neither $\bar{X}$ nor $\sum X_i$ are sufficient for the mean. If $n$ is known, then either are sufficient. It may be clearer if you take a specific situation. Suppose $n=100$. Someone tells you that $\bar{X}=3.18$. Then, you automatically know that $\sum X_i=318$. On the other hand, if they told you that  $\sum X_i=318$, then you would know $\bar{X}$. They both have the same information from the sample because once you know one, you know the other.
Comment: @JohnL - I feel dumb here - If you tell me that $\bar{X} = 3.18$ then I don't need to know what $n$ was. On the other hand, $\sum{X_{i}} = 318$ is meaningless without knowing $n$. If I'm allowed to communicate just **one** number for the estimate of $\mu$, then  $\bar{X}$ is not only better but is also everything the receiver of my communication needs to know. The same cannot be said about the $\sum{X_{i}}$ (That's my informal understanding of sufficient statistic).
Comment: @dariober, $n$ has sort of a special status, yes. Together with $\sum X_i$ allows you to estimate the mean, even though by itself carries no information whatsoever about it.
Comment: @F.Tusell Thanks again - *n  has sort of a special status* that's what I came to realize and wasn't clear to me before. Once $n$ is known, it's easy to see why $\sum{X_{i}}$ and $\bar{X}$ are in 1-1 correspondence. And $n$ has special status because it doesn't depend on the population the sample came from.