How to deduce the area of an equilateral triangle whose inscribed circle has radius $r$?

Question: What is the area of an equilateral triangle whose inscribed circle has radius $r$?  I would like to learn how to deduce the formula.
I deduced the circle outside the triangle, so now I tried to do it with the circle inside the triangle, but I haven't arrived to a solution yet.
Comment: Hint: draw radii that are perpendicular to each side. That will cut up the triangle into 3 smaller triangles whose areas are relatively easy to deduce.
Comment: Closely related: http://math.stackexchange.com/questions/172601/deriving-the-formula-for-the-radius-of-the-circle-inscribed-in-an-equilateral-tr
Answer: Make a construction like so
Here, $OC = r$, $BC = \frac{l}{2}$, $AB = l$. Since $ABC \sim BOC$, taking ratios, we get $AC = \frac{l^2}{4r}$.
By the Pythagorean theorem,
$AB^2 = AC^2 + BC^2$,
Therefore, $$l = \sqrt{\frac{l^2}{4} + \frac{l^4}{16r^2}}$$
Simplifying, we get $l = r\sqrt{12}$
The area would be $\frac{\sqrt{3}}{4}l^2$, which would be
$$3\sqrt{3}r^2$$
Answer: Using the circle in SS_C4's answer, We know that triangles BOC and ABC are similar, so both are 30-60-90 triangles.
Applying the properties of 30-60-90 triangles $(r,\,{\sqrt 3}r,\,2r)$: We have, $OC=r,\,BC= {\sqrt 3}r,\,\,\text{and }\,AC={\sqrt 3}({\sqrt 3}r)=3r$
Therefore, the area is $\frac{1}{2}bh=\frac{1}{2}(2BC)(AC)=\frac{1}{2}(2{\sqrt 3}r)(3r)=3{\sqrt 3}r^2$


O que pode mudar com a implementação do variadic function?

Question: O PHP 5.6 implementou uma funcionalidade chamada Variadic function.
É como se fossem argumentos infinitos. Eles podem ser usados tanto na declaração de uma função como para o chamamento.
Exemplos PHP 5.6
Exemplo na declaração:
function test($arg, ...$args)
{
    print_r($args);
}

test('first argument', 1, 2, 3); // imprime: array(1, 2, 3);

Exemplo no chamamento:
function test($first_name, $last_name)
{
    return "{$first_name} {$last_name}";
}

$args =  ['Wallace', 'Maxters'];

$alias = 'test';

$alias(...$args); // Wallace Maxters

test(...$args); // Wallace Maxters

Exemplos versões anteriores a 5.6
Esses exemplos se fossem utilizados em versões anteriores a 5.6, poderiam ser feitos da seguinte forma:
Exemplo declaração:
function test($arg)
{
    $args = array_slice(func_get_args(), 1);

    print_r($args);
}

test('first argument', 1, 2, 3); // array(1, 2, 3)

Exemplo chamamento:
function test($first_name, $last_name)
{
    return "{$first_name} {$last_name}";
}

$args = ['Wallace', 'Maxters'];

$alias = 'test';

echo call_user_func_array($alias, $args); // Wallace Maxters
echo call_user_func_array('test', $args); // Wallace Maxters

Depois da implementação do variadic function, para quem usar o PHP 5.6, qual vai ser a finalidade das funções call_user_func_array e func_get_args?
Essa implementação do variadic function pode comprometer essas funções e, futuramente, torná-las obsoletas?
Answer: Eu não acompanho de perto os desenvolvimentos do PHP, mas o pouco que vejo passa a impressão de que eles são bastante conservadores, e que mesmo quando algo é marcado como obsoleto (deprecated) ainda pode levar um bom tempo para ser de fato removido. Concordo com o @gmsantos nesse ponto, o PHP evita ao máximo criar incompatibilidades com códigos legados.
Quanto às duas funções citadas, o func_get_args eu acredito que seja mantido, pois tem uma função diferente do parâmetro splat das funções variádicas, já que retorna todos os argumentos recebidos. O call_user_func_array também tem seu papel, pois permite a passagem de argumentos dinâmicos mesmo que a função não seja variádica. Isso sem dizer que permite ainda chamar uma função pelo nome (como string), como o call_user_func. Em resumo, vejo motivos para as duas funções serem mantidas, principalmente func_get_args.
Answer: Ao meu ver as variadic function irão substituir call_user_func_array e func_get_args.
Elas ficariam ali por alguns releases para manter a compatibilidade com códigos que precisem funcionar em versões anteriores do PHP 5.6 até que um belo dia entrem em votação para serem descontinuadas.
Não espere que isso seja feito em breve. As últimas versões incluíram sintaxe alternativa para outras coisas, como a sintaxe de array no PHP 5.4, que substitui a função array() e o operador de potenciação também no PHP 5.6 que faz a mesma coisa que a função pow(). Ambos os casos continuam valendo até que seja decidido que não vale mais a pena mantê-los ali, como aconteceu várias coisas (exemplo da extensão mysql_*).
Answer: Apenas como complemento às respostas anteriores:
um simples exemplo é o de melhoria da sintaxe e a diminuição da chamada de funções, melhorando o desempenho.
Antigamente:
call_user_function_array(array($controller, $method), $parameters);

Atualmente:
$controller->$method(...$parameters);

Outra vantagem pode ser vista na declaração de métodos ou funções. Vou dar um exemplo que sempre utilizo, que é a utilização de um método estático pra facilitar a criação da instância da classe.
Antigamente:
 class Controller {

    public function __construct(Request $request, Response $response)
    {

    }

    public static function make(Request $request, Response $response)
    {
         return new static($request, $respone);
    }

}

Atualmente:
class Controller {

    public function __construct(Request $request, Response $response)
    {

    }
    /** Não precisa declarar as mesmas coisas de construct, é um atalho **/
    public static function make(...$arguments)
    {
         return new static(...$arguments);
    }

}

Controller::make(new Request, new Response);

Comment: Concordo que são vantagens. Mas isso responde ao que foi perguntado (por você mesmo)?
Comment: @bfavaretto, foi apenas um detalhe adicional que acho que poderia ter sido colocado em alguma das questões.
Comment: Talvez isso caiba na própria pergunta.


Dúvida pesquisa SQL

Question: Registro entradas de 'determinadas' pessoas na tabela movimento, tudo certinho. Agora preciso listar essas 'determinadas' pessoas que não efetuaram o registro de entrada. Essas determinadas pessoas estão marcadas como true na tabela pessoas. Listo quem registrou a entrada, mas estou me embananando em quem não efetuou o registro. Alguma luz?
select m.prontuario, p.nome,m.data, m.motivos from pessoas p left join movimento m on p.prontuario = m.prontuario  where p.ativo = true and m.codmov in (19) and m.data = current_date order by p.nome

A tabela pessoas possui os campos prontuario(int), nome(str) e ativo(boolean)...na tabela movimento, id(int), codmov(int), prontuario(int), data(date) e motivos(str)...
Em resumo, quero listar as pessoas marcadas como true na tabela pessoas que não registraram entrada na tabela movimento na data de hoje...
Comment: Sem passar a descrição das tabelas fica difícil ajudar.
Comment: Você pode editar a pergunta para incluir o conteúdo do comentário.
Comment: se fez o left join e não houver correspondente na tabela, a informação virá null, então deve bastar adicionar ao where `and m.prontuario is null`
Comment: @RicardoPontual...mesmo com o `and m.prontuario is null` continua retornando 0
Answer: Se vc selecionar todos que não estao com a data atual?
 select m.prontuario, p.nome,m.data, m.motivos from pessoas p
 left join movimento m
 on p.prontuario = m.prontuario
 where p.ativo = true
 and m.codmov in (19)
 and m.data not in(current_date)
 order by p.nome

Comment: Como está escrito atualmente, sua resposta não é clara. Por favor, pode [edit] para adicionar mais detalhes, que ajudarão outras pessoas a entender como isso resolve a pergunta feita. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).
Comment: Dessa forma @alexBaiaroski, ele seleciona todos os registros existentes na tabela `movimento` que não sejam de hoje...
Comment: Opa eae @Jones713, deixa ver se eu entendi, qnd vc tem movimento, uma nova linha na tabela movimento é criada, certo? se a pessoa nao passou la nao tem linha nova certo? entao...nao sei se te ajudaria mas eu faria esse script, onde busco todos que nao tem movimento na data X e faria uma comparação com a tabela de pessoas, tipo where pessoas not exists ....ai saberia que a pessoa nao passou la...
Comment: Sua descrição é perfeita: tem um movimento, nova linha na tabela, sem movimento, sem linha add...se puder esclarecer melhor sua lógica e script, agradeço...
Comment: testa ai esse exemplo

SELECT * FROM PESSOAS P
WHERE NOT EXISTS(SELECT 1 FROM MOVIMENTO M
WHERE M.data = current_date
AND codmov in (19)
AND p.prontuario = m.prontuario )
AND p.ativo = true
order by p.nome
Comment: o script não funcionou @alexBaiaroski...ele retorna todas as pessoas
Comment: entao...entendi que a ideia é vc buscar as pessoas que nao tem na movimento, entao, select pessoas where not exists em movimento onde o movimento.data=data e o movimento.id=19
Comment: Após as valorosas sugestões do amigo @alexBaiaroski (ao qual agradeço muito), consegui resolver a questão:  `select p.prontuario,p.nome from pessoas p
left join movimento m on p.prontuario = m.prontuario
where p.ativo = true
and not exists (select null from movimento m where p.prontuario = m.prontuario
and m.codmov in (19) and m.data = current_date)
group by p.prontuario,p.nome
order by p.nome;`
Comment: Show, que bom que conseguiu @Jones713, parabéns!

Dúvida pesquisa SQL


What distribution has exactly three parameters for mean, variance, and skewness?

Question: Common distributions usually fix their skewness. Beta distribution has two parameters to determine all of the mean, variance, and skewness.
Student-T's skewness can change by some definitions but it does not have a dedicated parameter.
What distribution has exactly three parameters for mean, variance, and skewness?
Comment: Infinitely many answers are possible.  Some appear at https://en.wikipedia.org/wiki/Pearson_distribution.
Comment: https://reference.wolfram.com/language/ref/ExpGammaDistribution.html
Answer: Infinitely many answers are possible, some links in comments. One family is the skew-normal, but it only admits limited degrees of skewness. The same ideas used to construct the skew-normal family from the normal family can be used for other families!
For empirical modeling with skewness have a look at the gamlss system, which admits many families.


jquery preventing default event on elements via ajax

Question: How can I prevent default event action on html elements loaded after dom has been created.
I have page which includes another page via jquery .load method as you can see in first line of code.
Code starting from third line does not seem to work.When  I click the link with a.clearCart the browser just loads the page instead of requesting page in background.
The link with class clearCart is located in separate file called 'Cart.php' which is loaded when page is ready.
Page below is :index.php
$(document).ready(function(e) {
    $('#cart').load('./ajax/Cart.php');//a.clearCart is located in this file

    $("a.clearCart").click(function(e)
    {
        e.preventDefault();
        return false;
        $.getJSON('./ajax/clearCart.php?','id=12',check);
        function check(data)
        {
            if(data.Status == "Success")
            {
                alert("Update Cart");//For Debugging Only,should call UpdateCart()
            }
            else if(data.Status == "Failed")
            {
                alert("WTF");//Welcome to Finland
            }
        }
    });

    function UpdateCart()
    {
        $('#cart').load('./ajax/Cart.php');
    }
    $('.formInfo form').submit(function(e) {

        var id = this.prodId.value;
        var qta = this.qty.value;
        var data = {prodId:id,qty:qta};
        $.getJSON('./ajax/addcart.php',data,processData);

        function processData(data)
        {
            if($('p.message').text().length > 5)
            {
                $('p.message').empty().removeClass('.success').removeClass('failure');

            }
            if(data.Status == "Failed")
            {
                $('p.message').append(data.Reason).addClass('failure');
            }
            else if(data.Status == "Success")
            {
                $('p.message').append(data.Reason).addClass('success');
                UpdateCart();
            }
        }

        return false;
    });

});

