Problemas com NaN

Question: Alguém pode me ajudar com este site. A parte frontal exibe os preços só que logo abaixo exibe novamente com NaN. Quando entra em qualquer produto, o NaN desaparece. Alguma dica de como posso resolver isso?
Algum truque para "ocultar" o NaN na tela frontal seria interessante.
O site: https://jsfiddle.net/brunoarchanjo88/
Comment: Já tem um "3x sem juros" mostrando acima. Onde tem o NaN seria o mesmo valor?
Comment: Sim, tem dois "sem juros" na tela frontal, sendo um normal e o outro com "NaN". Quero eliminar esse com o "NaN" mas não consigo de jeito nenhum! Esse que está com o NaN é o mesmo que esta dentro de cada produto. Ou seja, ele imprime certo lá dentro e lá fora ele imprime errado
Comment: Veja a resposta que postei.
Answer: Substitua o código deste bloco:
<code>   // Imprime os preços internos
// Aqui é para limpar os excessos do setInterval
    var counter = 0
    var timer = setInterval(function(){
        if($(".ecwid-productBrowser-details").is(":visible")){
            mostra = "";
        }else{
            mostra = "display: none;";
        }
    if(counter >= 0){
      $("h5").remove()
    }
    counter++
// Aqui pega as classes para serem tratadas
        var demo = $('div.ecwid-productBrowser-price');
            demo.each(function() {
            var valor = parseInt(this.innerHTML.replace(/\./g, '').replace(',','.').substr(2) / 3, 10).toFixed(2).replace('.',',')
                $(this).after("<h5 class='demo' style='"+mostra+"color: #e9d0ba;font-size:15px;'>3x de " +valor+ " sem juros </h5>")
        })
        }, 1000)
</code>
Fiddle
Comment: @BamDeveloper Resposta atualizada.
Comment: @BamDeveloper Veja agora.
Comment: Agora sim. Funcionou perfeitamente!
Comment: Já havia feito isso, funciona, só que daí quando entro nos produtos da loja, some a frase "3x sem juros" de lá de dentro! Tem que ter a frase lá dentro e lá fora
Comment: Entendi. Vou editar a resposta.
Comment: @BamDeveloper Legal!

Problemas com NaN


Fail safe SSH tunnel Ubuntu (always up)

Question: I need your advise for a very important technical issue on our project. We need to have a SSH tunnel always up between our two servers. We have a MySQL database replication process going between those two servers.
We want two things:

When the connection is lost it automatically reconnect without our
external help
When the computer restart the connection go
automatically online

We are running under Ubuntu.
For the moment I have to manually check if the tunnel is still active. We use SSH Tunnel Manager to start the tunnel. Previously, we were using this command : ssh root@MY_SERVER.com -L 8806:localhost:3406.
Do you know a script or a software that may help us on that case? On another Windows machine we use Bitvise that can satisfy those criteria. Normally, I found Linux easier to adapt for those kind of things, but I kind of out of options this time.
Answer: The autossh utility may do what you want

autossh is a program to start a copy of ssh and monitor it, restarting it as necessary should it die or stop passing traffic.

You should really do the job correctly and create a VPN between the two systems using openvpn (or similar).
Comment: I added this command in our crontab to solve the problem: `@reboot autossh root@MY_SERVER.com -L 8806:localhost:3406`. Thanks!

Fail safe SSH tunnel Ubuntu (always up)


Confusion in understanding continuous function

Question: Okay so I've started to study derivatives and there is this idea of continuity. The book says "a real valued function is considered continuous at a point iff the graph of a function has no break at the point of consideration, which is so iff the values of the function at the neighbouring points are close enough to the value of the the function at the given point"
So what I dont understand is that why is it that values of the function at the neighbouring points should be close enough to the value of the function at the given point, isn't it enough if they are defined why do they have to be close enough the value of the function at the given point?
Comment: $f(x)=-1$ for $x\leq0$ and $f(x)=1$ for $x>0$ is discontinuous.
Comment: Otherwise there is a break.
Comment: @MadDawg. The example from Maja shows that it is *not* enough that the function is defined for every $x$, which was your question: "isn't it enough if they are defined".
Comment: @MadDawg "isn't it enough if they are defined" my example shows it isn't enough.
If values for "close point" aren't close enough it means there's a discontinuity.
Comment: @MajaBlumenstein yeha it is discontinuous but i dont understand how it answers my question
Comment: @YvesDaoust how?
Comment: The definition is meant to be simple to make the concept acceptable. The term "neighboring point" is not very well defined, which point to consider neighboring? A stronger definition would tell you no matter how close a point to the other f(x) would still have a finite value.
Answer: Intuitively, the idea is that the closer and closer you get to $x$, the closer and closer $y$ gets to $f(x)$. A small neighborhood of $x$ must correspond to a small neighborhood of $f(x)$.
When there is a discontinuity, the image of a neighborhood of $x$ always includes that discontinuity and that blocks it from being as small as you want.
Answer: Continuity isn't a property of a point of the graph, but a property of neighborhoods of points of the graph. You need information about a neighborhood of a point to say anything about continuity at that point.
When we say continuous at a point we are really saying something about neighborhoods of that point.
Answer: I hope your textbook also provides a more formal definition of continuity at a point:
$f(x)$ is continuous at a point $a$ if and only if all three of the following hold---
(1) $f(a)$ is defined.
(2) $\lim_{x \to a} = L$ exists. (Keep in mind this is a 2-sided limit.)
(3) $f(a) = L$
If any one of the above three fail to hold, then $f(x)$ is not continuous at $a$.
``No break'' in the graph of the function at $a$ is but a consequence of the above definition.
Comment: But why do the value of the function at the neighbouring poins should be close enough to the value of the function at the given point?
Comment: Because of the formal (i.e.) $\delta-\epsilon$ definition of limit. That must be understood first in order for the concept of continuity to make sense.
Answer: If the values of the function in points $x$ close enough to a specific point $x_0$ are not arbitrarily close to $f(x_0)$ the graph will be (usually) broken.
This definition is not completely rigorous, as it assumes we have intuitive understanding what a "graph with no break is", and it can create some misunderstandings. For example, it can be proven that the graph of function $$ f(x) = \left\{\begin{array}{l} \sin\frac{1}{x} & \text{for }x\neq 0 \\ 0 &\text{for }x=0 \end{array}\right. $$
is connected, but the function is still non-continuous.
It's better to consider "iff the values of the function at the neighbouring points are close enough to the value of the the function at the given point" as the definition, or, rigorously speaking

Function $F : X \rightarrow Y$ is called continuous at point $x_0\in X$, iff $$ \forall \epsilon>0 \exists \delta>0 \forall x\in X: \Big((|x-x_0|<\delta) \Rightarrow \big(|f(x)-f(x_0)|< \epsilon\big)\Big)$$

which means: "For arbitrary distance $\epsilon$ I can choose a neighbourhood of $x_0$ small enough for the values of function to be within distance of $\epsilon$ from the value of function at point $x_0$".
Comment: Ok, I understand the downvote, there was a typo. Corrected.


Examples of hyperbolic sets of dynamical systems

Question: I am studying the definition of hyperbolic set: a compact invariant set $\Lambda$ of a diffeomorphism $f$ such that the tangent space in each point of the set $\Lambda$ can be split in two invariant directions (stable and unstable).
However, I am having some trouble trying to figure out examples of such hyperbolic sets.
Answer: Here are some standard examples:

Hyperbolic fixed points of a diffeomorphism: Let $f:M\to M$ be a $C^1$ diffeomorphism of a $C^\infty$ manifold and $x\in M$ be such that $f(x)=x$. Then the derivative $T_xf:T_xM\to T_xM$ is an invertible operator acting on the tangent space at $x$. $\Lambda=\{x\}$ is $f$-hyperbolic if $T_xf$ has no eigenvalues of modulus $1$.

In particular, if $X$ is a Banach space and $T:X\to X$ is a hyperbolic invertible operator, then $\Lambda=\{0\}$ is a $T$-hyperbolic set (see Space of linear, continuous, hyperbolic functions is open, dense in the set of invertible functions).

Hyperbolic periodic points of a diffeomorphism: Let $f:M\to M$ be a $C^1$ diffeomorphism of a $C^\infty$ manifold and $x\in M$ be such that $f^p(x)=x$ for some $p\in\mathbb{Z}_{>0}$. Then the derivative $T_xf^p:T_xM\to T_xM$ is an invertible operator acting on the tangent space at $x$. $\Lambda=\{x\}$ is $f$-hyperbolic if $T_xf^p$ has no eigenvalues of modulus $1$.

State space of an Anosov diffeomorphism: Let $f:M\to M$ be a $C^1$ diffeomorphism of a compact $C^\infty$ manifold. $f$ is Anosov iff $\Lambda=M$ is $f$-hyperbolic.

In particular, if $A$ is a $d\times d$ invertible matrix with integer entries whose inverse also is with integer entries, then it defines an diffeomorphism of the torus $\mathbb{T}^d$. If $A$ has no eigenvalues of modulus $1$, then ($A$ is Anosov and) $\Lambda$is $A$-hyperbolic (see my answer in Examples of conjugate-like structures across mathematics, or Lyapunov exponent for 2D map?, or A question on hyperbolic toral automorphism, or What's so hyperbolic about hyperbolic sets?).

There is a diffeomorphism $f$ of a two dimensional closed disk, called Smale's horseshoe map, that has a Cantor set $\Lambda$ as a (compact invariant) hyperbolic set. (see How does Smale's horseshoe map work? or What's the point of a Horseshoe map?).

The Smale-Williams solenoid $\Lambda$ can be obtained as the attractor of a diffeomorphism of a solid torus. This diffeomorphism stretches and makes thinner the donut; see p.2-5 of Milnor's notes available at https://www.math.stonybrook.edu/~jack/DYNOTES/dn2.pdf. $\Lambda$ is a hyperbolic set for this particular diffeomorphism, and along the direction the diffeomorphism makes the donut thinner it looks like a Cantor set. (Also see Solenoid is hyperbolic set)


Partner Authentication Failed

Question: Does the Developer's Integrator Key expire after a certain period of time? And if so, is there a way to reset it without going through registration again? I am testing some rest calls and the response I received was:

"errorCode": "PARTNER AUTHENTICATION FAILED" "message": "The specified
  integrator key was not found or disabled. An integrator key was not
  specified."
Answer: Integrator Keys do not expire.  There must be something else going on.  You should figure out what web service call is being made and with what key.  Also you might have gotten a key from our developer's sandbox and started pointing to production in which case the key is not enabled there.
Comment: Correct. There was a CR in there that was causing the problem
Comment: Correct meaning that's the answer? :)

Partner Authentication Failed


Assigning state to a nested array with ReactJS

Question: I am currently trying to assign state to a nested object using the hook setState() but I'm struggling a little bit with figuring out the syntax and how exactly I am supposed to do it.
I have structured my component like this:
const MainCard = props =>{

       const passedState = props.location.state;

     return(

                    <AttendeeCard passedState={passedState} />

                    <AttendeeCard passedState={passedState} />

   )
}

export default withRouter(MainCard)

So the props received from location are the data that I'll be passing to the AttendeeCard component.
Here is the data I'm passing down the component.
I have structured my AttendeeCard component the following way:
  const AttendeeCard = props =>{

            const students= props.passedState.students;
            const [isChecked, setIsChecked] = useState(false);

            const checkInStudent= () =>{
               setIsChecked(!isChecked);
            }

        return(
             students.map((student,i)=>{
                 return(

                              <input type="checkbox"
                                  onChange={checkInStudent}
                                  checked value={isChecked}/>

                  )
             })

     )
   }

So instead of using const [isChecked, setIsChecked] = useState(false); to assign one state to all checkboxes, I'd like to assign each checkedin state corresponding to the users.
I've tried  writing something like:
       students.map((student,i)=>{
             const [isChecked, setIsChecked] = useState(student.checkedin);

           return(

                              <input type="checkbox"
                                  onChange={checkInStudent}
                                  checked value={isChecked}/>

                  )
             })
       })

but I got an error and it didn't compile.
How can I assign state for each of the checkedin nested objects per student in my array?
UPDATE:
The error I get whenever I try the code above is:

React Hook "useState" cannot be called inside a callback. React Hooks
  must be called in a React function component or a custom React Hook
  function  react-hooks/rules-of-hooks
