VBA - Não consigo referenciar há um Range usando o método Cells - ERRO 400

Question: Esse primeiro método me da um ERRO 400
Worksheets("RELAT").Range(Cells(i, 3), Cells(i + 1, 12)).Value = Worksheets(mes).Range("P5:Y6").Value

Esse segundo método funciona normalmente
Worksheets("RELAT").Range("C7:L8").Value = Worksheets(mes).Range("P5:Y6").Value

O Primeiro e o segundo método não são as mesmas coisas ? O que tem de errado ?
Código completo:
Sub atualizar_Relatorio()

    Dim i As Integer
    Dim j As Integer
    Dim mes As String

    j = 1

    For i = 7 To 30 Step 2
     mes = ActiveSheet.Cells(i, j).Value    'pegando o mês na planilha

     MsgBox (mes & " " & i)     'testando o nome do mês na msgbox, código roda normalmente até aqui

     Worksheets("RELAT").Range(Cells(i, 3), Cells(i + 1, 12)).Value = Worksheets(mes).Range("P5:Y6").Value   'este não funciona
     Worksheets("RELAT").Range("C7:L8").Value = Worksheets(mes).Range("P5:Y6").Value      'este funciona

    Next i

End Sub

Resumo do código:
Estou pegando um range (valores) de uma planilha (a qual pego o nome (mês) na planilha "RELAT" usando o for) e estou copiando os valores desta em outra planilha usando a referência por células, para que eu possa fazer a alteração de linha na planilha "RELAT" para que os dados não sejam substituídos, porém o Excel me mostra um Erro 400.
Substitui o for pelo seguinte código, porém queria reduzir usando o for
Código que estou usando e está funcionando:
Sub atualizar_Relatorio()

Worksheets("RELATÓRIO").Activate

Worksheets("RELAT").Range("C7:L8").Value = Worksheets("JANEIRO").Range("P5:Y6").Value
Worksheets("RELAT").Range("C9:L10").Value = Worksheets("FEVEREIRO").Range("P5:Y6").Value
Worksheets("RELAT").Range("C11:L12").Value = Worksheets("MARÇO").Range("P5:Y6").Value
Worksheets("RELAT").Range("C13:L14").Value = Worksheets("ABRIL").Range("P5:Y6").Value
Worksheets("RELAT").Range("C15:L16").Value = Worksheets("MAIO").Range("P5:Y6").Value
Worksheets("RELAT").Range("C17:L18").Value = Worksheets("JUNHO").Range("P5:Y6").Value
Worksheets("RELAT").Range("C19:L20").Value = Worksheets("JULHO").Range("P5:Y6").Value
Worksheets("RELAT").Range("C21:L22").Value = Worksheets("AGOSTO").Range("P5:Y6").Value
Worksheets("RELAT").Range("C23:L24").Value = Worksheets("SETEMBRO").Range("P5:Y6").Value
Worksheets("RELAT").Range("C25:L26").Value = Worksheets("OUTUBRO").Range("P5:Y6").Value
Worksheets("RELAT").Range("C27:L28").Value = Worksheets("NOVEMBRO").Range("P5:Y6").Value
Worksheets("RELAT").Range("C29:L30").Value = Worksheets("DEZEMBRO").Range("P5:Y6").Value

End Sub

Comment: Só respondemos perguntas em português no SOPT
Comment: ok, fiz a edição, obrigado
Answer: Não pode misturar os conceitos de Range e Cells.
Range
Seleciona uma célula ou um intervalo, o argumento é referenciado igualmente ao utilizado em fórmulas nativas, com letra para coluna e número para linha. Exemplos: "A1" ou "A1:B5".
Cells
Seleciona uma célula específica, o argumento é referenciado com números. O primeiro referente a linha e o segundo referente a coluna. Exemplo: "(1, 1)"
Portanto, não é possível referenciar um dentro do outro da forma que espera, como um endereçamento.

O caso em específico:
Há outras opções, mas eu sugeriria deixar os argumentos da Range dinâmicos, mesclando variáveis (para as linhas) e referências diretas (para as colunas), similar a:
Worksheets("RELAT").Range("C" & i & ":L" & i + 1).Value = Worksheets(mes).Range("P5:Y6").Value

Ao executar o código, supondo que i = 7, teremos a construção:
Worksheets("RELAT").Range("C7:L8").Value = Worksheets(mes).Range("P5:Y6").Value

Comment: compreendi a diferença de Range e Cells, porém quando utilizo a seguinte estrutura que está no código:

Range(Cells (i,j) , Cells(x,y)) eu estaria selecionando um range no intervalo de 2 células não ? eu achei que ja havia usado deste método e outro código, mas devo estar enganado então
Vou testar conforme me indicou e depois comento aqui
Comment: Muito o brigado Jean, deu certo esta sintaxe que me passou, mas ainda estou encabulado que jurava ja ter visto algo do tipo que usei anteriormente kkk

Mas agradecido !


Theory with non archimedean models

Question: Is there a consistent theory in the language of ordered groups (or ordered rings) whose models are non archimedean ordered groups (or rings or fields)?
(note: I am not asking for the existence of an axiomatization of the quality of being a non achimedean ordered group.)
Answer: If the underlying order of a nontrivial ordered group is discrete (i.e. every element has a successor and a predecessor), then either the group is isomorphic to $\mathbb{Z}$ or it is non-archimedean. Indeed, if $1$ (the successor of $0$) does not generate the whole group, then there is some element which is greater than $n\cdot 1$ for all $n\in \mathbb{N}$. The same statement holds for ordered rings, since the only ordered ring structure on $\mathbb{Z}$ compatible with the ordered group structure is the standard one.
So for a theory of ordered groups or rings all of whose models are non-archimedean, we can take $\mathrm{Th}(M)$, where $M$ is any discretely ordered group or ring which is not elementarily equivalent to $\mathbb{Z}$. At this point, you might worry that the theory of discretely ordered groups or discretely ordered rings is complete, so every model is elementarily equivalent to $\mathbb{Z}$. Fortunately, that's not the case.
For example, consider $T = \text{Th}(\mathbb{Z}\times\mathbb{Z},0,+,-, <)$, where $\mathbb{Z}\times \mathbb{Z}$ is ordered lexicographically. The sentence asserting that for all $x$, either $x$ or its successor is divisible by $2$ is true in $\mathbb{Z}$ but false in $\mathbb{Z}\times\mathbb{Z}$ (neither $(1,0)$ or $(1,1)$ are divisible by $2$).
Comment: @Noah Schweber Those are actually both great answers!
Answer: Here's a silly example, coming from proof theory:
Consider the theory $T=PA+\neg Con(PA)$. Since $PA$ is consistent, the standard natural numbers don't satisfy $T$; but by Goedel's Second Incompleteness Theorem, $T$ is consistent. So any model of $T$ has to be a non-Archimedean ordered semiring.
Now moving this example from semirings to rings is an easy exercise.
More generally, we can get an example of this type from any sentence $\varphi$ in the language of ordered semirings which is false in $\mathbb{N}$ but not disprovable in $PA$.

This also lets us get an example in fields. It turns out that $\mathbb{Z}$ is definable in $\mathbb{Q}$; this gives us a recursively axiomatizable theory $T$ of fields which is strong enough to do Goedel coding (by moving things onto the integer part), and such that $\mathbb{Q}\models T$. Now consider the theory $S=T+\neg Con(T)$. This theory will be consistent, so it will have models (which in particular are ordered fields) - but those models will need to have nonstandard integers since $T$ is actually consistent, and hence any model of $S$ will be non-Archimedean.

Theory with non archimedean models


Looking up the value of cells above a cell

Question: thank you for reading this.
I have a row containing a list of text.
APA
VEN
GRAB
I have a table containing either I or Super. Below the table, there are corresponding text such as APA, VEN, GRAB or blank formula cells.
I want to get the cells above a non-blank formula cell. For example, in the row APA, VEN, GRAB that I have..
I want APA to return the value of 5 cells above it. I know how to return one value above it (i.e. Super), but I am not sure how to get the 4 cells above Super.
APA I I I I Super
VEN
GRAB
Edit: =INDEX(AZ53:BA57,MATCH(BA58,BA53:BA57,0)-1,0) This is what I tried to return the cell above APA. I am trying to figure out how to return the 5 cells above APA.
I know I can enter formula to each cell. I wanted to do it in a formula if possible. Thank you again.
<code>=INDEX(AZ53:BZ57,MATCH(BA58,BA53:BA57,0)-2,0)
=INDEX(AZ53:BZ57,MATCH(BA58,BA53:BA57,0)-3,0)
=INDEX(AZ53:BZ57,MATCH(BA58,BA53:BA57,0)-4,0)
=INDEX(AZ53:BZ57,MATCH(BA58,BA53:BA57,0)-5,0)
</code>
enter image description here
Comment: *I want....*" is not really a good question. Let us know what you attempted and where you are stuck. Narrow your question down please.
Comment: how would you do it for 1 row above?
Comment: Thanks for the feedback! I edited to show what I attempted.
Comment: Please include a screenshot within the question or construct a table to make your Q much clearer - I'm having difficulty visualising whilst paying attention to whether you're referring to a row or column, and where the various tables are positioned in relation to one another.  Ta
Answer:
Answer based on inital question
Cell F10 contains the following formula <code>=INDEX(F:F;ROW(F$10)+INDEX($C$2:$C$4;MATCH(F$9;$B$2:$B$4;0))-1)</code> which has then be copied to G10 and I10.
I used the area B2:C4 to define the negative offsets for your non-blank content. As the field in which I display the result of the formula is one row below your non-blank content I added an additional -1 to the formula.
The grey numbers and the yellow highlights have been used to quickly validate the outcome.
Update based on questioner's comment
According to your instructions, source ranges (purple) would intersect with target ranges (blue), see cells with red border.

As it is not possible to put both a formula and a value into the same cell, I assumed that you wanted to explain independently

how the target should be structured and
how the source should be structured.

Hence, it looks like you are looking for a formula that transposes your values from columns into rows.

In the above image, the highlighted cells contain the following formula (example for cell S14):
<code>=OFFSET(source_anchor,COLUMN(S14)-COLUMN(target_anchor),ROW(S14)-ROW(target_anchor))
</code>
source_anchor refers to cell Q3
target_anchor refers to cell R13
Please let me know if this is what you are looking for. If it is not the case, then please provide a mock-up.
Comment: Hi, thank you Qualia. So in Cell C2:H2, next to APA (cell B2), I am looking to try to pull in F2:F7 in your example using a single formula.

Another example is for Cell C4:H4, I am trying to pull H2:H7.

If possible, I can just drag C2 down using a formula, and it will refer to column B, and search for the corresponding cells above row 9. Thank you again for your time.
Comment: @user16233760: did you look at the update? Is this what you are looking for?
Comment: Hi Qualia, it's not, but thank you very much, I really appreciate it. I am attaching a screenshot in my original image. What I am trying to do is to find a way that if I drag the formula in a row (e.g. from Row 1 to 10), the column will fill out automatically. The reason is that I have thousands of column, and it takes a lot of work to do it for multiple sheets.
Comment: I am sorry, but I still do not get it. Could you provide a template with sample data, e.g. one tab showing the initial table and another one showing the desired result?


habilitar e desabilitar butão em react