Answer: You can use live() or on() function. I will show with on() because live() is deprecated as of jQuery 1.7:
Change
$("a.clearCart").click(function(e)

To
$(document).on('click', 'a.clearCart', function(e) {
    // Code goes here
}).

See

http://api.jquery.com/live/ - Deprecated as of jQuery 1.7
http://api.jquery.com/on/
Comment: Thank you so much!!I was pulling my hair
Answer: The click function does nothing because of the return false; in it. This will end the function by returning false.
Remove that and the ajax code will be executed.


Ratio Measurement Scale and Absolute Zero

Question: Levels of measurement are: Nominal, ordinal, interval and ratio.
What happens when the absolute zero of a data set using the ratio scale is a negative number? I.E when the absolute zero is -25,000? How does this impact related math. Or does it?
Comment: Note that the levels of measurement typology you refer to ({Stevens' typology](https://en.wikipedia.org/wiki/Level_of_measurement)) is just one of many; the way your question is phrased it sounds like you think it's the only way to categorize variables.
Comment: Emphasis on the *just one of many!* For example: there are also (among others) discrete modular, and continuous modular, rank, and continuous, and complex measures.
Answer: If you use the absolute scale, for which 'absolute 0' is the $0,$ then
that's a ratio scale.
For example, $0^o$ Kelvin is the same as $-273.15^o$ C. On the Kelvin scale you can make sense of the statement $100^0$ K is half as 'hot' as $200^0$ K. [Half is a ratio.]
In cooking, you couldn't make sense of "$100^0$ C (boiling water) is half as 'hot' as $200^0$ C" (baking bread).
Comment: And 15 degrees celcius is one degree hotter than 14 degrees celcius - so celcius is an interval scale (and as @BruceET inferred Kelvin is a ratio scale)
Answer: If the absolute zero on your scale is -25,000, by which I presume you mean observing a score of -25,000 implies that there is none of the construct of interest, then you have an interval scale, not a ratio scale.
A ratio scale is one in which a score of 0 corresponds to having none of the construct, and doubling the score corresponds to doubling the amount of the construct. Counts and amounts are ratio; most other numerical measurements (e.g., IQ score, SAT score, score on visual analog scale, etc.) are interval. If you could shift the entire scale by a constant and the new values would have the same meaning as the old values, then you have an interval scale (e.g., measuring on a scale from -3 to 3 is the same as measuring on a scale from 1 to 7).
Comment: This is helpful. Thank you for your time. One follow-on questions using temperature as an example of an interval scale-- these is no decipherable meaning to "zero temperature". As I understand it, Ratio scales have an absolute zero beyond which there is nothing (no construct nor value). So what happens when there is a point beyond which there is nothing (no value) but that point is a negative number. Is it still an interval scale when there is an point beyond which there is no value, but that point is less than zero?
Comment: Yes, it is still interval. Temperature measures the thermal motion in matter; if there is no motion, temperature is at its absolute minimum. In Celcius, this is  −273.15°. Celcius is an interval measure. In Kelvin, this is 0°; Kelvin is a ratio measure.


Versionamento SQL Server integrado ao Entity Framework

Question: Na empresa que trabalho optaram por criar os modelos a partir do banco de dados com o Entity Power Tools.
Temos uma versão online da nossa aplicação e as locais para teste e desenvolvimento.
Quando necessário alterar algo nos modelos, alteramos no banco e geramos os modelos denovo... até ai tudo bem, usamos versionamento e todo mundo fica com os modelos iguais.
O problema é as alterações no banco, por exemplo:

Um campo VALOR_NOTA era double agora passou a ser decimal

Dai temos que fazer essa alteração no SQL de todas as máquinas.
Existe uma forma de fazer um versionamento da estrutura de uma tabela no SQL Server?
Comment: Não é mais fácil vocês usarem *Migrations*? Aí o versionamento do banco fica no código da aplicação.
Comment: Já sugeri com pesquisas e provas, aceitaram a dica mas somente após a finalização do prospecto. Então terei que aguardar!
Comment: Olha, existir existe. O problema é mapear essas mudanças de estrutura. Há uns 5 anos atrás escrevi uma ferramenta em Python que lia um repositório SVN com a estrutura e gerava os scripts de mudança de versão, mas dava muito trabalho e era muito demorado. A gente versionava scripts SQL com a declaração da tabela. Era o que dava pra fazer.
Comment: hum... boa ideia, da pra colocar as declarações em um SQL e versionar dai eu crio uma macro pra executar elas a um clique já me ajuda! Vou esperar alguém pode saber uma forma... Caso ninguém apareça como devo fechar a pergunta?
Comment: Eu respondo pra você. Só queria validar algumas coisas.
Comment: @CiganoMorrisonMendez como movo essa conversa para um chat? Gostaria de perguntar algumas coisas sobre o migrations se possível!
Comment: Vamos [continuar esta discussão no bate-papo](http://chat.stackexchange.com/rooms/16871/discussion-between-cigano-morrison-mendez-and-trxplz0).
Answer: O melhor seria usar Migrations, mas conforme o autor da pergunta pediu por não ser possível, vou sugerir uma solução alternativa.
Ao gerar suas Migrations, execute um Update-Database imediatamente com o seguinte comando:
Update-Database -Verbose

Isso fará o SQL executado ser mostrado no Console. Salve esse Log dentro de algum diretório do projeto com a extensão .sql.
Ao publicar seu projeto, execute as Migrations em ordem. O resultado deve ser muito semelhanto ao do Entity Framework automatizado.


Supremum of conditional expectations

Question: Let $X_{n \in \mathbb{N}}$ be a sequence of real valued random variables defined on a filtered probability space $(\Omega,F,P)$ with filtration $F_{n}\subseteq F$ and the $X_{n}$ being not adapted. If we have: $$\mathbb{E}(\underset{n}{\sup} |X_{n}|)<\infty$$
Does it hold true that: $$\mathbb{E}(\underset{n}{\sup} (\mathbb{E}(X_{n}|F_{n})))<\infty$$ ?
Comment: I know that: $$\underset{n}{\lim}\mathbb{E}(\sup X_{m}|F_{n})=\mathbb{E}(\sup X_{m}|F_{\infty})$$ a.s. by a martingale convergence theorem and in $L^{1}$. For each member of the convergent sequence i have trivially: $$\mathbb{E}(X_{n}|F_{n})\leq \mathbb{E}(\sup X_{m}|F_{n})$$. With uniform convergence in hands i could have some estimations. Or even the above for the limes superior.
Comment: What are your thoughts on this problem?
Comment: If i have $X_{1},X_{2}$ being iid. for example and i take $F_{1}=\sigma(X_{2}), F_{2}=\sigma(X_{1},X_{2})$ then i have $\mathbb{E}(X_{1}|F_{1})=\mathbb{E}(X_{1})$ and $\mathbb{E}(X_{2}|F_{2})=X_{2}$. So the one supremum might be bigger than the other one wether $X_{1}\geq \mathbb{E}(X_{1})$ or not. The conditional expectations do less vary than the original unconditional versions and they have less greater values but also less smaller values. But do they behave well enough?
Answer: If I further assume $b:=\mathbb{E}((\underset{i \in \mathbb{N}}{\sup} X_{i})^{2})<\infty$ then i have by an application of Doobs Maximal Inequality:
$$\mathbb{E}(\underset{k\leq n}{\max}\mathbb{E}(X_{k}|F_{k}))\leq \mathbb{E}(\underset{k\leq n}{\max}\mathbb{E}(\underset{i \in \mathbb{N}}{\sup} X_{i}|F_{k}))\leq \mathbb{E}(\underset{k\leq n}{\max}|\mathbb{E}(\underset{i \in \mathbb{N}}{\sup} X_{i}|F_{k})|)\leq 1 + \mathbb{E}((\underset{k\leq n}{\max}|\mathbb{E}(\underset{i \in \mathbb{N}}{\sup} X_{i}|F_{k})|)^{2})\overset{\text{DoobsMaximalIneq.}}{\leq}1 + 4
\mathbb{E}((\mathbb{E}(\sup X_{i}|F_{n}))^{2})\overset{\text{JensenIneqCond.}}{\leq}1 + 4
\mathbb{E}(\mathbb{E}((\sup X_{i})^{2}|F_{n}))= 1 + 4 \mathbb{E}((\sup X_{i})^{2})= 1 + 4b <\infty$$
So $\mathbb{E}(\underset{k\leq n}{\max}\mathbb{E}(X_{k}|F_{k}))$ is bounded and converges by monotone convergence to $\mathbb{E}(\underset{i \in \mathbb{N}}{\sup} \mathbb{E}(X_{i}|F_{i}))$ which is also bounded by 1+4b cause it holds true for every member of the sequence.

Supremum of conditional expectations


How do I make a Microsoft Word application appear on top of the Microsoft Access for which instantiated it?

Question: I have a Microsoft Access form which will display a Microsoft Word app with a blank document when a particular button is clicked using the following code :
Set wrdApp = CreateObject("Word.Application")
wrdApp.Visible = True
Set wrdDoc = wrdApp.Documents.Add ' create a new document

All is fine except I can never get the Word window to appear on top of the Access window. It just appears in the task bar.
Basically, I want to use Microsoft Word as a pop-up rich text editor.
How can I position the newly opened Microsoft Word app on top of the Microsoft Access form which instantiated it?
Answer: After much trail and error, I've found the solution:
If Tasks.Exists("Microsoft Word") Then
   AppActivate "Microsoft Word"
End If

Comment: You should accept this as the answer, even if you answered it yourself :-)
Comment: Worked for me but I have to add the document name. Something like "MyDocName.docx - Microsoft Word"
Answer: GeneQ's own answer didn't work for me. What did work was
Set w = New Word.Application
w.Visible = True
w.Activate
w.WindowState = wdWindowStateMaximize

Comment: Good answer. I tried the above logic on something I am working on and i had tried GeneQ with not much success. I understand what the code is doing. Its say make it visible, activate it and set the window state.


Change field label used in node display

Question: I have a custom content type in Drupal 8.6.x. I want to be able to change the text used for a field label based on the value of a taxonomy term reference in the node.
For example, I want to change the field label used for the body field, to display "Description" or "Definition" or "Introduction", etc. based on the value in the taxonomy reference field. This is when rendering the node - I don't need to change the field label on the form. I'll need to alter the label in the full and teaser display modes, and just for the custom content type. I don't need to change any of the text in the body field, just what label is shown above it.
Answer: You can do this by implementing hook_entity_view_display_alter() in a custom module, for example using code similar to the following one. (Replace mymodule with the machine name of the module containing this function.)
function mymodule_entity_view_display_alter(EntityViewDisplayInterface $display, array $context) {
  if ($context['entity_type'] == 'node' && $context['bundle'] == 'CUSTOM_CONTENT_TYPE') {
    if (in_array($context['view_mode'], ['full', 'teaser'])) {
      foreach ($display->getComponents() as $name => $options) {
        if ($name == 'text' && isset($options['label'])) {
          $node = \Drupal::routeMatch()->getParameter('node');
          $options['label'] = $node->FIELD_TERMS->entity->label();
          $display->setComponent($name, $options);
        }
      }
    }
  }
}

Change field label used in node display


Product of a closed subgroup and a discrete subgroup in a Hausdorff group

Question: Let $G$ be a Hausdorff group. Let $A$ be a closed subgroup of $G$ and $B$ be a discrete subgroup of $G$ (note $B$ is closed since $G$ is Hausdorff). Is the product set $AB$ necessarily closed in $G$?
Comment: A subgroup is not closed because the group is Hausdorff: consider $\Bbb Q$ inside $\Bbb R$, e.g. The title mentions discrete while the question does not?
Comment: @hanno sorry my typo, thank you!
Answer: The answer is no, assuming you meant for $B$ to be the discrete subgroup, which seems likely. In the additive group $\mathbb R$ we have two discrete, closed subgroups $\mathbb Z$ and $\mathbb Z\sqrt 2$, but the sum of these subgroups is dense and not all of $\mathbb R$ and hence is in particular not closed.


check a macro value in run-time

Question: Suppose I pass a macro defs via -D during compilation:
% gcc -DDEF1=ABC -DDEF2=DEF ...

Now, I need to check the value of DEF1 or DEF2 in a runtime, however this doesn't work:
#if DEF1==ABC
...
#else
...
#endif

What am I doing wrong? Is it possible to achieve what I need?
Thanks.
Comment: possible duplicate of [String comparison in preprocessor conditions in C](http://stackoverflow.com/questions/18278868/string-comparison-in-preprocessor-conditions-in-c)
Answer:
Now, I need to check the value of DEF1 or DEF2 in a runtime,

That is not possible. The values of preprocessor macros are processed even before compile time.
You can convert the processor macros to values of variables and check the values of the variables at run time.
Something along the following lines should work.
#define STR2(x) #x
#define STR(X) STR2(X)

char const* str = STR(DEF1);

if ( strcmp(str, "ABC") == 0 )
{
   // Process "ABC"
}
else if strcmp(str, "DEF") == 0 )
{
   // Process "DEF"
}

Answer: You mean at compile time, no? The run-time if is the one without the hash sign.
Macro expressions for #if are evaluated as integers and undefined macro expressions silently default to zero.
I'm not sure what you want to accomplish, but if the values of your macros are defined in the source before you switch on them with #if, you can do something like this:
#define APPLE 1
#define ORANGE 2
#define PEAR 3

#if FRUIT==APPLE
    const char *fname = "Apple";
#elif FRUIT==PEAR
    const char *fname = "Pear";
#elif FRUIT==ORANGE
    const char *fname = "Orange";
#else
    #error "Must specify a valid FRUIT"
#endif

Of course, the selection will also be done when your macro is the numeric value of one of the possible values or another macro that happens to expand to the same value, which might lead to surprises.
Answer: A macro is expanded by the preprocessor to ordinary C source code and from then on used just like that.  For example, if you have a macro MY_NUMBER that should be #defined to a number, you can inspect its value at run-time like you would do with any other number.
if (MY_NUMBER == 42)
  printf("MY_NUMBER is 42\n");
else
  printf("MY_NUMBER is not 42 but rather %d\n", MY_NUMBER);

However, if your macro expands to nasty stuff and you would like to inspect that text, you would have to convert the macro to a string and then look at that string.  For example:
if (strcmp(STRINGIZE(MY_MACRO), "for (;;)") == 0)
  printf("MY_MACRO was #define'd to an infinite loop.");

The usual trick to "stringize" a macro looks like this, if you haven't seen it before.
#define STRINGIZE_R(X) #X
#define STRINGIZE(X) STRINGIZE_R(X)

check a macro value in run-time


Significance (p-value) in regression/size of parameter estimate

Question: In a linear (OLS) regression, I find that the sizes of the coefficients vary a lot: one of them is about 0.0005 and another is ~150. The p-values are all under 0.1. Is this  reliable result? These are time-series variables by the way.
Separately, in another OLS time series regression, I am finding a variable to be significant which according to the business client, should not be. This variable has much higher variance than other input variables we tried in the model and also has high correlation with the dependent variable. COUld the low p-value/statistical significance/ high correlation arise due to the variance? The other variables have low variance over the observed time period.
Thanks for any insight.
Answer: The size of the coefficients is dependent on the scale of the explanatory/right-hand-side/independent/x-variable. Say we use annual household income as an explanatory variable measured in euros. The coefficient will tell us how much we expect the outcome to change for a euro change in annual income. That effect will in all likelihood be very small. It would probably make more sense to measure annual income in 1000s of euros (just divide the old income by 1000). In that case the effect will be a 1000 times the old effect. The p-value will remain unchanged, as we did not change the model: If 1 euro increase leads to a 0.01 change in y, then a 1000 euro increase will lead to a 10 change in y. These are just different ways of saying the same thing. So it is very well possible to have such huge differences in coefficients and similar p-values. In practice, if I see such large differences in coefficients I always reconsider the unit of the explanatory variables.
Comment: (+1). See also http://stats.stackexchange.com/questions/165027/why-is-the-age-squared-variable-divided-by-100-or-1000/165122#165122
Comment: Thanks for the answer, it is very helpful. However, I am also wondering about the role of the variance of an input predictor variable: does higher variance make them somehow more likely to be significant in a model? If I have 2 variables X1 and X2 in a regression model, such that X1 doesn't vary much, but X2 does, does this impact their final p-values/ coefficients in the model? Thanks.


Tangent space manifold

Question: Let M be a differentiable manifold of dimension m and also let $\{\xi_1,\dots,\xi_m\}\subset \text{T}_pM$ be an linearly independent set of the tangent bundle of M at a certain point $p\in M$.
I have to proof that there is a chart $(\varphi=(u_1,\dots,u_m), U)$ with $\varphi(p)=0$ and:$$ \xi_i =\left( \frac{d}{du_i}\right)_p$$
-My approach: Let $(\varphi, U)$ be a chart with $\varphi(p)=0$, there is an unique linear endomorphism $F$ of $\text{T}_pM$ that sends (since both sets are bases), $$\left( \frac{d}{du_i}\right)_p\longrightarrow \xi_i$$
from this point I supose you should be able to define a diffeomorphism $f:M\rightarrow M$ with $df(p)=F$ wich would end the argument by taking the chart $(\varphi \circ f,U)$. I really don't know how to define such a map or if it even exists.
Comment: I'd suggest that, instead of trying to cook up such an $f$, instead, find a matrix $A:\mathbb{R}^n\rightarrow \mathbb{R}^n$ and consider $A\circ \varphi$.
Comment: @john thanks for your fast answer, sadly it contains some notions I am not supposed to use yet, like forms or the dual of the tangent space.
Comment: I think I'm close to the answer but can't get there. There is a matrix $\{a_{ij}\}$ wich transforms the basis $\{ \left( \frac{d}{du_i} \right) _p\}$ in $\{\xi_i\}$, I think the trick is use the chart $(A^{-1}\circ \varphi,U)$ where $A=\{a_{ji}\}$, but I am not sure how to write it with precision.
Answer: You've made an initial choice of a random chart $(\phi,U)$ such that $\phi(p)=0$. Let $V_1,\ldots,V_m \in T_0(\mathbb{R}^m)$ be the image of $\xi_1,\ldots,\xi_m$ under $d\phi_p$. The desired effect is that $V_1,\ldots,V_m$ is the standard basis for $T_0(\mathbb{R}^m)$, but it might not be.
Instead of doing a precomposition in $M$, do a postcomposition in $\mathbb{R}^m$.
Using the standard identification of $T_0(\mathbb{R}^m)$ with $\mathbb{R}^m$, let $F$ be the linear transformation of $\mathbb{R}^m$ taking $V_1,\ldots,V_m$ to the standard basis for $\mathbb{R}^m$.
Finally, let $\phi' = F \circ \phi$. An application of the chain rule together with linearity of $F$ will give the proof that $\phi'$ is the desired chart.
Some more details: Here's the final calculations to put this all together. Applying the chain rule,
$$d\phi'_p = dF_{\phi(p)} \circ d\phi_p = dF_0 \circ d\phi_p
$$
Applying linearity of $F$ we have $dF_0=F$ and so
$$d\phi'_p = F \circ d\phi_p
$$
Letting $e_1,\ldots,e_m$ be the standard basis, $F$ was chosen so that $F(V_i)=e_i$, and so
$$d\phi'_p(\xi_i) = F(d\phi_p(\xi_i)) = F(V_i) = e_i
$$
which is what was wanted to be shown.
Comment: Thanks for your answer @Lee . I get what you've done there, but I still can't manage to apply linearity and the chain rule correctly to get the job done. I'm sorry if I am asking for something too obvious, I've been thinking about this too much I can't think straight anymore.
Comment: @Jorge: I added some more details.

Tangent space manifold


Examine the convergence of the improper integral $\int_1^{\infty} f(x) dx$

Question: Examine the convergence of the improper integral $\int_1^{\infty} f(x) dx$ where
$f(x) = \frac{1}{x^3}$ if $x$ be rational $\geq 1$ and
$f(x) = \frac{-1}{x^3}$ if $x$ be irrational $>1$.
The solution given is straight forward $\int_{1}^{\infty}|f(x)|dx= \int_{1}^{\infty}\frac{1}{x^3}dx$ so its convergent, since is $f(x)$ absolutely convergent so is $\int_1^{\infty} f(x) dx$.
But what I don't understand is, the set of points of discontinuity of  $f(x)$ is infinite and has infinite number of limit points. If so its not even riemann integrable in the first place. How then can we comment on its convergence ?
Comment: Not Riemann integrable but Lebesgue integrable since $f(x)=-1/x^3$ almost everywhere.
Comment: Just to be sure, does the book handle only Riemann integrability? Or does it discuss Lebesgue integrals as well? The comment of Did applies.
Comment: If the book writes the formula $\int_1^\infty f(x)\,dx$ and means it in the Riemann sense, then the book is wrong. Does the book actually write this formula, or only the perfectly correct formula $\int_1^\infty|f(x)|\,dx$
Comment: @mickep just reimann integrability .....its mostly undergraduate math...so would help if the answer is from reimann integration point of view
Comment: @Did i have copied it line to line from the book.....
Answer: We aren't integrating f(x), so we don't have to worry about f(x) being continuous. Rather, we are integrating g(x) = (1/x)^3, which is continuous.
Since |f(x)| = g(x), we can say that
Since we know g(x) > f(x) and -g(x) < f(x).
If g(x) approaches C, then f(x) is between C and -C. Therefore, it approaches a finite value.
Basically, we avoid having to worry about integrating f(x) by integrating a different function, g(x), instead and comparing the two.
Edit because my answer was unsatisfactory: Basically squeeze theorem is what proves the correctness of this method. Because squeeze theorem does not require a function to be continuous, this method works.
Comment: I understand the method being followed ..... just concerned about its correctness


Sobre Hooks ClassMethods Sequelize

Question: Estou com uma dúvida no funcionamento do classmethod hooks etc
eu tenho um model:
const bcrypt = require('bcrypt');
module.exports = (sequelize, DataType) => {

    const User = sequelize.define('tb_users', {
        name: {
            type: DataType.STRING,
            allowNull: false,
            validate: {
                notEmpty: true
            }
        },
        email: {
            type: DataType.STRING,
            allowNull: false,
            unique:true,
            validate: {
                isEmail: true,
                notEmpty: true
            }
        },
        password: {
            type: DataType.STRING,
            allowNull: false,
            validate: {
                notEmpty: true
            }
        }
    },
        {
        hooks:{
            beforeCreate: user => {
                try{
                    const result = User.findAll({
                        where:{
                            name: user.name
                        }
                    });
                    console.log(result);
                    if(result != null){
                        console.log('login já existe');
                    }else{
                        const salt = bcrypt.genSaltSync();
                        user.set('password',bcrypt.hashSync(user.password,salt));
                        console.log(user.password);
                    }
                }catch(error){
                    console.error(error);
                }
            }
        },
        classMethods:{
            isPassword: (encodedPassword, password) => bcrypt.compareSync(password, encodedPassword)
        }
    });

    return User;
};

no meu class methods eu tenho essa verificação de password, mas eu tenho dúvida de como eu vou chamar ela em meu controller.
Ou como esse classMethods funcionaria.
Answer: Atualmente o uso correto para se instanciar um método no Sequelize é esse:
const bcrypt = require('bcrypt');

module.exports = (sequelize, DataType) => {

    const User = sequelize.define('tb_users', {
        ...
    },
        ...
    });

    User.isPassword = (encodedPassword, password) => bcrypt.compareSync(password, encodedPassword)

    return User;

};

Para ser chamado você deve usar:
if (Users.isPassword(encodedPassword, password)) {
    ...
}

Sobre Hooks ClassMethods Sequelize


Access Value of variable content in twig template

Question: I'm new in a Drupal 8 and using Devel kint() function for debugging. In my twig template menu--main.html.twig, I have looped for the menu items like this:-
{% for item in items %}
   {{kint(item.url)}}
The output like this:-

What I should write to print the URI, I've tried {{item.url.uri}} but not working
Comment: Do you try {{item.url.getUri}} ?
Comment: Just guessing, `{% if item.url.isExternal() %}foo{% endif %}`
Comment: Him want  get uri  of url not external :D
Comment: @MrD It's working fine, Thanks so much. but how I know that I have to write `getUri` to render it
Answer: You can try {{item.url.getUri}}.
You can change to tab Available methods to see other method. Example isExternal. :D


Links Won't Open When Using Multiple Tabs (Jquery Tabs)

Question: Code for multiple tabs on my page (displaying these tabs and content dynamically):
jQuery('.tab-block li a').click(function() {
var theitem = jQuery(this);
theitem.parent().parent().find("li").removeClass("active");
theitem.parent().addClass("active");
theitem.parent().parent().parent().parent().find(".tab-content > ul > li").removeClass("active");
theitem.parent().parent().parent().parent().find(".tab-content > ul > li").eq(theitem.parent().index()).addClass("active");
return false;
});

Code in my HTML to display tabs:

TAB 1

TAB 2

Goole.com

Content

Goole.com

Content

Now all tabs work great but no links will open (the H3 link within the tabs themselves). Any ideas what I'm doing wrong?
Thank you.
Comment: No one can figure this out eh? Neither can I :(
Comment: Never mind, I figured it out. Change this line: .tab-block li a to .tabs li a and it works.
Answer: I don't know what your specific problem is, you may want to provide a link to a jsfiddle, to make yourself clear, but if you need tabs, try EZ tabs jQuery plugin.
HTML:

TAB 1

TAB 2

Goole.com

Content

Goole.com

Content

jQuery, on document ready:
$('.tab-block').eztabs({
    tabsList : 'ul.nav',
    animation: 'slideLeftRight',
    boxContainer: '.tab-content',
    animationTime: 200
});

jsfiddle


How is it called a minimal morphism of category Rel?

Question: How is it called a Rel-morphism $(f;A;B)$ such that: a. $f=\varnothing$; b. $f\ne\varnothing$?
Is there any special term for this?
Answer: First things first: $\textbf{Rel}$ is an enriched category, and in more than one way.

$\textbf{Rel}$ is a pointed category: that means it has a zero object and is enriched over the category of pointed sets. The empty relation $\emptyset : A \to B$ can be characterised as the unique relation $A \to B$ that factors through the zero object $\emptyset$, so we call it a zero morphism. Obviously, this property is preserved by composition on the left and on the right.
$\textbf{Rel}$ is a locally posetal category: that means each hom-set is partially ordered, and composition is monotonic. The empty relation is clearly the bottom element of each hom-poset.
Extending the above in a trivial way, $\textbf{Rel}$ is a 2-category: that means each hom-set is a category, and composition is functorial. The empty relation is clearly the initial object of each hom-category.
$\textbf{Rel}$ is in fact enriched over itself, as discussed here, but to make this concrete, we should say that $\textbf{Rel}$ is enriched over the category of cocomplete join semilattices. (I say this instead of boolean algebra because composition only preserves joins.) As in (2), the empty relation is distinguished here as the bottom element of each hom-semilattice.
Answer: It is called a zero morphism of Rel.


UMP unbiased test

Question: I was wondering if any of you folks could help me with this statistics problem. Here is the problem :
set T an exhaustive statistic which $T \sim  \Gamma(n,1)$. We need to find a UMP unbiased test for $H_0 : \tau = \tau_0 \ vs \  H_1 : \tau \neq \tau_0$ .
I know that the form of reject zone must be $\mathcal{R} = \{T \notin [q_1, q_2]\}$ and I found two equations relating $q_1$ and $q_2$.
I have :
$$
F(q_2) - F(q_1) = 1 -\alpha
$$
and $$
q_1^ne^{-q_1} = q_2^ne^{-q_2}
$$
\tau is the parameter of the density $$f(x)=\frac{\tau}{x^{\tau +1}}$$ and I know that $$T= \tau \sum_{i=1}^{n} \log(X_i) \sim \Gamma(n,1)$$
I need to find a single equation and that solve it numerically.
Thank you for your help
Comment: Define $\tau$..
Comment: I define it as you asked
Comment: Did you use likelihood ratio test to arrive at $q_1^ne^{-q_1} = q_2^ne^{-q_2}$?
Answer: Assuming $X_1,X_2,\ldots,X_n$ are i.i.d with pdf
$$f(x)=\frac{\tau}{x^{\tau +1}}\mathbf1_{x>1} \,,\quad \tau>0$$
I suggest an alternative way to go about this.
A UMPU test as you said is of the form
$$\phi(t)=\begin{cases}1&,\text{ if }t<q_1 \text{ or }t>q_2 \\ 0 &,\text{ otherwise }\end{cases}$$
For a size $\alpha$ test, $(q_1,q_2)$ are such that $E_{H_0} \phi(T)=\alpha$ and $\operatorname{Cov}_{H_0}(T,\phi(T))=0$.
Note that $2T\sim \chi^2_{2n}$ under $H_0$. The two restrictions above then reduce to
$$P(q_1'<\chi^2_{2n}<q_2')=1-\alpha $$
and
\begin{align}
\operatorname{Cov}_{H_0}(T,\phi(T))=0 &\iff  E_{H_0}(T(1-\phi(T))=E_{H_0}(T)E_{H_0}(1-\phi(T))
\\& \iff E_{H_0}\left[2T(1-\phi(T))\right]=(1-\alpha)E_{H_0}(2T)
\\& \iff \int_{q_1'}^{q_2'} \frac{e^{-x/2}x^n}{2^{n+1}\Gamma(n+1)}\,dx=1-\alpha
\\& \iff P(q_1'<\chi^2_{2n+2}<q_2')=1-\alpha
\end{align}
with $$(q_1',q_2')=(2q_1,2q_2)$$
So for $\alpha=0.05$ (say), if $G_{2n}$ is the cdf of $\chi^2_{2n}$ distribution, you have
$$G_{2n}(q_2')-G_{2n}(q_1')=0.95 \tag{1}$$
and $$G_{2n+2}(q_2')-G_{2n+2}(q_1')=0.95 \tag{2}$$
Now for example, we can write $0.95=0.975-0.025$, so one choice of $(q_1',q_2')$ from $(1)$ would be that pair which satisfies $G_{2n}(q_2')=0.975$ and $G_{2n}(q_1')=0.025$. Similarly, with the decomposition $0.95=0.995-0.045$, you have another choice of $(q_1',q_2')$. Take four or five of these choices and choose that pair which satisfies $(2)$ the closest. If this works out, you have an approximate solution to $(q_1',q_2')$.
You can also try the same procedure with the two equations you derived involving $q_1,q_2$.

UMP unbiased test


If $f$ is an irreducible cubic over $\mathbb{Q}$ and $L$ is its splitting field, then $L$ is radical (condition on discriminant).

Question: Let $f$ be an irreducible cubic polynomial in $\mathbb{Q}[x]$ and let $L/Q$ be its splitting field. I want to show that $L/\mathbb{Q}$ is radical if and only if the discriminant is of the form $D = -3m^2.$ If $L$ is a radical extension, then I know that $L = \mathbb{Q}(\alpha)$ for some $\alpha^3 \in \mathbb{Q},$ and that the Galois group of $L/\mathbb{Q}$ is $S_3$ or $A_3$ depending on whether $D$ is a square. How do I proceed from here? There were previous questions similar to this, and they all seem to say something about extending $L$ by $\sqrt{-3}$ but I have no idea where that came from, hence the new question.
Comment: How are you defining radical?  I thought any irreducible cubic polynomial splits in an extension of $\Bbb{Q}$ that is a radical extension, because $S_3$ and $A_3$ are both solvable groups.
Comment: Perhaps you mean a Simple Radical Extension, cf. this post -> https://math.stackexchange.com/a/1101245/254075
Comment: @sharding4 Ah yes. I've read the post but I couldn't understand why we get $\Bbb Q(\sqrt[3]a, \sqrt{-3})$. Could you perhaps explain why? Thank you.
Comment: If you have one root $\sqrt[3]{a}$, then the other 2 roots will be $\omega \sqrt[3]{a}$ and $\omega^2 \sqrt[3]{a}$ where $\omega$ is a primitive cube root of unity, $\omega^3=1$.  The polynomial $x^3-1$ factors as $(x-1)(x^2+x+1)$, so that it actually splits over a quadratic field, namely $\Bbb{Q}[\sqrt{-3}]$.  I apologize I think I didn't entirely understand the usage of radical as in radical over $\Bbb{Q}$ meaning radicals of elements belonging to $\Bbb{Q}$.
Answer: If the discriminant is $-3m^2$ then the splitting field $L$ contains
$\sqrt{-3}$ and so also $\omega=\frac12(-1+\sqrt{-3})$, a primitive cube
root of unity. Therefore $L$ is a Kummer extension of $\Bbb Q(\sqrt{-3})$,
so $L=\Bbb Q(\sqrt{-3},\alpha)$ where $\alpha^3=\beta\in\Bbb Q(\sqrt{-3})$.
As $L$ is Galois over $\Bbb Q$, $L$ also contains a cube root of $\overline \beta$, the complex conjugate of $\beta$, which we can take to be $\overline\alpha$. Therefore $L=\Bbb Q(\sqrt{-3},\overline\alpha)$.
By Kummer theory, either $\overline\alpha/\alpha$ or $\overline\alpha/\alpha^2$ is a cube in $\Bbb Q(\sqrt{-3})$. The latter case leads to
Gal$(L/\Bbb Q)$ being cyclic, which is false. Therefore $\overline\alpha=\gamma^3\alpha=(\gamma\overline\gamma)^3\overline\alpha$ for
some $\gamma\in\Bbb Q(\sqrt{-3})$. Therefore $\gamma\overline\gamma=1$,
so $\gamma=\delta/\overline\delta$ by Hilbert 90, with $\delta\in\Bbb Q(\sqrt{-3})$. Then $s=\delta^3\alpha=\overline{\delta^3\alpha}\in\Bbb Q$.
Also $L$ contains $\Bbb Q(s^{1/3})$ which must be the field generated
by the real root of the original polynomial.
Answer: We have a cubic irreducible polynomial $$f(x)=\sum_{n=0}^3 c_n x^n = \prod_{j=1}^3 (x-\alpha_j) \qquad \in \mathbb{Q}[x]$$
Using $\alpha_1+\alpha_2+\alpha_3=-c_2 \in \mathbb{Q}, \alpha_1\alpha_2\alpha_3 = -c_0$ and $D = \prod_{i \ne j} (\alpha_i - \alpha_j) \in \mathbb{Q}$,
with $\sqrt{D} = (\alpha_1-\alpha_2)(\alpha_1-\alpha_3)(\alpha_2-\alpha_3)$  we find that  $L = \mathbb{Q}(\alpha_1,\sqrt{D})$ is the splitting field of $f$, with $[L:K] = 3$ and $[L:\mathbb{Q}]=3$ or $6$ depending on $D$ being a square.

If $D= -3 m^2$ then $L/\mathbb{Q}$ is a radical extension
$L = K(\alpha_1)$ where $K = \mathbb{Q}(\sqrt{D}) = \mathbb{Q}(\zeta_3)$.
Take any $\beta \in L, \beta \not \in K, \beta^3 \in K$. We know it exists from the Cardano's formula
So we have the tower $L/K(\beta)/K$, but $[K(\beta):K] \ | \ [L:K]$ means $[K(\beta):K] = 3$ and $K(\beta) = L$ ie. $$L = \mathbb{Q}(\sqrt{-3}, \sqrt[3]{\gamma})$$
where $\gamma =\beta^3= a+b \sqrt{-3}$.

If $L/\mathbb{Q}$ is a radical extension then $D= -3 m^2$
$L = K(\sqrt[3]{\gamma})$ for some $\gamma \in K = \mathbb{Q}(\sqrt{D})$ and $[L:K] = 3$. But $L/K$ is Galois so that $Gal(L/K)$ contains $3$ elements of the form $\sigma(\sqrt[3]{\gamma}) = \lambda$ where $\lambda$ is another root of $x^3-\gamma$, ie. $\lambda = \zeta_3^k\sqrt[3]{\gamma}$ and $\zeta_3 \in L$.
But $L/K$ doesn't have any quadratic subfield so that $\zeta_3 \in K$ and hence $K = \mathbb{Q}(\zeta_3)$ and $D = -3 m^2$.


How do I access .beam files from other directories in Erlang?

Question: I have successfully compiled my .erl files and now the .beam files are lying down in my working directory. However, for some reason I need to access those files from another directory... more specifically from the parent directory. The hierarchy is : ...\wkdir\ebin\beam_example.beam, and I wish to access the beam_example.beam from wkdir. Is it possible to do this?
Also, I'm using escript, so a valid import may be very likely to solve this problem, though I just can't figure that out.
Comment: See [this answer](https://stackoverflow.com/a/6545694) if you're looking for a way to add a code path relative to where your escript is stored.
Answer: You can modify the search path for the .beam with the code:add_path* methods. If the code server is in interactive mode (it should be), that'd be enough for the VM to locate the module files and load them lazily.


Location Module and Search api

Question: I am using the Location Module to add a location to a field on a content type
I am then using Views and Search Api to create an index and a view of this content type.
The problem I have is that I cant find any way to get the data from the location to the view. At the bottom of the search index page I can add other entities such as users that are linked to this node but not the Location this is the same for Relationships section in the view.
Answer: This was a compatibility issue with the Location module moving over to geofield
module allowed me to add the coordinates to the search api index
Answer: The Search API Location module provides integration with the Location module, indexing location data.
Comment: No, it doesn't.  As per the description it states 'location fields probably work, but I haven't tested it yet' and says that Geofield fields definitely work.  From the testing I've done the Location fields don't work at all.
Answer: Currently only the Solr Search API back-end with the Geofield module is supported for location searching.  In order to mimic the behaviour of the Drupal Location address field entry first install these three modules:

Geofield
Addressfield
Geocoder

Managing the Fields of the Entity create an Address field (Postal Address).  Then create a Geofield field with a widget type of 'Geocode from another field'.  Then select the first Address field as the 'Geocode from field' in the options.  Also select the service that will do the Geocoding (Google, Yahoo, Bing, etc.).

Location Module and Search api


Why is a URL alias messing up my view's contextual filter?

Question: I'm having an issue configuring a URL alias that redirects content to a view with a contextual filter.
Here's my working setup:

I have a bunch of content of type SEEL Lesson Plan.
To display these lessons in a Library, I created a view with the path http://example.com/seel/
I set up a contextual filter (Content: Title) on the view. So, if you access http://example.com/seel/eat-an-apple, it will display the lesson with title "Eat an Apple" in the Library.

Here's my objective:
I want to override the "Save" button, so when clients edit any content of type SEEL Lesson Plan, it takes them to the library (http://example.com/seel/eat-an-apple) rather than the content page (http://example.com/content/eat-an-apple).
How do I do that?

Here's what doesn't work:
I added the following URL alias at http://example.com/admin/config/search/path/patterns:

I created a new content of type SEEL Lesson Plan that uses this URL alias. I can see it in my list of URL aliases (http://example.com/admin/config/search/path/list/seel):

But, when I go to http://example.com/seel/fdsa to test it out, it totally messes up. I'd include a screenshot if I could, but the HTML elements are literally all over the place -- displaying below the block on the left sidebar instead of in the main content pane, floating all over the footer, etc.
Here's how I know it's a problem with URL aliases:
When I go back and delete the URL alias seel/fdsa, and then go to http://example.com/seel/fdsa, it displays exactly how I set it up originally in the view.
As well: other lesson plans, for which there is no URL alias, display just fine. (For example: http://example.com/seel/eat-an-apple still works.)
Why is this happening?
Comment: You have two conflicting routes - seel/* for the node, and seel/* for the View (the View will normally "win" in my experience)...couldn't say why that manifests itself as a broken layout without more info I think, but having two routes with the same pattern is likely to end with weirdness. You mentioned that the content page should be at http://example.com/content/eat-an-apple, so why add the pathauto alias as well? The node won't be available from the /content path once you've done that
Comment: And to answer your first question, "How do I do that?", you can take the (a) Site-Building approach: Use the Rules module, or (b) Programmatic approach: Use a custom Form API submit handler function, where you set the  `$form_state['redirect'] = SOME_DESTINATION;`.
Comment: @Clive I don't want it to be available from the content/* URL, only through the view.
Comment: @StefanosPetrakis Is (b) essentially the same as using .htaccess to set up a 301?
Comment: You should set up a redirect then, yes. Currently Drupal is getting confused because you're trying to jam 2 things into a single path. A and B are the same thing by the way, just accomplished with different approaches
Answer: At @Clive's suggestion, I ditched the idea of trying to do this with URL aliases, and instead set up a redirect with the Rules module.
This was done by going to /admin/config/workflow/rules, clicking "Add New Rule", and reacting on event "Content is viewed".
The final rule looks like this:

And it works :-)


Prove or provide a counterexample: Finite simple group with $|G|\geq 6$ cannot have an index-2 or index-3 subgroup.

Question:
Let $G$ be a finite simple group with $|G|\geq 6$. For each of the following statements, prove or provide a counterexample.

$G$ cannot have an index-$2$ subgroup.
$G$ cannot have an index-$3$ subgroup.
$G$ cannot have a proper subgroup of index less than $6$.
Comment: One can show that any index $2$ subgroup must be normal. Hint: What are the left cosets? What are the right cosets? So by that result, you answer 1), and see why looking at $S_4$ or any $S_n$ won't help in this problem: $A_n$ is always a normal subgroup, so $S_n$ is not simple.
Comment: @POTUS: You have two hypothesis: $G$ is simple, and $|G|\geq 6$. The way Ragib wrote his statement, "If $G$ had a subgroup of index $2$ then that subgroup would be normal, contradicting that $G$ is simple" is not correct. Simple groups *do* have normal subgroups: they just can't be proper. So the correct full argument is tat if $G$ has a subgroup of index $2$, then the subgroup is normal. Since $G$ is simple, that subgroup must be *trivial*. Therefore, $G$ must have two elements, **contradicting that $|G|\geq 6$** (which was the "latter hypothesis").
Comment: @RagibZaman Thanks! I forgot I am working only with simple groups. Also with regards to your comment "So by that result, you answer 1)" I don't see how. Can you please elaborate? Thanks.
Comment: If G had an index 2 subgroup, that subgroup would be normal, contradicting that G is a simple group.
Comment: @RagibZaman Yes! I should go to bed!
Comment: @Ragib: No, because the subgroup might be trivial; what it contradicts is the hypothesis on the *size* of $G$.
Comment: @ArturoMagidin I don't understand. We have $|G|\leq 6$ so a subgroup of index $2$ must be of order $3$, not trivial? EDIT: Never mind, I think your comment was to show there's no contradiction if the group is of order $2$, so we see how the hypothesis on the size of $G$ is relevant.
Comment: @Ragib: The assumption is that $|G|$ is *at least* $6$, not at most. There **are** simple groups (or rather, a unique simple group) that has a subgroup of index $2$: the cyclic group of order $2$ has the trivial subgroup, which is of index $2$. And there *is* a simple group with a subgroup of index $3$: the cyclic group of order $3$. But neither of these satisfies the *extra* hypothesis that says that $G$ is not only simple, but of order **at least** $6$. It's the latter hypothesis that is contradicted, not the former.
Comment: Sorry, that was a typo, I knew it was $|G|\geq 6.$ I've understood your point, thanks.
Comment: @ArturoMagidin I am confused! Sorry, but I don't understand how "the latter hypothesis that is contradicted, not the former."
Comment: @POTUS: (And I was pointing out to Ragib that there is a simple group with a subgroup of index $2$, and a simple group that has a subgroup of index $3$; so it was the fact that you are assuming your group has order at least $6$ which causes the contradictions)
Answer: Let $G$ be a group. If $H$ is a subgroup of index $n$, then $H$ contains a normal subgroup of $G$ of index at most $n!$.
This is a common problem; consider the action of $G$ on the left cosets of $H$ by left multiplication, $g\cdot xH \longmapsto gxH$. This induces a homomorphism $G\to S_n$, and the kernel is contained in $H$. Since $G/K$ is isomorphic to a subgroup of $S_n$, the index of $K$ is at most $n!$.
If $G$ is assumed to be simple, then $K$ must be trivial.
This will tell you the only possible counterexamples for index 2 or 3. Try them and see if they meet all your hypothesis.

Added. Assume that $G$ is a simple group, and $H$ is a subgroup of index $2$ in $G$. Then $H$ contains a subgroup $K$ that is normal in $G$, and has index at most $2!$. Since $K\subseteq H$ and $[G:H]=2$, then $[G:K] = [G:H][H:K] = 2[H:K]\geq 2$, it follows that $[G:K]=2$, so $H=K$. Since $G$ is simple and $H$ is normal, it follows that $H=\{e\}$. But since $[G:H]=2$, it follows that $|G|=2$. That is, $G$ is the cyclic group of order $2$. In summary: the only simple group that has a subgroup of index $2$ is the cyclic group of order $2$.
Thus, if $G$ is a simple group and $|G|\geq 6$, then $G$ cannot have a subgroup of index $2$. Thus, 1 is true.
Assume $G$ is a simple group and $H$ is a subgroup of index $3$ in $G$. By the result above, $H$ contains a normal subgroup $K$ of $G$ that has index at most $3!$ in $G$. Thus, $K=\{e\}$ by the same argument as above, so $|G|= [G:K] \leq 6$. The only simple groups of order at most $6$ are $C_2$, $C_3$, and $C_5$; the only one that has a subgroup of index $3$ is $C_3$. So $G$ will be cyclic of order $3$.
Thus, if $G$ is a simple group of order at least $6$, then $G$ cannot have a subgroup of index $3$. Thus, 2 is true.
For subgroups of index $4$, we get as above that $G$ contains a normal subgroup of index at most $4! = 24$; this must be trivial, so $|G|\leq 24$. The only simple groups of order at most $24$ are $C_p$ with $p$ a prime, $p\leq 24$, and none of them has a subgroup of index $4$. So no simple group has a subgroup of index $4$.
Subgroups of index $5$ yield a normal subgroup of index at most $5!= 120$. Now we have some possibilities, since there are nonabelian groups of order less than $120$. For instance, we have $A_5$, of order $60$. Does $A_5$ have a subgroup of index $5$? That would be a subgroup of order $12$. And in fact, $A_5$ does contain subgroups of order $12$, for example, the stabilizer of a point is isomorphic to $A_4$, of order $12$. Thus, $A_5$ is a simple group of order at least $6$ that has a subgroup of index $5$. So 3 is false (though "barely", as it were, since a simple group as given does not have subgroups of indices 2, 3, or 4).

$S_4$ does you no good, since $S_4$ has lots of normal subgroups: $A_4$, and also a normal subgroup of order $4$.
Comment: @POTUS: The point is that the only simple group that has a subgroup of index $2$ is the group of order $2$; but that group does not satisfy your hypothesis that $G$ has  order at least $6$. For part 2, you conclude that $|G|=6$ (since the normal subgroup guaranteed by the result quoted above has index at most $6$, but must be trivial). But there are no simple groups of order $6$, so this cannot occur. For index $4$, $5$, or $6$, you'll want to think about it a bit more.
Comment: I don't think I need counterexamples for 1). 1) is true by the above discussion, so I need prove it, right?
Comment: I am still confused, can you clarify which of the statements are true and which are not? Right now I feel like you are arguing that it is and it is not!
Comment: @POTUS: Hrmph. I see why you are confused; I keep saying "false" when I meant "true".
Comment: Okay! Phew! Thank you for being patient with me though!
Comment: @POTUS: Sorry for being confusing; I wasn't checking the phrasing of 1, 2, and 3, and misremembered them when I typed the now-deleted comment.


Is there an introduction to uniform structures besides Bourbaki?

Question: Chapter 2 of Bourbaki's General Topology is the only introduction to uniform structures on topological spaces of which I am aware.
However, for me it is very time-consuming to extract any understanding at all from Bourbaki's writing. Because of this I would be very grateful for an introduction to the topic which is at a more elementary level, even though I understand that Bourbaki is the definitive reference.
Is there an introduction to uniform structures besides Bourbaki?
Comment: If you can read German: _Mengentheoretische Topologie_ by Boto von Querenburg [that's not a real name, it's the topology department of the university of Bochum, which is situated in Querenburg].
Comment: Engelking has a chapter on uniformities and nearness spaces as well. But if Bourbaki is too tricky, so will Engelking be. There is some Dover pocket on uniform spaces, cheap and quite accessible.
Comment: I think Botho is a bit too short on uniform spaces, personally (just the one chapter, and not very in-depth)...
Comment: @DanielFischer Thankfully I can read German. Thank you for the helpful reference!
Answer: If you read German (as you can from the comments), Herrlich's 2 book series Topologie I (Topologische Räume), Topologie II (Uniforme Räume) are quite accessible, and have lots of exercises. You can use the first book to get acquainted with his terminology (which is sometimes non-standard) and the uniform spaces part start completely from scratch, connecting the notions to topological ones from book 1.
Also, James' book on Topologies and Uniformities (Springer Undergraduate series) is also pretty easy-going.
Warren Page's book on uniform structures is very oriented towards functional analysis and quite formal in its treatment; it covers topological groups and vector spaces quite early on, as well as Haar measure and function spaces. It's more of a reference book than James and Herrlich's (which are self study-able books)
Engelking (General Topology) has a chapter on uniform spaces as well. But that is pretty basic. Just to get the flavour, really, and see the connection to topologies. This from browsing my shelves.
Answer: Metric notions (such as  well-chainedness, completeness, precompactness,
and uniform continuity, for instance) can be best clarified and treated in relator spaces (X, Y)(Cal R) consisting of two sets X, Y and a family
Cal R of relations on  X to Y.
There, it turns out that connectedness and compactness are particular cases
of well-chainedness and precompactness. Moreover, convergent and Cauchy are
actually equivalent notions. Furthermore fat and dense sets are usually
more important than the open and closed ones.
And instead of continuities of functions it is better to define and
investigate those of relations and relators.
Unfortunately, the publications of our papers on relators are frequently
prevented by the leading topologists acting in editorial boards of various
journals. And we cannot even publish in the mathematical journals of Debrecen and Budapest.
Several authors study generalized topologies instead of generalized uniformities. Moreover, relators are also completely ignored by
the editors of the  Mathematical Subject Classification.
Comment: Do you have any recommendations for introductory references to this field?


Gerar mês subsequente in R

Question: Como faço para colocar o mês subsequent?
df1
dt          nome idade
01/03/2018  ll    15
07/03/2019  dd    33
31/12/2019  ff    44

Após regras
df1
dt          nome idade
01/03/2018  ll    15
01/04/2019  dd    33
01/01/2020  ff    44

A regra é a seguinte, caso o dia seja diferente de "01" o mesmo terá que ter o dia como "01" do mês subsequente, como mostra o df.
Answer: Usando os pacotes lubridate e dplyr:
library(lubridate)
library(dplyr)

#Criando o data.frame cedido. A função dmy converte para o formato data
df1 <- data.frame(dt = c(dmy("01/03/2018"), dmy("07/03/2019"), dmy("31/12/2019")),
                  nome = c("11", "ff", "dd"),
                  idade = c(15,33,44))

#O paste cria a data "01/mês/ano" da linha, %m+% adiciona o mês
#sem estourar a data limite do mês anterior, e months(1) a quantidade de mêses a serem somadas
df1 %>%
  mutate(dt2 = dmy(paste("01", month(dt), year(dt)))  %m+% months(1))
dt nome idade        dt2
1 2018-03-01   11    15 2018-04-01
2 2019-03-07   ff    33 2019-04-01
3 2019-12-31   dd    44 2020-01-01

Gerar mês subsequente in R


How do I add an attribute in an anchor tag?

Question: I want to make a module which will add some attributes in an anchor tag, whether the user adds in CKEditor or it is from Drupal menu system, before rendering it to the browser.
I can do it through jQuery with <code>$('a').attr('data-anchor', 'arial');</code>, but is there any way to do it through a module?
Comment: I think you mean through PHP? Because you can add your jQuery to your module and make file.js load on every page or on specific pages.
Comment: Yes, I want to do through PHP because jQuery may increase the rendering time.
Answer: You can do it using hook_link_alter
<code>/**
 * Implements hook_link_alter().
 */
function mymodule_link_alter(&$variables) {

    $variables['options']['attributes'] = array('data-anchor' => 'arial');

}
</code>
Comment: @AkashJain, that's a different question. You need a text filter. See https://www.drupal.org/docs/8/api/filter-api/overview. The last link on this page has a good tutorial.
Comment: Yes, if you want to add attributes in a text filter you can use the DOM structure of the field content, see http://drupal.stackexchange.com/questions/208445/ckeditor-and-site-style
Comment: Thanks for your answer but I think this might not work in my case. I want to alter all anchor tag whether the user added through CKEditor or rendering through a block like Hello<./a>. I don't think this hook will call for anchor tag that defined in content.
Comment: After testing, yes that's correct, this does not work with CKEditor. I would stick to the jQuery method, a few lines of jQuery will not slow you down.
Comment: @4k4 is correct, even if you manually type in CKEditor `link` the `data-anchor="arial"` part gets filtered out, removed. So I guess you need to create a text filter so it allows it.
Comment: ... allow it or add it for all links.
Comment: Actually, I was wondering some function where I got whole DOM structure but nevermind I will do it though Text filter. Thanks @4k4


Problema de leitura e inserção de dados no arquivo DBF após a exclusão de todos os registros

Question: Estou criando um sistema que vai ler um arquivo xls, excluir os dados de um arquivo dbf para então incluir todos os registros do xls na tabela.
Porem, esse sistema é um sistema intermediário, pois os dados do dbf são utilizados em um sistema em VB.
O sistema intermediário está consultando o xls, gravando os dados em um DataTable, está excluindo os dados do dbf (inclusive está dando "PACK" para confirmar a exclusão dos dados) e insere novos registros no arquivo.
Estou utilizando o DBF Commander para verificar se os dados estão realmente lá. Mas quando abro o sistema e mando gerar uma consulta, ele não retorna nenhum registro e também não me permite inserir novos registros.
Estou colocando o código da exclusão, pois verifiquei que mesmo sem inserir um registro pelo meu sistema, deixando o dbf limpo, não consigo incluir novos registros
private void btnDeletar_Click(object sender, EventArgs e)
{
    // Pergunta se deseja continuar
    if (clsGeneric.MsgDialog("Você está prestes a deletar a tabela. Deseja continuar?", "Cuidado!", clsGeneric.DialogType.Question) == DialogResult.Yes)
    {
        // Instâncias
        string vStrFileTree;
        string vSql;
        OleDbConnection conn;
        OleDbCommand com;
        vStrFileTree = edtPathDBF.Text;

        // Busca do diretório
        string strDirectoryPath = Path.GetDirectoryName(vStrFileTree);
        string strTable = vStrFileTree.Replace(strDirectoryPath, "");
        strTable = strTable.Replace("\\", "");

        // Conexão para a alterar a flag de "registro deletado" do DBF [Não Exclui os dados]
        conn = new OleDbConnection(clsConnection.strConnectDBF(strDirectoryPath, "EXCLUSVE=YES;"));
        conn.Open();
        try
        {
            com = new OleDbCommand();
            com.Connection = conn;
            vSql = "DELETE FROM " + strTable;

            com.CommandText = vSql;
            com.ExecuteNonQuery();
        }
        finally
        {
            conn.Close();
            conn = null;
            com = null;

        }

        // Regerando as conexões, fazendo o PACK do arquivo DBF [PACK - Exclusão Permanente dos dados deletados]
        conn = new OleDbConnection(clsConnection.strConnectDBF(strDirectoryPath, "EXCLUSVE=YES;"));
        conn.Open();
        try
        {
            com = new OleDbCommand();
            com.Connection = conn;

            com.CommandText = "PACK " + strTable;
            com.ExecuteNonQuery();
        }
        finally
        {
            conn.Close();
            conn = null;
            com = null;
        }
    }
    getDBFTable(grdImpDBF, edtPathDBF, false);
}

Logo abaixo está o código da string de conexão:
public static string strConnectDBF(string Path, string Extended = "")
{
    vStrConn = "Provider=VFPOLEDB.1;";
    vStrConn = vStrConn + "Data Source=" + Path + ";";
    if (Extended != "")
    {
        vStrConn = vStrConn + Extended;
    }

    return vStrConn;
}

Answer: Descobri qual era o problema. O problema era que ao alterar o arquivo .DBF, eu não estava reindexando a tabela no arquivo .CDX, desse modo o sistema principal não encontrava as informações no arquivo .DBF, só retornando os registros já indexados no .CDX.
Resolvi o problema criando uma rotina que excluía o arquivo .CDX, pois o sistema principal ao consultar os dados já criava o arquivo caso não existisse.


bson.errors.InvalidDocument: Cannot encode object: ec2.Image()

Question: When I try to insert the following document:
 aws_data = {u'ami_launch_index': 0,
             u'image': ec2.Image(id='xxx')
            }

I get the following error:
bson.errors.InvalidDocument: Cannot encode object: ec2.Image(id='xxx')

MongoDB is not able to encode ec2.Image(id='ami-xxx')
How do I fix it?
Answer: Store the image id directly to MongoDB. I would have advised serialization but it's pointless. With the image id, you can always perform other ec2 API operations.
aws_data = {
    'ami_launch_index': 0,
    'image': 'xxx'
}

You can't insert just about any objects into a collection. Supported data types include:

int
long
float
None
dict
list
tuple
str
bool
datetime
Uuid
Mapping
Byte
ObjectId
Regex
Code
Timestamp
DBRef
RawBSONDocument
MinKey
MaxKey
unicode

https://github.com/mongodb/mongo-python-driver/blob/3.6.0/bson/_cbsonmodule.c#L693


A major scale flat and natural accidental

Question: Wikipedia states the following for the A major scale

The key of A major is the only key where a Neapolitan sixth chord on 2 requires both a flat and a natural accidental.

Can anyone explain what the above means and how does that relates to the scale on a guitar
Answer: The Neapolitan sixth chord is a major triad with its root on the ♭2 of the scale, most commonly played in first inversion. So in A major it is a Bb major triad, which in first inversion is:
D F Bb
Since the A major scale contains an F# and a B, in order to get the required F and Bb you need one natural (for the F) and one flat (for the Bb).
Answer: A Neapolitan sixth chord in A-major (3#) needs a natural (F) and a flat (B) accidental:

Bb
F♮
D

D

Cadence:

A  Bb_G# A
E  F♮_E  E
C# D  D  C#

A  D  E  A


Função com dois parênteses? funcao()()

Question: Não sei como descrever por isso não consegui achar informação sobre. kkk
No final do código ao exportar o "connect", o que faz o segundo parêntesis? Como se chama essa sintaxe?

import React from 'react';
import { connect } from 'react-redux';

const Sidebar = ({ modules }) => (

        { modules.map( itModule => (

                {itModule.title}

                    {itModule.lessons.map( itLesson =>(

                            {itLesson.title}

                    ))}

        ))}

);

export default connect( state => ({ modules: state }))(Sidebar); // <---------<<
Comment: Você pode dar uma olhada no código da função para matar a curiosidade também. O [`connect` exportado](https://github.com/reduxjs/react-redux/blob/master/src/index.js#L4) é [essa função](https://github.com/reduxjs/react-redux/blob/master/src/connect/connect.js#L46)
Answer: A função connect() está retornando uma função. Então quando você faz connect()(Sidebar), você está passando Sidebar como parâmetro pra função retornada por connect e invocando-a. Um exemplo mais simples:
// Essa função recebe um parâmetro umNumero. Aí ela retorna outra função,
// que recebe outroNumero e soma com umNumero.
function soma(umNumero) {
    return (outroNumero) => umNumero + outroNumero;
}

soma(2)(3) // 5

Answer: Talvez fique mais fácil de entender a resposta do Allan Juan se você atribuir o retorno da função de alta ordem a uma variável.

function soma(umNumero) {
    return (outroNumero) => umNumero + outroNumero;
}

let somaDois = soma(2) // i.e., somaDois é a função (outroNumero) => 2 + outroNumero
let somaTres = soma(3) // i.e., somaTres é a função (outroNumero) => 3 + outroNumero

let resultado1 = somaDois(3)
let resultado2 = somaTres(4)

console.log(soma(2)(3), resultado1, resultado2)

Função com dois parênteses? funcao()()


Serving up webpage from Amazon EC2 instance

Question: If I'm serving up a website using apache from an Amazon EC2 instance, does it ever make sense for me to stop the machine? Also, I'm extremely new to EC2 so I'm not entirely sure how EBS works. It looks like Amazon does gave me 8gb of storage for free, but am I actually being charged for that storage 24/7? Thanks
Answer: If you stop the server, it is down. If you're in a development stage, and you want to limit your costs to the bare minimum, yes, you can stop the server at the end of each day.  This is one of the advantages to an EBS backed instance.
EBS is basically external network attached storage.  For most people, EBS backed servers are the way to go, since you can easily clone them, stop and start them, etc.  You can also make snapshots of an ebs volume, so it's a great way to have low cost backups of your server.
As for EBS storage, yes you pay for it, but it is relatively inexpensive.  The real cost of EC2 ends up being CPU/runtime for the most part, although EBS certainly makes it easy to use up large amounts of storage.
Comment: I also really recommend the Amazon linux distros. They make things really easy and stable, not to mention thoroughly tested.  Amazon linux is a hybrid of Centos and Fedora, with the paravirtualization patches already installed.  If you know Centos/RHEL you'll be comfortable with Amazon Linux (yum packages) etc.
Answer: does it ever make sense for me to stop the machine?
For production machine, no. I never had to stop prod machines in last couple of years. We launch new machines from our AMI when required and kill them when not.
However, for load testing or some research work for clustered environment -- we had to pause machines for a while. We use stop feature at that time.
...I'm not entirely sure how EBS works.
Quoting from official doc:

Amazon EBS volumes are off-instance storage that persists independently from the life of an instance. Amazon Elastic Bionlock Store provides highly available, highly reliable storage volumes that can be attached to a running Amazon EC2 instance and exposed as a device within the instance.

So, in highly simplified terms, it's like an external HDD or NAS
It looks like Amazon does gave me 8gb of storage for free, but am I actually being charged for that storage 24/7?
If you're paying for the instance... it should include the cost of the storage that AWS provides. For a given instance type, EBS backed instances cost more than Instance Store ones, so I guess it would include the EBS cost, but it's their pricing policy -- I can't really comment.
Side Note
Being a network storage, EBS backed images have its pros and cons. The biggest benefit is, if instance ever crashes, your root device would not vanish (please make sure you have checked 'do not delete root device on termination' while creating the instance). It comes handy in times of hardware failures or accidental termination.
However, being on network, it has all the issue that any networked device can have. For some applications that has really really fast and excessive IO (like for Cassandra), EBS seemed to be a bad idea.
Answer: If you have a free instance (it has to be a micro instance running their brand of EC2 Linux, not, say CentOS) then there is no reason to turn it off.
If you are paying per hour, then yeah, it makes sense to shutdown when not in use.
Comment: but even if it's a website that's going to be receive traffic all day around the world? I'd assume then the answer would be keep it on all the time, right?
Comment: also, if I 'stop' the machine, it maintains all of it's uploaded software and such, right?
Comment: Well, d'oh.  IF you want it running, then don't turn it off.  And yes, it the disk state survives being shut down.
Comment: thanks for that MK. Nice to know that your willing to cut a noob some slack
Answer: If you need more computing power and have a bigger instance, you could have the instance running on a higher CPU rate (more expensive instance type) for those hours the site is going to be accessed a lot and after that just change the instance type back to some minor. Just don't mess with the volumes.
If you don't want to be offline for those couple of minutes you're going to need, you could set up a free (micro) instance and assign the elastic IP to that instance or even redirect to a static web page on s3...
example: redirect to a s3 static page with "Maintenance in progress" message displayed.
Also, watch out while stoping/terminating your instance, I dont know is that the case just on windows instances but after starting instance again my non-root drive (volumes for non system partitions) went offline (when checking "volumes" they were attached) so I had to mount them again.


Kumaraswamy - Exponential Family

Question: I'm trying to proof that Kumaraswamy belongs to the exponential family and then get the expect value and it's variance.

The Kumaraswamy density distribution is given by:
$$ f(y;\alpha,\beta) = \alpha\beta y^{(\alpha-1)}(1-y^{\beta-1})$$

We know that a exponential family has the follow format:
$$f(x) = exp{\left(\frac{\theta x- b(\theta)}{a(\phi)} + c(x,\theta)\right)}$$

1) First step is take log of all terms in the equation:
$$ln(f(y;\alpha,\beta)) = \left( ln(\alpha) + ln(\beta) + (\alpha - 1) ln(y) + (\beta -1 ) ln(1-y^{\alpha})  \right)  $$
2) Second step is take the exponential of the terms:
$$f(y;\alpha,\beta) = exp{\left( ln(\alpha) + ln(\beta) + (\alpha - 1) ln(y) + (\beta -1 )ln(1-y^{\alpha})  \right)}$$

Then, when I expand the equation:
$$f(y;\alpha,\beta) = exp{\left( ln(\alpha) + ln(\beta) + \alpha ln(y) - ln(y)  + \beta ln(1-y^{\alpha}) - ln(1-y^{\alpha})  \right)}$$
Forward I don't know to adjust the terms to find the exponential family.
Somebody can help me?
Thank you!
Answer: I hate to break it to you, but it isn't part of the exponential family.
Typo in q: should be $(1-y^\alpha)^{\beta-1}$ in the PDF.
$\ln f(y; \alpha, \beta) = \ln \alpha + \ln \beta  + (\alpha-1)\ln y - (\beta-1)\ln(1-y^{\alpha}) $
The final term has $y, \alpha , \beta$ in it, while not being a linear function of $y$, so it can't be said to be of the form $\frac{\theta y}{a(\phi)}$
Comment: How can I obtain the expect value and variance of that density?
Comment: https://en.m.wikipedia.org/wiki/Kumaraswamy_distribution
Comment: They've done it for you there

Kumaraswamy - Exponential Family


The Visual Studio 2022 Error "Failed to launch debug adapter. Additional information may be available in the output window."

Question: I am using Visual Studio 2022 for Blazor WebAssembly Project and the ASP.NET Core API Project. When I run these projects independently, they works fine in Edge, Chrome browsers but, when I select Multiple-Startup projects, I am getting the following error.

Microsoft Visual Studio
One or more errors occurred.
Failed to launch debug adapter.  Additional information may be available in the output window.
The operation was canceled.
OK
Comment: Rebooting my computer solved this for me.
Comment: Which version of VS2022?  What is the relation between Wasm and API projects? Are they from the Hosted template or did you set up 2 indep projects?
Comment: On what URLs (port numbers) and in which order are they started?
Comment: The API Project is started first and then the WASM Application. The WASM application is calling the API for Authentication. This is really irritating.
Answer: I had the same issue with Visual Studio 2022. I could solve the issue by disabling the script debugging in the drop-down of green arrow where we run the project. Please see the following screenshot.
Comment: Disabling WebView debugging in a winforms app also helped.
Answer: One working tweek is disabling JavaScript debugging in either of these two ways:
1. Disabling Script Debugging from IIS

2. Removing the 'Enable' tick from JavaScript Debugging option
Comment: Unchecking it doesn't help me.
Comment: Above screenshot action works for me
Thanks
Comment: Sure this workaround works. But I need script debugging. This happened after I upgraded VS.
Comment: I have this problem with the latest preview community version (Version 17.6.0 Preview 1.0
) but Pro 2022 (2) works fine.
Comment: This worked for me. Thanks!
Comment: They were already both disabled. Still have problem.
Comment: If you're using IIS Express, try resetting it. You can do this by right-clicking the IIS Express icon in the system tray and choosing Stop Site, or by manually killing the process in the Task Manager.
Answer: I had this issue until I removed this line from launchsettings.json under profiles on the server side code.
Failed to launch debug adapter
Unable to launch browser...
"inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}",

Comment: I voted for this because it did work, but unfortunately removing that line prevents breakpoints from binding in Razor views (possibly elsewhere but that's the problem I ended up with). I suppose I should have expected trouble disabling something that's part of a "debug adapter" :-)
I've stopped trying to debug framework sources now (which was what caused the initial problem), and re-added the line and everything's working. Except framework source debugging...
Answer: Finally..... I resolved by modifying Tools-->Options-->Debugging--->General and enabling following two checkboxes as shown in image
Comment: I don't even see those option in Visual Studio 2022 Preview.
Comment: I have only "Enable Javascript debugging for ASP.NET (Chrome, Edge and IE)".  Unchecking it doesn't help.
Comment: In my case I had to set 'enable JavaScript debugging for ASP.NET' and 'Enable using the multi-target .... for ASP.NET projects' but not the Node.js setting.
Comment: Didn't work for me.
Comment: I just closed all browsers and restarted etc. And it worked
Answer: I solved this problem by setting the config "launchBrowser": false for the current profile in the file Properties/launchSettings.json.
It seems there is a browser launch problem. This may be caused by rights issues.
Answer: For me, just closing the browser solved it.
Comment: Same here, I had some hidden instances of Edge. Killed them from task manager and it was fixed
Comment: Same for me in my Blazor WebAssembly application. Solved it by filtering for Edge in the task manager and closing all instances.
Answer: Try to stop the site in the IISExpress background process in the system tray of the target project. Then exit the IISExpress background process itself.

Refer to this article:
https://techstrology.com/failed-to-launch-debug-adapter-the-program-has-exited-with-code-1-0xffffffff-visual-studio-failed-and-crashed/
Comment: I am not using IIS Express. I am using.NET Core 6 app.
Answer: On a related note, I encountered this error message after cloning the first Blazor project I'd worked on in VS 2022.
It turned out that I hadn't installed all the build tools required for the (WebAssembly) Blazor project.
Go to Tools \ Get Tools and Features... then the Individual Components tab.
After adding .NET 6.0 WebAssembly Build Tools and .NET WebAssembly Build Tools I was able to successfully debug the project.
Comment: That did it for me, cheers
Answer: I run into this issue because of powershell restrict mode.

Cannot dot-source this command because it was defined in a different
language mode. To invoke this command without importing its contents,
omit the '.' operator.

I solve it by the following steps.

Download the VsDbg downloaded from https://aka.ms/getvsdbgps1
Open the powershell terminal and navigate to the location where the downloaded file is located.
Execute - .\GetVsDbg.ps1 -Version vs2017u5 -RuntimeID linux-x64 -InstallPath "C:\Users[YOUR_USER_NAME]\vsdbg\vs2017u5"
Execute - .\GetVsDbg.ps1 -Version vs2017u5 -RuntimeID linux-musl-x64 -InstallPath "C:\Users[YOUR_USER_NAME]\vsdbg\vs2017u5\linux-musl-x64"
Comment: C:\Users\xxx\AppData\Local\Temp\GetVsDbg.ps1 : Cannot dot-source this command because it was defined in a
different language mode. To invoke this command without importing its contents, omit the '.' operator.
    + CategoryInfo          : InvalidOperation: (:) [GetVsDbg.ps1], NotSupportedException
    + FullyQualifiedErrorId : DotSourceNotSupported,GetVsDbg.ps1
Answer: deleting the VSDBG debugger folder located at "%USERPROFILE%\vsdbg\vs2017u5" may help resolve the issue.
Once you have deleted this folder, you can restart the debugger by pressing F5. Doing so will trigger the automatic recreation of the VSDBG debugger.
For further information on debug properties, you may want to consult Microsoft's official documentation, which can be found at https://learn.microsoft.com/en-us/visualstudio/containers/container-msbuild-properties?view=vs-2022. This documentation covers the use of various properties in MSBuild files to control the behavior of the debugger in containerized environments.
Answer: I wanted to see more info about some Exceptions that my app was raising, so I ticked the following setting in the VS Launch Profiles dialog. But once I'd ticked this I started getting the "Failed to launch debug adapter" error when I tried to debug the app. So I unticked the setting again.
Answer: I was getting this error alongside the following error in the console:
Invalid value for NO_PROXY: ... (Expected values: "localhost" or "127.0.0.1")
Just like it is documented here, if your environment is using a proxy, then you need to add localhost to your NO_PROXY environment variables.
On Windows:

Open Control Panel
Search for "Environment Variables"
Click "Edit the Environment Variables for your account
Set the variable NO_PROXY to a value of localhost.
Answer: For me, restarting all instances of Visual Studio worked.
Answer: in launchSettings.json, in profiles object set "jsWebView2Debugging": false, this resolved my issue
Answer: I had renamed my NodeJs folder in C:\Program Files\Microsoft Visual Studio\2022\Professional\MSBuild\Microsoft\VisualStudio as it conflicted with other NodeJS versions installed. By restoring it back to original state, this problem went away.
Answer: I started getting this error when attempting to debug a Static Web App, running behind the SWA CLI, with Visual Studio 2022. It had been working previously, so it's likely that some unknown update was responsible for the change in behaviour, but after hours of trying and failing to find the cause I hit upon this workaround.
In my case, the app's launchSettings.json had both a launchUrl and an applicationUrl setting:
  "launchUrl": "http://localhost:4280",
  "applicationUrl": "http://localhost:5080"
  "inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}",

In this case, the {url.port} placeholder in the inspectUri setting was expanding to the port specified in the launchUrl setting, i.e. 4280 - the port the SWA CLI was running on. Examining the visualstudio-js-debugger.txt file showed that this request was being refused. Changing it to explicitly use the port that the app was running on, i.e. 5080, fixed the problem for me.
  "inspectUri": "{wsProtocol}://{url.hostname}:5080/_framework/debug/ws-proxy?browser={browserInspectUri}"

Answer: In my case, I got the same error message as the original post, but the Additional Information part indicated that EACCESS to the port for the debugger was denied. I fixed the issue by stopping and restarting the WINNAT service as follows.
net stop winnat

net start winnat

Answer: I was able to resolve this issue by selecting a newer version of python in the debug properties. To do that, go to Debug>ProjectName Debug Properties>General. In that window select a newer python version next to Interpreter. In my case, Python 3.9 worked.
If no other python versions are displayed, you will have to install a newer version of python. I was making a console application and this is the only thing that worked.


Testing transfer of slave zone from master results in connection refused

Question: I'm using bind9 with webmin to try and set up a dns secondary for our primary nameserver. I'm in what I assume should be a very simple situation but I'm not able to get the master to transfer zones to the slave.
I've configured the master to have the slave in the Webmin Server Index then configured it as a slave under Cluster Slave Servers, then configured allow_transfer on the master with the ip of the slave. iptables -nL shows ports 53 and 953 as open on both master and slave. netstat -lnpt shows named listening to 53 (on master and slave), yet when I run test transferring the records to the slave I get:
Testing transfer of slave zone from 10.191.0.2 .. .. from 10.191.0.2 :
Failed : ;; Connection to 10.191.0.2#53(10.191.0.2) for
test.example.com failed: connection refused.

Configs for zone on master .2
zone "test.example.com" {
  type master;
  file "/var/lib/bind/test.example.com.hosts";
  notify yes;
  allow-transfer {
    10.191.0.3;
    };
};

Configs for zone on slave .3
zone "test.example.com" {
  type slave;
  masters {
    10.191.0.2;
    };
  file "/var/lib/bind/test.example.com.hosts";
  allow-transfer {
    10.191.0.2;
    };
  allow-update {
    10.191.0.2;
    };
};

I know I'm missing something, but I can't seem to figure it out.
Thanks for any help
Comment: Go on the secondary server, and do `dig @primary test.example.com AXFR` and see what happens. If nothing or timeout, you have a network problem between both hosts. If something and an error, you should see more clearly what happens and with details in primary server logfiles.
Comment: DNS lookups typically use UDP:53 and zone transfers are often over TCP:53. Have you checked that both are allowed from primary to secondary?
Comment: @JensEhrich That was it, only had udp open. Post it as an answer if you want more magic internet points
Comment: @PatrickMevzek Thanks too, that helped narrow down the fact that tcp 53 wasn't responding at all.
Comment: `AXFR` uses TCP indeed. You should use any online tool like DNSviz or Zonemaster to verify your nameserver configuration, replying to both UDP and TCP for any query is mandatory for good operations. You can also easily test locally, using `dig +notcp` and `dig +tcp` towards your nameserver.
Answer: Let me summarize and add a reason for the behaviour to the answer for the people who may come to this issue in the future...
DNS system by the definition is utilizing as default UDP protocol on port 53. But the service is designed to prevent fragmentation of the answer so once the answer would be bigger size it "fall" back to TCP protocol.
With UDP (in principle) you cannot guarantee that the answer will arrive fully and that some part is not lost during delivery once TCP is sending the confirmation. As a result once the answer is small enough that it would fit to one piece the UDP is used. Once the answer would be bigger to be safe the system send it out as TCP to not care about the fragmentation and delivery order. The example of bigger answer could be "regular" answer with glue records (where to ask for the next query iteration step - chicken and egg ;-) or DNSSEC stuff) or just mentioned zone transfer.
As rfc5936 - DNS Zone transfer Protocol (AXFR) is stating:

Because accuracy is essential, TCP or some other reliable protocol must be used for AXFR requests.

...

With the addition of EDNS0 and applications that require many small zones, such as in web hosting and some ENUM scenarios, AXFR sessions on UDP would now seem desirable.  However, there are still some aspects of AXFR sessions that are not easily translated to UDP.
Therefore, this document does not update RFC 1035 in this respect:
AXFR sessions over UDP transport are not defined.

So based on the citation you see that TCP protocol for zone transfer is mandatory.
In general (so not only because of zone transfer) you should allow both TCP/53 and UDP/53 on the DNS server to have it properly working. Allowing only UDP/53 would allow only partial operability.
-- edit (Thu Jun 20 10:20 UTC 2019) --
adding the actual answer to the question as well (AXFR uses TCP) - thanks to Håkan Lindqvist
Comment: Please consider adding the actual answer to the question as well (AXFR uses TCP), not only the additional reasons why you need TCP.
Comment: Done (I hope :) ). Thank you for valuable feedback Håkan.


Ruby Cucumber AfterStep not running after every step in a scenario

Question: I'm using Cucumber with Ruby and I want to execute some code after each step of the scenario. I have implemented the AfterStep hook, but I have found that it is not running after every step.
AfterStep do |step|
  puts "After step"
end

Is there any reason why Cucumber wouldn't run this hook after a particular step in the scenario?
Answer: If you are running cucumber 0.3.11 and the scenario has a background, the documentation indicates that an AfterStep hook will not work:
Warning: AfterStep hook does not work with scenarios which have backgrounds
(cucumber 0.3.11)

AfterStep do |scenario|
  # Do something after each step.
end

Comment: This is the extract from the Gemfile.lock:

`cucumber (2.0.1)
      builder (>= 2.1.2)
      cucumber-core (~> 1.2.0)
      diff-lcs (>= 1.1.3)
      gherkin (~> 2.12)
      multi_json (>= 1.7.5, < 2.0)
      multi_test (>= 0.1.2)
    cucumber-core (1.2.0)
      gherkin (~> 2.12.0)`

When I run the test with `puts "After step"` in the AfterStep block it seems to print it put for half the steps but not for everyone.
Answer: check your file path.For example, if the code are put in a file named hooks.rb , the file' path should be features/support/hooks.rb.


How do the notes on the treble and bass staves here correspond to each other? (Mozart K331 Mvmt 1 Var. V Measure 100)

Question:
In this measure 100 of the Variation V of Mozart's K.331, I'm trying to get it right which note on the treble staff is played at the same moment as which note on the bass staff. In the image I drew the lines of what I think is the correspondence (played at the same time), with dashed lines in doubt.
Every two quadruple beam notes together is equivalent to one triple beam note, right? So in Measure 100 (the second measure in the image), the first 8 notes on the upper staff correspond to the first 4 notes on the lower staff, right?
Then the 9~12th notes on top (BCDE) on a quadruple beam correspond to the 5~6th notes on the bottom (AF on a triple beam), right?
From the 13th note on top (F), and the 7th note on bottom (D), both staves are now triple beams, so the notes have one-to-one correspondence, correct? Are the dashed lines I drew correct? Is that the printing doesn't have the accurate positioning of the two staves' notes (the magenta line should be rather vertical)? Also, does the DF on treble correspond to the last F on the bass? or no?
Comment: by the way, I know it makes it harder to fit to your diagram, but these are all F#s and C#s, and would be written in text as "F#", "C#", rather than "F", "C".
Comment: @Kilian Foth For a beginner it's important to get everything right. I'm glad I asked the question; it really helps me to learn about beats, better than just reading general theory without a context or example, and without my having a question/curiosity first.
Comment: Mozart took the trouble to notate everything correctly here, but even if he hadn't, the obviously intended effect would "a really fast run up to the high D", and no one will much care (or notice) whether the triplet notes are *really* 25% slower than the preceding notes or not.
Comment: @James Martin Yes I  know, I wrote the notes there just for referring convenience.
Answer: In the upper staff, the fourth group of notes is a triplet. Those three notes correspond to the lower staff's seventh and eighth notes (i.e., second grouping, second two notes).
Here, given by note number, are the correspondences.

RH 1 3 5 7    9 11 13    16 18    20    22
LH 1 2 3 4    5  6  7     9 11    13/14 15/16
Comment: @GrandAdagio If the "3" were missing, the beaming would still make things clear. But I think what you're really asking is "what it wasn't a triplet and, instead, just three ordinary 32nd notes?" in that case, the right hand part would be one 32nd note too long, so it would be clear there was some sort of error.
Comment: @GrandAdagio "I guess the sure way is always to count the beats": if you had done that without taking the triplet into account you would have come up with an extra thirty-second note (demisemiquaver) in the right hand because the triplet consists of three notes played in the time of two "normal" notes of the same value. In other words, if you removed the "3" without making any other changes then the notation would be incorrect.
Comment: @GrandAdagio In general, music engravers try to align note heads according to when that note is played, but in measure like this one with so many notes, it can be difficult to show the alignment clearly.
Comment: @GrandAdagio Yes, the triplet is a bit slower than what came before and a bit faster than what comes after. *Very* tricky for a beginner.
Comment: Thank you Aaron! I definitely need to study the beats (been too lazy). Two questions: (1) In that triplet you mentioned (FGA), if the number "3" were not there, would it make difference? (2) Do all music scores print the notes in the exact positions they should be, as far as aligning upper and lower staves is concerned (such as where you drew the two vertical dashes above)? Or do some printing have the notes shifted away a little making it inaccurate? I guess the sure way is always to count the beats, but just wonder if the printing could also help me to reassure.
Comment: So that triplet FGA on treble staff is played a little slower than the group before it (BCDE), and a little faster than the group following it (BCDF)? Quite subtle and tricky for a beginner!
Comment: Thank you so much Aaron. Great learning here!