Answer: One of the rules of React hooks is don't call hooks inside loops. You can instead move your code into a new component and call the hook inside the component:
function StudentCard({ checkedIn }) {
  const [isChecked, setIsChecked] = useState(checkedIn);
  const checkInStudent = () => {
    setIsChecked(!isChecked);
  };

  return (

        <input
          type="checkbox"
          onChange={checkInStudent}
          checked
          value={isChecked}
        />

  );;
}

const AttendeeCard = props => {
  const students = props.passedState.students;

  return students.map((student, i) => {
    return (
      <StudentCard
        checkedIn={student.checkedin}
        key={i}
      />
    );
  });
};

Answer: I think you can make your code work by creating a new child component for the studentCard. So your code would be something like this :
const AttendeeCard = props =>{
    const students= props.passedState.students;

    return(
         students.map((student,i)=>{
             return(
                  <StudentCard student=student/>
              )
         })

 )

}
and StudentCard would be like this:
const StudentCard = props =>{
       const [isChecked, setIsChecked] = useState(props.student.checkedin);

       return(

                          <input type="checkbox"
                              onChange={checkInStudent}
                              checked value={isChecked}/>

              )
}

By this way every StudentCard has it internal state and you can change it every time you want.
I hope it solves your problem. If it works please vote me up:)


What is the longest additional time ever added in Europe's top five leagues?

Question: What is the longest additional time ever used in Europe's top five leagues? Please mention the details of the match.
Answer:
English Premier League

A match between Brentford and Wolverhampton on 22 January 2022 had at least 19 minutes of stoppage time at the end of the first half, after the match had to be temporarily halted due to a drone hovering over the pitch.

Referee Peter Bankes took both teams off the pitch just after the half-hour mark when the device was spotted above the Brentford Community Stadium.
[...]
When play did eventually resume, 19 minutes were added on at the end of the first half.

La Liga

Barcelona vs Espanyol 2008 match got extended for 13 minutes.

While not technically "injury time," the fireworks of the Catalan derby between Espanyol and Barcelona were extended for 13 minutes in 2008 after fans continued to disrupt play.

Ligue 1 (not sure whether this is longest or not)

Strasbourg vs PSG 02 Dec 2017 had nine minutes of stoppage time.

PSG had chances to win during nine minutes of stoppage time ...

Source

Pressure was intensely applied to the Strasbourg goal, with nine minutes of stoppage time giving them even greater hope of a leveller.

Source

Strasbourg defended relentlessly during nine minutes of stoppage time ...

Source

Bundesliga (not sure whether this is longest or not)

Cologne vs Hamburg 2017 had 13 minutes of added time. In this game Lewis Hotlby made history by scoring a Bundesliga goal in the 100th minute.

A bizarre Bundesliga match between Cologne and Hamburg saw two goals and a VAR review during over 13 minutes of added time

Source

The extremely late action came because of an injury to referee Felix Brych early in the second half, with the final whistle ultimately blown in the 114th minute.

Source

Other notable matches:

Brentford vs Bristol City in 2000-01 2

...there were about 23 minutes of stoppage time in the first-half alone after a broken leg, a dislocated shoulder (Bees striker Lloyd Owusu passed out from the pain and an ambulance had to be driven up to the pitch), and serious concussion caused the delay...

Western Sydney Wanderers vs Guangzhou Evergrande

Seventeen minutes did the board read, the longest added time in the Asian Champions league, the A-League and all recorded Asian premier leagues.

Mexico vs Panama Gold Cup

Geiger then awarded an 89th-minute penalty when Torres fell on the ball after an attempted clearance to plunge the game into extra time and spark a 10-minute stoppage marred by flying beverages and scuffles on the field.

Source

The match was delayed for more than 10 minutes before order was restored.

Source

Note: Haven't found any resources for Serie A, not sure the one I mentioned for Ligue 1, Bundesliga is the longest or not. Question mentions injury/stoppage time. Thanks to dly for information on Bundesliga.
Comment: It's not worth an answer of its own, but in the Bundesliga it was (probably) HSV - Cologne with [14 minutes](http://www.goal.com/en-tza/news/lewis-holtby-makes-history-with-100th-minute-goal-in-bizarre/ftj7bndw6bj1sbv3edfpcu0e) when the ref got injured and had to be replaced.
Comment: I'd like to suggest an addition to the "other notable matches" section: [an FA Cup first-round tie](https://www.bbc.co.uk/sport/live/football/54751462) between Torquay United and Crawley Town that featured at least 21 minutes of second-half stoppage time.


How to alter the owner/authored by field to the current user when using quick_node_clone

Question: Using Drupal 8 with quick_node_clone module.
When a node is cloned I need to change the 'owner' or 'authored by' value to the person who is cloning the node.
There is an opportunity of manually changing this but I need to automate this.
I am have been trying the hook_form_alter with some alternatives, see the commented out section, without success.
function quick_node_clone_form_alter(&$form, FormStateInterface $form_state, $form_id) {

 print_r($form_id);

 if ($form_id == 'quick_node_clone') {
  // change author
  //$form['author']['name']['#value'] = $user->uid;
  //$form->setOwnerId($current_user);
  //$form->uid = $user->uid;

  print_r($form['field_author']['nid']['nid']['#value']);
  global $user;
  $form['field_author']['nid']['nid']['#value'] == $user->uid;
 }
}

Any direction would be appreciated.
Comment: I think you need a presave hook rather than an alter hook...
Answer: Try this out:
use Drupal\Core\Entity\EntityInterface;
/**
 * Implements hook_entity_presave().
 */
function customModule_entity_presave(EntityInterface $entity) {
  $current_user_id = \Drupal::currentUser()->id();
  $entity->setOwnerId($current_user_id);
}

Edit
You would be better to check on your content type:
use Drupal\Core\Entity\EntityInterface;

/**
 * Implements hook_entity_presave().
 */
function customModule_entity_presave(EntityInterface $entity) {
  $current_user_id = \Drupal::currentUser()->id();
  if ($entity->bundle() == 'your_content_type_name'){
    $entity->setOwnerId($current_user_id);
  }
}

Comment: I appreciate the help but it doesn't seem to get the current_user_id into the Authoring Information Authored by field. And yes cache was cleared. Just to be clear for my understanding also. This is meant to trigger when the clone button is clicked. How does that trigger the _presave?
Comment: i tested it works, for me, you did dump the $current_user_id variable its correct ?
Comment: Maybe I am missing something @berramou and appreciate your help. Here is what I have done. 1) in mymodule.module file I added this to the top `use
\Drupal\Core\Entity\EntityInterface` 2) then added the code as you have it replacing customModule with mymodule. 3) Cleared cache and visited the admin/content page and from the edit Operations selected clone. 4) A cloned copy is created but the Author Information is still the original author. What am I missing? What did you mean by dump.
Comment: in this hook print the `$current_user_id`  just to see if the function executed and you get the right user id ? if you use devel you can use `dpm($current_user_id);`
Comment: i think the original other of the node you clone is the current user that's why you don't see the change.
Comment: again appreciate @berramou help. I don't believe that I am calling the right hook. I don't get any return for dpm($current_user_id); And since that is outdated I also tried kint($current_user_id); die(); but get nothing returned. I also tried a simple echo "can you see this"; to no avail. It does seem as though I am calling the wrong hook.
Comment: I would click clone and view the content the authored by in the admin/content path does not update with the currentUser so would go back and start again. BUT if you click save it does update. No wonder I couldn't see results and you could! Thanks that part does work.   But, it still is a bit confusing if the editors check the authored by field. First prize would be to update the 'preview' authored by field. Is there a hook for that?


Segundo botão substituindo conteúdo do primeiro

Question: Com esse código abaixo quando clico no botão mat ele me trás os dados em uma table. Gostaria que ao clicar no botão sp substitua o conteúdo da tabela por outro.
Código:
<button id="mat" class="button"></button>
<button id="sp"></button>

Comment: Qual erro apresenta?
Comment: Não apresenta erro, unica coisa que envés de substituir ele poe o conteúdo do outro botão embaixo do que já tem.
Comment: Nao entendi muito bem, ele ta criando outra tabela? Com qual id?
Comment: Ele faz em lugar separado porque você está dizendo pra fazer, se quer que ele substitua utilize a mesma tabela, agora se quer que ele alterne entre as tabelas, esconda uma e mostre a outra
Comment: Você só pode carregar 1 únivo evento `.html()` na sua página, para fazer isso mais de uma vez, tem que usar o evento `.delegate()`
Comment: @Kevin.F Você quer substituir o conteúdo de qual `table` quando clicar em `#sp`?
Comment: O conteúdo da table `matriz` pelo conteúdo da de `saopaulo`.
Comment: @Kevin.F desculpa a persistência mas é para ter certeza pegar o conteúdo da table `matriz` e passar para `table` `saopaulo`?
Comment: Não, tem 2 conteúdos o da table `matriz` quando clico nela cai o conteúdo dela, e quando clico na `sp` cai o conteúdo diferente que é a de `saopaulo` substituindo o da `matriz`. Vou editar la no código para ver melhor. Vê se deu para entender melhor, cada botão traz um conteúdo diferente só quero fazer o  da matriz sumir quando o de saopaulo apaerecer e vice e versa.
Answer: O constragimento está aqui.:
$("#matriz").html(retorno);

e

$("#saopaulo").html(retorno);

Está a inserir o conteudo em sitios diferentes o por isso de aparecer as duas tabelas.
Poderá colocar apenas 1 id ou então alterar para.:
$("#matriz").html(retorno);
$("#saopaulo").html('');

e

$("#saopaulo").html(retorno);
$("#matriz").html('');

Answer: Basta adicionar dentro da function do done no ajax antes de atribuir o retorno no método .html(...); adicionar a seguinte linha:
No ajax de do click sp:
$("#matriz").empty(); //remove todos os nós filhos da table

Mesma coisa no ajax do click mat:
$("#saopaulo").empty(); //remove todos os nós filhos da table

Comment: @Kevin.F vê se isto resolve?
Comment: Show de bola, era isso valeu.
Answer: Eu acredito que se você fizer desta maneira irá resolver o seu problema, eu não testei, mas se não funcionar, tente colocar o delegate para cada um dos eventClick:
$(function() {
   $("#matriz, #saopaulo").hide();
        function eventClick(elClick, elEvent, otherElement, url) {

         $(document).delegate(elClick, 'click', function() {
            if (!$(elEvent).is(":visible")) {
                $(elEvent).show();
            } else {
                $(elEvent).hide();
            }
              $.ajax({
                        url: url,
                        cache: false,
                        dataType: 'html'
                    })
                    .done(function(retorno) {
                        $(elEvent).html(retorno);
                        $(otherElement).html('');
                    })
                    .fail(function() {
                        alert("Algo está errado");
                    });
             });
       }
      eventClick('#matriz', '#mat', '#saopaulo', "../Conteudo/Matriz.html");
      eventClick('#saopaulo', '#sp', '#matriz',"../Conteudo/Matriz.html");
});