Question: estou fazendo um quis de perguntas em react, na qual faço uma requisição pro banco e ele retorna as pergunta e assim eu crio o front, só que o botão de responder eu só quero que seja ativado quando o usuário clicar em alguns dos input de resposta, quando o usuário clica o estado e alterado o botão e ativado, mas ele ativa todos os botões de todas as outras pergunta também, eu queria que ativasse somente o daquela pergunta na qual o input foi clicado, como posso fazer isso?
meu código:
const [estadoBtn,setEstadoBtn]= useState(true)
function ativaBtnResposta(event){ // vai na div inputs
        let alvo=event.currentTarget
        let id=alvo.parentElement.id
        let box=document.getElementById(id)
        let input=box.querySelectorAll('.boxResposta input')
        let btnRes=box.querySelector('.resposta button')

        input.forEach(element => {
            if(element.checked){
                setEstadoBtn(false)

            }

        });

 return(

quiz

 {cont.map((id,index) =>{
return(

   div className="inputs" onClick={ativaBtnResposta} >

                                <input type="radio" name="resposta" value='A'  ></input>

A - {id.A}

                                <input type="radio" name="resposta" value='B'  ></input>

B - {id.B}

                                <input type="radio" name="resposta" value='C'  ></input>

C - {id.C}

                                <input type="radio" name="resposta" value='D'  ></input>

D - {id.D}

                                <input type="radio" name="resposta" value='E'  ></input>

E - {id.E}

  <button className="btnRespostaHtml" disabled={estadoBtn}onClick{showResposta}>Responder</button>
  {id.res}

)

)

Comment: O código está uma bagunça muito grande, mas a ideia é a mesma por trás do React como um todo: suas perguntas devem ser "encapsuladas" em um componente, assim o state vai se referir àquela pergunta e nenhuma outra. Ou, ativando o modo programação orientada a mangue, num componente só, é só fazer um state contendo um objeto composto, com um subitem para cada pergunta.
Answer: Opa, tudo certo?
Primeiramente, no React temos o princípio da imutabilidade, na qual elementos em React são imutáveis, ou seja, não podem mudar seus atributos uma vez que criados.
Pelo que entendi da sua pergunta, tu quer que cada botão seja ativado apenas quando clicar no input do tipo radio daquela pergunta. Mas quando você clica em um todos os botões ficam habilitados.
Se for isso, isso acontece pois a mesma variável é usada para todos os botões no mesmo contexto. Para resolver isso, tu pode fazer um componente representando um conjunto de input/label/button e recebendo a questão como parâmetro. Eu fiz aqui em typescript, vou te enviar e veja se te ajuda em algo.
Arquivo App.tsx (tsx é react com typescript)
import { Input } from "./input";
import "./styles.css";
export default function App() {
  const questions = ["question1", "question2", "question3"];
  return (

      {questions.map((question) => {
        return <Input question={question} />;
      })}

  );
}

Arquivo Input.tsx (é o componente que criei)
import { useState } from "react";

interface InputProps{
  question: string
}

export function Input({question}: InputProps) {
  const [questionIsSelected, setQuestionIsSelected] = useState(false);

  function inputIsFocus() {
    setQuestionIsSelected(true);
  }

  return (
    <>
      {question}
      <input type="radio" onClick={inputIsFocus} />
      <button disabled={!questionIsSelected}>Enviar</button>
    </>
  );
}

Não fiz seguindo todos os padrões de clean code etc, tentei deixar de um jeito mais fácil de entender pelo que entendi de sua necessidade.
Espero ter ajudado!

habilitar e desabilitar butão em react


Use promise to wait for database operation

Question: I have a function that calls another function, which connects to a database to get some value. Until the execution is completed, I cannot proceed further as that value is to used for another transaction on the database.
I am using yield to determine the completion of that method, and promise to resolve or reject the response. This is how I am doing it:
co(function*() {
  rec.x = yield getX(a, b);
  //use rec to update something else
  conn.update(rec);
}).catch((err) => {
  console.error(err.stack)
});

function getX(a, b) {
  return conn.getVal(a, b);
}

exports.getVal = function(a, b) {
  return sql.connect(connStr).then(function() {
    return new sql.Request()
      .input('a', sql.VarChar(100), a)
      .input('b', sql.VarChar(50), b)
      .execute('someProc').then(function(recordSet) {
        return Promise.resolve(recordSet[0][0]);
      });
  });
};

I am getting this error:
ConnectionError: Connection is closed.
    at node_modules/mssql/lib/main.js:1613:17
    at doNTCallback0 (node.js:417:9)
    at process._tickCallback (node.js:346:13)

edit
Connection string:
Uname:pass@server/database

Comment: _at node_modules/mssql/lib/main.js: **1613** :17_ which line is number 1613 in the code you posted
Comment: Does the request work without going through the generator/yield? Meaning, if you call `getVal` function directly, does it work?
Comment: Can you share your connection string in the post?
Comment: @Freyday yes. The request works fine without yield..
Comment: What happens if you assign `sql.connect(conStr)` to a `connection` variable, then pass `connection` into `sql.Request()` like `sql.Request(connection)`? Do you get the same error?
Answer: After spending hours on figuring out this vodoo of mssql. It seems like mssql does not handle concurrent connection well enough. Therefore, using setTimeout on making connection requests solved the problem for me.
If it helps anyone, this is what I did:
exports.getVal = function(obj, cb) {
    var connection = new sql.Connection(config, function(err){
        if (err){
            console.log(err);
        }
        console.log('connected..');
        var request = new sql.Request(connection);
        request.input('a', sql.VarChar(100), obj.a);
        request.input('b', sql.VarChar(50), obj.b);
        request.execute('proc', function (err, recordSet, returnValue, affected) {
            if (err) {
                console.log(err);
            }
            cb(recordSet[0][0]);
        });
    });
};

This is how I call:
 setTimeout(function(){
                                getVal(rec, function(obj){
                                    console.log(obj);
                                });
                            }, 500);


Can Jags be used to fit classical inference state space models?

Question: Can Jags be used to fit classical inference state space models (that is without using a Bayesian approach by specifying a prior)?
To be fully clear: can I estimate a state space model such as the following:
$y_t = \mu_t + \epsilon_t$
$\mu_{t+1} = \mu_t + \eta_t$
in Jags using classical inference?
I thought of using Jags as it has many options that other state space packages do not have (I am already familiar with those, so I am not looking for answers that suggest those).
Answer: The answer is no. JAGS is not designed for such models. However Stan provides such possibility.

Stan provides optimization algorithms which find modes of the density
  specified by a Stan program. Such modes may be used as parameter
  estimates or as the basis of approximations to a Bayesian posterior;
  see Chapter 52 for background on point estimation. Stan provides three
  different optimizers, a Newton optimizer, and two related quasi-Newton
  algorithms, BFGS and L-BFGS (...)

Notice that if uninformative prior is used then

the posterior mode corresponds to the maximum likelihood estimate
  (MLE) of the parameters. If the prior is not uniform, the posterior
  mode is sometimes called the maximum a posterior (MAP) estimate. If
  parameters (typically hierarchical) have been marginalized out, it's
  sometimes called a maximum marginal likelihood (MML) estimate.

So with Stan you can use optimization algorithm rather then MCMC sampling and with using flat prior the results obtained are congruent with MLE estimates (see also this).
Source: Stan Development Team (2015). Stan Modeling Language User's Guide and Reference Manual. Stan Version 2.6.2. pp. 22, 23, 458.
Comment: Great answer, thank you very much! Could you please tell me what exactly you mean with a 'flat prior' (how would you define it)?
Comment: flat = uniform. In JAGS there is even `dflat` "distribution" as a synonym for uniform. In Stan you can even declare uniform in $[-\infty, \infty]$ range, what makes Stan to find out the proper range using its algorithms. (check the Stan manual, it has >500 pages and goes into many details)
Comment: ...however I am not sure if it is the best way to use the software. There are optimization algorithms implemented in R, MATLAB and in other software that could be more suitable.
Comment: I know, I tried out several ones of them. But the problem that I have with them is that most of them are only for Gaussian models and that I want to estimate state space models with other distributions.
Comment: In R you can set up model with any possible distributions and use one of the [multiple optimization algorithms](http://www.jstatsoft.org/v60/i01/paper), and probably the only advantage of Stan or JAGS are *the* sampling algorithms you are not interested in.
Comment: The thing is, this question is actually an attempt to solve my question here: http://stats.stackexchange.com/q/144573/31563 . I thought that maybe by using Jags/Stan I could fit state space models with a t distribution. Because this doesn't seem possible in all the other state space packages.
Comment: I get it, but you can as well define the likelihood in R and use the optimization algorithm. In both cases it needs the same amount of coding from you and there won't be many differences. (I am talking here about coding it by hand in R rather then using some already existing package.)
Comment: Maybe that's the best option indeed. But I wanted to do that as a last option since I think it will probably be more error prone. But I guess it helps that at least the optimization algorithms are already preprogrammed.
Comment: Actually then I would also have to program the filtering though... hope it's gonna work out.


verilog wrapper around systemverilog intefaces with inout ports

Question: I just downloaded a behavioral model of a DDR4 interface from micron.  To my surprise, they converted the ports entirely to a system interface, which creates a problem when interfacing this model to a mixed language simulation of Verilog or VHDL.
My question is this.  How to create a verilog or VHDL wrapper around a DDR4 SystemVerilog interface that contains inout ports?  Here's an example of what I'm trying to do:
//SystemVerilog Interface
interface micron_ddr4_if();
   wire [7:0]  DQ;
   wire        DQS_t;
   wire        DQS_c;

   modport  system (inout DQ, DQS_t, DQS_c);

endinterface

// System Verilog Module
module micron_ddr4_model(
    micron_ddr4_if  ddr4_if
);
    // ...
endmodule

// Convert SystemVerilog Interface into Verilog Interface
module my_verilog2001_wrapper(
   inout wire [7:0]  DQ,
   inout wire        DQS_t,
   inout wire        DQS_c
);
   micron_ddr4_if     ddr4_if();

   micron_ddr4_model  ddr4_model(ddr4);

   // How to connect this part?
   //
   //   DQ      <=> ddr4_if.DQ;
   //   DQS_t   <=> ddr4_if.DQS_t;
   //   DQS_c   <=> ddr4_if.DQS_c;
   //
endmodule

Comment: The interface code you show should never have worked. You cannot model bi-directional inout ports with variables. They need to be wires.
Answer: You can use port expressions. People see this syntax on module instances but don't realize they can also use it in port declarations.
module my_verilog2001_wrapper(
   inout .DQ(ddr4_if.DQ),
   inout .DQS_t(ddr4_if.DQS_t),
   inout .DQS_c(ddr4_if.DQS)
);
   micron_ddr4_if     ddr4_if();

   micron_ddr4_model  ddr4_model(ddr4_if);

endmodule

Comment: cool, is that a SystemVerilog Feature, or a Verilog-95 Feature.?
Comment: That's a Verilog-**1986** feature.
Answer: tri [7:0] tri_DQ;

assign tri_DQ     = DQ;
assign tri_DQ     = ddr4_if.DQ;
assign DQ         = tri_DQ;
assign ddr4_if.DQ = tri_DQ;


Extract final value from nested field collection

Question: I have a content type with a field collection. This field collection has, as fields, other field collections. It works well, it groups the content for a node perfectly, but when trying to extract the data programmatically, I cannot access the values introduced. How would be the method. I tried with this piece of code, but it throws an error. Also not sure if adequate to my case (nested field collections):
$node = node_load($node->nid);
$node_wrapper = entity_metadata_wrapper('node', $node);

foreach ($node_wrapper->field_rich_text_group as $field_collection_wrapper) {
            $field_collection = $field_collection_wrapper->value();
                print_r($field_collection);
}

Answer: Try this :
$node = node_load($node->nid);
$node_wrapper = entity_metadata_wrapper('node', $node);

foreach ($node_wrapper->field_rich_text_group->value() as $value) {
  $field_collection_wrapper = entity_metadata_wrapper('field_collection_item', $value);
  $field_collection_myfield = $field_collection_wrapper->field_myfield->value();
  print_r($field_collection_myfield);
}

Field Collection is an entity, so if you want to access its field you have to pass the field collection in entity_metadata_wrapper. Then you can access the value of your fields in field collection like you do with your $node_wrapper
Comment: I have tried, but still an error and does not return the expected values. I am going to start from the beginning, with a single level field collection, and so on... I'll be back to report. Thanks anyway, surely you are right but I am missing something.
Answer: I have managed to get the value by direct access.
$node = node_load($node->nid);
$node_wrapper = entity_metadata_wrapper('node', $node);
echo $node_wrapper->field_rich_text_group->field_meta_datos->field_meta_title->value();

I guess that the foreach would be needed if I have multivalued data.
Please someone explains to me why this solution works and pbonnefoi does not print anything and throws error. Adapting from his code,
$node = node_load($node->nid);
$node_wrapper = entity_metadata_wrapper('node', $node);
foreach ($node_wrapper->field_rich_text_group->value() as $value) {

$field_collection_wrapper = entity_metadata_wrapper('field_collection_item', $value);

 $field_collection_myfield = entity_metadata_wrapper("field_collection_item", $field_collection_wrapper->field_meta_datos->value());

print $field_collection_myfield->field_meta_title->value();

Print OK but throws this error, probably because in the loop there is something it does not locate:
`// EntityMetadataWrapperException: Unknown data property field_meta_datos. en EntityStructureWrapper->getPropertyInfo() (line 335 of /home/public_html/sites/all/modules/entity/includes/entity.wrapper.inc).`

Comment: What is meta_datos ? Is it a field collection ?
Comment: Yes. What is even worst; Now I am not able to reproduce the structured jerarchy above. I have come to the final strcuture: ` $node_wrapper->field_seo->field_seo_com->field_seo_general->field_meta_title->value() just for having seo boxes for several domains. Instead of two levels I have 4 levels and cannot get it working with less. **I am not understanding the nested field collection.**
Comment: Are your field collection set to multiple ? In that case you have to use nested foreach.
Comment: No. it is multiple levels, not multiple values. I do these steps: In the content type, I create field_seo_general (embedded) and field_seo (hidden) just to get them available. In the field_seo which is the last level, I create the field field_meta_title. In field_seo_general I create field__com and field__us, which are field collection. Then, editing these two, I assign existing field, which is the type field_seo. So I can access via `echo $node_wrapper->field_seo_general->field__com->field_seo->field_meta_title->value();` . There are no multiple values. I am doing right? It is so convoluted.
Comment: Well I have to say I have trouble understanding your problem. For me you only use field collection if you need multiple instance of a group of field ?
Comment: My problem is that I thought I had too many levels. In fact, I think I have the correct number. The first one is the node. The second the field, which is a field collection, of SEO data for different domains (Domain Access node). The third level is one of the domains, and finally I have fourth level which is the field collection of metadata fields, and the last and fifth level is the data itself. The fourth level is necessary if I don't want to repeat the fields for every domain field collection, so now I think I understand it all. But `entity_metadata_wrapper` would be needed just once.


Express $\tan3\theta$ as a rational function in terms of $\tan\theta$

Question: So I know that a rational function is a function that can be defined by a rational fraction and I managed to expand
$$\tan3\theta=\frac{3\tan\theta-\tan^3\theta}{1-3\tan^2\theta}$$
Is this considered as a rational function? Thanks guys.
Comment: $$\dfrac{3t-t^3}{1-3t^2}.$$
Answer: Yes, you have represented $\tan3\theta$ as a rational function of $\tan\theta$, because both the numerator and denominator are polynomials in $\tan\theta$.


Banner Animado com Google Web Design

Question: Eu criei um banner animado usando a ferramenta Google Web Design.
Pra quem já usou ele cria o banner com HTML5 CSS e Javascript.
para incorporar esse banner na minha página  eu utilizei a tag do HTML:

Queria saber se essa é a forma correta de incorporar um banner animado em um site, ou se existe outra maneira, por exemplo: Fazer com que o google web design  salve como um arquivo SVG algo do tipo.
Comment: Você diz isso baseado nas limitações que o Google Web Design oferece a você ou em termos gerais de desenvolvimento com HTML e CSS?
Comment: é pq nunca tinha feito, um banner animado pra botar em uma página, ai quando fiz por padrão a ferramenta GWD cria uma página em html, e arquivos CSS e JS. ai unica forma que achei de incorporar esse banner foi pro IFRAME, ai queria saber se era assim que fazia mesmo
Answer: Abordando sua questão em termos gerais de desenvolvimento front-end e deixando um pouco de lado as possibilidades da ferramenta Google Web Design.
Há várias formas de se incluir sua página banner/rodrigo.html, digo que o atributo iframe não é a melhor opção para este caso, pois é muito limitado. Ressalto que iframe não necessariamente está errado, apenas que não é uma boa prática.
Se você estiver desenvolvendo com PHP, dinamicamente é possível incluir sua página da seguinte forma:
<?php include 'banner/rodrigo.html'; ?>

Pratique a inclusão com PHP neste link.

Caso esteja apenas desenvolvendo o design em si, nada de conteúdo dinâmico, dá pra utilizar Javascript da seguinte forma:
Inclua a tag

Leia mais sobre da inclusão via Javascript neste tópico.

*Como o Google Web Design deve incluir jquery, você não necessitará da tag que faz a chamada da biblioteca.
*Vale lembrar que não estou considerando o conteúdo de seu arquivo banner/rodrigo.html, o seu arquivo .css, conflitos de jquery, etc.

Banner Animado com Google Web Design


Factoring 4 terms with a difference of squares as two of the 4 terms

Question: Can someone help show me step by step how to factor:
$9x^2 - 24xy + 16y^2 - 81$
I see a difference of squares in the last two terms and am stuck at this stage (did I start wrong in doing the factoring?) :
$9x^2 - 24xy + (4y+9)(4y-9)$
Please show me the steps to get the final factored form to:
$(3x-4y+9)(3x-4y-9)$
Answer: HINT: $$9x^2 - 24xy + 16y^2=(3x-4y)^2$$
Answer: HINT: $$(a-9)(a+9)$$ is the main indea


Count occurences of values inside a list stored in a dictionary in python

Question: I have a dictionary like this:
dict = {
     key1: [1, 5, 65, 78, 4],
     key2: [1, 5, 3, 90],
     key3: [1, 5, 785, 908, 65, 3]
 }

Goal to achieve:
I want to count the occurrences of all the single values inside the lists in my whole dictionary. Something like this:
count = {
    1:3,
    5:3,
    3:2,
    4:1,
    65:2,
    78:1,
    90:1,
    785:1,
    908:1
}

Then, I want to compute the occurrence percentage of every item inside the whole dictionary:
percentage = {
       1: 33.3,
       5: 33.3,
       3: 22.2,
       4: 11.1,
       65: 22.2,
       78: 11.1,
       90: 11.1,
       785: 11.1,
       908: 11.1
 }

My code:
I've tried implementing a list in which I store all the values of dict to later use a Counter to count all the value's occurrences, and at the end I'm trying to compute all the percentages, but I don't know why this doesn't work.
all_dictionary_values =[]
for v in dict.values():
    for x in v:
        all_dictionary_values.append(x)
print(len(all_dictionary_values))

count = Counter(all_dictionary_values)

percentage = {}
for k,v in count.items():
percentage = {k: (v/len(all_dictionary_values))*100}

Note:
The total items (without repetitions) inside all the lists (that are the values in the key-value  pair in my dictionary are near 300000, so if anyone knows a faster way to make this whole computation, any advice is well accepted.
Answer: You can use chain.from_iterable to flatten three lists. You can use collection.Counter to count each value and at the end use the length of dict for computing the percentage.
from itertools import chain
from collections import Counter

dct = {
     'key1': [1, 5, 65, 78, 4],
     'key2': [1, 5, 3, 90],
     'key3': [1, 5, 785, 908, 65, 3]
 }

dct_cnt = Counter(chain.from_iterable(dct.values())) # list(chain.from_iterable(dct.values())) -> [1, 5, 65, 78, 4, 1, 5, 3, 90, 1, 5, 785, 908, 65, 3]
print(dct_cnt)

# count of keys in the dictionary
len_dct_cnt = len(dct_cnt)

res = {k : round((v/len_dct_cnt)*100, 1) for k,v in dct_cnt.items()}
print(res)

Output:
# print(dct_cnt)
Counter({1: 3, 5: 3, 65: 2, 3: 2, 78: 1, 4: 1, 90: 1, 785: 1, 908: 1})

# print(res)
{1: 33.3, 5: 33.3, 65: 22.2, 78: 11.1, 4: 11.1, 3: 22.2, 90: 11.1, 785: 11.1, 908: 11.1}


Calculation of triple integrals like $ \int_{V'} \frac{ \mathbf{r} - \mathbf{r'}}{\mid \mathbf{r} - \mathbf{r'} \mid ^3} dV' $, on spherical domain

Question:
How could one solve integrals in the form:
  $$ I(\mathbf{r})= \int_{V'} \frac{ \mathbf{r} - \mathbf{r'}}{\mid \mathbf{r} - \mathbf{r'} \mid ^3} dV'  $$
  where the domain of integration is the sphere:
  $$ x'^2+y'^2+z'^2 \leq R^2 ~?$$

I would change the integration variables from $ x' $ to $ x'' = x-x' $ (similarly for  $y $ and $z$), obtaining:
$$ I(\mathbf{r''})=\int_{V''} \frac{ \mathbf{r''}}{\mid \mathbf{r''} \mid ^3} dV'' $$
where now the domain of integration is the sphere centered at $(x,y,z)$:
$$ V'' = \{(x'',y'',z'') \in R^3 : (x-x'')^2+(y-y'')^2+(z-z'')^2 \leq R^2 \} $$
and then using spherical coordinates $(r,\theta,\phi) $ such that $$ x''=r \text{cos}\theta \text{sin}\phi $$ $$ y''=r \text{sin}\theta \text{sin}\phi $$ $$ z''=r \text{cos}\phi $$
Obtaining, considering for example the first component of $ I$:
$$ I_1(\mathbf{r''})= \int\int\int \frac{ r\text{cos}\theta \text{sin}\phi}{r^3}r^2 \text{sin}\phi dr d\theta d\phi= \int\int\int \text{cos}\theta \text{sin}^2\phi dr d\theta d\phi  $$
At this point my problem here is to find the integration intervals for the varibles $(r,\theta,\phi) $; i.e. the description of the domain of integration $V''$ in spherical coordinates.
These kind of integrals arises for example in electrostatic when one has to compute the electric field produced by a uniformly charged sphere centered at the origin. There one would use Gauss' law, but how the integral itself could be calculated?
Comment: Comments are not for extended discussion; this conversation has been [moved to chat](http://chat.stackexchange.com/rooms/21114/discussion-on-question-by-nnec-calculation-of-triple-integrals-like-int-v).
Answer: Hint:
Let $\mathbf r=(0,0,a)$ with $a>0$.
The z-component of the integral is given by$$\iiint\limits_{V'} \frac {a-z'}{[x'^2+y'^2+(a-z')^2]^{3/2}} \,dx'dy'dz'=$$$$\int_0^R\int_0^{2\pi}\int_0^\pi \frac {\rho^2(a-\rho\cos\phi)\sin\phi}{(\rho^2+a^2-2a\rho\cos\phi)^{3/2}} \,d\phi \,d\theta \,d\rho$$ Now use $$\rho^2+a^2-2a\rho\cos\phi=t^2$$ to find $$\int_0^\pi \frac {(a-\rho\cos\phi)\sin\phi}{(\rho^2+a^2-2a\rho\cos\phi)^{3/2}} \,d\phi=$$$$\frac 1{2a^2\rho} \int _{|\rho-a|}^{\rho+a}\left [1-\frac {\rho^2-a^2}{t^2} \right]\, dt=$$$$\frac 1{2a^2\rho} \left(2\rho-\frac {\rho^2-a^2}{|\rho-a|}-|\rho-a| \right)=\begin {cases} 0\qquad \text{if}\quad a<\rho\\ \\\dfrac 2{a^2}\quad\; \text{if}\quad a>\rho \end {cases}$$ so $$\iiint\limits_{V'} \frac {a-z'}{[x'^2+y'^2+(a-z')^2]^{3/2}} \,dx'dy'dz'=\begin {cases} \dfrac 43\pi a^3\, \cdot \dfrac 1{a^2}\quad\; \text{if}\quad a<R\\ \\\dfrac 43\pi R^3 \cdot \dfrac 1{a^2}\quad\, \text{if}\quad a>R \end {cases}$$ The x- and y-components are zero because the integrand has odd simmetry respectively over the yz-plane and the xz-plane and $V'$ is symmetric over those planes.


Manipulate search results on site

Question: We have a few scenarios on a project where we want results to be presented at the top of the of the page despite not having any keywords in the body copy related to the search keyword.
For instance, if someone on our site searches for "baseball," we'd like a few choice results about "football" to come up, even though the nodes are strictly about baseball.
Are there any modules that allow for this behavior in the search functionality of Drupal?
Comment: For which Drupal version are you asking?
Comment: Drupal 6 is the version where I'm currently using for this particular project.
Answer: If you are using ApacheSolr then I imagine this could be solved with the use of 'Synonyms'.
See the documentation on this.
Example synonyms file you might use:
<code>#Equivalent synonyms may be separated with commas and give
#no explicit mapping.  In this case the mapping behavior will
#be taken from the expand parameter in the schema.  This allows
#the same synonym file to be used in different synonym handling strategies.
#Examples:
ipod, i-pod, i pod
baseball, football
</code>

Manipulate search results on site


Question about Trigonometry

Question: How do I solve this:
If $A + B + C = \pi$ and $\sin \left(A + \frac{C} {2}\right) = 4\sin\left(\frac{C}{2}\right)$
Then $\tan\left(\frac{A} {2}\right)\tan\left(\frac{B}{2}\right) =\,\text{?}$
Comment: Please indicate what you have done so far and where you are stuck. This will help others better tailor their answers to your background and situation. It will also show them that you are interested in your question and not just trying to get someone to do your homework - StackExchange is not a homework site.
Comment: Begin with the work and mention source of  your difficulties when lot of help comes in.
Comment: thanks for the tips I will remember that next time
Answer: With
$$C=\pi-A-B$$
we get
$$\cos \left(\frac{A}{2} -\frac{B}{2}\right)=4\cos\left(\frac{A}{2}+\frac{B}{2}\right)$$
and from here we have with the addition formulas
$$\cos \left(\frac{A}{2}\right)\cos \left(\frac{B}{2}\right)+\sin \left(\frac{A}{2}\right)\sin \left(\frac{B}{2}\right)=4 \left(\cos \left(\frac{A}{2}\right)\cos \left(\frac{B}{2}\right)-\sin \left(\frac{A}{2}\right)\sin \left(\frac{B}{2}\right)\right)$$
Dividing both sides of this equation by $$\cos \left(\frac{A}{2}\right)\cos \left(\frac{B}{2}\right)$$
we get
$$1+\tan \left(\frac{A}{2}\right)\tan \left(\frac{B}{2}\right)=4 \left(1-\tan \left(\frac{A}{2}\right)\tan \left(\frac{B}{2}\right)\right)$$
Can you proceed?
Answer: Clearly, we need to eliminate $C$ by replacing with $\pi-A-B,$
$$\dfrac{\cos\left(\dfrac A2-\dfrac B2\right)}{\cos\left(\dfrac A2+\dfrac B2\right)}=\dfrac41$$
Applying Componendo and Dividendo,
$$\dfrac{\cos\left(\dfrac A2-\dfrac B2\right)-\cos\left(\dfrac A2+\dfrac B2\right)}{\cos\left(\dfrac A2-\dfrac B2\right)+\cos\left(\dfrac A2+\dfrac B2\right)}=\dfrac{4-1}{4+1}$$
$$\iff\dfrac35=\dfrac{2\sin\dfrac A2\sin\dfrac B2}{2\cos\dfrac A2\cos\dfrac B2}=\tan\dfrac A2\tan\dfrac B2$$

Question about Trigonometry


Drupal behaviors not attached after Ajax load

Question: I'm facing a weird problem on my clean Drupal Installation
I attached a js library to page with this
function fs_gal_preprocess_page(&$variables) {
    $variables['#attached']['library'][] = 'fs_gal/fs_gal';
}

This js file I have:
(function ($, Drupal, drupalSettings) {
  'use strict';
   Drupal.behaviors.GalJs = {
    attach: function (context, settings) {
        alert("Gal");
    }
  };
}) (jQuery, Drupal, drupalSettings);

In my custom theme I created a Ajax call:
$('.button a').on('click', function (e) {
    e.preventDefault()
    $.ajax({
        type: "POST",
        url: "path-to-controller",
        cache: false,
        success: function(htmlText) {
            $('.text-container').html(htmlText);
        }
    });
});

After clicking the button, the text is correctly replaced in the .test-container but the library is not re-attached to the newly changed DOM.
Do someone know a technique to re-attach all behaviors to the content injected after an Ajax call ?
Many thanks for your help
Comment: @Clive solution's fixed everything.
Answer: Behaviours are fired after a Drupal AJAX call - a call to jQuery.ajax isn't the same thing.
Fortunately it's easy to attach them yourself, just add this in the success callback when you've finished manipulating the DOM:
Drupal.attachBehaviors();

Comment: Excellent @Clive you point me to the right direction. 1) I didn't know that Jquery and Drupal AJAX calls aren't the same. `Drupal.ajax({ url: endpoint }).execute();` was a solution too  2) . Attaching back manually all behaviors with `Drupal.attachBehaviors();` works well too. Thank you very much Clive


Cout giving garbage output when looping through a const char

Question: When executing the following code I get what I expect plus some unexpected output:
#include <iostream>

using std::cout;
using std::endl;

int main()
{
    const  char ca[] = {'h', 'e', 'l', 'l', 'o'};
    const char *cp = ca;
    while (*cp)
    {
        cout << *cp << endl;
        ++cp;
    }
}

Output:
h
e
l
l
o
ⁿ
■
m

What are the last remaining characters? Is there something in the const char array that is not being accounted for?
Comment: `while (*cp)` the condition never becomes `false` unless you have a `'0'` nul terminator in your array.
Comment: @πάνταῥεῖ Technically, it's `'\0'` character, which is not the same as `'0'`.
Comment: @AlgirdasPreidžius Must have been editing out the `\ ` when I editing my comment, it's `'\0'` actually. Putting that stuff in backticks seems to be hard :)
Answer:
while (*cp)

This loop ends when cp points to a null character.

const  char ca[] = {'h', 'e', 'l', 'l', 'o'};

The array does not contain the null character.
Therefore the loop iterates over the array, and outside of its bounds. The behaviour of accessing an array outside of its bounds is undefined.
Answer: The while loops until *cp equal 0.
This fix:
#include <iostream>

using std::cout;
using std::endl;

int main()
{
    const  char ca[] = { 'h', 'e', 'l', 'l', 'o', '\0' }; // <-- add '\0'
    const char* cp = ca;
    while (*cp) // loop until *cp equal '\0'
    {
        cout << *cp << endl;
        ++cp;
    }
}

Or this:
#include <iostream>

using std::cout;
using std::endl;

int main()
{
    const  char ca[] = { "hello" };
    const char* cp = ca;
    while (*cp)
    {
        cout << *cp << endl;
        ++cp;
    }
}


.get() and .find() for search results

Question: So I have a search bar on a page (/Search), and when the user searches for something, it will run a filter on the input text and refresh the page with the filtered results.
If someone searched the word "monkey", the URL of the search results will be

/Search?searchBoxText=monkey

I'm trying to make that happen without having to refresh the page.
So in my main.js I have:
$(function () {
    $("#searchBox").keyup(function (e) {
        var searchBoxText= $("#searchBox").val();
        $.get("/Search?searchBoxText=" + searchBoxText, function (getHtml) {
            $("#resultsDiv").html(getHtml);
        });
    });
});

The problem is that it displays the whole body of the page in #resultsDiv and I want it to just display #resultsDiv. So it displays the header, search bar & button again.
Essentially I want to display the new results (which would be in #resultsDiv) in the old #resultsDiv but I can't seem to constrain the .get() to only get a specific element from the resulting page.
I tried to do

$.get("/Search?searchBoxText=" + searchBoxText + " #resultsDiv", function (getHtml)
$("#resultsDiv").html(getHtml).find("#resultsDiv");

And other alterations like that but nothing seemed to work.
Thanks!
Answer: Please try following
$("#resultsDiv").html($(getHtml).filter("#resultsDiv"));

Demo
Comment: `getHtml` is a string so won't have the `find()` method
Comment: Yeah this doesn't work. I believe it was one of the things I tried
Comment: Still doesn't work. I get the console error message:
"Uncaught TypeError: getHtml.filter is not a function"
Comment: @Sadikhasan Oops. I don't know if you saw my comment before I deleted it but that error wasn't related. I just missed it before. Although your method still doesn't work, there is no error message in console.

.get() and .find() for search results


Remover efeito "piscar a tela" ao apertar um botão!

Question: Eu estou fazendo um projeto — com Arduino — juntamente com controles em uma pagina web feita em HTML, está tudo certo. Porém, ao apertar um botão dessa aplicação web, a página é recarregada, dando um efeito de "piscar" a tela, como consigo tirar esse efeito ?
Segue trecho do código:
void loop()
{
  acionamentos(); //Vai para a função que executa o acionamento dos botões
  EthernetClient client = server.available();// Verifica se tem alguém conectado
  if (client)
  {
    boolean currentLineIsBlank = true; // A requisição HTTP termina com uma linha em branco Indica o fim da linha
    String valPag;
    while (client.connected())
    {
      if (client.available())
      {
        char c = client.read(); //Variável para armazenar os caracteres que forem recebidos
        valPag.concat(c); // Pega os valor após o IP do navegador ex: 192.168.1.2/0001

        if(valPag.endsWith("0201"))
        {
          cont=2;
        }
        if (c == '\n' && currentLineIsBlank)
        {

          if (cont==1){
          //Inicia página HTML
          client.println(F("HTTP/1.1 200 OK"));
          client.println(F("Content-Type: text/html"));
          client.println();
          client.print(F(" "));

          client.print(F(""));
          client.print(F("<meta charset='utf-8' name='viewport' content='width=device-width, initial-scale=1, user-scalable=no'/> <title>Automação</title>"));
          client.print(F( ""));
          client.print(F( ""));
          client.print(F( ""));

          client.print(F( "<p1><botao>Iluminação</botao> </p1>"));
          client.print(F( " <p1><botao2>Controle</botao2></p1>"));
          client.print(F("

"));
          client.print(F( "
<button>Lâmpada 1</button>
"));
          client.print(F( "
<button>Lâmpada 2</button>
"));
          client.print(F( "
<button>Lâmpada 3</button>
"));
          client.print(F( ""));
          client.println(F(""));

          break;
          }

          else if (cont==2){
//Inicia página HTML
          client.println(F("HTTP/1.1 200 OK"));
          client.println(F("Content-Type: text/html"));
          client.println();
          client.print(F(" "));

          client.print(F(""));
          client.print(F("<meta charset='utf-8' name='viewport' content='width=device-width, initial-scale=1, user-scalable=no'/> <title>Automação</title>"));
          client.print(F( ""));
          client.print(F( ""));
          client.print(F( ""));

          client.print(F( "<p1><botao2>Iluminação</botao2> </p1>"));
          client.print(F( " <p1><botao>Controle</botao></p1>"));
          client.print(F("

"));
          client.print(F( "
<button2>   </button2> <button2>    </button2>  <button>ON/OFF</button>
"));
          client.print(F( "
<button>Vol +</button> <button> ˄ </button> <button>Can +</button>
"));
          client.print(F( "
<button> < </button> <button> OK </button> <button> > </button>
"));
          client.print(F( "
<button>Vol  -</button> <button> ˅ </button> <button>Can  -</button>
"));
          client.print(F( "
<button>1</button> <button>2</button>  <button>3</button>
"));
          client.print(F( "
<button>4</button> <button>5</button>  <button>6</button>
"));
          client.print(F( "
<button>7</button> <button>8</button>  <button>9</button>
"));
          client.print(F( "
<button>0</button>
"));
          client.print(F( ""));
          client.println(F(""));

          break;
          }
        } //Fecha if (c == '\n' && currentLineIsBlank)

      } //Fecha if (client.available())

    } //Fecha While (client.connected())

    delay(3);// Espera um tempo para o navegador receber os dados
    client.stop(); // Fecha a conexão

  } //Fecha if(client)

} //Fecha loop

void acionamentos()

Comment: Seu botão tem a propriedade type desta forma: `` ?
Answer:

function chamaArduino(id){
  var botao = $("#"+id).value;
  $.ajax({
    type: "POST",
    url: botao,
    success:function(data){
      console.log(data);
    },
   error:function(xhr, status, error) {
      var err = JSON.parse(xhr.responseText);
      alert(err.Message);
  }
  });
}

<button onclick="chamaArduino(this.id);" id="1" value = "http://192.168.0.100/0200">Botão</button>

<button onclick="chamaArduino(this.id);" id="2" value = "http://192.168.0.100/0200">Botão</button>

<button onclick="chamaArduino(this.id);" id="3" value = "http://192.168.0.100/0200">Botão</button>

<button onclick="chamaArduino(this.id);" id="4" value = "http://192.168.0.100/0200">Botão</button>

Se você deseja efetuar alterações no html sem ter recarregamento da página só do elemento, recomendo que você dê uma estudada em Ajax isso pode lhe ajudar a fazer o que você deseja. Segue um link que lhe auxiliará no estudo:
http://api.jquery.com/jquery.ajax/. Caso queria esclarecer o que deseja só perguntar nos comentários.
EDIT:
Adicionei um trecho de código que pode fazer o que você quer
Comment: Qual o motivo da negativação? estou errado? explique-se por gentileza
Comment: Lucas boa noite, muito obrigada, andei dando uma pesquisada, como posso implentar o ajax nesse caso ? editei a pergunta com um trecho de codigo
Comment: Adicionei um código na resposta, veja se convém para o que você necessita


An asymptotic expansion for MeijerG function

Question: By using Mathematica
Series[MeijerG[{{-(1/2)}, {}}, {{-(1/2), -(1/2), 1/2}, {}}, a x], {x,0, 0}, Assumptions -> a > 0],
I got an asymptotic expansion of MeijerG function at $x\approx 0$ for $a>0$ as
$$G_{1,3}^{3,1}\left(a x\left|
\begin{array}{c}
 -\frac{1}{2} \\
 -\frac{1}{2},-\frac{1}{2},\frac{1}{2} \\
\end{array}
\right.\right)\xrightarrow{} \frac{-\log (a)-\log (x)-2 \gamma }{\sqrt{a} \sqrt{x}}+O\left(\sqrt{x}\right).$$
However, with available asymptotic expression in MeijerG, I could not derive above expression.
Does anyone have an idea of deriving this?
Here is the plot:
Comment: Is the MA result correct?
Comment: I added an example plot.
Comment: You may reduce the `MeierG`to simpler functions. Have a look here Bateman, H.; Erdélyi, A. (1953). [Higher Transcendental Functions](http://apps.nrbook.com/bateman/Vol1.pdf), Vol. I (PDF). New York: McGraw–Hill. (see § 5.3, "Definition of the G-Function", Eq.(32) on p. 218)
Answer: We can roundtrip your expression by first finding the MellinTransform and then instead of applying InverseMellinTransform, we can just take the first residue. This ends up giving the main series term. [formula]
Here's the Mellin transform:
mei = MeijerG[{{-(1/2)}, {}}, {{-(1/2), -(1/2), 1/2}, {}}, a x];

mel = MellinTransform[mei, x, s]

$-\frac{1}{2} \pi  (2 s-1) a^{-s} \sec (\pi  s) \Gamma \left(s-\frac{1}{2}\right)^2$

Now in order to find where to take the residue, we need to know the strip in which this transform exists:
MellinTransform[mei, x, s, GenerateConditions -> True]

ConditionalExpression[..., 1/2 < Re[s] < 3/2]

It turns out summing residues in the complex plane to the right of the strip will diverge and so we sum to the left. This means we'll start with s == 1/2:
Residue[mel x^-s, {s, 1/2}]

$\displaystyle \frac{-2\gamma - \log(a) - \log(x)}{\sqrt{a} \sqrt{x}}$
Comment: Clear explanation! Thanks @Chip Hurst.


Updates: keep panels pages, views, etc.. updated via hook_update_n?

Question: im having a little trouble keeping a project update.
I track the code via a private git repo, and for each update I follow those steps (first on stagin, then on production):

update all the 3rd pars modules (from drupal.org)
Update database (via drush updb)

Then if everything is ok:

update my modules (via git repo)
update database (drush again)

All works perfectly, except for pages/views exported via Features module: in my module i hav a function like this:
/**
 * Implements hook_default_page_manager_pages().
 */
function mymodule_default_page_manager_pages() {
    // Second page...
    $page = new stdClass();
    // page definition, display, etc..
    $pages['page_machine_name'] = $page;

    // Second page...
    $page = new stdClass();
    // page definition, display, etc..
    $pages['page_machine_name'] = $page;

    return $pages;
}

The structure is the same for views.
I noticed that if i update that function changing something in a previous declared (and imported) page (add a pane, change a configuration on a content, etc..), this one wont get updated! (yeah, i flushed the cache different times both via UI and via drush)
Am I doing something wrong? There is a specific way to update those elements?
Answer: Well, this can not be the best solution but it works:
function mymodule_update_7001(&$sandbox) {
  // Views.
  if (is_callable('views_save_view')) {
    $views = module_invoke_all('views_default_views');
    foreach ($views AS $view_object) {
      views_delete_view($view_object);
    }
    // Rebuild it.
    $views = module_invoke_all('views_default_views');
    foreach ($views AS $view_object) {
      views_save_view($view_object);
    }
  }

  // Pages
  module_load_include('inc', 'page_manager', 'plugins/tasks/page');
  if (is_callable('page_manager_page_save')) {
    $pages = module_invoke_all('default_page_manager_pages');
    foreach ($pages AS $page_object) {
      page_manager_page_delete($page_object);
    }
    // Rebuild it
    $pages = module_invoke_all('default_page_manager_pages');
    foreach ($pages AS $page_object) {
      page_manager_page_save($page_object);
    }
  }
}

Basically just keep updated the views and pages definitions (views_default_views and default_page_manager_pages), the delete and rebuild them.
Obviously, this remove all customizations done via the Drupal's UI, so only do it for the views and pages you need to update!


How to move "Add new comment" link

Question: How would I go about moving the "Add new comment" link above certain items in my content type display? Here's an example: http://www.jcpenney.com/women/fall-trend-shop/boyfriend/ana-boyfriend-cardigan-/prod.jump?ppId=pp5002961049&catId=cat100300005&subcatId=cat100250027&deptId=dept20000013&dimCombo=null&dimComboVal=null&colorizedImg=DP0705201317172824M.tif
In the link above you'll see the "write a review" link. This is where I want to place the "Add new comment" link.
Answer: You can create the node template for your content type. You can review the template suggestions link for reference.
You can add below code in your template file to generate a link for the comments.
<code>print render($content['links']['comment']);
</code>
Kindly see that you need to uncheck 'Show reply form on the same page as comments ' checkbox in the comment settings for your content type.

How to move "Add new comment" link


mysql has table name case sensitive with efcore

Question: Our mysql database was on Tencent Cloud before,
Now we have created one in k8s.
Then our program reported an error means "Table packagedb_dev.ShopOrder" doesn't exist;
Our table name is lowercase.
When I change the table name to uppercase, the error disappears.
I have been using EFcore and mysql for a long time and have never encountered this error.
The orm is EntityframeworkCore,Version: Microsoft.EntityFrameworkCore 3.1.9
Comment: Please check your mysql database, ensure that the ShopOrder table exists.
Comment: You also need check the connetionstring in your project.
Answer: I have solved the problem.
The cause is that the self-built database is case-sensitive and the database in the container can be cumbersome to set this parameter.


Does probability change is the denominator is split into multiple pools or concentrated into a single pool?

Question: Having a debate and would love a statistically sound confirmation :)
Here is the scenario:
You have 9 tickets to enter into a drawing pool. That pool of individual entries is 100 each day. You have a choice of entering all 9 in a single day (9/100 = 9%) or you can choose to enter them over 3 different days of pools with a size of 100, 3 tickets each day. 3/100 * 3 days = 9%.
Are these in fact the same odds and probability?
It feels like condensing them into the same pool would be better (100) vs going up against 3x pools of 100 (300).
It's a very competitive debate so scientific mathematical evidence of which is better (or are they the same) would be VERY AWESOME. Thanks!
Comment: Thank you! So the probability is 9% in both cases but the odds are When you enter all in one day the chances are slightly better (ref your answer) - correct?
Answer: Your expected number of wins is the same in either case at $0.09$.  The probability of at least one win is slightly higher if you enter all of them the same day.  It is also $0.09$.  If you enter three each on three days there is some chance that you will win two or three prizes, so the chance of at least one is reduced.  In this case the chance of not winning on a day you enter is $0.97$, so the chance of losing every time is $0.97^3$ and the chance of at least one in is $1-0.97^3 =0.087327$ You need to be careful what question you are asking.
Comment: I should mention each applicant has the opportunity to win only once. There are no odds of being selected multiple times.
Comment: Normally each pool is independent, so each person can only win a given pool once but might win more than one if he enters more than one.  If you have special rules that prevent that you should make that clear.  The answer may change if you change the rules.
Answer: When you enter all in one day the chance of losing is $0.91$.  If you enter 3 each in 3 days, the chance of losing all is $0.97^3=0.912673$, so you are slightly better off if you enter all in one day.
However if you enter in 3 days, there is a chance you will win more than once.


Finding regular expressions

Question: I'm given the DFA shown below and need to find regular expressions for the following languages: $L_{1,2}^0, L_{2,1}^6, L_{2,5}^4, L_{2,3}^5, L_{1,3}^5$.

The language $L_{p,q}^r$ is defined as $L_{p,q}^r=\{x_1...x_n \in \Sigma^* : \delta(p,x_1...x_n)=q$ and for $i=1,...,n-1$  $\delta(p,x_1...x_i)\leq r\}$- The reason for introducing this notation is the following concept:
In my lecture notes it says that for an automaton with states $Q=\{1,...,m\}$ it follows that $L_{p,q}=L_{p,q}^m$ and we can then find regular expressions for $L_{p,q}$ by making use of the following formula $L_{p,q}^{r+1}=L_{p,q}^r\cup L_{p,r+1}^r(L_{r+1,r+1}^r)^*L_{r+1,q}^r$ and reducing until $r=0$, for which regular expressions can easily be found.
My first question is: Is that a useful concept? I have found this to be extremely time consuming for automata with more than 3 states. Does it ever make sense to apply this?
Finally for the given languages I have found the following regular expressions:
$L_{1,2}^0 : a$
$L_{2,1}^6$ : I don't think there is any input that lets the given DFA go from state 2 to 1
$L_{2,5}^4 : (aa)^*b$
$L_{2,3}^5 : ((aa)^*|(bb)^*)^*a$
$L_{1,3}^5 : (bb)^*(a((bb)^*|(aa)^*)^*a)|(bab((bb)^*|(aa)^*)^*a)$
Are these regular expressions correct?
Comment: Based on a quick check, it seems that the expressions are correct. Some of the regular expressions could be simplified (for example $((aa)^*|(bb)^*)^* = (aa|bb)^*$ and the last one seems to be equivalent to $(bb)^*(a|bab)(aa|bb)^*a$, although such simplifications would make their origin less clear. As for the first question -- I believe it's more of an exercise in applying a particular algorithm, rather than something that'd be "useful" for human. On the other hand, it's certainly simple enough for a computer to use.
Answer: Answer to the first question. Yes, this algorithm, due to McNaughton-Yamada, is a useful concept, at least theoretically. In practice, one may prefer to solve linear equations to pass from an automaton to a regular expression.
Your exercise. Did you find this automaton by yourself? It looks like you were trying to solve this question and found this automaton which is not minimal: you can merge the states 1 and 3 and the states 4 and 6. Then with only four states, the algorithm is much more manageable...
Comment: Thanks for the answer. I did not create that automaton, it was given in a homework exercise.

Finding regular expressions


Why is the Mirror on a midpoint, rather than the root note, in Negative Harmony theory?

Question: I'm curious about why Negative Harmony music theory relies on finding the midpoint between the Tonic and Dominant Degrees in a scale, and flipping the scale around that point, instead of simply playing the scale's intervalic pattern inverted from the tonic.
For instance, when mirroring C Major at the midpoint between the Tonic and Dominant, you get:
C - G
 D - F
 E - E♭
 F - D
 G - C
 A - B♭
 B - A♭
(I pulled this little diagram off Reddit.)
Apparently, the mirror point lands between the Major, and Minor third. (E, Eb, respectively.)
But why is Negative Harmony done this way, and not by flipping right at the Tonic?
Up   Down
 - C - C
w
 - D - Bb
w
 - E - Ab
h
 - F - G
w
 - G - F
w
 - A - Eb
w
 - B - Db
h
 - C - C
If someone could explain to me why this isn't done, or alternatively, what to call this, if this isn't called mirror or Negative Harmony, I'd be really appreciative!
Thanks so much!
P.S: I used a scale finder tool to see the many names of scales that show up with this particular set of Notes:
https://www.scales-chords.com/fscale_res_en.php?rn1=C&rn2=A%23%2FBb&rn3=G%23%2FAb&rn4=G&rn5=F&rn6=D%23%2FEb&rn7=C%23%2FDb&rn8=C&rn9=&normal=1&greek=1&greekalt=1&other=1&etnic=1&c1=&t1=&c2=&t2=&c3=&t3=
Obviously, lots of names for the scale, and, it is possible one of them exactly matches the Inverse intervalic pattern, I didn't check them all, but none of them match exactly what I've written down above.
Answer: The notion of negative harmony really comes from Ernst Levy, who discussed it in his A Theory of Harmony (1985). Recently it's become a bit of a trend thanks to Jacob Collier.
But the basis of negative harmony (or "mirror harmony") is really a rehashing of a 19th-century Austro-German theory called dualism. This system was actually about mirror inversions around a chord root. Take, for example, C major: C E G. The harmonic dual of this chord measures the intervals from C, but in the opposite direction. C to E is an ascending major third, and C to G is an ascending perfect fifth. As such, the harmonic dual has a descending major third (C to A♭) and a descending perfect fifth (C to F).
You'll notice that this creates an F-minor triad. (But back then, they actually called this "C dual minor," since it was generated starting on C.)
In contrast, negative harmony sought a way to change the mode of the key without changing the tonic. As such, it inverts around the midpoint between tonic and dominant. This way, the negative harmony of C E G is C E♭ G, and major just switches to minor. (But note that chords built on other scale degrees will typically change their root.)
In other words, harmonic dualism does exactly what you're asking about: it inverts around the tonic pitch. But negative harmony just changed the rules a bit by inverting around tonic and dominant.

PSA: Due to the recent influx of questions on negative harmony and the number of views these questions receive, I've taken the liberty of creating the negative-harmony tag. Feel free to consult the other questions marked with that tag!
Comment: I first heard about it from Jacob Collier =)


HP workstation Z420 cannot be turned on without unplugging and reinserting mainboard supply

Question: A customer of mine has an HP Z420 workstation with a very strange behaviour.
The computer generally works well, but occasionally refuses to turn on.
The customer observed that unplugging the power socket of the motherboard and reinserting it always worked; after doing that, the computer turns on without problem. This is very boring as it involves kneeling down to open the case.
I went on site to see that from my own eyes. Although I'm aware that invisible solder cracks may be present, the power socket appeared to me being firmly soldered. I also could observe the malfunction and that the trick worked.
In an attempt to solve the problem, the power supply has already be replaced by a previous IT company, without success. I must admit that I don't know if the power cable was replaced as well.
As a first thing, I replaced the BIOS battery with a new one.
It seem have fixed the problem during about 10 days, but then the problem came again.
I suspect the presence of some parasitic current (due to capacitors?) that would prevent the computer turning on until the power socket is unplugged and reinserted.
Here are the specs:

HP Workstation Z420 Tower
Processor Xeon E5-1620 v2 @ 3,7 GHz
Graphics: NVIDIA Quadro
(8 GB RAM, 120 GB SSD, 1TB HDD, ...)

The power supply is a 600W one, and that seem sufficient according to the specs.
The HP warranty unfortunately expired.
Are there known power supply problems with the motherboard of this workstation?
Comment: @Alexander: Thank you for the improvements in the layout and the correction of the typo.
Answer: Solved: it was a failing capacitor.
Comment: Can you please tell the location of the capacitor ?


How is solfège approached when there is harmony in the background?

Question: Instead of trying to memorize every interval out of context, a more useful ear training goal is the "memorization" of each scale degree in relation to the tonic (Movable-do solfege). Each degree will eventually produce a certain sensation. [The context of a C major scale is used in this post when examples are given]
Some degrees are more stable than others (1, 3 and 5; 1 being the most stable) and some degrees are more unstable (2, 4, 6 and 7; 7 being the most unstable). The unstable tones produce a certain desire to step into another close stable degree. It's like 7 wants to be followed by 1; 2 wants to be followed by 1 or 3; etc...
My question is: How does that work if there is an underlying harmony?
If we play some melody on our solo instrument alone, the feeling of tendency tones and stable tones is easily heard. However, the degrees of the same melody will produce a different sensation over a different set of chords. A "C" would become less stable when played over an F chord and a "B" would be more stable if played over an Em chord.
It seems that solfege books don't introduce the "problem" of existing background chords. It seems to me that there is a "main center of gravity" (the tonality) and "movable satellite centers of gravity" (the chords). So, when you finish exercises of internalizing degrees and you are able to audiate simple melodies, you are an expert of doing so over a C chord, but when the harmony changes to an F chord, everything becomes much more difficult (the unstable "F" doesn't have such a strong desire to be followed by an "E", for example).
Would the recommendation still be to hear everything in relation to the tonic? It's not very natural to keep the tonic in mind while the harmony changes and it somewhat ruins the experience of hearing the music.
Comment: the same way you are hearing tendencies in the melodic notes the chords have tendencies as well, and this is why we have functional harmony to analyse these types of problems. https://en.wikipedia.org/wiki/Diatonic_function#Diatonic_functions_of_notes_and_chords
Comment: When you write stable and unstable degrees, you do mean strong and weak degrees, don't you?
Comment: I'm not sure about the nomenclature. I'm talking about this as a solfege learning technique: [What are Active Tones and Restive Tones?](http://www.youtube.com/watch?v=blJCnCrd1W0) or this [Why Do Chord Progressions Progress?](http://www.youtube.com/watch?v=BpeP7tJWDc8) (around 20:40)
Comment: Just found something like what I had in mind: [Tonal Gravity](http://www.garygarrett.me/?p=1076)
Comment: @user45784 I don't believe the OP knows what scale degrees are. From the directions they assign to the notes I believe they hear the notes of the scale in context of a tonic chord (otherwise the directions make no sense, the chord on the third degree is certainly not more stable than the chord on the fourth degree, whereas the 1st, 3rd and 5th note are clearly the three most stable notes of the scale in context of a tonic chord) so when they talk about degrees they talk about single notes of the scale and not harmonies.
Comment: That is exactly what I think and it is the origin of my question. They indeed talk about notes, you might have misread something or I wasn't clear enough. Books on solfege have this approach of tendency tones without harmony. So, it seems to me that it only makes sense in the context of a tonic chord as you say.
Comment: Is this from a classical context (rather than jazz/pop/any other genre I don't know much about)? If so, I will try to formulate a slightly more comprehensive answer than the present two tomorrow.
Comment: Nice :) Well, the books I followed more closely are classical oriented.
Answer: Your fifth paragraph seems correct to me. The principle behind solfege singing is that all the local stabilities—the stability of fa over the IV chord or ti over the V7 chord—are bracketed in a larger tonality rooted on do, the most stable pitch.
You are hinting at the idea of an "even more" movable do—if the goal is to have do be the most stable note, why not rename fa to do when you sing it over the IV chord?
The reason is that this obscures the relationship between the chords and their parent key. While the note fa is stable over the IV, the IV chord itself is unstable relative to the tonic (I). Using the same solfege syllables even as the accompanying harmony moves around is a way of acknowledging this larger tonal schema.
(If the piece is actually switching keys, e.g. by modulating to the IV, then you may switch your solfege syllables if the modulation persists for a long time.)
Another way to think about this is to recognize that the solfege system privileges melody over harmony. All of the tension and release in music, as far as solfege is concerned, is determined by what scale degree the melody is on. We know, of course, that this picture is incomplete and that harmony matters a great deal, which is why theory courses incorporate harmonic analysis as well. But the purpose of solfege is to help you, as a singer dealing with one pitch at a time, feel the gravity of the key center and know intuitively how far you are from the tonic at any given moment.
You seem unsatisfied by this, and I don't blame you, so here's a thought experiment: Could we come up with a solfege system that acknowledges both the global key center and local harmonic shifts? To do this, we'd probably need multiple names for each scale degree. E.g. do could be called do when it appears over the tonic, but (let's say) sa when it appears over a IV chord (as the fifth degree thereof). That way, even if you were just singing the melody in isolation, you could encode information about the background harmony.
In practice, such a detailed system isn't necessary; once you've practiced the song a few times with an accompanist, you'll easily remember which dos went with I chords and which ones went with IV chords and so on. But playing around with this sort of augmented solfege might give you some insight into why musicians have settled on the dual system of seven-syllable solfege and separate harmonic analysis.
Comment: "Could we come up with a solfege system that acknowledges both the global key center and local harmonic shifts?" this is exactly how it worked in past systems https://books.google.com/books?id=yyJnDAAAQBAJ&pg=PA36
Comment: Awesome, that is exactly what was in my mind. There could be a Do, Re, ... for notes over I; Do', Re', ... for notes over ii; Do'', Re'', ... for notes over iii, ... which is insane. So, it seems that our system throws away some information, but its idea is to privilege the relation to the parent key.
Comment: @MichaelCurtis Thanks for the reference, it was already on my list of books to read for some time.
Comment: The part about solfege and hexachords was probably the hardest part to read - for me - because the ideas were new to me. But, IMO, it's one of the most important parts of the book!
Answer:
...Some degrees are more stable than others (1, 3 and 5; 1 being the most stable) and some degrees are more unstable (2, 4, 6 and 7; 7 being the most unstable).

The unstable tones are called tendency tones.

...How does that [solfege/tendency tones] work if there is an underlying harmony?

I think the way to think about this is: solfege/tendency tones and functional harmony are just "two sides of the same coin." Solfege tones don't happen over a harmonic background, the solfege tones are the harmony! I don't mean to be glib. We don't fit solfege to pre-existing functional harmony. It's the other way around. When tones move according to characteristic patterns of solfege/tendency then functional chord identities emerge.
The easiest way to think about it is to consider the tendency tones ^2, ^4, and ^7. Together they make a viio6 chord which has a strong resolution to the tonic chord.
The next question that comes up is: "how to consider the dominant tone ^5?" The dominant can be a chord tone in both the tonic I and the dominant seventh V7. The V7 chord has a strong resolution to the tonic I. This seems to case ^5 in an ambiguous role of both stable and unstable. Let's try to clarify this.
Tonic ^1 and dominant ^5 are both stable degrees. The are the pillars of stability in tonal music! When a plain triad is built on ^5 the V is a stable chord! This stability can be clearly head in the half cadence. The leading tone ^7 is in the V chord so it does resolve to I but V should be considered stable as the music can cadence on it.
When the seventh is added to V to make V7 the chord becomes unstable. FA has the tendency to move to MI and that is the source of the unstability. My understanding (mostly from William Caplin's writing) is that the unstable V7 would not be the goal of a half cadence.
So, the level stability of dominant harmony is the interplay of stability from ^5 and the instability of ^2, ^7, and ^4. Especially important is which tone is the bass! While V is stable, V6 is not.
A similar interplay of tone stability happens with the IV chord and I. Obviously the ^1 degree in both chords is stable, but the ^6 and ^4 in the IV chord are unstable and resolve down to ^5 and ^3 respectively. It is interesting to examine bass tones and inversions with these chords. With IV64 to I the inverted subdominant is obviously the unstable chord. With that specific voice leading we clearly hear LA and FA resolve down to SOL and MI respectively. But, what if we use difference inversions and voice leading? With I6 to IV the tonic chord is unstable and IV becomes relatively stable. This movement can be interpreted as a tonicization of IV in which case the movement of MI to FA becomes TI to DO.
However, if we don't have a tonicization and instead it's a move to a half cadence with I6 IV V we get to another important concept: tendency tones do not always move according to tendency! Again, the harmonic context is critical. In this half cadence progression FA is the stable root of IV. Compare this to another harmonic context: V42 to I6 where FA is in the bass, but as a chord tone it is the dissonant seventh of the dominant chord.
The examples above may be confusing, because the context keeps changing: tonicization changes the tonic, inversion makes stable chords unstable. But that gives us the background information for a generalization: tendency tones exhibit their tendencies when they are used in dominant harmony. In other words V7 to I is where we see tendency tones in action.
This leave LA as the tone with probably the least tendency, or perhaps the most ambiguity. LA's tendency to move to SOL is best understood by IV64 to I a contrapuntal movement to resolve the unstable 64 chord, or in cases like ii6 to V and IV6 to V the move LA to SOL is about doubling the V root instead of the chord 3rd/leading tone. The falling thirds sequence is a case where LA doesn't follow the tendency to SOL - I V6 vi iii6 - in this case LA moves to FA notice how that non-tendency movement doesn't involve V nor I.

tendency tones are most clearly observed in dominant harmony
tonicization redefines solfege members and effects tendency
chord inversion and counterpoint effect tendency
tendency tones do not always move according to the baic definition
Comment: Nice discussion and examples. So, it seems that you did a job similar to what I had in mind, but there is importance just on the V degree. Solfège notes are heard just over I and V, and the tendency comes just from considering these 2 chords! I just can't see how V can be considered stable under any definition. It can be present in the half-cadence, but this cadence is itself unstable.
Comment: There is a variable degree of stability with cadences: like an imperfect cadence V to I6, the tonic is inverted and therefore unstable. A half cadence would be stable in the sense that it's a root position V, and SOL as the root of that stable triad is surely a stable tone - notice that SOL _doesn't move in the resolution to tonic I_ - but the chord is relatively unstable due to the presence of the leading tone.
Comment: After re-reading... the importance is not about V being a stable chord, but about SOL being a stable tone. V is surely unstable to the degree the leading tone moves to the tonic. But, again, notice that SOL doesn't move in resolving V to I.
Answer: Not exactly sure where you're coming from - as differing intervals will mean different things to different listeners. You mention 1,3,5 as stable. But when you're in C, but  on F, the C note is a 5, so could be construed as stable, it now being a 5. Just like your B example over an Em - another 5. The concept seems a little confused with these examples.
And, the stable/unstable is questionable - 1, 4 and 5 could easily be seen as very stable, as it's the staple diet of most sequences - take any '3 chord trick' and there's 1,4 and 5.
Comment: Yes, that's my point. So, you would say that we should get used to hear "5" played over a C, over a Dm, over an Em, ... ? (By the way, I added some links in a comment in the original post)
Comment: Ok, some clarification: in my first paragraph, I mean the idea of memorizing the 12 intervals (ascending and descending) and sometimes even associating some song with each interval. When I write numbers, I mean the scale degree in relation to the tonic, which is the idea of solfege (So, in C major, 5 will always be "G").
Comment: I understand, but have the feeling that some will feel that G in a C chord may take on a different mantle when it's in a G chord, if that makes sense.
Comment: I think that's the way to go, as the harmony will keep changing during a piece, and while we may recognise a B in Em as the 5th, it becomes a maj7 in Cmaj7, which effectively gives it a different job, even though it's the same note - but it can't be called a 5th anywhere else except in an E something.
Comment: So, you would disagree with the practice and teaching of solfege as aural skill? Because calling 5 everywhere is the definition of solfege (..., 3 = mi, 4 = fa, 5 = sol, ...). A "sol" is a "sol" over any chord.
Comment: After many years of not using solfege, I'm in a position where solfege (fixed doh) is in regular use. I find it quite foreign (it would be!) but it certainly works for those around me who are steeped in it. It doesn't help me, but if I'd used it for many years, it would probably be easy. movable doh makes far more sense, but I still prefer numbers. Transferable to NNS gives it more meaning.
Answer: I'd still recommend hearing everything in relation to the tonic. Movable-do solfege and Roman numeral notation are analogous in that regard.
As an extreme example, secondary dominants like #4 and borrowed notes like b6 should stay that way to denote how foreign they are in the context of the greater tonic (yet we're able to get away with using them at all because of the underlying harmony).
Only switch solfege note labels once you modulate and switch tonics.
Comment: It does, but according to what I've read, solfege generally isn't fine-grained enough to pick up on the contrast in roles that "1 = do" has between implied I and implied vi (for example). For an exercise in getting used to that lack of devotion, try notating Schubert's "Die Forelle" in movable do solfege.
Comment: That makes sense, but don't you think that the feeling of the "1 = do", for example, changes over each chord of a progression like: I-III7-vi-IV-ii-V7-iv-I ? For every chord, the feeling of "do" is a little bit different from the one acquired when practicing while singing alone without varied backgrounds in aural skills classes.
Answer: I was taught that solfege meant that the symbols are always the same in any key, and therefore there is no distinction between whether underlying harmony is present or not. In C, Re is always D, and solfege doesn't show how the notes wish to resolve, even if that D feels stable over a Dm chord. In a more classical analysis, yes, certain scale degrees do tend to resolve in certain directions, but these are separate ideas from solfege, as solfege doesn't reflect resolution patterns by itself.
Comment: This is not true. Tendency and resolution are a critical part of solfege. FA to MI and TI to DO - the half step movements - are critical in the history of counterpoint and harmony. https://books.google.com/books?id=yyJnDAAAQBAJ&pg=PA34
Comment: @MichaelCurtis Very true. My argument is that those resolution tendencies are unrelated to the actual syllables used to describe, say, Fa and Mi.
Comment: I think that meaning might not be clear from your wording
Answer: you should be able to do both. Hear what the intervals are over each chord, and also in relation to the main key of the song.
Answer: If your question is "How does that work if there is an underlying harmony?", we could say that note perception in general depends on underlying harmony. Chord under note (real or under-heard, suggested) and tone under-heard decide the perception.
Let's take the C prelude by Bach (we can see it as a monodic music — in a cathedrale with reverberation).
in: C E G C E, C is very stable, 1 is 1
then in: C D A D F, C isn't so stable.
Even more when you know this piece. Perception changes when you know the piece, when you know where go the notes.
When you don't know the piece, you can hear a pedal. C is not very stable, on this II, but stable anyway (due to the "pedal" function maybe).
But when you know this piece well, I feel this C very instable here, it can be heard as a "sus 4" of the dominant. It desires to "resolve" on the B of the G7 after.
1 is not 1 anymore. Not 7th (of the II). But 4th of the V.
1, 2, 3 etc. is just a conventional way to talk about notes outside a particular tone. But that's not decide the functions nor the stability of the notes nor how we hear them. Chord does. Harmony (heard or suggested) does. Concerning perception, we change it every time we change chord.
Comment: Yes, it can be a good practice. More over, I recommend to listen carefully at every note of each chord. It's not so easy to hear the notes. And maybe you could use harmonic progressions more interesting than I ii iii, IV etc.
Comment: Thanks. So, would you recommend the practice of solfège over every set of chords? For example, sing the major scale over the I chord, but also, ii, iii, IV, etc... ?


Summing columns for each value in a different table

Question:
Given tables A and B as shown below:
Table A       Table B
┌────┬───┐    ┌────┬─────┬───────┐
│ id │ c │    │ id │ Aid │ value │
┝━━━━┿━━━┥    ┝━━━━┿━━━━━┿━━━━━━━┥
│  1 │ 1 │    │  1 │  1  │    50 │
├────┼───┤    ├────┼─────┼───────┤
│  2 │ 0 │    │  2 │  1  │    20 │
├────┼───┤    ├────┼─────┼───────┤
│  3 │ 1 │    │  3 │  2  │    75 │
└────┴───┘    ├────┼─────┼───────┤
              │  4 │  3  │    23 │
              ├────┼─────┼───────┤
              │  5 │  3  │    17 │
              └────┴─────┴───────┘

How does one get the sum of the column B.value for each value of A.id that meets the condition c=1?
That is, the following:
┌────┬───────┐
│ id │ value │
┝━━━━┿━━━━━━━┥
│  1 │    70 │
├────┼───────┤
│  3 │    40 │
└────┴───────┘

I've tried doing
SELECT A.id as id, SUM(B.value) as value
  FROM A INNER JOIN B ON B.Aid = A.id
  WHERE c = 1

but that just returns the following:
┌────┬───────┐
│ id │ value │
┝━━━━┿━━━━━━━┥
│  3 │   110 │
└────┴───────┘

Comment: You forgot `GROUP BY`.
Answer: I think you need a group by:
SELECT A.id as id, SUM(B.value) as value
FROM A INNER JOIN
     B
     on B.Aid = A.id
WHERE c = 1
GROUP BY A.id;


Strange error using JPA on OpenShift

Question: I got an error I am worrying about for days already - also because it is hard to test whether it still occurs or not.
From an Java EE application hosted at OpenShift I am connecting to a MySQL cartridge. I am using JPA (Hibernate) to handle my connection and for ORM purposes.
The connection and the application itself is working fine - but when trying to access the database after some hours (I guess after OpenShift "hibernated" the servlet) it doesn't work anymore.
I get the following exception (that is just an excerpt, but it seems to me to be the most important part):
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: No operations allowed after connection closed.
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:377)
at com.mysql.jdbc.Util.getInstance(Util.java:360)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:956)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:935)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:924)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:870)

Of course I know what the exception is trying to the me - I just do not know why it is thrown...
My database access class looks the following:
public class JPAUtils implements ServletContextListener {
    private static final Logger log = LoggerFactory.getLogger(JPAUtils.class);
    private static EntityManagerFactory emf;
    private static EntityManager em;

    public static EntityManagerFactory getEntityManagerFactoryInstance() {
        if (emf == null || !emf.isOpen()) {
            String environment = "test";

            if (System.getenv("OPENSHIFT_MYSQL_DB_URL") != null) {
                environment = "production";
            }

            emf = Persistence.createEntityManagerFactory(environment);
        }

         return emf;
    }

    public static EntityManager getEntityManagerInstance() {
        if (em == null || !em.isOpen()) {
            em = getEntityManagerFactoryInstance().createEntityManager();
        }

        return em;
    }

    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        log.debug("Context initialized!");
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        try {
            log.debug("Closing JPA connection...");
            em.close();
            emf.close();
            em = null;
            emf = null;

            log.debug("Closed JPA connection!");
        }
        catch (Exception e) {
            log.error("Error occurred during closing of JPA connection!", e);
        }
    }
}

persistence.xml:
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
   http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
             version="1.0">
    <persistence-unit name="test">
        <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>

        <properties>
            <property name="hibernate.archive.autodetection" value="class, hbm" />
            <property name="hibernate.show_sql" value="false" />
            <property name="hibernate.format_sql" value="true" />
            <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" />

            <property name="hibernate.connection.url" value="jdbc:mysql://localhost/<db_name>?autoReconnect=true" />
            <property name="hibernate.connection.username" value="***" />
            <property name="hibernate.connection.password" value="***" />

            <property name="hibernate.hbm2ddl.auto" value="update" />

            <property name="hibernate.c3p0.min_size" value="5" />
            <property name="hibernate.c3p0.max_size" value="10" />
            <property name="hibernate.c3p0.timeout" value="300" />
            <property name="hibernate.c3p0.max_statements" value="50" />
            <property name="hibernate.c3p0.idle_test_period" value="300" />
            <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect" />
        </properties>

    </persistence-unit>
    <persistence-unit name="production">

        <non-jta-data-source>java:comp/env/jdbc/MySQLDS</non-jta-data-source>
        <properties>

            <property name="hibernate.hbm2ddl.auto" value="update" />
            <property name="hibernate.show_sql" value="false" />

        </properties>
    </persistence-unit>
</persistence>

I already looked up many examples and tutorials - but I cannot find the problem.
Thanks in advance!
Answer: Keeping around references to EntityManager instances is never a good practice, the static variable em in your case is keeping a stall object after the connection is closed.
Best practices advice to scope EntityManagers to the current transaction.
Comment: Yes, I think it should, if the connection is closed for any reason (passivation, etc.) the EntityManager you keep in the static variable continues to use it, and it is closed. That's the origin of the error I think.
Comment: Ok, good point.
But that probably won't fix it, at least if I got your advice right....
Comment: Ok, so after exhausting testing it seems to work this way - thank you!
So it seems (this is also what the error message said) that entityManager has been closed - I just expected em.isOpen() to return false in case the connections gets closed... Ok, that might be because of setting em = null and there might be a limit for active entityManger instances....

Strange error using JPA on OpenShift


Android - How does uiThread block executes?

Question: doAsync {
    doSomethingAsync()
    uiThread {
        doSomethingUiThread()
    }
}

Based on the code above. I understand that doAsync creates a thread and executes the code inside its block in that new thread. Also, that uiThread executes its block code in the main UI thread. But how does the code execute in a thread that already exists? I mean the UI thread is already executing code (e.g. receiving input events, creating new activities, etc.), so how is the code executed? It just stops all other UI thread code, execute itself and then return to the other code? Or something like that? Please enlighten me.
Answer: I heard that RunOnUiThread method posts a runnable( the {} block in kotlin)  to the handler of the UI thread. Then the UI thread will execute the runnable.run() method when it is not busy. As you know there must be a time when the UI thread us not busy, because it will cause the system to show ANR(applicafion not responding) message if not (And even it throwsExceptions when the UI thread tries to run time-consuming(lagging) jobs like networking :)).
**edit **
Here's a java code that shows you how runOnUiThread works.
Cited from this blog (Korean)
@Override
public final void runOnUiThread(Runnable action)
{
    if (Thread.currentThread() !=mUiThread)
    {
        mHandler.post(action);
    }
    else
    {
        action.run();
    }
}

P.S. I am not an export in kotlin, but I hope my answer helped you.
Comment: So it just executes as soon as possible.
Answer: It posts a message to the looper on the ui thread, passing it a Runnable with the code in your runOnUiThread block


Username converted to us-ascii (unix-style)

Question: I want to convert unicode characters in user names to us-ascii. I.e my first name is Søren and my last name is Sjøstrøm. It should be converted to soren.sjostrom (unix style) as the user name. How do I do that?
Answer: If you only want to transliterate non-ASCII European characters (like those used in Nordic, German and French names), you can use the PHP function strtr. E.g:
<code>$name = strtr($name,
   'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ',
   'AAAAAAACEEEEIIIIDNOOOOOOUUUUYTsaaaaaaaceeeeiiiidnoooooouuuuyty');
</code>
If you want to do romanization of a wider range of non-ASCII alphabets (cyrillic, greek, etc.) take a look at the contributed project Transliteration.
While this is specifically to transliterate file names to US-ASCII, at its core is UTF-8 normalization (based on UtfNormal.php from MediaWiki) and transliteration (based upon Sean M. Burke's Text::Unidecode).  You should be able to use the same libraries for romanization of names and other strings.
Comment: Thx, I will look into it :)


Entity Framework does not map columns that are defined as Decimal

Question: I have a hard time understanding why Entity Framework skips columns that are defined as decimal. I've tried deleting the model a couple of times and adding it back using the database first approach but for some reason a few columns are not mapped.
The ones that are defined as Date, Int or Text have absolutely no problem. The ones that are giving me a hard time are the decimal ones and I have defined them as such:

Name: Hours, Datatype: Decimal, Length/Set: 10,2, Unsigned: Checked, Allow Null: Unckecked, Zerofill: Unchecked, Default value: 0.00.

If I create a view with sums based on that same table, EF has no problem identifying the decimal columns. How can I add the missing columns to my model? What am I doing wrong and is there a workaround?
Thank you
Comment: if you tried to go to reference on your model, does it include the property?
Comment: Thank your the prompt reply Jeric. The property is not included. It's like the columns are not even in that table.
Comment: what version of EF are you using?
Comment: Version 126.96.36.199
Comment: Why can't you add them manually yourself? Also, what database are you using? I reckon you are generating the model from the database using VS, right?
Comment: Ricardo, I already tried that and I got an error, something about not being mapped. You are right. I finally found a solution.
Answer: After spending hours on this I finally figured it out. If you are facing the same problem make sure that your column are not UNSIGNED.
For some reason Entity Framework does not map decimal columns that are unsigned. Just uncheck that option and you should be good.


Is there any use for the quantity $\int f(x)^2 dx$ in statistics or information theory?

Question: Is there any use for the quantity
$$
\int f(x)^2 dx
$$
in statistics or information theory? $f$ is a probability density.
Comment: **[Renyi entropy](http://www.google.com/search?q=Renyi+entropy)**
Comment: $f$ is a pdf, right?
Comment: Yes, $f$ is a density.
Comment: @cardinal Answer!
Comment: @mbq: Ok, I'll try to type something up a bit later that is worthy of an answer. :)
Comment: @mbq: I've submitted an answer, though, unfortunately it's suboptimal. :)
Answer: Letting $f$ denote a probability density function (either with respect to Lebesgue or counting measure, respectively), the quantity $\newcommand{\rd}{\mathrm{d}}$
$$
H_\alpha(f) = -\frac{1}{\alpha-1} \log(\textstyle\int f^\alpha \rd \mu)
$$
is known as the Renyi entropy of order $\alpha \geq 0$. It is a generalization of Shannon entropy that retains many of the same properties. For the case $\alpha = 1$, we interpret $H_1(f)$ as $\lim_{\alpha \to 1} H_{\alpha}(f)$, and this corresponds to the standard Shannon entropy $H(f)$.
Renyi introduced this in his paper

A. Renyi, On measures of information and entropy, Proc. 4th Berkeley Symp. on Math., Stat. and Prob. (1960), pp. 547–561.

which is well worth reading, not only for the ideas but for the exemplary exposition style.
The case $\alpha = 2$ is one of the more common choices for $\alpha$ and this special case is (also) often referred to as the Renyi entropy. Here we see that
$$\newcommand{\e}{\mathbb{E}}
H_2(f) = - \log( \textstyle\int f^2 \rd \mu ) = -\log( \e f(X) )
$$
for a random variable distributed with density $f$.
Note that $- \log(x)$ is a convex function and so, by Jensen's inequality we have
$$
H_2(f) = -\log( \e f(X) ) \leq \e( -\log f(X) ) = - \e \log f(X) = H(f)
$$
where the right-hand side denotes the Shannon entropy. Hence the Renyi entropy provides a lower bound for the Shannon entropy and, in many cases, is easier to calculate.
Another natural instance in which the Renyi entropy arises is when considering a discrete random variable $X$ and an independent copy $X^\star$. In some scenarios we want to know the probability that $X = X^\star$, which by an elementary calculation is
$$\renewcommand{\Pr}{\mathbb{P}}
\Pr(X = X^\star) = \sum_{i=1}^\infty \Pr(X = x_i, X^\star = x_i) = \sum_{i=1}^\infty \Pr(X = x_i) \Pr(X^\star = x_i) = e^{-H_2(f)} .
$$
Here $f$ denotes the density with respect to counting measure on the set of values $\Omega = \{x_i: i \in \mathbb{N}\}$.
The (general) Renyi entropy is also apparently related to free energy of a system in thermal equilibrium, though I'm not personally up on that. A (very) recent paper on the subject is

J. C. Baez, Renyi entropy and free energy, arXiv [quant-ph] 1101.2098 (Feb. 2011).
Comment: I was indeed using the Renyi entropy as a substitute for the Shannon entropy; it is nice to see confirmation of my intuition.  Thank you for the enlightening response.
Comment: Many (but not all!) of the properties and usefulness of Shannon entropy arise from its convexity. If you look at the build up of the basics results in information theory, they more or less hinge on Jensen's inequality. So, in a certain (vague) sense, there is not too much that is (terribly) special about $-\log x$ as the particular nonlinearity that leads to a notion of "information".
Comment: I see.  Specifically, I need the property that the maximum entropy joint distribution which satisfies given marginals is the product of the marginals (what you would get from independence.)