Comment: Não aconteceu nada nem um botão funcionou. E se eu quiser carregar outro conteúdo no botão `sp` que não seja o `Matriz.html` como faço ?
Comment: Pergunto: precisa fazer duas requisições ajax, ou pode ser uma só? Eu não vejo porque fazer duas? Além disso, é melhor trabalhar com dados em json, em vez de html.
Comment: Duas por que cada botão que clicar vira um conteúdo, tem como fazer com uma requisição isso ?
Comment: Olha, claro que tem... você teria que carregar todo o conteúdo, de ambas as tabelas não no click... mas direto no autoload do jquery... e no botão, vc coloca só para mostrar o conteúdo que vc quer mostrar.
Comment: O ideal é vc trabalhar os dados em JSON, e depois dar um loop na tabela... O processo é bem mais rápido.
Comment: Não sei mexer com JSON.
Comment: JSON é como array: `[{chave:valor1}, {chave:valor2}]`, no php seria: `$data['chave'] = array('valor1','valor2');`
Comment: Ok entendi, vou fazer um estudo em JSON.
Comment: [Aqui tem mais sobre esse assunto](http://www.json.org/).


what is actually the difference between prior and evidence?

Question: when saw bayes theorem prior and evidence,  it has similarity to joint probability (A n B). so is there really a clear difference between them???
Comment: It sounds like you are ready for some [Statistical Rethinking](https://www.youtube.com/playlist?list=PLDcUM9US4XdPz-KxHM4XHt7uUVGWWVSus).
Comment: i want direct answer.
Comment: The question in your title about what is the difference between prior and evidence is an interesting one. Unfortunately I am not a Bayesian, so perhaps not the person to answer that question for you. Bayes theorem, on the other hand, is a theorem about conditional probability and is well regarded in all schools of statistics.
Answer: Bayes theorem says: $P(A|B) = P(A) \times \frac{P(B|A)}{P(B)} = \frac{P(A, B)}{P(B)}$. In this, A is as you say your 'prior belief' and B is your 'evidence'. Bayes theorem thus updates your prior belief with new evidence.
So what does the term $P(A,B)$ mean? As the mathematics show you, it is the same as $P(A) \times P(B|A)$, which contains how strong your prior belief is and how strongly your prior belief supports the new evidence.
Short example: You want to go out for a walk and wonder if you should take an umbrella with you. Your prior belief is that it is going to rain 70% of the time (this is merely a guess that you base on your 'experience', which is subjective, priors can also be objective!). The new evidence (or likelihood) might be checking the forecast of today or looking at the weather for a few hours to see what happens. You now will update your prior belief using this new evidence using Bayes theorem.
So prior belief is what you used to know, evidence is what you gain or collect at the moment to update your prior beliefs.
Comment: i often see that bayes theorem is almost has same concept as confusion matrix which has precision and recall. can P(B) also identified as actual value  and P(A) is identified as predicted value?


Why android studio need to sync every change in gradle?

Question: I know my question is something like axioms, but why android-studio require sync for every change in the gradle even this change adding a space or comment.
As far as I know running the application will make that, Can someone explain why this behavior required in gradle?
Answer: Because gradle downloads libraries or removes according to your changes
Answer:
why android-studio require sync for every change in the gradle even this change adding a space or comment

It is difficult for the IDE to determine, automatically, what a syntactically-relevant change is to build.gradle, so it errs on the side of caution.

As far as I know running the application will make that

Yes, but you may want to see the impacts of the changes (e.g., new dependencies) before running the app.


Community detection and modularity

Question: I am reading the book "Network science" of Barabasi and in particular the chapter on community detection.
If I understand correctly, modularity is a goodness factor of partition  calculated by a certain algorithm: the greater the value of modularity and better is the structure of the communities found.
I tried several algorithms in R on the same network:
library(igraph)
library(GGally)
library(ggplot2)
library(ggdendro)

# load dataset
net <- read.graph("./ds.gml", format = c("gml"))

# find degree
deg <- igraph::degree(net, mode = "all")

###### GIRVAN & NEWMANN (divisive) ##################################################
girvNew <- cluster_edge_betweenness(net, modularity = TRUE)

girvNew_sizesComm <- sizes(girvNew)
girvNew_numComm <- length(girvNew_sizesComm)
girvNew_modularity <- modularity(girvNew)

print(girvNew_numComm)
print(girvNew_sizesComm)
print(girvNew_modularity)

girvNew_den <- as.dendrogram(girvNew)

###### GREEDY ################################################################
fastgreedy <- fastgreedy.community(net)

fastgreedy_sizesComm <- sizes(fastgreedy)
fastgreedy_numComm <- length(fastgreedy_sizesComm)
fastgreedy_modularity <- modularity(fastgreedy)

print(fastgreedy_numComm)
print(fastgreedy_sizesComm)
print(fastgreedy_modularity)

fastgreedy_den <- as.dendrogram(fastgreedy)

###### WALKTRAP ################################################################
walktrap <- cluster_walktrap(net)

walktrap_sizesComm <- sizes(walktrap)
walktrap_numComm <- length(walktrap_sizesComm)
walktrap_modularity <- modularity(walktrap)

print(walktrap_numComm)
print(walktrap_sizesComm)
print(walktrap_modularity)

walktrap_den <- as.dendrogram(walktrap)

###### LOUVAIN ################################################################
louvain <- cluster_louvain(graph = net, weights = NULL)

louvain_sizesComm <- sizes(louvain)
louvain_numComm <- length(louvain_sizesComm)
louvain_modularity <- modularity(louvain)

print(louvain_numComm)
print(louvain_sizesComm)
print(louvain_modularity)

The result I get are:

Looking at the table I would say that the algorithm of detection communties  more efficient is Louvain, then Girvan-Newmann, Wolktrap and Greedy.
Is this statement right?
The book says that the first algorithm (to Girvan-Newmann) calculates all partitions and doesn't choose the best one.
To do this you need to select the best cut of the dendrogram based on modularity.
Having said that, what means the value of modularity found (0.5380681)? But above all, how do I find the modularity for each step of algorithm?
What I would like to get is something similar to this chart:

That is, a chart that allows me to see the various modular values obtained and can then choose the best one.
This shows Modularity for each cut of the dendrogram.
Answer: Here are some answers to the multiple questions in your post (which I would avoid in the future- better answers will come with clear, individual questions).
Which algorithm is more efficient?
Perhaps I am misunderstanding what you mean by "efficiency", but I assume you mean computational efficiency. You can't know that from looking the table you provided- you need to check the CPU time, e.g., using system.time.
library(igraph)

# Random graph
net <- sample_gnm(100, 300, directed = F, loops = F)

# CPU time for modularity algorithms
system.time(cluster_edge_betweenness(net, modularity = TRUE))
#   user  system elapsed
#  0.160   0.001   0.159
system.time(fastgreedy.community(net))
#   user  system elapsed
#  0.002   0.000   0.004
system.time(cluster_walktrap(net))
#   user  system elapsed
#  0.002   0.000   0.003
system.time(cluster_louvain(graph = net, weights = NULL))
#   user  system elapsed
#  0.001   0.000   0.001

You can see that there are differences in the CPU time used by the four algorithms, and the Louvain method is the fastest.
What does the modularity value mean?
In general, you can think of modularity as the fraction of edges lying within modules minus the expected fraction of edges lying within modules if there is no modularity. But the single modularity value that is output from these algorithms is the value of Q for the optimal partition found by the algorithm. The higher this maximum modularity is, the better the partition is. Thus, based on the table you included, the Louvain method found the best partition.
To be clear, the igraph function you are using to find communities with the Girvan-Newman algorithm DOES return the optimal communities found using the algorithm- you don't need to select it yourself. Look at the ?help page for the cluster_edge_betweenness function you use, and see the description of the modularity argument:

Logical constant, whether to calculate the maximum modularity score, considering all possibly community structures along the edge-betweenness based edge removals.

So the modularity you get IS the maximum modularity, and the partition you can extract using the communities function will give you the maximum partition. You don't need to find it yourself.
How can you extract the modularity score for each step of the Girvan-Newman algorithm?
As I mentioned above, I don't think you actually need to do this for any reason. But if you really do want to do that (for reasons that aren't clear in your post), it is probably a better question for Stack Overflow because it is about coding.

Community detection and modularity


Stability analysis for PDE using von Neumann

Question: I need help understanding this stability analysis for the given finite difference approximation, I don't understand the middle part where if we assume $p^{2} >1 $ so $p>1$ how is this the same as $ p<-1$ , where did assumption come from? Also if $p<-1$ how does this make $ \left\lvert \xi _-\right\rvert>1$? can someone please look at the solution and explain?
Thank you.
Answer:
To ensure that $1-p^2\sin^2(\omega)<0$ for all $\omega$, it requires $p^2>1$, i.e. $p>1$ OR $p<-1$.

Addressing your first question, $p^2>1$ implies that either $p>1$ or $p<-1$, which makes sense, since in case of negative $p$ it can be written as $p = -1\!\cdot\! r,\ r\ge0$, and so
$$
  p^2 = \left(-r\right)^2 = r^2  >1 \implies r >1 \implies p = -r <-1
$$

Also, since for the case $p^2>1$ we have
$$
  1-p^2\sin^2\omega<0 \qquad
  \text{and}\qquad
  \left\lvert\xi_-\right\rvert = \big\lvert \,p\sin\omega -\sqrt{p^2\sin^2\omega - 1}\, \big\rvert
$$
The first condition $1-p^2\sin^2\omega<0$ means that the expression under root sign is non-negative.
If $p<-1$ and $-1\le\sin\omega\le1$ then the term $p\sin\omega$ can take values less than $-1$ (e.g. $\omega=\frac\pi2$) and so subtracting the (nonnegative) root term from $p\sin\omega$ will increase magnitude of the whole expression for certain values of $\omega$.

Example
$$
  p=-2, \omega=\dfrac{\pi}{3} \Rightarrow p\sin\omega = -\dfrac{\sqrt{3}}{2}
  \Rightarrow \left\lvert\xi_-\right\rvert = \Big\lvert \,-\dfrac{\sqrt{3}}{2} -
  \sqrt{\dfrac{9}{4} - 1}\, \Big\rvert = \Big\lvert \,\dfrac{-\sqrt{3}-\sqrt{5}}{2}\, \Big\rvert \approx 1.984.
$$
Comment: @italy You are correct about $\omega$, I think. Although it could have been restricted previously in the book.
The part with $p>1\implies\left\lvert\xi_+\right\rvert>1$ for some $\omega$ follows exactly like the case in my answer, except instead of $\left\lvert\xi_-\right\rvert$ use formula for $\left\lvert\xi_+\right\rvert$ in the above derivations.
Comment: Thank you so much for the explanation. I understand it a lot better, just wanted to ask when it's say 'for all values of omega is this between -pi and pi?
Comment: And also the part about if p>1,  $| \xi _+ | > 1$ for some omega? Thank you


Prove Lebesgue integrability

Question: Let $f_n \in L_0(X), |f_n|\leqslant\phi \in L_1(X), n \in N$ and $f_n \rightarrow f$ in measure. Prove that $f \in L_1(X)$ and
$$\lim_{n\to\infty}\int_{X}{f_n}d\mu = \int_{X} fd\mu$$
Here $L_0(X)$ stands for Lebesgue measurability, and $L_1(X)$ — for Lebesgue integrability on $X$.
As far as I understand, we should use the fact that $f_n$ is bounded by a Lebesgue integrable function being itself measurable, so $f$ is also Lebesgue integrable. Is that correct? I remember similar reasoning being used in the classroom.
If the first part is correct, how do I prove the equality?
Answer: Let $\{f_{n_k}\}_{k=1}^\infty$ be an arbitrary subsequence of $\{f_n\}_{n=1}^\infty$. Then $f_{n_k} \to f$ in measure, so one may extract a further subsequence $\{f_{n_{k_j}}\}_{j=1}^\infty$ of $\{f_{n_k}\}_{k=1}^\infty$ such that $f_{n_{k_j}}\to f$ pointwise a.e. in $X$. By Fatou's lemma $f\in L_1(X)$; by the dominated convergence theorem $\int_X f\, d\mu = \lim\limits_{j\to \infty} \int_X f_{n_{k_j}}\, d\mu$. Since $\{f_{n_k}\}_{k=1}^\infty$ was arbitrary, the result follows.
Comment: Why does the result follow from $f_{n_k}$ being arbitrary?
Comment: @Gaucho If every subsequence of a sequence of real numbers converges to some number $A$, then the sequence converges to $A$. In this case, the sequence under consideration is $\int_X f_n\, d\mu$.
Comment: But it is only proved that a subsequence of every subsequence converges to $\int f$.
Comment: @GuachoPerez no, it has been shown that every subsequence of $\int_X f_n\, d\mu$ has a further subsequence which converges to $\int_X f\, d\mu$, so $\int_X f_n\, d\mu \to \int_X f\, d\mu$. Indeed, since $\int_X f_{n_j}\, d\mu$ has a subsequence which converges to $\int_X f\, d\mu$, then $\int_X f_{n_j}\, d\mu$ to converges to the same number. But since $\int_X f_{n_j}\, d\mu$ is an arbitrary subsequence of $\int_X f_n\, d\mu$, $\lim_n \int_X f_n\, d\mu = \int_X f\, d\mu$.
Comment: @Gaucho take a look here: https://math.stackexchange.com/questions/397978/every-subsequence-of-x-n-has-a-further-subsequence-which-converges-to-x-the.
Comment: Of course. Nice solution, (+1)

Prove Lebesgue integrability


How to word a survey question comparing alternative purchase choices?

Question: I'm creating a survey to ask a customer that just bought a product what other products they considered before buying and how seriously they considered them.  I'd like to use a Likert scale type of answers, but am having trouble selecting.  Thus far I the question looks like this:
                  Strongly  |            |          | Strongly | Did not consider
                 Considered | Considered | Rejected | Rejected |  / Not Familiar
Competitor A
Competitor B
Competitor C
Competitor Other

I'd really like at least five answers with knowledge, with another added between Considered and Rejected. However, using Neutral between those I'm afraid sounds too much like Did not consider / Unaware of choice.
I'm also concerned that I'm mixing Considered with Rejected, because you must first consider before you reject and this might confuse respondents.  What other pairs of opposite words might I use instead?
Are there any commonly accepted examples in the art of a question like this that I could model mine after?
Answer: You can always phrase the question so the response will become strongly agree to strongly disagree. For example, your stem can be: "Please answer on a scale from strongly agree to strongly disagree, the following statement: I considered buying _____ before buying the product."
Or, you can stick to considered and rejected, but not label the points between them. Some people think this is a better idea if you intend to treat the variable as continuous because it is arbitrary whether the distance between strongly considered vs considered and considered vs neutral is the same.
Comment: Since the survey is being given verbally over the phone, I cannot use unlabeled middle items.  Also whether you could have strongly considered buying the product and after looking into it, strongly rejected buying it based on reviews you read, etc.


Preferred way to write elements of the direct sum of vector spaces

Question: Suppose $V$ and $W$ are vector spaces over the same field and $V\oplus W$ is
their direct sum. Reading through the literature I found essentially two
ways of writing elements of $V\oplus W$.
1.) We have the 'product like description' $(v,w)\in V\oplus W$
2.) We have $v+w\in V\oplus W$
Is there a correct or preferred way to write the elements?
I mean the direct sum is the coproduct in the category of vector spaces
not the product, so the first one is eventually misleading
(although the product $V\times W$ is the same here, this is only for finite many factors/terms)
On the other side, the second one can eventually be misleading. For
example, consider $a+b+c+d \in V\oplus W$. What does $+$ mean here? Is it the
$+$ from $V$ or from $W$ or from the direct sum? Is $b \in V$ or $b\in W$ ? You can't say ....
Comment: The key is to use the notation that makes things clear. Consistent notation is irritating. When talking about $\mathbb Z/m\mathbb Z$, we'll often mention $2$, when we mean $2+m\mathbb Z$. Being a stickler for notation doesn't really get you much.
Comment: You can also write $v\oplus w$. $a+b+c+d$ is okay, because we are really just just writing $w$ when we mean $(0,w)$ and $v$ when we mean $(v,0)$. So long as we know which of $a,b,c,d$ is in $V,W,$ or $V\oplus W$, it isn't confusing. But if $W=V$, or even $W\subseteq V$, or visa versa, then it is ambiguous, of course.
Comment: I like the $v\oplus w$. Thought about it myself, but couldn't find it in the literature. Have you any 'example-book' or something, that uses this? -- For the $a+b+c+d$ the problem is, I think, that we don't know where the single terms are from, because you can't see. So this one depends on cleverness and that certainly not a good idea in general.
Comment: I've seen $v\otimes w$ for elements of $V\otimes W$. I'm sure I've seen $v\oplus w$ in some place or other, but it isn't common.
Comment: But its certainly the most fail-save version.
Comment: I agree with Jim, though, I don't really see anything ambiguous with the ordered pair.
Comment: THen tell me, is $b\in V$ or $b\in W$ in the previous example? One way to put is like $(a +_V b) \oplus (c +_W d)$ another is $a \oplus (b+_W c +_W d)$ In a strict type-logic environmwnt you would get the "type-missmatch error", since the ymbol $+$ could either mean $+_V$ or $\oplus$ or $+_W$.
Comment: I was agreeing with Jim's answer, using $(v,w)$, not that expression. As I said, you couldn't write $a+b+c+d$ if you didn't know implicitly which vector space each element was in. That goes without saying. But if you have that information, there is no ambiguity in writing $a+b+c+d$.
Comment: Sorry. Jims answer?
Comment: Do you see that marker below, that says "1 Answer." Then several paragraphs and then text "Answered (some time) Jim." That's Jim's answer. Perhaps you need to reload the page?
Comment: Oh of course! Stupid. Had to reload...
Comment: A typical example is polynomials. We often write $1+xy+2+x^2$, but polynomials are really a graded ring - a direct sum of $1$-dimensional vector spaces with a multiplication added. The terms make clear which vector space we are taking each term from.
Comment: Right. Here it is not ambiguous at all.
Answer: The first is not misleading, the notation $(v, w)$ does not imply product vs. coproduct, it's just notation for a tuple.  If we had infinitely many summands (so that product $\neq$ coproduct) then writing $(v_i)$ just indicates that you have a tuple indexed by $i$.  It does not tell you whether that tuple has finite support or not and when it does have finite support this doesn't imply that you're considering the coproduct, elements of the product can have finite support as well (it's just not a requirement for the product).
The notation $(v, w)$ just indicates tuples.  As with most notations you have to either say explicitly or make sure it's clear from context in what domain you consider that element to be living.
The notation $v + w$ is also just as good though you're correct that you have to be extra careful to say where things live because the notation no longer indicates that $v$ is from the left factor and $w$ is from the right.
So use whichever you like, there is no correct choice or preference.  The thing to remember about all notation is that no matter how clear you think it is, it's never perfect.  You will always need to include prose to explain your mathematics.
Comment: Yes ok. The question of course remains, why the $v\oplus w \in V\oplus W$ is not used that often.
Comment: It's not used because $(v, w)$ already suffices for that purpose.


Determinant of $det(E+\beta u u^TJ)$

Question:
Let $J \in Mat_{2n \times 2x}(\mathbb{R})$ - Skew-symmetric matrix( $A^T = -A$), $\beta \in \mathbb{R}+$, $u \in \mathbb{R}_{2n}$ - nonzero vector
I need to find $det(I+\beta u u^TJ)$

For case $2 \times 2$ its easy:
$$B=u u^T J = \left ( \begin{matrix} u_1 \\ u_2 \end{matrix} \right ) \left ( \begin{matrix} u_1  u_2 \end{matrix} \right )
\left ( \begin{matrix} 0 & j\\ -j & 0\end{matrix} \right )$$
$$ B =  \left ( \begin{matrix} -u_1 u_2 j & u_1^2j\\ -u_2^2j & u_1 u_2 j \end{matrix} \right )$$
$$det(I+\beta B) = 1 $$

I tried with large dimensions - in all cases answer is 1,
 but i have no idea how to prove it in general case. Any hint will be appriciated
Comment: $E$ it's identity matrix (it's synonim to $I$). J can't contains zeroes on diagonal: https://en.wikipedia.org/wiki/Skew-symmetric_matrix
Answer: You can use the Sylvester determinant theorem (or the  matrix determinant lemma). It states that
$$\det(I+ \beta u u^T J)  =\det(1+ \beta u^TJ u)  .$$
Now we have that $u^TJ u$ is a $1\times 1$ matrix and thus
$$\det(I+ \beta u u^T J)  =\det(1+ \beta u^TJ u)
=  1+ \beta u^TJ u.$$
Note that so far, we have not used the fact that $J$ is antisymmetric at all.
With $J$ antisymmetric, we have additionally
$$ u^T J u= -u^T J^T u = - (u^T J u)^T = - u^T J u$$
such that $u^T J u=0$ and thus
$$\det(I+\beta uu^T J)= 1.$$
Comment: It's awesome! Thanks. Never knows when there is a theorem that makes task easier

Determinant of $det(E+\beta u u^TJ)$


Ramanujan's rational elementary results on $A^3+B^3=C^2$.

Question: In the bottom of one of the pages of Ramanujan's notebooks (see below), he writes down the following equations: $$\left(11\frac 12\right)^3+\left(\frac 12\right)^3=39^2$$ $$\left(3\frac 17\right)^3-\left(\frac 17\right)^3=\left(5\frac 47\right)^2$$ $$\left(3-\frac 1{105}\right)^3+\left(\frac 1{105}\right)^3=\left(5\frac 6{35}\right)^2$$ $$\left(3\frac 1{104}\right)^3-\left(\frac 1{104}\right)^3=\left(5\frac{23}{104}\right)^2$$ It is clear he was studying the equation $A^3+B^3=C^2$ just like how Euler did, but he also took it one step further and extended the solutions to the set of rational numbers. Now Ramanujan was particularly fond of finding remarkable general identities, but often his most curious ones was he going to remember the most. So he never really wrote them down, and predominantly wrote special cases of them. From the elegant form of the equations above, I presume he had a general identity.
Empirically I have found a near solution (my best one).
$$\left(14+\frac 13\right)^3+\left(\frac 13\right)^3\simeq \left(54+\frac{442}{1665}\right)^2$$
And some solutions with irrationals. $$\left(6-\frac 4{3\pm \sqrt 5}\right)^3+\left(\frac 4{3\pm \sqrt 5}\right)^3=12^2$$
$$\left(1\pm\frac 2{\sqrt 5-1}\right)^3\mp\left(\frac 2{\sqrt 5-1}\right)^3=2^2$$
Anybody know how Ramanujan got these results? I just factored out $(a+b)^3-b^3$ since the $b^3$ terms cancelled out, leaving me with quadratics, which is fairly simple. I think if Ramanujan had a general identity for this, it would do the same. Note that $(-1\frac 12)^3+(\frac 12)^3=0^2$ which is another solution to his first equation, and both solutions can be written as $\frac{10\pm 12}{2}$ and $\frac{39\pm 39}{2}$ which looks quadratic.
Any thoughts?
Thanks.
Comment: https://math.stackexchange.com/questions/369846/integer-solutions-of-x3y3-z2/764127#764127
Comment: https://math.stackexchange.com/questions/1018893/when-does-x3y3-kz2/1019616#1019616
Comment: @individ I have made my own formula some time ago for some value $n$, but letting $n\in\mathbb{Q}$ would have been much too cumbersome. The formula is:$$\big\{8(2n+1)\underbrace{(4n+1)(16n^2+20n+7)}_{(4n+2)^3-1}\big\}^3+\big\{\underbrace{(8n+5)(64n^2+56n+13)}_{(8n+4)^3-1}\big\}^3$$ $$=\big\{(32n^2+40n+11)(1024n^4+1792n^3+1248n^2+424n+61)\big\}^2$$ Thank you for revealing those much simpler formulae.
Answer: Ramanujan could not have had a general formula with the machinery of the time. Note that all of the listed results can be rewritten to have the same denominator $A$ in each number, so after multiplying by $A^3$ we have
$$x^3+y^3=Az^2$$
where $x,y,z$ are integers.
The given solutions correspond to the following integral relations:
$$23^3+1^3=2\cdot78^2$$
$$22^3-1^3=7\cdot39^2$$
$$314^3+1^3=105\cdot543^2$$
$$313^3-1^3=104\cdot543^2$$
Also note that the second term is always $\pm1$. So Ramanujan was merely looking for factorisations of incremented and decremented cubes with small squarefree parts.
From this framework other solutions arise, like
$$\left(\frac47\right)^3-\left(\frac17\right)^3=\left(\frac37\right)^2$$
$$\left(\frac{31}{38}\right)^3+\left(\frac1{38}\right)^3=\left(\frac{14}{19}\right)^2$$
Comment: @MrPie Done that.
Comment: It seems I made a typo in the fourth relation; it has been edited now and is currently true.
Answer: We argue about equation:
$$x^3 ± y^3=A z^3$$
Let  $y=t-x$ such that:
$$x^3+(t-x)^3=t^3-3t^2x+3tx^2=t[t^2-3x(t-x)]$$
Suppose $t=z^2$, then:
$$A=t^2-3xt+3x$$
This equation can have infinite solutions, for example:
$(t, A)=(25, 163)$
which gives:
$x=11, y=14, z=5$ such that:
$$11^3+14^3=163\times 5^2$$
Now suppose $A=k^3$, then we have:
$$3x^2-3xt+k^3-t^2=0$$
$$x=\frac{3t ±\sqrt{12k^3-3t^2}}{6}$$
for example:
$(t, k)=(9, 21)$ which gives $x=60, y=-51, z=3, A=21$:
$60^3-51^3=21^3\times 3^2$  ⇒ $\big(\frac{60}{21}\big)^3-\big(\frac{51}{21}\big)^3=3^2$
Or:
$t=676=26^2$,$A=k^3=1183^3$, $x=23829$, $y=-507$ such that:
$$\big(\frac{23829}{1183}\big)^3-\big(\frac{507}{1183}\big)^3=25^2$$
If discriminant $\Delta=9t^2-12t^2+12k^3=0$, then there are also infinite solutions, such that $x=y$, for example:
$(k, t)=(64, 1024)$ which gives $x=y=512$ and we have:
$\big(\frac{512}{64}\big)^3+\big(\frac{512}{64}\big)^3=32^2$
Which can be reduced to: $2\times 8^3=32^2$
Or:
$(t, k)=(11664=108^2, 324)$ which gives $x=y=5832$ and we have:
$\big(\frac{5832}{324}\big)^3+\big(\frac{5832}{324}\big)^3=108^2$
Which can be reduced to:
$2\times 18^3=108^2$
Comment: In equation we have $z^2$, so I meant $t=z^2$ to be able to argue.
Comment: In your first equation, I think you mean to let $t=z^3$ not $z^2$, but I still follow. Nice answer! :)
Comment: Oh whoops, sorry, idk why I thought that. Fermat's Last Theorem should have spoken to me sooner!


Add comment link to a view

Question: I created a new content type (News). I then added a new node.  After doing these, I created a 'view' of the node. In the view I added the "Add comment link" as a field.
I have the following issues:

In the "Add comment link" settings of the View, if I do not select the "Show teaser-style link" option, the link does not appear on the view page.
When I select the "Show teaser-style link", the "Add comment link" appears on the page as expected. However, the link redirects to the original node page.

What I would really like to do is show the 'full node form' on the view page without it redirecting to the original node.
Answer: If you want to render full node change the view settings as follows
In your view change the FORMAT settings as follows
Comment: Thank you. In this format, please how can i add and position a field like the "Share this Link"? Also how do I add the post date since it is not normally displayed in the node. Thanks again.
Comment: @seyi If you have other question please make it as another post. BTW, Can you try the above answer? is that what you are looking for?
Comment: I tried your answer and it works (the comment field now appears). But i do not know how to display some fields in this format. When i was using the 'fields format', i could display all kinds of fields related to the node.
Comment: @seyi what is 'share this Link'? did you install ShareThis module? or is this  a custom link?
Answer: The easiest way would be to change the view's format from "fields" to "content". Then you can activate the comments in the format settings.
Also, you then have the option of displaying the entire node (with or without links to the original node page).

Add comment link to a view


Prove that the function $L^2$ converges

Question: Prove that the series
$$\sum_{n=0}^\infty (-1)^n x^{2n}$$
$L^2$ converges in $(-1,1)$.
I thought that we needed a target function since the definition of $L^2$ convergence is that
$$\lim_{N\to \infty}\int_a^b |f(x) - \sum_{n=0}^Nf(x_n)|^2 dx = 0$$
but this problem has no target function
Comment: $$(-1)^nx^{2n}=(-x^2)^n$$ for integer $n$
Comment: In general: This is why completeness is so important. If there isn't an obvious limit, prove that a sequence is Cauchy
Comment: What is $x_n$ in $f(x_n)$?
Answer: $\sum_{n=0}^{N}(-1)^{n} x^{2n}=\frac {1-(-x^{2})^{N+1}} {1+x^{2}}$. Hence the partial sums of the series tend to $\frac 1 {1+x^{2}}$ and they are dominated by $\frac 2 {1+x^{2}}$.  By Dominated Convergence Theorem the series converges in $L^{2}(-1,1)$.
Answer: Hint. There is a target function $f\in L^2(-1,1)$. For $x\in(-1,1)$ we have a convergent geometric series:
$$f(x)=\sum_{n=0}^\infty (-1)^n x^{2n}=\frac{1}{1+x^2}.$$
Comment: Then you may use the Cauchy criterion. Recall that $L^2$ is complete.
Comment: A downvote? Am I missing something?
Comment: Ok, but what if it wasn't? Is every problem solvable without a target function stated?
Answer: HINT: you dont need a target function. Using the Cauchy criterion it is enough to show that for each $\epsilon>0$ there is an $N\in\Bbb N$ such that
$$\left|\sum_{k=m}^\infty(-1)^kx^{2k}\right|<\epsilon$$ for all $m\ge N$ (for the chosen $x\in(-1,1)$). Then it is enough to see that $$\left|\sum_{k=m}^\infty(-1)^kx^{2k}\right|< |x|^{2m}$$
Comment: I get downvoted, lol, can someone explain why?
Answer: This converges to
$$f(x) = \frac{1}{1+x^2}$$
Thus $$|f(x) - \sum_{n=0}^Nf(x_n)|^2 = \frac{(x^2)^{4N+4}}{(1+x^2)^2}$$
Integrating this
$$\int_{-1}^1 \frac{(x^2)^{4N+4}}{(1+x^2)^2} dx \leq \int_{-1}^1(x^2)^{4N+4} dx = \frac{2}{4N+5}$$
$$\lim_{N\to \infty} \frac{2}{4N+5} = 0$$
Therefore, the sum converges in $L^2$ sense in this interval
Comment: Your first line is $f(x) = \frac{1}{1+x^2}$, so you KNOW the target function. In your question I read "this problem has no target function".

Moreover your second line follows from Kavi Rama Murthy's answer.
Comment: I didn't downvote a single answer
Comment: BTW, why did you answer your own question?
I think that you should write your progress (did you use the hints given in the other answers?) by editing your question.
Comment: Because I came up with a solution. I didn't use them so I added my own.

Prove that the function $L^2$ converges


QtConcurrent map() on in place array

Question: I have a large array of float.
I would like to call QtConcurrent::map() on it and change the values in place.
Can I do that without making a copy of the array?
It seems map() takes a QVector as parameter and I can't find a mean to initialize a QVector from an array without making a copy.
Answer: QtConcurrent also has versions with STL-style iterators. Raw pointers have the properties of STL-style iterators for this purpose.
float x[] = {1.3f, 2.5f, 4.6f};
QFuture<void> f = QtConcurrent::map(x, x+3, [](float & a) { a = 2*a; });
f.waitForFinished();
qDebug() << x[0] << x[1] << x[2];

This prints:
2.6 5 9.2

QtConcurrent map() on in place array


Bitwig doesn't have ties in the imported Midi file

Question: When I create a MIDI file in Guitar Pro 6, and load it into Bitwig, everything is fine, except for the ties. For instance, I create this track on Guitar Pro:

Export it as MIDI and load it onto Bitwig. This is what I get:

Instead of the tie, there is nothing there, and of course there is no sound in that part.
In this simple example I can easily drag the line and fix the problem, but when I have a long piece, with many ties, it can get really tiresome. Is there any way I can fix this?
Also, is the problem generated from Guitar Pro, when the file is created, or is there something wrong with the way Bitwig loads the file?
Comment: I would think the problem is in guitar pro as there is no information on ties in midi, just absolute midi clock values that can be read from standard notation.
Comment: @Dom so it's some kind of Guitar Pro bug?
Comment: you'll get better help from the guitar pro forum where they support the product.
Comment: @Shevliaskovic yes as if it's bitwig's problem it has nothing to do with ties.
Answer: The only way that I found to solve this is to export the file to .gp5 file extension and open it in guitar pro 5, then export midi from there.
Hope this solution helps.
Answer: I would anticipate this to be a bug in Guitar Pro, as this piece of software isn't known for having the best export routines...
If you don't wanna wait, until Arobas Music fixed that, try the following in the meantime: Export a MusicXML file from Guitar Pro. Install MuseScore (free), open file there and try to export a MIDI file from MuseScore.
Answer: pick some other midi viewer than bitwig and see if it has the same problem.  if so, guitar pro is at fault.  if not, bitwig is at fault.  i'd suspect guitar pro off the top of my head.  they probably have a much better support forum anyway.
then go to whichever forum (which probably would have been a good idea to do in the first place) and pray that they'll prioritize your fix.
Comment: We've had many questions pertaining music software just -> [here](http://music.stackexchange.com/questions/tagged/software)
Comment: Why is it downvoted? His answer is totally the correct way to figure out the problem.
Comment: This answer is the correct way to diagnose the problem. Sevliaskovic: do what this answer says, and then you will know if it's Bitwig's or Guitar Pro's fault.
Answer: MIDI doesn't deal with ties, clefs, articulation symbols, any of that stuff. Ties are a part of written music notation. MIDI is a digital interface for communicating with musical instruments, whereas musical notation is for communicating to human musicians. Does your guitar have a "tie" button?
In your screenshot you have two written notes that are tied together, but they are used for describing a single sounding note. Most probably the issue should be corrected on the exporting program's side.


Why does a major minor modulation with the same root work (e.g. C to Cm)

Question: There are very few chord changes I cannot rationalize and fit into some mode of a major scale.  One of these is a major minor change with the same root (e.g. C to Cm).  The C chord has c, e, and g notes.  The Cm has c, eb, and g notes.  There is no major scale that fits these notes.  Is there a scale that can be used to riff across these chord changes with impunity or must the change be noted and respected?
This question is similar to Theory behind the change from a major chord to the same in minor but I'm not seeing an answer in that post that includes a scale that includes the notes c, eb, e, and g.  What scale(s) include the notes c, eb, e, and g.
These notes make up a C(#9) chord so the question could also be asked as what scale contains all of the notes in a C(#9) chord.
Comment: Also I don't think you're actually talking about a modulation. It seems you just want to understand a progression that uses C and Cm or something similar.
Comment: You might want to look up "borrowed chords" as a way of analyzing this.  Using the enharmonic chord (i. e. the minor with the same root if you're in major, and vice versa) is a common musical decoration.  One pop tune that come to mind that uses it fairly prominently is "Heart of Glass."
Comment: Why SHOULD there be one scale that can be used over two adjacent chords in a song?
Answer: As pointed out in @mramosch's answer, there is no standard seven-note (heptatonic) scale containing both an Eb and an E. Also note that we're not talking about modulation when we encounter the movement C to Cm (see below for the most common occurrence of this progression without modulation).
When playing a melody over the change C - Cm you want to make the difference between the two chords clear, so you need to change scales (or only use notes that both scales have in common, but that might be a bit boring).
The most common occurrence of the progression C - Cm is actually in the key of G major. It is very common to move from the IV (C) via the iv (Cm) to the I (G). This cadence works so well because the note E in the C chord moves down chromatically to the Eb of Cm, which in turn resolves to the note D of the G major chord. Once you know how it sounds you'll start hearing it almost everywhere.
If you want to play a melody over that progression, the simplest thing is to just alter the E to an Eb as soon as you move to the Cm chord. In the key of G that would mean to move from the G major scale (C lydian) to the G harmonic major scale. Another common option is to alter two notes (E->Eb, F#->F) and play the C melodic minor scale over Cm. Yet another option commonly used is to move to G natural minor (C dorian), in which case you alter three notes of the original G major scale (E->Eb, F#->F, B->Bb).
Answer: The relative key modulation would not be Cmin to CMAJ but rather C minor to Eb Major the relative Major key. This will enable you to use a couple of pivot chords that smooth out the modulations.
If you have your c minor phrase and you end the phrase on the dominant you can let it resolve with the chord c-eb-g which could either be tonic chord of c minor or sub mediant chord of Eb Major which is both perfectly fine resolutions to a dominant chord.
As you rightly point out the type of modulation you mention will be hard to resolve easily for the reasons you point out. Although I can imagine somewhere in the history of music someone did a modulation in that manner it is not a very natural modulation.
The transition between keys is just important that what you modulate to and when your two keys seem to clash it is very hard to modulate seamlessly.
Comment: But what about the case where there is a chord change from a major to the minor of the same root (maybe modulation is not the correct word).  To use an example from popular music: in Bob Dylan's "Simple Twist of Fate" the progression is D-Fm-D7-G-Gm-D-Fm-G-D-G.  In this case what is happening when the progression goes from G to Gm?
Answer: You can never have a scale that includes an Eb and an E at the same time because that would mean two notes are derived from the same root, namely E.
That is not the definition of a scale. You can only have each note once!!!
If you said C D# E -> this would be possible but that would not leave any place for a D. So you are stuck with a one-and-a-half step there. This interval can only be found in a harmonic minor scale (between the b6 and the major7) or any of the more exotic - lets call them gypsy-scales - that can have one or several one-and-a-half step intervals.
And - there are of course a lot of variants of Blues-scales that incorporate this interval, like:
C D# E F# G A Bb C
or even scales with 6 notes only, like:
C Eb F F# G Bb C
But as you see - with these 'artificial' scales you'll soon run out of arguments about how to interpret their notes. Of course you could interpret it as:
C D# E# F# G Bb/A# C
so there would be only one note derived from each root but I guess this is a little far fetched.
But with regular diatonic scales with 7 notes you should stick to the rules!
IONIAN (major), DORIAN, PHRYGIAN, LYDIAN, MIXOLYDIAN, AEOLIAN (minor), LOCRIAN
Comment: "You can only have each note once"... that's not really true. Think an 8 note scale (like the half-whole diminished scale). You have to duplicate at least one note to spell the scale
Comment: Definitely true. But as the OP refers to diatonic C major and C minor I composed my answer with regards to his question.. And that's why I also pointed out the difference between diatonic and 'artificial' scales (like a 6 notes blues scale) and how to interpret these ;-) Same of course holds true for a 8 note scale...
Comment: I'd be careful coining those scales "artificial"; some of them are not derived from the major or minor scale.
Comment: That's exactly why I put the quotation marks ;-)
Answer: One possible answer is E harmonic minor.  E harmonic minor has all of the notes I'm looking for.
http://www.jazclass.aust.com/scales/scahar.htm
Comment: No, it doesn't. E harmonic minor has a D#, no Eb. This might seem a little picky, but it does make a difference. Play the scale over the change C -> Cm and you'll see / hear that it doesn't work.
Answer: Just for clarification about the term modulation:
As a musical term it means the process of moving to another key (as TONICA) (root) by means of a chord-progression that clearly establishes the functional part (TONICA) of the new key.
Sometimes it is enough to play a DOMINANT seventh chord to establish the new TONICA of a chord that lies a perfect 4th above the DOMINANT. This can be for two beats of a bar only, or sometimes even a single 'dominant-shot' on the last quarter note of a bar is sufficient.
If you want to hear this kind of modulation in the pure classical way listen to Puccini's Madam Butterfly where he even enforces this DOMINANT functionality with a sharp 5th (#5)in the dominant 7th chord and making a whole chain of modulation as a sequence:
C(maj7) - A7/#5 -> D(maj7) - B7/#5 -> E(maj7) - C# 7/#5 etc.
Of course this goes hand in hand with the instrumentation. For these tricks he always uses the harp, because - although being a diatonic instrument like a piano, and thus having 7 notes per octave - you can re-interpret/re-tune these strings with the pedals of a harp and finally get only the notes of this augmented dominant 7th chord. Which means you can really 'harp' up and down with both hands the full range and all strings sounding loudly at the same time (arpeggio -> arp == harp).
For other modulations you need something more sophisticated than a single dominant-7th-chord. A little cadence with a SUBDOMINANT-DOMINANT-TONICA pattern like IIm - V7 - I or IV - V7 - I or even a DOUBLE-DOMINANT pattern like II7 - V7 - I
e.g. Dm - G7 - C , F - G - C or D7 - G7 - C
My personal favorite for popular music is again from the 80's Barbra Streisand Albums where they use a pattern like:
IV/V - V  ->  that finally leads to -> I
to establish the new tonality. Either each chord for a whole bar or the whole set two times each chord half a bar. You can modulate from absolutely any key to any other key within a bar or two. Of course the bass note which already comprises the DOMINANT functionality has to be played decidedly while the chords above change between SUBDOMINANT and DOMINANT (IV and V).
Anything else cannot be considered as a modulation but rather a  shift-over...
German has a very nice word 'RÜCKUNG' for this kind of unprepared change of tonality! It essentially means move/shift something to another place!


Bootstrap data-toggle="button" not working with

Question: I'm using the 'data-toggle'-option from Bootstrap for a button. In the button I have a  with glypicons and sometext. However, when you click on the text it works, but when you click on the glyphicon it doesn't trigger the data-toggle.
Since the data-toggle does not work in JSFiddle I cannot post a link to it.
HTML:
<button type="button" id="showHide" class="btn btn-default" data-toggle="button"> show</button>

JavaScript:
document.getElementById("showHide").onclick = function () {
    if ($("#showHide").text() == " show") {
        document.getElementById("showHide").innerHTML = " hide";
        document.getElementById("showHide").blur();
    } else {
        document.getElementById("showHide").innerHTML = " show";
        document.getElementById("showHide").blur();
    }
}

I've looked online but haven't found a solution or someone with the same problem.
Comment: Seems to work in this jsfiddle: https://jsfiddle.net/5qe31kw0/1/

Could you post a link to your code or re-create it in another jsfiddle?
Comment: @Brammz, I have provided a JSFiddle that looks like it provides the solution. What do you think? is that what you are after?
Comment: @Brammz, I remove the solution as I agree with Antfish, it appears that this is already working
Comment: @Antfish, thank you for the JSFiddle, when I tried it, I couldn't get it to work, but when you click the icon, the data-toggle does not go off
Comment: @Brammz What do you mean by "the data-toggle does not go off" ?

If you mean that the attribute is not removed then there is nothing in your code to remove it. I just managed to remove the attribute and it still works: https://jsfiddle.net/5qe31kw0/2/

I imagine it is a bootstrap hook for something.
Comment: @Antfish I mean that when the button text says "hide" the button itself is not toggled on. But the answer from Derek S works for me.
Answer: It appears the span is being replaced before the toggle event is propogated. You can use the button method to activate the toggle rather than the data attribute.
<button type="button" id="showHide" class="btn btn-default"> show</button>

document.getElementById("showHide").onclick = function () {
    if ($("#showHide").text() == " show") {
        document.getElementById("showHide").innerHTML = " hide";
        jQuery("#showHide").button('toggle');
        document.getElementById("showHide").blur();
    } else {
        document.getElementById("showHide").innerHTML = " show";
        jQuery("#showHide").button('toggle');
        document.getElementById("showHide").blur();
    }
}

View Fiddle


Show that gcd of any two consecutive odd integers is 1

Question: What is the gcd of any two consecutive odd integers
Comment: Please do research out before asking questions and don't spam math.StackExchange
Comment: It's 1 ${}{}{}{}{}$
Answer: $\gcd(a,a+2)=\gcd(a,a+2-a)=\gcd(a,2)$. Since $a$ is odd, $2\not\mid a$ so their $\gcd$ is $1$.


Is there a category-theoretic perspective on induced functions?

Question: Let $X$ and $Y$ denote sets. Given a function $f : X \rightarrow Y$ and a natural number, there is an induced function $g : X^n \rightarrow Y^n$ defined by $g(x_1,\cdots,x_n) = (f x_1,\cdots,f x_n).$
Similarly, given an arbitrary relation $f : X \rightarrow Y,$ there is an induced function $g : \mathcal{P}(X) \rightarrow \mathcal{P}(Y)$ defined by asserting that for all $A \in \mathcal{P}(X)$ it holds that $g(A) = \{y \in Y|\exists x \in A : (x,y) \in f\}$. Edit. In other words, $g(A) = \mathrm{rng}(f|_A)$.
Intuitively, these constructions work because $X^n$ and $\mathcal{P}(X)$ are "built on top of $X$."
My question is, does category theory shed light on these kinds of constructions? And/or the idea of "built on top of"?
Comment: Right-click > Show Math As > TeX Commands: `\upharpoonright`.
Comment: The codomain, in category theory, is a convenience for the algebra of morphisms. If you want an associative operation with left and right units for all morphisms--and this is very nice to have--then each morphism can only have one of each such unit. The codomain is a nice device for making the units (identities) make sense. That said, set theoretically there is indeed little reason to care.
Comment: For a relation the notation is usually $f\subseteq X\times Y$. And $g$ is merely $\operatorname{rng}(f\upharpoonright A)$.
Comment: EDIT: In category theory relations are viewed as possessing a "source" (or "domain") and a "target," (or "codomain") thus $f \subseteq X \times Y$ is slightly misleading as a definition, as it suggests that $f$ is merely its graph.
Comment: How do you do that vertical line with a "flick" at the top?
Comment: @user18921: Well, I was never a fond of the distinction between $\sin$ as a real valued function and $\sin$ as a real valued function whose values lie in the interval $[-\pi,\pi]$. But fair enough, if you want to use this approach then I am not the one who'll stop you. :-)
Comment: Asaf im actually completely with you. I actuallly asked a question about, "whats the payoff associated with codomains" and nobody really had an answer. You can look it up, if youre interested.
Comment: Ah. There was a discussion about this on MathOverflow once. In set theory there is none. It can be problematic when we want to talk about functions from sets into a class, sometimes in the context of forcing. There are ways around it but those are cumbersome compared to the simple approach of taking a function as a set of ordered pairs.
Answer: The question is quite broad, therefore my answer will also be broad. I hope that it is an answer at all ...
The idea of "canonical induced maps" leads to the general notion of a functor. Your first example is the $n$th power functor in the category of sets. More generally, if $C$ is a category with products and $n \in \mathbb{N}$, then there is a functor $C^n \to C$ which maps the object $(X_1,\dotsc,X_n)$ to $X_1 \times \dotsc \times X_n$ and the morphism $(f_1,\dotsc,f_n)$ to $f_1 \times \dotsc \times f_n$, which is the morphism $f$ defined by the equation $p_i f = f_i p_i$, using the universal property of products. You can compose with the diagonal functor $C \to C^n$ to get the $n$th power functor $C \to C, X \mapsto X^n$. Your second example is the covariant power set functor $\mathcal{P} : \mathsf{Set} \to \mathsf{Set}$. It can be generalized to suitable categories with a subobject classifier. Somehow a more basic functor is the contravariant power set functor, because it is just the hom functor $\hom(-,\{0,1\})$.
The idea of objects canonically built up from other objects leads to the general notion of limits, colimits and more generally universal properties.
Answer: I find that the question is somewhat unfocused, or at least I can't pinpoint what it is you are trying to ask except for "on top of $X$" part which is answered simply by considering concrete categories: categories $C$ equipped with a functor $C\to Set$ which behaves like a forgetful functor. You can find a lot information in the book "Abstract and concrete categories" (free on the web) that I think might answer, or at least provide you with lots of clarifications and ideas, for what you intended to ask.
Answer: More than a year later, here's my answer to the question posed by my old self: the concept of a monad is what you're grasping for.


H264 HW accelerated decoding in Android using stagefright library

Question: I`m trying to decode h264 video using HW with Stagefright library.
i have used an example in here. Im getting decoded data in MedaBuffer. For rendering MediaBuffer->data() i tried AwesomeLocalRenderer in AwesomePlayer.cpp.
but picture in screen are distorted
Here is The   Link of original and crashed picture.
And also tried this in example`
sp<MetaData> metaData = mVideoBuffer->meta_data();
int64_t timeUs = 0;
metaData->findInt64(kKeyTime, &timeUs);
native_window_set_buffers_timestamp(mNativeWindow.get(), timeUs * 1000);
err = mNativeWindow->queueBuffer(mNativeWindow.get(),
mVideoBuffer->graphicBuffer().get(), -1);`

But my native code crashes. I can`t get real picture its or corrupted or it black screen.
Thanks in Advance.
Comment: FWIW, there are public APIs for this in Android 4.1+.  The bad image looks like a stride/alignment problem in a YUV buffer.
Comment: Thanks very much for your reply. But i want to work with Android 4.0+.
Thats why i`m using Android NDK.
Answer: If you are using a HW accelerated decoder, then the allocation on the output port of your component would have been based on a Native Window. In other words, the output buffer is basically a gralloc handle which has been passed by the Stagefright framework. (Ref: OMXCodec::allocateOutputBuffersFromNativeWindow). Hence, the MediaBuffer being returned shouldn't be interpreted as a plain YUV buffer.
In case of AwesomeLocalRenderer, the framework performs a software color conversion when mTarget->render is invoked as shown here. If you trace the code flow, you will find that the MediaBuffer content is directly interpreted as YUV buffer.
For HW accelerated codecs, you should be employing AwesomeNativeWindowRenderer. If you have any special conditions for employing AwesomeLocalRenderer, please do highlight the same. I can refine this response appropriately.
P.S: For debug purposes, you could also refer to this question which captured the methods to dump the YUV data and analyze the same.
Comment: Thanks very much for your reply. First when i tried AwesomeNativeWindowRenderer,native code crashes. Here is how i used it.
        mVideoRenderer = new AwesomeNativeWindowRenderer (mNativeWindow, 0);
        mVideoRenderer->render(mVideoBuffer); //In while Loop.

This is backtrace.
#00  pc 00000000
#01  pc 00005678  mylib.so (AwesomeNativeWindowRenderer::render (android::MediaBuffer*)+260)

And when im using addr2line, the error in this line of this
status_t err = mNativeWindow->queueBuffer(mNativeWindow.get(), buffer->graphicBuffer().get(),
-1);
The error in probably in -1.
Comment: @user3215358.. In your code, how did you create `mNativeWindow`? The -1 is present in `AOSP` code and hence, I will not doubt it. Can you share your code for a review? `mNativeWindow` should point to a `Surface` or `SurfaceTextureClient` which internally has a `SurfaceTexture` attached to the same. My doubt is `mNativeWindow` may not be populated properly.
Comment: @Ganesh.. Im getting mNativeWindow from SurfaceView. Here is the code how im getting it  [link](http://pastebin.com/ZefHRW2z).
Comment: @Ganesh.. Im using [This](https://github.com/roman10/android-ffmpeg-tutorial/blob/master/android-ffmpeg-tutorial02/jni/tutorial02.c) Tutorial And im changing reading and decoding part.
Comment: @user3215358.. I will require some time to review.. but can you quickly enable logs in `BufferQueue` and check?
Comment: @Ganesh.. How to enable logs? open comment //#define LOG_NDEBUG 0 and recompile it ?
Comment: @user3215358..Yes that's correct.. If you are enabling for `BufferQueue`, consider doing so for `SurfaceTextureClient` and `SurfaceTexture` also
Comment: @Ganesh.. i have added #defind LOG_NDEBUG 0 But nothing was changed. Was else i should do, to see the problem???
Comment: @user3215358.. Did you capture the logs in `logcat`? If so, can you share the same?
Comment: @Ganesh.. [Here](http://pastebin.com/FCYUxrRr) is the paste of logcat, But i dont see any logs about BufferQueue.
And i have a question, Am i doing something wrong in my code???
Comment: @Ganesh.. in `queueBuffer`, second parameter is `NULL`.
`buffer->graphicBuffer()` is `NULL`. What can be the problem?
Comment: @user3215358.. Sorry I couldn't read your code. Can you please reshare your code and logcat? I can have a quick look
Comment: @Ganesh.. Now i'm using [this](https://vec.io/posts/use-android-hardware-decoder-with-omxcodec-in-ndk) example. For rendering i can use or local rendering or native window rendering. what do you advise?
[This](http://pastebin.com/iD81dSFY) is my main part of code.
[This](http://pastebin.com/WAS2DwDd) is renderers.


invalid type argument of unary '*' (have 'double') em C

Question: nao entendi mt o porque desse problema estar acontecendo, ja fiz isso em outros programas e nunca tive problema, abaixo esta a funcao q esta dando o erro, se necessario posto todo o codigo.
<code>    double Perimetro(Poligono P){
        Poligono A, B;
        int i = 0;
        double *D; //armazena a distancia entre dois pontos
        double numvert, soma = 0;
        numvert = NumeroDeVertices(P);
        D = (double*)malloc(sizeof((double)*numvert));
        A = P;
        B = P->prox;
        for (i = 0; i < numvert; i++){
            D[i] = Distancia(A, B);
            A->prox = B;
            B = B->prox;
            soma = soma + D[i];
        }
        return soma;
    }
</code>
Comment: Creio que aqui: D = (double*)malloc(sizeof((double)*numvert)); deva ser: D = (double*) malloc(sizeof(double) * numvert);
Comment: Por que você está declarando o número de vértices como um `double`? Faz sentido ter 3.75 vértices? E por que você cria o vetor de distâncias, sendo que o seu problema é bem claro que não se faz necessário armazenar essa informação? E o que você esperava obter do tamanho de `(double)*numvert`? Ou você queria pegar o tamanho de `double` para só então multiplicar por `numvert`?
Answer: Você esta multiplicando um double dentro do sizeof. o correto é: tamanho do tipo de dado * quantos espaços na memória você quer.
<code>malloc(sizeof(double) * numvert);
</code>


Solving PDE in 3D

Question: Could anyone solve below pde in 3d?
r is dposition vector in spherical coordinate.

$$
\nabla^{2}\mathrm{f} =
\frac{a r^4}{1}\,\left[-1 + 3\left(\hat{e} \cdot \hat{r}\right)^{2}\right]
$$

$\hat{e}$ is a defined vector in the x_y plane.
Comment: Find the Green's function in the appropriate coordinate system?
Comment: yes. That's the problem @KirylPesotski
Comment: How is $\hat{e}$ defined?
Comment: $\hat{e}$ is equal to (cos($\theta_0$), sin($\theta_0$),0). $\theta_0$ is a constant angle. @Dmoreno Could you please help me?
Comment: Do you have any boundary conditions?
Comment: f becomes zero as r tends to infinity @Dmoreno
Answer: WLOG choose our coordinates such that $\hat{e} = \hat{z}$.  Using the fact that
$$
3 (\hat{e} \cdot \hat{r})^2 - 1 = 3 \cos^2 \theta - 1 = 2 P_2(\cos \theta),
$$
where $P_2(x)$ is the second-order Legendre polynomial, we guess a solution of the form
$$
f(r, \theta) = R(r) P_2(\cos \theta).
$$
Plugging this solution into the Laplacian, we get
$$
\nabla^2 f = \frac{P_2(\cos \theta)}{r^2} \frac{d}{dr} \left( r^2 R'(r) \right) + \frac{R(r)}{r^2 \sin \theta} \frac{d}{d\theta} \left( \sin \theta \frac{d P_2(\cos \theta)}{d\theta} \right) \\
= \frac{P_2(u)}{r^2} \frac{d}{dr} \left( r^2 R'(r) \right) + \frac{R(r)}{r^2 } \frac{d}{du} \left( (1- u^2) \frac{d P_2(u)}{du} \right)
$$
where $u \equiv \cos \theta$. But by the definition of Legendre's equation,
$$
\frac{d}{du} \left( (1- u^2) \frac{d P_n(u)}{du} \right) = - n(n+1) P_n(u),
$$
and so the original equation $\nabla^2 f= \frac{a}{r^4} (-1+ 3 (\hat{e} \cdot \hat{r})^2)$ becomes
$$
\frac{P_2(u)}{r^2} \frac{d}{dr} \left( r^2 R'(r) \right) + \frac{R(r)}{r^2} \left(-6 P_2(u) \right) = \frac{2a}{r^4} P_2(u),
$$
or
$$
\frac{d}{dr} \left( r^2 R'(r) \right) - 6 R(r) = \frac{2a}{r^2}.
$$
This is a non-homogenous Euler equation and can be solved for $R(r)$ using standard techniques from ODEs.  One of the arbitrary coefficients in the resulting solution will vanish due to the demand that $f \to 0$ as $r \to \infty$.  Note, however, that no solutions exist such that $f \to 0$ as $r \to 0$ (regardless of the boundary conditions at infinity.)
Note that throughout this answer, I am using the "physics" convention for spherical coordinates where $\theta$ is the angle between the position vector and the $z$-axis, hence the need to pick $\hat{e} = \hat{z}$ above.  Once the overall solution for $f$ has been found, the coordinates in the solution can then be rotated such that $\hat{e}$ coincides with its original definition in the $xy$-plane (if desired.)
Comment: Thank youfor your nice answer. I have found general solution to the last equation, but I can not find particular solution :(
Comment: @OliverRange:  If you can't figure it out via guess-and-check, you can always use [variation of parameters;](http://tutorial.math.lamar.edu/Classes/DE/UndeterminedCoefficients.aspx) it's tedious, but it should work.
Comment: Do you have any guess for the particular solution?
Comment: why is "Note, however, that no solutions exist such that f→0f→0 as r→0" is correct?
Comment: @OliverRange:  The particular solution diverges as $r \to 0$, and the homogenous solution also diverges as $r \to 0$.  (And you can't combine them to get a finite solution as $r \to 0$.) Since this looks like a homework problem, I'd encourage you to try to work it out on your own from here.
Comment: You are right. Maybe the question was wrong.
Answer: $\newcommand{\bbx}[1]{\,\bbox[15px,border:1px groove navy]{\displaystyle{#1}}\,}
 \newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack}
 \newcommand{\dd}{\mathrm{d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
 \newcommand{\ic}{\mathrm{i}}
 \newcommand{\mc}[1]{\mathcal{#1}}
 \newcommand{\mrm}[1]{\mathrm{#1}}
 \newcommand{\pars}[1]{\left(\,{#1}\,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,}
 \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
 \newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$
$\ds{\mathsf{I'll\ slightly\ modify\ the\ original\ post,\ as\ follows,}\
\mathsf{in\ order\ to\ discuss\ the\ convergence\ of\ radial}\
\\
\mathsf{integrals}}$:

$\ds{\nabla^{2}\mathrm{f}\pars{\vec{r}} =
{1 \over a^{3}}\pars{r \over a}^{\nu}\bracks{-1 + 3\pars{\hat{\mrm{e}}\cdot\hat{r}}^{2}} =
-4\pi\bracks{{1 \over 2\pi a^{3}}\pars{r \over a}^{\nu}\,\,
{3\cos^{2}\pars{\angle\pars{\hat{e},\hat{r}}} - 1 \over 2}}:\
{\large ?}}$.

Note that
\begin{align}
&{3\cos^{2}\pars{\angle\pars{\hat{e},\hat{r}}} - 1 \over 2} =
\,\mrm{P}_{2}\pars{\cos\pars{\angle\pars{\hat{e},\hat{r}}}} =
{4\pi \over 5}
\sum_{m = -2}^{2}\mrm{Y}_{2m}\pars{\hat{r}}
\overline{\mrm{Y}_{2m}\pars{\hat{\mrm{e}}}}
\\[5mm]
&\mbox{such that}\
\nabla^{2}\mathrm{f}\pars{\vec{r}} = -4\pi\bracks{%
{1 \over 2\pi a^{3}}\pars{r \over a}^{\nu}\,{4 \pi \over 5}
\sum_{m = -2}^{2}\mrm{Y}_{2m}\pars{\hat{r}}
\overline{\mrm{Y}_{2m}\pars{\hat{\mrm{e}}}}}
\end{align}
where $\ds{\,\mrm{P}_{\ell}}$ is a
Legendre Polynomial and
$\ds{\,\mrm{Y}_{\ell m}}$ is a Harmonic Spherical.
$\ds{\,\mrm{f}\pars{\vec{r}}}$ is given by
\begin{align}
\mrm{f}\pars{\vec{r}} & = \iiint_{\mathbb{R}^{3}}
\bracks{{1 \over 2\pi a^{3}}\pars{r' \over a}^{\nu}\,{4 \pi \over 5}
\sum_{m = -2}^{2}\mrm{Y}_{2m}\pars{\hat{r}'}
\overline{\mrm{Y}_{2m}\pars{\hat{\mrm{e}}}}}
\,{\dd^{3}\vec{r}\,' \over \verts{\vec{r} - \vec{r}\,'}}
\end{align}

Hereafter, I'll use some properties which are explained in the above mentioned links.

Expanding $\ds{\verts{\vec{r} - \vec{r}\,'}^{\,-1}}$ in Harmonic Spherical:
\begin{align}
\mrm{f}\pars{\vec{r}} & = {1 \over 2\pi a^{3}}\iiint_{\mathbb{R}^{3}}
\bracks{\pars{r' \over a}^{\nu}
{4\pi \over 5}\sum_{m = -2}^{2}\mrm{Y}_{2m}\pars{\hat{r}'}
\overline{\mrm{Y}_{2m}\pars{\hat{\mrm{e}}}}}\,\times
\\[3mm] & \phantom{=\,\,\,}\ \underbrace{%
\bracks{\sum_{\ell' = 0}^{\infty}\sum_{m' = -\ell'}^{\ell'}{4\pi \over 2\ell' + 1}{r_{<}^{\ell'} \over r_{>}^{\ell' + 1}}\,\mrm{Y}_{\ell'm'}\pars{\hat{r}}
\overline{\,\mrm{Y}_{\ell'm'}\pars{\vec{r}\,'}}}}
_{\ds{=\ {1 \over \verts{\vec{r} - \vec{r}\,'}}}}\
\,\dd^{3}\vec{r}\,'\,,\qquad
\left\{\substack{\ds{r_{<} = \min\braces{r,r'}}\\[2mm]
                 \ds{r_{>} = \max\braces{r,r'}}}\right.
\\[1cm] & =
{1 \over 2\pi a^{3}}\,{4\pi\over 5}\sum_{m = -2}^{2}
\sum_{\ell' = 0}^{\infty}\sum_{m' = -\ell'}^{\ell'}{4\pi \over 2\ell' + 1}
\int_{0}^{\infty}\pars{r' \over a}^{\nu}{r_{<}^{\ell'} \over r_{>}^{\ell' + 1}}
\overline{\mrm{Y}_{2m}\pars{\hat{\mrm{e}}}}
\,\mrm{Y}_{\ell'm'}\pars{\hat{r}}\,\times
\\[3mm] & \phantom{=\,\,\,}\ \underbrace{%
\int_{\Omega_{\vec{r}\,'}}\mrm{Y}_{2m}\pars{\hat{r}\,'}
\overline{\,\mrm{Y}_{\ell'm'}\pars{\hat{r}\,'}}\,\dd\Omega_{\vec{r}\,'}}
_{\ds{\delta_{\ell' 2}\delta_{mm'}}}\
\,r'^{2}\,\dd r'
\\[1cm] & =
{2 \over a^{3}}\ \overbrace{\bracks{{4\pi \over 5}\sum_{m = -2}^{2}
\mrm{Y}_{2m}\pars{\hat{r}}\overline{\,\mrm{Y}_{2m}\pars{\hat{e}}}}}
^{\ds{3\cos^{2}\pars{\angle\pars{\hat{r},\hat{e}}} - 1 \over 2}}
{1 \over a^{\nu}}
\int_{0}^{\infty}r'^{\nu + 2}\,{r_{<}^{2} \over r_{>}^{3}}\,\dd r'
\\[5mm] & =
{3\cos^{2}\pars{\angle\pars{\hat{r},\hat{e}}} - 1 \over a}
\bracks{{1 \over a^{\nu + 2}}\int_{0}^{r}{r'^{\nu + 4} \over r^{3}}\,\dd r' +
{1 \over a^{\nu + 2}}\int_{r}^{\infty}r'^{\nu - 1}r^{2}\,\dd r'}
\end{align}

Both integrals converge whenever
  $\ds{\nu + 4 > -1\ \mbox{and}\ \nu < 0 \implies -5 < \nu < 0}$. Then,

\begin{align}
\mrm{f}\pars{\vec{r}} & =
{3\cos^{2}\pars{\angle\pars{\hat{r},\hat{e}}} - 1 \over a}
\bracks{{1 \over a^{\nu + 2}}\,{r^{\nu + 2} \over \nu + 5} -
{1 \over a^{\nu + 2}}\,{r^{\nu + 2} \over \nu}}
\\[5mm] & =\
\bbox[#ffe,15px,border:1px dotted navy]{\ds{5\,{3\cos^{2}\pars{\angle\pars{\hat{r},\hat{e}}} - 1 \over a}
{\pars{r/a}^{\nu + 2} \over -\nu\pars{\nu + 5}}}}\,,\qquad \nu \in \pars{-5,0}
\end{align}

Solving PDE in 3D


'Cash Account' cannot be empty

Question: When trying to create a new Customer using the REST API, it throws the following exception when PUT at the endpoint https://my.site/entity/Default/17.200.001/Customer
PX.Data.PXException: Error:  'Cash Account' cannot be empty.

PX.Data.PXOuterException: Error: Inserting 'Customer Payment Method' record raised at least one error. Please review the errors.

at PX.Data.PXUIFieldAttribute.CommandPreparing(PXCache sender, PXCommandPreparingEventArgs e)
at PX.Data.PXCache.OnCommandPreparing(String name, Object row, Object value, PXDBOperation operation, Type table, FieldDescription& description)
at PX.Data.PXTableAttribute.PrepareParametersForInsert(PXCache sender, Object row, Type[] tables, ISqlDialect dialect, Boolean audit, List`1[] pars)
at PX.Data.PXTableAttribute.PersistInserted(PXCache sender, Object row)
at PX.Data.PXCache`1.PersistInserted(Object row)
at PX.Data.PXCache`1.Persist(PXDBOperation operation)
at PX.Data.PXGraph.Persist(Type cacheType, PXDBOperation operation)
at PX.Data.PXGraph.Persist()
at PX.Objects.CR.BusinessAccountGraphBase`3.Persist()
at PX.Objects.AR.CustomerMaint.Persist()
at PX.Data.PXSave`1.d__2.MoveNext()
at PX.Data.PXAction`1.d__31.MoveNext()
at PX.Data.PXAction`1.d__31.MoveNext()
at PX.Api.SyImportProcessor.SyStep.a(Object A_0, PXFilterRow[] A_1, PXFilterRow[] A_2)
at PX.Api.SyImportProcessor.ExportTableHelper.ExportTable()

The JSON I'm using to create the customer is:
{
    "CustomerID": {
        "value": "ABCD1234"
    },
    "CustomerName": {
        "value": "TEST CUSTOMER"
    },
    "CustomerClass": {
        "value": "01"
    },
    "StatementCycleId": {
        "value": "01"
    },
    "ShippingAddressSameAsMain": {
        "value": true
    },
    "CashAccount": {
        "value": "BANAMEXMN"
    },
    "MainContact": {
        "DisplayName": {
            "value": "TEST CUSTOMER"
        },
        "Email": {
            "value": "firstname.lastname@example.com"
        },
        "Address": {
            "AddressLine1": {
                "value": "Test test"
            },
            "AddressLine2": {
                "value": "Test test"
            },
            "City": {
                "value": "Monterrey"
            },
            "State": {
                "value": "NL"
            },
            "PostalCode": {
                "value": "00300"
            },
            "Country": {
                "value": "MX"
            }
        }
    }
}

I've looked at the Endpoints screen but I can't find the CashAccount attribute under the Customer definition. The only place where I've found it is under Customer Payment Method but that'd be for creating a new Method, not adding the method to the customer.
Answer: For REST Web Services:
You need to extend the endpoint to add the cash account field:

Then select the PaymentInstructions entity in the left pane tree view and click on Extend Entity then Populate:

This will open a popup from where you can add the cash account field:

Finally when you call web service, change the 'Default' endpoint name in URL with the one you chose for the extended endpoint:

Ex:
http://domain/virtual_directory/entity/DefaultPlus/

instead of:
http://domain/virtual_directory/entity/Default/

For Screen Web Services:
Use Help->Web Service->Service Description to locate the fields:

This will open the XML Web Service Description where you can see which field can be passed with JSON:

Notice that the field container is named BillingSettingsDefaultPaymentMethod which matches the name of the tab and group box where the CashAccount field is located:

The JSON pattern to pass the field in BillingSettingsDefaultPaymentMethod group is the same one you're already using for MainContact. Notice that it only populates MainContact, it doesn't create a new contact. Same applies for default payment method group, it won't create a new payment method, it will only populate the Billing Settings tab Default Payment Method group fields.
The CashAccount field in your request is on the top level entity (Customer/BAccount) instead of being in the BillingSettingsDefaultPaymentMethod group. I suspect it doesn't exists at that level so you should remove it. To confirm it doesn't exists, look a the JSON response, it should omit the invalid fields in the response. It does so silently without raising an error.
Comment: I tried adding `"BillingSettingsDefaultPaymentMethod": { "CashAccount": { "value": "BANAMEXMN" } }` and `"BillingSettings": { "DefaultPaymentMethod": { "CashAccount": { "value": "BANAMEXMN" } } }` at the same level that `MainContact` with no success, it returns the same error. I just want to populate the Main Contact Information.
Comment: On second thought I think I've mistaken the Screen with REST API. For REST API instructions are to follow the Web service entity but the PaymentInstructions doesn't contain that CashAccount field so you would need to extend the endpoint to add it. I'll write a better answer.
Comment: When you create a customer it defaults the DefaultPaymentMethod field. The error seem to imply that it gets a value that requires a validation for a non null cash account. I would think you either have to pass that non-null cash account information or choose another payment method that doesn't require cash account validation or change the configuration so it defaults to a payment method that needs no validation.
Comment: I've added instructions on adding cash account field by extending endpoint. If you prefer to try without it, I suggest you manually fill out the screen with the same information you would send with web service then try to save. It could surface the same Payment Method error if the default value requires Cash Account field and if that field doesn't populate automatically.
Comment: I see. I'm going to do it and hope it works. If it works, i'll mark it as the correct answer. Thank you.
Comment: Now It returns the following error: `Cannot deserialize the current JSON object into type 'System.Collections.Generic.IEnumerable' because the type requires a JSON array to deserialize correctly. Path 'PaymentInstructions.CashAccount', line 1, position 504.` I have added `"PaymentInstructions":{"CashAccount":{"value":"BANAMEXMN"}}` at `MainContact` level. I've confirmed that the JSON is valid
Comment: You mean PaymentInstructions nested in Customer as it should be right? not nested in MainContact?
Comment: Yes, not nested in MainContact
Comment: It is a purely syntaxic error, PaymentInstructions is an array. Fixing syntax can be achieved by wrapping the value in brackets: "PaymentInstructions":[{"CashAccount":{"value":"BANAMEXMN"}}],
Comment: However I'm still having doubt about the proper entity to extend. This array seems to apply to the payment detail grid below the default payment method. You could try instead to extend BillingContact and populate on "Billing Settings -> Default Payment Method"
Comment: `"PaymentInstructions":[{"CashAccount":{"value":"BANAMEXMN"}}]` didn't work. It returned `'Cash Account' cannot be empty.` I'll try to extend BillingContact
Comment: You need to provide value that match and validate too, you should really check if the values you pass are working when you manually fill out the page. If you pass an invalid CashAccount for the default payment method it will silently validate it and make the field null if 'BANAMEXMN' is invalid. Because of that it could be a good idea to also explicitly provide DefPaymentMethod. The main issue though on my side is that I'm unsure where exactly we should extend Payment Method because it isn't available out of box.
Comment: I'll check the value too. I'll report back in a few hours.
Comment: I extended the `BillingContact` and tried again but got this error: `PX.Data.PXLockViolationException: Error: Another process has added the 'Address' record. Your changes will be lost.`
Comment: It is hard to tell what's going on. Usually that occurs when two threads are modifying the same object. Maybe you were using the web page to modify the same customer that the web service tries to modify too. Besides that, I'm not getting any of the errors you are having. I can pass PaymentInstructions without errors. At this point I would suggest trying out an Acumatica instance populated with SalesDemo data. I doubt this is gonna lead to the errors you have. You could compare configuration between instances after that. I suspect errors are due to your instance configuration.
Comment: I checked the `Address` Table and the address was created successfuly but the `BAccountID` is `-2147483647`. I used the `Profiler` to check and for some reason is using that ID when creating the records but I can't find the query that creates the customer. It search for the `CustomerID` twice and then `DECLARE @P0 AS INT = -2147483647;` to search for that `BAccountID`
Comment: That's not good at all, this means the ORM is failing to generate proper IDs for business accounts. Again very hard to understand what happens with so many errors. Do you know how that specific instance was configured?
Comment: I do not know how it was configured.
Comment: Do you think that if i delete this orphan record, it may allow me to try again without throwing the `Address locked` error?
Comment: I think your getting errors due to deployment or configuration (database). I would advise to compare behavior with a new instance deployed using SalesDemo data which is known to be properly configured. Indeed the solution might be to delete/change data in your instance.

'Cash Account' cannot be empty