HTML generated by Jupyter Book does not recognise inline equations

Question: The official JupyterBook documentation states that simply placing an equation between two $ signs should be all that is needed, e.g. $y = wx + b$. Unfortunately, on creating the book (jb build ... on the command line) the HTML file is generated incorrectly so that the equation is not recognised and, therefore, rendered as plain text (including the $ signs).
Interestingly, blocked equations using double $$ signs come out correctly.
Updating JupyterLab to 4.0.3 had no effect, same with updating the following:

Jupyter Book      : 0.15.1
External ToC      : 0.3.1
MyST-Parser       : 0.18.1
MyST-NB           : 0.17.2
Sphinx Book Theme : 1.0.1
Jupyter-Cache     : 0.6.1
NbClient          : 0.5.13

An extensive search yielded no answers.
At least it was possible to find out that HTML generated via the export function of JupyterLab works flawlessly.
Comment: I'd suggest updating the question with a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example).
Answer: I had the same problem. I found that "dollarmath" was disabled as default, so in your _config.yml file, simply enable it and it works (at least it did for me)
For example:
parse:
  myst_enable_extensions:
    # don't forget to list any other extensions you want enabled,
    # including those that are enabled by default!
    - amsmath
    - dollarmath


How does Champions League work?

Question: Thanks to an answer to a previous question, I now have a better understanding of the BPL. But now I am trying to figure out the Champions League.
What is the criteria for getting into it?
How is the season scheduled?
What takes priority (a domestic league fixture, or a Champions League match)?
And while this may warrant a whole different question later, how do player contracts/salaries change when a their club is in the Champions League?
Comment: In my eyes this question is too broad to be answered in a satisfactory manner. It's like asking; "how does NFL work" or "what's that NBA thing really?" You have multiple questions that could and should be asked separately to get factual answers.
Comment: See also [UEFA coefficient#Country coefficient](http://en.wikipedia.org/wiki/UEFA_coefficient#Country_coefficient) at Wikipedia.
Answer:
What is the criteria for getting into it?

The Champions league is a football tournament organised by Union of European Football Associations(UEFA).
Read this article for learning about the format and criteria for playing in the UEFA champions league.
The criteria is a detailed one, which is best explained by reading the wiki link.

How is the season scheduled?

The season starts around July with the qualifying matches being played. Once the qualifying rounds are over, we have 8 groups having 4 teams each giving a total of 32 teams.
Then the group stages begin, followed by round of 16, quarter-finals, semi-finals and then finals.
The dates for this year's champions league are:

1 July – 27 August 2014 (qualifying).
16 September 2014 – 6 June 2015 (competition proper).

What takes priority (a domestic league fixture, or a Champions League
  match)?

Champions league matches are generally played on Tuesdays/Wednesdays and the league matches are played over the weekend. So mostly they don't clash. But there have been instances of the league's governing body(FA, LFP), rescheduling their league matches if their league's team has an important champions league match.
Regarding the player's salaries and contracts: It's better if there is a separate question regarding this. But i do believe the salaries and contracts would change when champions league is involved with respect to their salaries and bonuses.

How does Champions League work?


Integration Problem: $\frac{1}{\sqrt{2\pi}}\int^{\infty}_0\sqrt{w}e^{-w-\frac{wx^2}{2}}dw$

Question: I know that:$$\frac{1}{\sqrt{2\pi}}\int^{\infty}_0\sqrt{w}e^{-w-\frac{wx^2}{2}}dw=\frac{1}{{(x^2+2)}^{3/2}}$$
I've attempted to solve this with integration by parts $\int{fdg}=fg-\int{dfg}$
I let
$$\begin{array} ff=\sqrt{w} & dg=e^{-w-\frac{wx^2}{2}}\\df=\frac{1}{2\sqrt{w}}& g=\frac{-2e^{-w-\frac{wx^2}{2}}}{2+x^2}{}\end{array}$$
Which is:$$\frac{1}{2\pi}\bigr[\frac{-2\sqrt{w}e^{-w-\frac{wx^2}{2}}}{2+x^2}\Bigr|^{\infty}_{0}+\frac{1}{2+x^2}\int^{\infty}_0\frac{e^{-w-\frac{wx^2}{2}}}{\sqrt{w}}dw\bigr]=\frac{1}{2\pi}\bigr[\frac{1}{2+x^2}\int^{\infty}_0\frac{e^{-w-\frac{wx^2}{2}}}{\sqrt{w}}dw\bigr]$$
I have to integrate by parts again, this time I have:
$$\begin{array} ff=e^{-w-\frac{wx^2}{2}} & dg=\frac{1}{\sqrt{w}}\\df=\frac{(x^2+2)^2e^{-w-\frac{wx^2}{2}}}{2}& g=2\sqrt{w}\end{array}$$
Which is:
$$\frac{1}{\sqrt{2\pi}}\bigr[\frac{1}{x^2+2}\bigr(2\sqrt{w}e^{-w-\frac{wx^2}{2}}\Bigr|^{\infty}_{0}+(x^2+2)\int^{\infty}_{0}\sqrt{w}e^{-w-\frac{wx^2}{2}}dw\bigr)\bigr]=\frac{1}{\sqrt{2\pi}}\int^{\infty}_0\sqrt{w}e^{-w-\frac{wx^2}{2}}dw$$
So, I'm back to where I started. Can somebody spot my mistake?
Comment: I guess you went one step to the north and then one step to the south...It happens sometimes with integration by part to end after applying it twice to end where you have started..
Answer: Hint
you have nearly with $w=u^2 \implies dw=2udu$ this:
$$I=\int \sqrt w e^{-w}dw=2\int u^2e^{-u^2}du$$
$$I=2\int u\times ue^{-u^2}du=\int u\times (-e^{-u^2})'du$$
Integrate by part once...
$$\int_0^{\infty} u\times (-e^{-u^2})'du=(u\times (-e^{-u^2}))|_0^{\infty}-\int_0^{\infty} (-e^{-u^2})du$$
And use gaussian integral to get the value of the last integral
$$\int_0^{\infty} e^{-u^2}du=\frac {\sqrt {\pi}}2$$


Interpreting odd's ratios

Question: If A is a binary faction (1 A and 0 not A) and if the odds ratios of A to B is (say) 1.2409 (24 percent or e ^ 0.2158). Then is the odds ratio of B to A 76% or 1 – 0.24?
Comment: the odds ratio of B to A = 1/1.0249.
Comment: I constantly  mix odds and odds ratio up. I ended up creating a confusion table like the one below.
Comment: Definition of OR of A to B: $OR_{AB} = \frac {P(A=1)/(1-P(A=1))} {P(B=1)/(1-P(B=1))}$. Definition of OR of B to A: $OR_{BA} = \frac {P(B=1)/(1-P(B=1))}{P(A=1)/(1-P(A=1))}$. So $OR_{BA} = 1/OR_{AB}$
Answer: Neither, maybe you are confused with odds and odds-ratios. But odds and odd ratios are two different things.
The odds ratio is defined as the ratio of the odds of A in the presence of B and the odds of A in the absence of B. Or equivalently (due to symmetry), the ratio of the odds of B in the presence of A and the odds of B in the absence of A.
Given your example, you could construct the following 2x2 table:

Therefore, if the odds ratio of A to B is 1.2409 to 1, then the odds ratio of B to A is 1.2409 to 1 too.
Comment: Finding that (10/12)>1 should tell you something needs changing.

Interpreting odd's ratios


Understanding the construction, copy and destruction when inserting objects to a vector

Question: I am trying to understand how STL handles the insertions of objects.
I understand that STL calls the constructor or copy construct from a temporary.
This is the code I am trying to understand:
#include <iostream>
#include <string>
#include <vector>
using namespace std;

class A
{
      public:
      int ObjId;;
      A(int id) : ObjId(id)
      {
            cout << "Constructing object with id: " << ObjId << endl;
      }

      A(const A& objToCpy)
      {
            ObjId = objToCpy.ObjId;
            cout << "Copying object with id: " << ObjId << endl;
       }

      ~A()
      {
            cout << "Destructing object with id: " << ObjId << endl;
      }
};

int main()
{
      std::vector vecOfA;

      vecOfA.push_back(A(1));

      cout << "....................." << endl << endl;

      vecOfA.push_back(A(2));

      return 0;
}

This gives the following output:
Constructing object with id: 1
Copying object with id: 1
Destructing object with id: 1
................
Constructing object with id: 2
Copying object with id: 2
Copying object with id: 1
Destructing object with id: 1
Destructing object with id: 2
................
Destructing object with id: 1
Destructing object with id: 2
I can understand the first insertion. A temporary object with ID=1 is created and it then copy constructed and inserted in to the vector. And this temporary then gets destructed.
However, I do not understand why the copied object has ID=0, and not 1.
As for the second part, I have no idea what is going on and why it is not identical to the first insertion, with the only exception of the ID being different. Why are 2 objects copy constructed, and both of them with ID=0, not 2.
Can anybody help me understand this behavior?
Comment: "I do not understand why the copied object has ID=0, and not 1." your copy constructor does not copy anything...
Comment: I prefer for the copy constructor member initialisation to be used. So  `A(const A& objToCpy) : Objid(objToCpy.Objid)
      {
           cout << "Copying object with id: " << ObjId << endl;
       }`
Answer:
However, I do not understand why the copied object has ID=0, and not 1.

Your copy constructor leaves ObjId uninitialized, so the behaviour of the program is undefined when the value is accessed.

As for the second part, I have no idea what is going on and why it is not identical to the first insertion, with the only exception of the ID being different. Why are 2 objects copy constructed

This is because of how the dynamic array data structure - which is what std::vector is - works. Arrays can not be resized. Once the internal array of vector is too small, a bigger array is created, the old elements copied (or moved) to the new array, and the old array is destroyed.

That means vector usually initialize to a capacity of 1?

One experiment doesn't tell what vector usually does. It appears that after the first push, the capacity was indeed one in this case on your system. There is no guarantee that it will be one in other cases (such as other implementation of std::vector).
Comment: Thank you. My mistake. I changed the copy constructor (edited the question) but I still see multiple objects for the second insertion.
Comment: Thank you. You are right. When I reserved(), it worked.
Answer: In the first case, you leave ObjId uninitialized, this means you got lucky that there was 0 inserted, but there also could be basically any value visible.
By typing A(const A& other) {...} you define your own copy constructor and that means you show how every field is copied, so you miss ObjId = other.ObjId statement in your constructor.
The second case happens because your vector is resizing and thus it has to copy all elements from old storage to new, bigger one, storage that will also fit new element.
Comment: Yes, that's initial value for this particular implementation of vector. However I'm not sure if initially that's 0 and whenever you add an element it's allocating any additional memory. But it's not cruicial here.
Comment: You are right! When I did reserve(10), got the behavior I expected. Thank you. That means vector usually initialize to a capacity of 1?
Comment: leaving `ObjId` uninitialized leads to undefined behaviour, there is no luck involved
Comment: actually undefined behaviour that gives you the result you expect is the worst, because you wont spot it until its too late


summing roots of unity elementary question (complex numbers)

Question: Suppose we have $$e^{i2\pi/n} = w_n$$
the question asks to prove $S_n = w^0_n + w^1_n + \cdots + w^{n-1}_n = 1 + w^1_n + \cdots +w^{n-1}_n = 0$
The solutions are as follows:
$w_nS_n = w_n + w_n^2 + \cdots + 1$ so $(1-w_n)S_n = 0$ and as $w_n \not = 0$ $S_n = 0$. My question is why is $w_n \not= 0$, similarly if we use the geoemtric series we get $\dfrac{1-w^n_n}{1-w_n}$, why is $w_n \not= 1$?
Comment: You want to say $w_n\ne1$?
Comment: Why is there $w$ and $w_n$? Are they different or the same?
Comment: ill edit the question sorry
Comment: $n>1$ is required for $w_n\ne 1$.
Answer: it's different from $0$ because $0$ is not a root of unity, but anyway in both aspects you use the fact that $w \not= 1$ which comes directly from the definition of $w = \exp(\frac{2\pi i}{n})$. a number $\exp(i 2\pi y)$ is equal to $1$ if and only if $y$ is a real integer - it's easy to see from the trigonometric definition of such a number (the one with sin and cos)
Comment: but $ y = n = 1$ gives $ w = 1$?
Comment: yeah, but for $n=1$ it is trivial (and not true) since the only root of unity of order $1$ is the unity, $1$, itself


How do you load a javascript file into a scope

Question: I'm trying to figure out how to load the contents of a JavaScript file into a scope.  The reason for this is I want to be able to have plug and play capability and be able to load different functionality into my app.  Perhaps the user role determines what functionality is loaded, or perhaps I want to tailor my app for a given client.
Here's an example of the contents of one of my pluggable JavaScript file:
myApp.LoginViewModel = (function ()
{
    //DATA
    var self = this;

    return {
        HelloWorld: function ()
        {
            alert('Hellow World from Login View Model');
        }
    };
})();

Here is an example of the configuration file listing what JS files should be loaded:
var myApp = myApp || {};

myApp.ViewModelRegistry =
{
    BaseViewModel: { JavaScriptPath: "/Scripts/ViewModels/BaseViewModel.js"},
    LoginViewModel:{ JavaScriptPath: "/Scripts/ViewModels/LoginViewModel.js"}
};

Here's my code that loops through ViewModelRegistry and uses jQuery to load the script:
    InitializeApp: function ()
    {
        //REGISTER VIEW MODELS
        for (var viewModelName in myApp.ViewModelRegistry)
        {
            var registeredModel = myApp.ViewModelRegistry[viewModelName];

            $.getScript(registeredModel.JavaScriptPath, function (data, textStatus, jqxhr)
            {
            });
        }

        console.log(myApp);
    }
};

My goal is to load the JavaScript function from the JS file into the myApp scope.  Each pluggable JS file is scoped to myApp.  I thought simply using jQuery's getScript to load the JS file would automatically update the myApp scope since all pluggable JS files are designed to that scope.  However, the console.log(myApp) doesn't reveal the code from the JS files.  What am I missing? Is this even feasible?
Answer: I believe your console.log is executed before any of your JS files have been retrieved and parsed.  Other than that, you seem to be on the correct course.  This is definitely feasible, and the terminology used to describe what you want to achieve is called Asynchronous Module Definitions.
Comment: Yes, you are right.  I wasn't finished loading JS files.  Thanks for the terminology tip.


How does Bayes' theorem work with independent events?

Question: I understand conditional probability whereby I can use known or unknown variables. In terms of the variables from this question, for instance, I can safely get the favourable probability by using the formula
$$
P (a,b|c) = P (a∣c,b)P(c∣b)
$$
Where

event a = goals conceded so far by a team
event b = goals scored so far by a team
event c = total wins by a team

These events are used in context of each of the competing sides we seek to compare.
The equation above would then be given as
goals conceded so far by team A x team A total wins ...(8.8)

goals conceded so far by team B x team B total wins ... (7.7)

Then I intend finding the probability of a loss for team A using $P(a|b) = P(a)$ which would evaluate as
1- 8.8 =  8.8

which is obviously impossible. How do I correlate independent events when all prior probabilities have already been found? Or is there another formula I should use instead?
Comment: What are events $a$, $b$ and $c$?
Comment: @LmnICE I've added those details to the original post so it's easily accessible to anyone else trying to help. Thank you
Comment: Your previous question was put on hold as unclear. This one is also unclear. What is your data? How do you know that it's independent? How did you calculate those values?
Comment: @Tim I clearly posted the data in that question. I don't know what format you expect the data to be but for your convenience, I'm [reposting it here](https://pastebin.com/JeeYWbLP). I know they are independent because Team B's results or wins does not affect team A's wins or losses. Those variables still stand for team A even if they were playing against another team. I calculated the values using the RHS of Bayes' formula $P(a∣z,b)P(z∣b)$. The variables I used are in my original post. Please don't block this question also
Comment: Your data does not contain any information about conditional probabilities so where did you get the conditional probabilities?
Comment: The conditional probabilities stem from the row "team A/B total wins". The other rows rely or submit to that row i.e. the eventual outcome of how many goals they score or concede is channeled and reflected in their total percentage win
Comment: This has nothing to do with conditional probabilities!
Comment: @Tim What has it got something to do with? Help me friend. We're here to guide each other in the right direction right? I thought they are conditional since it's those other rows that dictate what the eventual percentage total win is
Comment: You have probabilities of 8.8 and 7.7.  These are impossible. Probabilities are between 0 and 1.
Comment: As stated by others, your question is confusing. Clearly you want to find out what are the chances of a loss for Team A. So you need to think about how your data (number of goals scored and conceded, number of wins and percentage of home wins) relates to the probability of a loss. For example, clearly the more goals a team has scored, the lower the probability of a loss, but what is the exact relationship between those two quantities? In other words, you need a model.
Answer: You seem to be misunderstanding the notation that you are using.
$$
P(A,B|C) = P(A∣C,B)\;P(C∣B)
$$
in plain English is probability that $A = x$ and $B = y$ when $C = z$, i.e.
$$
P(A=x,B=y\,|\,C=z)
$$
so this is probability that the number of "goals conceded so far by a team" is equal to $x$ and, at the same time, the "number of goals scored so far by a team" is $y$, when the "total wins by a team" is $z$ etc. Same with $P(A∣C,B)$ and $P(C∣B)$, they should be probabilities, not the "numbers of goals" or  other values.
So your data should consist of a table with different values $x,y,z$ and accompanying probabilities. What you present as your "data" has nothing to do with it. You do not have information about neither of the probabilities.
You definitely should check the Wikipedia article on conditional probabilities and refer to some probability handbook before proceeding further.
Comment: But it does and I said so in my original post. event a = goals conceded so far by a team (team A or B)
event b = goals scored so far by a team(team A or B)
event c = total wins by a team(team A or B) the values are substituted in both equations.
Comment: How else do you propose I go about finding probabilities when I'm not given the total number of outcomes but my current sample data?
Comment: @IWantAnswers But the number of goals is **not** the same as probability of scoring such number of goals! Bayes theorem can be applied to *probabilities*, not to any numbers. If you don't have the data on probabilities, then you don't have the data, period. You cannot use Bayes theorem in here.
Comment: OK. My data source have no business with probabilities, if they even know of its existence. That's why I tried deriving it by myself using the row with percentage values to fill the probability spot in Bayes' equation. What concept or formula do you suggest I use to find any probabilities or arrive at any certainty, with the dataset I've shown?
Comment: Probabilities cannot be "filled". Either you have data or not. Your question is unclear (as previous one) since you assume the readers to know things about your data and your problem that are not stated in your question. What  you are showing us is a very limited data and to understand it we would need to know more about it (as stated in comments to the other question). You want to calculate from it something that cannot be calculated, unless not with the information you provided in the question.
Comment: All rows as I have received (unadulterated) in the dataset can be found [here](https://pastebin.com/knCeh0VS). All the rows that end with the number '1' represent the opposing/away/visiting team e.g wins1 is the same as 'wins for the visiting team'. What probabilities can you derive from that? NOTE: I don't intend using all those columns at the same time, just the ones I know will influence the eventual win/loss for either team. They are also the same rows I posted in my original question
Comment: Or does the dataset present an impasse instead of a solution, as discussed in [these answers](https://stats.stackexchange.com/questions/222179/how-to-know-that-your-machine-learning-problem-is-hopeless)?
Comment: I don't know what your data is about, so I cannot help. You should probably start with some kind of probability & statistics handbook and you should try to define your problem more precisely.
Comment: I said the data is about football or soccer. The rows define statistics about two teams participating in a match or fixture. The rows contain various information about the pair against other teams in the league up till the moment the data is being served. You keep complaining about my vagary and non clarity. I don't know what language you want me to explain in. I've posted the entire data and repeated myself over and over to the point where it seems I'm spamming the forum. Is it that you don't understand how football works? Or you don't get the row names? Or you don't want to help?
Comment: You are being **rude**. Your question was about applying Bayes theorem to non-probabilities. My answer was simple: you can't do this. I answered your question. Now you post your data and ask "how to analyze this". Such question is broad an unanswerable without context (what is the data [not only what are the column names]; what are aims of your analysis etc.). Please check: https://stats.meta.stackexchange.com/questions/1479/how-to-ask-a-good-question-on-crossvalidated
Comment: The aim of my analysis is to find any possible probability among the data I sent. I'm analyzing to find all likely outcomes in a match between those two teams based on their record or data or statistics against other teams in the league
Comment: Probabilities of what exactly? It sounds like a logistic regression problem. Are you familiar with logistic regression? If not, then you should start with some kind of statistics handbook.
Comment: Probabilities as basic as 'team A has a 38% chance of beating team B' head to head, based on the facts that though both teams have conceded the same number of goals against other teams, team A has scored more goals against other teams thereby having a greater percentage of (row) 'wins'


Clicar e adicionar id no array. Se clicar de novo, remover este id

Question: Estou com um problema, tenho uma lista e quando o usuário clica ele adiciona o id dessa
 em um array, mas eu quero que quando ele clique de novo sobre essa
, esse id seja removido do id.
Aqui está no JSFIDDLE.
HTML:

Teste 1

Teste 2

Teste 3

Teste 4

Teste 5

Teste 6

Teste 7

Teste 8

Teste 9

Teste 10

Exibir selecionados

JavaScript
$(function(){
  var idsSelecionados = [];
  $('li').click(function(){
   var id = $(this).attr('id');
   idsSelecionados.push(id+',');
   $(this).toggleClass("active");
  });

    $('#show').on('click', function(){
        $.each(idsSelecionados, function(i, val){
          $('#retorno').append(val);
        });
    });
});

Answer: Acho que uma solução à pergunta é:
$(function(){
  var idsSelecionados = [];
  $('li').click(function(){
   var id = $(this).attr('id');
   var idx = idsSelecionados.indexOf(id+',');
   if (idx == -1) {
     idsSelecionados.push(id+',');
   } else {
     idsSelecionados.splice(idx, 1);
   }
   $(this).toggleClass("active");
  });

    $('#show').on('click', function(){
        $.each(idsSelecionados, function(i, val){
          $('#retorno').append(val);
        });
    });
});

Observações:
O método delete pode ser utilizado para excluir o elemento do array, mas fica um "buraco"com o valor undefined, o método Array.splice não deixa este "buraco".
Como não sei por que ter colocado a vírgula junto com o id, deixei. Mas pode ser um equívoco durante a programação, se necessário, modificar para ficar como desejado.
Falta uma coisa que não foi objeto principal da pergunta e não tenho certeza: toggleClass acho que só adiciona a classe active, então você ainda precisa achar como retira a classe active e colocar essas instruções dentro do if e do else.
Answer: var lista = [];

$("li").click(function(){
    var id = $(this).attr("id");
    var index = lista.indexOf(id);

    if(index > -1) {
        lista.splice(index, 1);
    } else {
        lista.push(id);
    }
    $("#retorno").html(lista);
});


Cant use base64 image inside img tag?

Question: Node js
unirest.get("MYROUTE")
.header("X-Mashape-Key", "MYKEY")
.end(function (result) {
  console.log(result.status, result.headers, result.body);
  if(result.status==200) {
    var buffer = (new Buffer(result.body.toString()));
    res.end(buffer.toString("base64")); // output content as response body
    //res.end('data:image/jpg;base64,'+result.body)
  }
});

Returns (I erased a lot, but its base64)
77+977+977+977+9ABBKRklGAAEBAAABAAEAAO+/ve+/vQBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDLvv73vv70AQwEJCQkMCwwYDQ0YMiEcITIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIy77+977+9ABEIAe+/vQHvv70DASIAAhEBAxEB77+977+9AB8AAAEFAQEBAQEBAAAAAAAAAAABAgMEBQYHCAkKC++/ve+/vQDvv70QAAIBAwMCBAMFBQQEAAABfQECAwAEEQUSITFBBhNRYQcicRQy77+977+977+9CCNC77+977+9FVLvv73vv70kM2Jy77+9CQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eu+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/vQAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgvvv73vv70A77+9EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIy77+9CBRC77+977+977+977+9CSMzUu+/vRVicu+/vQoWJDTvv70l77+9FxgZGiYn

With angular I get res.data which is the base64, I try to use it inside a img tag but the image is not working?
How do I use this base64 to display images?
Comment: You need to format it as a [data-uri](http://en.wikipedia.org/wiki/Data_URI_scheme#HTML)
Comment: How are you setting the response to img tag?
Comment: TemplateData.getData().then(function(res) {
      console.log(res.data);
      $('body').html('');
    }, function(status) {
      console.log(status);
    })
Comment: Just a quick thought - how large is the image? Is it falling foul of this issue http://stackoverflow.com/questions/695151/data-protocol-url-size-limitations.
Answer: You're on the right track.  The img tag should look something like this:

Taken from wikpedia

The base64 you pasted into your question does look correct; however, ensure that the client is receiving the proper payload and HTML encoding isn't stripping and/or converting characters.
Comment: Thanks for the response I am logging the `res.data` and it looks fine.

Cant use base64 image inside img tag?


Erro Conexão mysql e android

Question: Estou desenvolvendo um app que precisa ter uma conexão externa e estou tendo um problema na execução, como eu poderia resolver isso?
Segue o código:
import java.sql.DriverManager;
import java.sql.SQLException;
import com.mysql.jdbc.Driver;
import com.mysql.jdbc.Connection;

    public class conectar {
        Connection conn = null;
        public Connection getConexato() throws ClassNotFoundException, SQLException{
            Class.forName("com.mysql.jdbc.Driver");
            conn = (Connection) DriverManager.getConnection("jdbc:mysql://192.168.1.34:3306/localhost","root","");
            return conn;
        }
    }

import android.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.mysql.jdbc.Driver;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;

public class MainActivity extends AppCompatActivity {
    private Connection conn = null;
    private Statement st;
    private ResultSet rs;
    private String sql;

    @Override

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        conectar Conectar = new conectar();
        try {
            conn = Conectar.getConexato();
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            AlertDialog.Builder msg = new AlertDialog.Builder(MainActivity.this);
            msg.setTitle("Conctar!");
            msg.setMessage("Erro! " + e);
            msg.setNeutralButton("OK", null);
            msg.show();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            AlertDialog.Builder msg = new AlertDialog.Builder(MainActivity.this);
            msg.setTitle("Conctar!");
            msg.setMessage("Erro! " + e);
            msg.setNeutralButton("OK", null);
            msg.show();
        }
        Button bt = (Button) findViewById(R.id.btntest);
        bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder msg = new AlertDialog.Builder(MainActivity.this);
                msg.setTitle("Conctar!");
                msg.setMessage("Conectado!");
                msg.setNeutralButton("OK", null);
                msg.show();
                try {
                    conn.close();
                    msg.setTitle("Conctar!");
                    msg.setMessage("Desconectado!");
                    msg.setNeutralButton("OK", null);
                    msg.show();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });
    }
}

Logcat:

Error:PARSE ERROR:
Error:unsupported class file version 52.0
Error:...while parsing com/mysql/jdbc/JDBC42CallableStatement.class
Error:1 error; aborting
:app:transformClassesWithDexForDebug FAILED
Error:Execution failed for task ':app:transformClassesWithDexForDebug'.

com.android.build.api.transform.TransformException: java.lang.RuntimeException: com.android.ide.common.process.ProcessException: java.util.concurrent.ExecutionException: com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command 'C:\Program Files\Java\jdk1.8.0_101\bin\java.exe'' finished with non-zero exit value 1
Comment: Em uma rapida pesquisa achei esse link http://stackoverflow.com/questions/37902840/got-unsupported-class-file-version-52-0-after-including-a-module-to-a-project veja se é o mesmo caso seu.
Comment: Infelizmente não é o mesmo  Caso, testei essa solução mas não funcionou ... obrigado assim Cara!
Comment: Eu tenho um link no projeto no github talvez possa ajudar, a coneção está funcionando corretamente, ignore as gambiarras kkk https://github.com/luizfps/GLCMonitor
Comment: vou tentar estudar o codigo aqui e te retorno! valeu
Answer: O erro acontece porque você não especificou as opções de compatibilidade no próprio módulo. Geralmente acontece se o seu projeto está com JDK 7, mas está instalado e usando JDK 8, em seguida, todos os módulos que serão usados em um projeto tem que ser compatível com o JDK 7. Caso contrário, haverá um erro porque o JDK 7 não é possível analisar arquivos de classe que foram compilados pela JDK 8 e têm a versão 52.
Verifique:
apply plugin: 'java'

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')

    sourceCompatibility = 1.7
    targetCompatibility = 1.7
}

Detalhes

Source (Stackoverflow)
Comment: Verifiquei e Realmente NÃO tinha, MAS na hora que coloquei e sincronizei hum Gradle, e Aconteceu Esse Erro aqui:   Error:The 'java' plugin has been applied, but it is not compatible with the Android plugins.

Erro Conexão mysql e android


Confusion about the notation of empty interval

Question: Currently, I'm studying about intervals. I got the basic understanding and knowledge about them but while reading the page about intervals in Wikipedia, under the classification of intervals tab, I didn't understand some of the notations used for the empty interval. They are
$(b,a)$
$(b,a]$
$[b,a)$
where  $b>a$
What does the upper-bound (b) written before the lower-bound (a) in these three notations mean? And how do these notations work?
Thank you for your valuable suggestions.
Comment: Because $(b,a) = \{ r \in \mathbb R \mid x < a < b  a$, because in these cases the  inetrvals are empty.
Comment: and does **open** have any significance over here?
Comment: See [Interval (mathematics)](https://en.wikipedia.org/wiki/Interval_(mathematics)#Terminology) : **open** $(a,b)$; **closed** $[a,b]$.
Comment: Got it... Thanks for the help...
Answer: The empty interval is obviously ... empty; it is an empty set of numbers.
Why e.g. $(b,a) = \emptyset$ when $b > a$ ?
Because, in general :

$(a,b) = \{ x \in \mathbb R \mid a < x \text { and } x < b \}$.

When $b > a$ we have that :

$(b,a) = \{ x \in \mathbb R \mid b < x \text { and } x < a \}$

and there are no $x$ that satisfies the condition.


Fundamental solution of Laplace's equation

Question: For $n=2$ the fundamental solution of the Laplace's equation is given by
$P=-\frac{\log(|x|)}{2\pi}$.
But how do I show that
$\int_{\mathbb{R}^2}\Delta P \, f \,dx=f(0)$
for all $f\in C^\infty_c(\mathbb{R}^2)$.
My Idea is
\begin{align}
& \int_{\mathbb{R}^2}\Delta Pf \, dx =\lim\limits_{\varepsilon\to 0} \int_{\mathbb{R}^2\setminus B_\varepsilon} \Delta Pf \, dx \\[8pt]
= {} &-\lim_{\varepsilon\to 0} \left(\int_{\partial B_\varepsilon}\nabla Pf\cdot n \, dS+\int_{\mathbb{R}^2\setminus B_\varepsilon}\nabla P\cdot \nabla f \, dx \right) \\[8pt]
= {} &-\lim_{\varepsilon\to 0} \left( \int_0^{2\pi}\frac{1}{\varepsilon^2}f \, d\varphi+\int_{\mathbb{R}^2\setminus B_\varepsilon}\nabla P\cdot \nabla f \, dx \right)
\end{align}
Answer: You're idea is on the right track.  Here is a way forward if $f$ is differentiable and of compact support.
It can be shown that we can differentiate once (but not twice) under the integral to find
$$\begin{align}
\Delta \int_{\mathbb{R}^2}P(\vec x, \vec x')f(\vec x')\,d\vec x'&=\nabla \cdot \int_{\mathbb{R}^2}\nabla P(\vec x, \vec x')f(\vec x')\,d\vec x'\\\\
&=-\nabla \cdot \int_{\mathbb{R}^2}\nabla' P(\vec x, \vec x')f(\vec x')\,d\vec x'\\\\
&=\nabla \cdot \int_{\mathbb{R}^2} P(\vec x, \vec x')\nabla'f(\vec x')\,d\vec x'\\\\
&=- \int_{\mathbb{R}^2} \nabla ' P(\vec x, \vec x')\cdot \nabla'f(\vec x')\,d\vec x'\\\\
&=-\lim_{\varepsilon\to 0^+} \int_{\mathbb{R}^2\setminus B_\varepsilon} \nabla ' P(\vec x, \vec x')\cdot \nabla'f(\vec x')\,d\vec x'\tag1
\end{align}$$
Now, we integrate by parts the integral on the right-hand side of $(1)$ to obtain
$$\begin{align}
\Delta \int_{\mathbb{R}^2}P(\vec x, \vec x')f(\vec x')\,d\vec x'&=\lim_{\varepsilon\to 0^+} \oint_{ B_\varepsilon} \hat n'\cdot \nabla ' P(\vec x, \vec x')f(\vec x')\,dS'\\\\
&=\frac1{2\pi }\lim_{\varepsilon\to 0^+} \int_0^{2\pi}\frac1\varepsilon f(\vec x'=\vec x+\varepsilon \hat n')\,\varepsilon\,d\phi'\\\\
&=f(\vec x)
\end{align}$$
as was to be shown!  And we are done.
Comment: thank you. I think I have an idea for my problem now. I need to prove given fundamental solution of a differential operator, which the laplace operator is part of the differential operator and since i am new in this, u have me a lot.
Comment: @L.P. You're welcome. My pleasure. Pleased this was useful. And feel free to up vote and accept an answer as you see fit.
Answer: You have
$$
\int_{\mathbb{R}^2}\Delta Pf\,dx=\int_{\mathbb{R}^2\setminus B_\varepsilon}\Delta Pf\,dx+\int_{B_\varepsilon}\Delta Pf\,dx.
$$
Since $\Delta P=0$ outside of $B_\varepsilon$, the first integral is zero. Therefore, integrating by parts,
$$
\int_{\mathbb{R}^2}f\Delta P \, dx=\int_{B_\varepsilon}f\Delta P \, dx=-\int_{B_\varepsilon}\nabla P\nabla f \, dx+\int_{\partial B_\varepsilon}f\nabla P\cdot n \, dS_\varepsilon=
$$
$$
=-\frac{1}{2\pi}\int_{B_\varepsilon}\frac{x}{\|x\|^2}\cdot \nabla f\,dx-\frac{1}{2\pi}\int_{\partial B_\varepsilon}f\frac{x}{\|x\|^2}\cdot n dS_\varepsilon
$$
Now, the first integral approaches zero as $\varepsilon\to 0$ because $\nabla f$ is bounded and $x/\|x\|^2\sim 1/\varepsilon$ while $Area (B_\varepsilon)\sim\varepsilon^2$. As for the second, $x\cdot n=-\|x\|$ and $x\cdot n/\|x\|^2=-1/\varepsilon$. Therefore,
$$
-\frac{1}{2\pi}\int_{\partial B_\varepsilon}f\frac{x}{\|x\|^2}\cdot n dS_\varepsilon=\frac{1}{2\pi\varepsilon}\int_{\partial B_\varepsilon}fdS_\varepsilon=f(\xi)
$$
for some $\xi\in\partial B_\varepsilon$. In the limit $\varepsilon\to 0$, $f(\xi)\to f(0)$, as desired.


How to prevent certain bundled CKEditor plugins from loading

Question: There is hook_ckeditor_settings_alter() to change/alter CKEditor settings. But I can't find a way to prevent certain CKEditor plugins from loading.
I am trying to achieve similar behaviors as here: https://www.drupal.org/node/2546048#comment-10188390 but that is for wysiwyg module, we don't use wysiwyg module.
Answer: We can disable CKEditor plugins by following hook as show with the example for disabling image and image2 plugins:
/**
 * Implements hook_ckeditor_settings_alter()
 */
function MYMODULE_ckeditor_settings_alter(&$settings, $conf) {
  // Comma separate names of plugins to remove.
  $plugins_to_remove = 'image,image2';
  $settings['removePlugins'] = !empty($settings['removePlugins'])
    ? $settings['removePlugins'] . ',' . $plugins_to_remove
    : $plugins_to_remove;
}

(taken from my own article: http://kb.detlus.com/articles/drupal/drupal-7-disable-ckeditor-bundled-plugins/)
Answer: CKeditor plugins are enabled/disabled directly from Ckeditor profils.
Comment: Sorry, but I meant about bundled plugins that comes with CKEditor library itself.


'Turn off Automatic Root Certificates Update' and 3rd party root certificates

Question: The group policy setting 'Turn off Automatic Root Certificates Update' prevents Windows from deleting certificates that it cannot verify.
If a third party has provided me with their own self-signed root certificate, I can see no other option but to turn off automatic root cert update, else their self-signed certificate will be deleted at some point due to group policy rules.
Is it insecure to disable this checking?
Do I have any other options?  Can I set up more granular rules so that Windows will not delete the specific certificate, but will carry on updating the others I have installed?
Note:
I'm using a basic c# app to deploy the certificate, using the following code:
X509Certificate2 certificate = new X509Certificate2("trusted-root-cert.cer");
X509Store store = new X509Store(StoreName.AuthRoot, StoreLocation.LocalMachine);

store.Open(OpenFlags.ReadWrite);
store.Add(certificate);
store.Close();

I need to install the certificate via code, since my software is running as part of a farm of multiple machines, where it's not practical to install anything by hand.
Also, the machines are in a workgroup, NOT a domain.
Answer: As far as I'm aware, certificates deployed via Group Policy will not be removed when the Automatic Root Certificates Update runs.
I can't find a definite reference from MSFT. This is how I deploy private CA root certificates in my Customers' environments and I've had no problems with them being automatically removed. (Of course, now that I say that... >sigh<)
Comment: Thanks! That appears to be a manual method of installing a certificate, is there a script equivalent?
Comment: I tend to think you're going to be disappointed. I'm not seeing where there's any more granular functionality to control the Automatic Root Certificate update functionality. You may be stuck writing code to look for the absence of the certificate and put it back (assuming you want to keep the automatic updates enabled).
Answer: There are two options to distribute a custom root certificate over domain members:

Distribute it via Group Policies (already mentioned)

this option should be used when only specific domain members should install this certificate (as GPO supports targeting) or there are specific custom attributes.

Publish it to Active Directory.

This method is used to publish root CA certificate to all AD forest members (while GPO method can be used within particular domain/site only). Also this method supports command-line (unlike GPO method):
certutil -dspublish <path\certfilename.crt> RootCA

where <path\certfilename.crt> is the path to a certificate file. Clients will download this certificate from AD during next autoenrollment trigger.


3D convolutions and jitter

Question: I want to process a sequence of cropped and aligned face images from a video with a neural network. I am considering a use of 3D convolutions in order to capture the spatiotemporal dependency. However, despite alignment and cropping steps, there is still some jitter noise present in the sequence. I am wondering if it is going to be too difficult for 3D convs to finds useful patterns in such a sequence or maybe it will deal with the noise just fine?
Comment: Could you give us examples illustrating the problem? "Jitter" might be quite ambigous.
Comment: Jitter meaning that after alignment and cropping, the appearance of the face is still quite "shaky", so the same face feature can appear in different parts of face image.
Comment: What exactly means "I want to process"? Also, it sounds like it would be beneficial to improve your alignment. How do you do this?
Comment: I meant, I want to extract certain information from person's moving lips. I am simply wondering if it's better to process frames independently and then try to model temporal dependency on feature level or rather use 3D convs to do that jointly. For alignment, I am using a procedure similar to this one: https://github.com/deepinsight/insightface/blob/cdc3d4ed5de14712378f3d5a14249661e54a03ec/python-package/insightface/utils/face_align.py#L42 with 5 landmarks from MTCNN face detector.
Answer: You are asking if a convolutional neural network would work with images that are distorted and contain noise. I'm afraid that the answer is "it depends". In some cases, with some kinds of distortions and noise, they will work, in some not. The only way to figure it out is to verify it empirically. If the data is noisy, you may need more data than in a non-noisy case for it to work. It may be worth spending some time on preprocessing to de-noise it. Another possible approach would be to use data augmentation to create more data, where you would use noise-free data to generate artificial samples with different kinds and degrees of noise so that your model has more data to learn to figure out signal from noise.

3D convolutions and jitter


Cyclic Product of the Integers?

Question: I have a question about the following group:
$\mathbf{Z}_{32}\times\mathbf{Z}_{164750}$.
I am examining this group as part of a problem classifying the number of isomorphism types of abelian groups with $2^{6}3^{3}5^{5}$ elements. My question is the following: is the group $\mathbf{Z}_{32}\times\mathbf{Z}_{164750}$ cyclic? How would one prove or disprove this?
I think that I may be overthinking this because of how large of a number $164750$ is. Thanks in advance for any help!
Comment: No, there is an obvious divisor common to both 32 and 164750. Therefore, your group is not cyclic.
Comment: Exactly. If gcd(m,n) = 1, then (1,1) has order mn in $Z_m \times Z_n$. Therefore the group is cyclic.
Comment: Also a minor thing, I think 168750 factors to $2^6*3^3*5^5$, not $164750$ (which factors to $2*5^3*659$). It's minor and doesn't really change the answer to your question, but just in case, since you're examining groups of order $2^63^35^5$.
Comment: I think you need gcd to be 1 for true, and false otherwise(2 is clearly common)
Comment: As in the group is cyclic if $gcd(32, 164750)=1$ and not cyclic otherwise?
Comment: @YunusSyed In other words, the group I am examining would not be cyclic?
Comment: @YunusSyed Thank you very much! That makes much more sense now!
Comment: @yandz Thank you very much! I hadn't caught that mistake.
Answer: $ Z_m × Z_n $ is cyclic group if and only if m and n are coprime that is $gcd(m, n) = 1$.
Clearly $gcd(32, 164750) ≠ 1$ (because factor 2 is common in both).
So given group is "not" cyclic!!

Cyclic Product of the Integers?


Understanding beta/tau in the SIR model of Infectious disease for COVID modeling

Question: Inspired by the SARS-CoV-2 pathogen and COVID-19, I am writing an agent-based simulation to allow the modeling of heterogeneous populations (e.g., some folks abide by quarantine, some resist, or some are more likely to die, some aren't).
Naturally, I want to be able to run a baseline model that approximates the traditional understanding of infection trajectories, and so I built in a function to set initial parameters based on the $R_0$ or doubling time in the SIR model. I'm having a really hard time interpreting and understanding the transmissibility term ($\tau$ in particular, which is a component of $\beta$).
I can set parameters on my current version to approximate the same peak and timeframe of the SIR model, but the actual trajectories of infected/susceptible/recovered during the infection are very different – so I need help better understanding this term.
SIR Equation for New Infections
Terms rearranged from https://code-for-philly.gitbook.io/chime/what-is-chime/sir-modeling
$I_{t+1} = I_t - \gamma*I_t + \beta*I_t*S_t$
Interpretation
(# infections tomorrow) = (#infections today) - (# infections recovered today) + (new infections today)
And New Infections = $\beta$ * (# infections today) (# Susceptible today)
And  $\beta = c * \tau$; or contacts x 'transmissibility'
c is easy enough: number of candidate contacts per day in which the infection could be spread.
Different sources describe tau and beta differently: infectivity, virulence, transmissibility…  $\tau$ is a characteristic of the pathogen that appears to be constant in the models I've looked at.  I can use existing formulas to calculate it from the doubling time and I can calculate it from the $R_0$ based on existing equations, but being able to calculate a value doesn't really mean anything.
Subterm interpretation
I * c = the total number of contacts-that-can-transmit-the-infection today. Makes sense, and c is a attribute of the individual and can be modified if, say, people socially distance.
tau: I want tau to be "the average likelihood of spread during an unprotected, meaningful social interaction."  That meets the other assumptions: it is a relatively constant attribute of the pathogen, or at least the pathogen given the current timeframe. I was considering building into the agent-based model the ability for tau to decrease during the summer as some estimate due to higher humidity. Regardless, tau changes universally for the entire susceptible population, it's still an attribute of the infection * context, not related to human behavior like c
So then the infection term (beta * I * S) equals (c*I) * tau * S, or  [infected contacts today] * [spread per contact] * [raw susceptible population]
That only seems to make sense if there is exactly one infected individual and the entire population is susceptible. Right, because this basically needs to break down to the percentage of the susceptible population that gets newly infected TODAY due to the current infection.
Consider a point on the upswing and downswing of the infection in which the same number of people are infected (I) and all the other assumptions are true:
Infection term during the upswing = c * tau * I * S_up
Infection term during the downswing = c * tau * I * S_down
The number of infected contacts (c) for the day are the same because the (unknowingly) infected people are doing all the same things.
Tau is constant because it's a characteristic of the pathogen or infection…
S is the only thing that differs. And it's not just that the susceptible population is different, but the chance that you are interacting with a susceptible individual is much less likely because everyone is already infected or already recovered. And this would sensibly change the trajectory of the infection over time.
It seems like in the (c * I) * tau * S equation, instead, the interpretation of tau is "the likelihood that any susceptible member of the population is infected by any contact that the infected person has," regardless of whether infected people actually are in contact with susceptible people. This seems to have a weird assumption that anyone susceptible is equally likely to become infected, even if other criteria make that unlikely. In practical terms, it includes me kissing the person behind the counter who already recovered and then kisses their partner who was never infected, who then gets it. And the implications of this are significant. Sure, fewer people get infected on the downswing because S_down < S_up, but it should be many fewer people because S_down < S_up AND a larger proportion of the c contacts are not candidate infections because they happen between people who cannot be infected.
Why isn't the equation something more like:
[I:infected people] * [c:contacts/day] * [tau:likelihood-of-infection/contact] * [P: proportion of contacts with susceptible people left in the population ]

What am I missing? I can't effectively set parameters in my agent-based simulation to approximate the general SIR equation until I can better understand this parameter.
Comment: "`Tau` is constant because it is a characteristic of the disease." Leaps out as a simplifying assumption, but not as reality: first, the *pathogen* causing a given disease varies in its infectiousness based on (1) environmental conditions, (2) host characteristics, (3) ecological relationships, (4) individual virus characteristics (e.g., genetic variation); second "the" *disease* is a generalization applied to a constellation of signs and symptoms, in the case of COVID-19 *none* of which *neccesarily* result from infection with SARS-CoV-2, many of which are common, many of which are not.
Comment: @Alexis,

You're totally right that I'm trying to encapsulate pathogen characteristics not "COVID-19". I'll update the post accordingly.

But otherwise, I did suggest in the original post that Tau incorporates the current context/timeframe and likely changes. So, it does account for virus characteristics and at least the macro environmental and ecological relationships (though this may depend on your unit of analysis).  For the case at hand, the important separation is that [B] is c * T, where [c] is a person*context characteristic and tau is a pathogen*context characteristic.
Answer:
I'm having a really hard time interpreting and understanding the transmissibility term ($\tau$ in particular,...

It looks to me like $\tau$ is a probability of infection per contact.
The number of transmissions per day per person is then binomially distributed. According to a parameter
$$\text{new infections per time} \sim \text{Binomial}( \underbrace{n=c \cdot I \cdot S}_{\substack{\llap{\text{number of contacts per time }}\rlap{\text{}} \\ \llap{\text{= contacts per infected }}\rlap{\text{per susceptible per time}}\\ \llap{\text{ $\times$ infected}}\rlap{\text{$\times$ susceptible}}}} \, , \,  \overbrace{p=\tau}^{\llap{\text{probability of infection}}\rlap{\text{ per contact}}})$$
(or can also be approximated with a Poisson distribution if $c$ is large and $ \tau$ is small)

The standard SIR model is not deterministic and it does not explicitly sample the binomial distribution in order to compute the results.
Instead, it uses the mean or mode of this distribution $\beta = c\tau$. Which is the most likely outcome. (see also https://en.wikipedia.org/wiki/Thermodynamic_limit)
This approach is correct in the limit, when the infected population is very large. E.g. when $n_I$ people will each infect other people according to a Poisson distribution with parameter $\beta$, the total number of infected people will be distributed according to a Poisson distribution with parameter $n_I \beta$ and the ratio of the standard deviation and mean of that distribution will shrink as $n_I$ is large. So the error becomes relatively small for large populations.

Why isn't the equation something more like:
[I:infected people] * [c:contacts/day] * [tau:likelihood-of-infection/contact] * [P: proportion of contacts with susceptible people left in the population ]

It is like that. Your parameter P, the proportion of susceptible people left, is accounted for by the term $S$
$$I_{t+1} = I_t - \gamma*I_t + \beta*I_t*S_t$$
you will also often see a division by $N$
$$I_{t+1} = I_t - \gamma*I_t + \beta*I_t*\underbrace{\frac{S_t}{N}}_{\llap{\text{proportion of susceptible}}\rlap{\text{ people left}}}$$
This division with $N$ might make the interpretation of parameters more logical, but it is mathamatically not neccesary (it is effectively just a scaling of the parameters).
It depends a bit on whether you see the $\beta$ as 'infections per infected per susceptible' or as 'infections per infected'.
Comment: Thank you - this is great and very helpful. And I understand that at the limit, the division of N may be insignificant - but for comparing models of the same N, it does have a very significant effect on the overall characteristics of the result over time.... It's going to significantly "widen" the distribution / slow the acceleration, right? (sorry about the terminology - you might call me an educational sociologist, programmer, or data scientist, but I'm definitely not a mathematician)....
Comment: And I guess I am thinking of $\tau$ as "infections per infected" - based on my description, $c * \tau * I_t$ is "[raw possible] infections per infected," but doesn't take into account the percent of the susceptible population at all.  So it does seem like I need to include $S_t/N$ to correct my equation, right?

Perhaps it's more appropriate for me to think of it as $I_t / N * \beta * S_t = I_t / N * \tau * c * S_t $, or `[the proportion of the population that is currently infected] * [infectible contacts per day] * [infections / infectible contact] * [remaining susceptible population]`
Comment: You can use a proportion but you don't need to. It depends on how you define $\beta$ as 'new infections per infected per susceptible per day' $$new = \beta \cdot I \cdot S$$ or 'new infections per infected per day' (in fully susceptible population)
$$new = \beta \cdot I \cdot \frac{S}{N} $$ or 'new infections per susceptible per day' (in fully infected population) $$new = \beta \cdot S \cdot \frac{I}{N}$$ in the first case the $\beta$ has a different dimension and different value (it is scaled by $N$). The third case is not so common. The first case might be most useful if $N$ isn't constant.
Comment: Thanks so much again! I've now been able to develop both the SIR model using the traditional equation and adapting the parameters to the agent-based model to arrive at similar outcomes - so I can now add in the additional features that led me down this route to begin with!

Thanks again!


How to fix the variable names in a simplenews subscription confirmation mail?

Question: I have a Simplenews subscription block for the anonymous users of my site. When they enter their name and email address and hit subscribe, a mail is sent to their email ID for confirmation. It is a single confirmation email.
When i see the mail it displays the variable names that i am using.
For eg :

1) The subject of the mail is Confirmation for !newsletter_name.
  2) please use the link below, then click "Subscribe" on the web page that
  will open: !confirm_subscribe_url

How can it be fixed?
Answer: I am guessing you upgraded from D6. The tokens you are using are D6 tokens.
Go to /admin/config/services/simplenews/settings/subscription and change the tokens. For instance, the default subject for D7 is :
<code>Confirmation for [simplenews-category:name] from [site:name]
</code>
Note the new (D7) token format. You can find he new tokens by expanding 'Replacement patterns'.


React.js and arrow functions vs normal functions

Question: I was working on a react.js app and I initially used the arrow function which worked, but then just out of curiosity I decided to try the normal function and the normal function didn't work. I think that they both should output the same thing, what is going wrong?
handleChange = event => this.setState({init: event.target.value})

handleChange(event){
  this.setState({init: event.target.value})
}

Comment: check the es version you are using.According to that you should use the syntax.If the necessary module missing it will gives and error
Answer: Arrow functions and normal function are not equivalent.
Here is the difference:

Arrow function do not have their own binding of this, so your this.setState refer to the YourClass.setState.
Using normal function, you need to bind it to the class to obtain Class's this reference. So when you call this.setState actually it refer to YourFunction.setState().

Sample Code
class FancyComponent extends Component {
    handleChange(event) {
        this.setState({ event }) // `this` is instance of handleChange
    }

    handleChange = (event) => {
        this.setState({ event }) // `this` is instance of FancyComponent
    }
}


Consulta com Hibernate erro could not get a field value by reflection

Question: Possuo duas entidades: Profissao e Especialidade. Quando eu selecionar a profissão, gostaria que ele me retornasse todas as especialidades que aquela determinada profissão possui.
Quando mando fazer a busca ele me gera o erro:
    Advertência:   #{administradorBean.selecionarProfissao()}: org.hibernate.PropertyAccessException: could not get a field value by reflection getter of modelo.Profissao.idProfissao
javax.faces.FacesException: #{administradorBean.selecionarProfissao()}: org.hibernate.PropertyAccessException: could not get a field value by reflection getter of modelo.Profissao.idProfissao
    at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:118)
    at javax.faces.component.UICommand.broadcast(UICommand.java:315)
    at javax.faces.component.UIData.broadcast(UIData.java:1108)
    at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
    at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
    at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:658)
    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
    at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:416)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:283)
    at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
    at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:206)
    at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:180)
    at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
    at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:283)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:200)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:132)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:111)
    at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
    at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:536)
    at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:591)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:571)
    at java.lang.Thread.run(Thread.java:748)
Caused by: javax.faces.el.EvaluationException: org.hibernate.PropertyAccessException: could not get a field value by reflection getter of modelo.Profissao.idProfissao
    at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:101)
    at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
    ... 36 more
Caused by: org.hibernate.PropertyAccessException: could not get a field value by reflection getter of modelo.Profissao.idProfissao
    at org.hibernate.property.DirectPropertyAccessor$DirectGetter.get(DirectPropertyAccessor.java:60)
    at org.hibernate.tuple.entity.AbstractEntityTuplizer.getIdentifier(AbstractEntityTuplizer.java:346)
    at org.hibernate.persister.entity.AbstractEntityPersister.getIdentifier(AbstractEntityPersister.java:4740)
    at org.hibernate.persister.entity.AbstractEntityPersister.isTransient(AbstractEntityPersister.java:4459)
    at org.hibernate.engine.internal.ForeignKeys.isTransient(ForeignKeys.java:243)
    at org.hibernate.engine.internal.ForeignKeys.getEntityIdentifierIfNotUnsaved(ForeignKeys.java:293)
    at org.hibernate.type.EntityType.getIdentifier(EntityType.java:510)
    at org.hibernate.type.ManyToOneType.nullSafeSet(ManyToOneType.java:174)
    at org.hibernate.param.NamedParameterSpecification.bind(NamedParameterSpecification.java:67)
    at org.hibernate.loader.hql.QueryLoader.bindParameterValues(QueryLoader.java:613)
    at org.hibernate.loader.Loader.prepareQueryStatement(Loader.java:1900)
    at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1861)
    at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1838)
    at org.hibernate.loader.Loader.doQuery(Loader.java:909)
    at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:354)
    at org.hibernate.loader.Loader.doList(Loader.java:2551)
    at org.hibernate.loader.Loader.doList(Loader.java:2537)
    at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2367)
    at org.hibernate.loader.Loader.list(Loader.java:2362)
    at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:496)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:387)
    at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:229)
    at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1260)
    at org.hibernate.internal.QueryImpl.list(QueryImpl.java:103)
    at DAO.ProfissaoDAO.carregarEspecialidade(ProfissaoDAO.java:56)
    at bean.AdministradorBean.selecionarProfissao(AdministradorBean.java:173)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at javax.el.ELUtil.invokeMethod(ELUtil.java:332)
    at javax.el.BeanELResolver.invoke(BeanELResolver.java:537)
    at javax.el.CompositeELResolver.invoke(CompositeELResolver.java:256)
    at com.sun.el.parser.AstValue.invoke(AstValue.java:283)
    at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:304)
    at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
    at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
    ... 37 more
Caused by: java.lang.IllegalArgumentException: Can not set java.lang.Integer field modelo.Profissao.idProfissao to java.lang.Integer
    at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:167)
    at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:171)
    at sun.reflect.UnsafeFieldAccessorImpl.ensureObj(UnsafeFieldAccessorImpl.java:58)
    at sun.reflect.UnsafeObjectFieldAccessorImpl.get(UnsafeObjectFieldAccessorImpl.java:36)
    at java.lang.reflect.Field.get(Field.java:393)
    at org.hibernate.property.DirectPropertyAccessor$DirectGetter.get(DirectPropertyAccessor.java:57)
    ... 73 more

Grave:   javax.faces.el.EvaluationException: org.hibernate.PropertyAccessException: could not get a field value by reflection getter of modelo.Profissao.idProfissao
    at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:101)
    at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
    at javax.faces.component.UICommand.broadcast(UICommand.java:315)
    at javax.faces.component.UIData.broadcast(UIData.java:1108)
    at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
    at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
    at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:658)
    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
    at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:416)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:283)
    at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
    at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:206)
    at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:180)
    at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
    at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:283)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:200)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:132)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:111)
    at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
    at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:536)
    at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:591)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:571)
    at java.lang.Thread.run(Thread.java:748)
Caused by: org.hibernate.PropertyAccessException: could not get a field value by reflection getter of modelo.Profissao.idProfissao
    at org.hibernate.property.DirectPropertyAccessor$DirectGetter.get(DirectPropertyAccessor.java:60)
    at org.hibernate.tuple.entity.AbstractEntityTuplizer.getIdentifier(AbstractEntityTuplizer.java:346)
    at org.hibernate.persister.entity.AbstractEntityPersister.getIdentifier(AbstractEntityPersister.java:4740)
    at org.hibernate.persister.entity.AbstractEntityPersister.isTransient(AbstractEntityPersister.java:4459)
    at org.hibernate.engine.internal.ForeignKeys.isTransient(ForeignKeys.java:243)
    at org.hibernate.engine.internal.ForeignKeys.getEntityIdentifierIfNotUnsaved(ForeignKeys.java:293)
    at org.hibernate.type.EntityType.getIdentifier(EntityType.java:510)
    at org.hibernate.type.ManyToOneType.nullSafeSet(ManyToOneType.java:174)
    at org.hibernate.param.NamedParameterSpecification.bind(NamedParameterSpecification.java:67)
    at org.hibernate.loader.hql.QueryLoader.bindParameterValues(QueryLoader.java:613)
    at org.hibernate.loader.Loader.prepareQueryStatement(Loader.java:1900)
    at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1861)
    at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1838)
    at org.hibernate.loader.Loader.doQuery(Loader.java:909)
    at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:354)
    at org.hibernate.loader.Loader.doList(Loader.java:2551)
    at org.hibernate.loader.Loader.doList(Loader.java:2537)
    at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2367)
    at org.hibernate.loader.Loader.list(Loader.java:2362)
    at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:496)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:387)
    at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:229)
    at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1260)
    at org.hibernate.internal.QueryImpl.list(QueryImpl.java:103)
    at DAO.ProfissaoDAO.carregarEspecialidade(ProfissaoDAO.java:56)
    at bean.AdministradorBean.selecionarProfissao(AdministradorBean.java:173)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at javax.el.ELUtil.invokeMethod(ELUtil.java:332)
    at javax.el.BeanELResolver.invoke(BeanELResolver.java:537)
    at javax.el.CompositeELResolver.invoke(CompositeELResolver.java:256)
    at com.sun.el.parser.AstValue.invoke(AstValue.java:283)
    at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:304)
    at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
    at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
    ... 37 more
Caused by: java.lang.IllegalArgumentException: Can not set java.lang.Integer field modelo.Profissao.idProfissao to java.lang.Integer
    at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:167)
    at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:171)
    at sun.reflect.UnsafeFieldAccessorImpl.ensureObj(UnsafeFieldAccessorImpl.java:58)
    at sun.reflect.UnsafeObjectFieldAccessorImpl.get(UnsafeObjectFieldAccessorImpl.java:36)
    at java.lang.reflect.Field.get(Field.java:393)
    at org.hibernate.property.DirectPropertyAccessor$DirectGetter.get(DirectPropertyAccessor.java:57)
    ... 73 more

Classe Profissao
    @Entity
@Table(name = "profissao")
@XmlRootElement
@NamedQueries({
    @NamedQuery(name = "Profissao.findAll", query = "SELECT p FROM Profissao p")
    , @NamedQuery(name = "Profissao.findByIdProfissao", query = "SELECT p FROM Profissao p WHERE p.idProfissao = :idProfissao")
    , @NamedQuery(name = "Profissao.findByNomeProfissao", query = "SELECT p FROM Profissao p WHERE p.nomeProfissao = :nomeProfissao")})
public class Profissao implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "idProfissao")
    private Integer idProfissao;
    @Size(max = 45)
    @Column(name = "nomeProfissao")
    private String nomeProfissao;
    @JoinTable(name = "profissional_has_profissao", joinColumns = {
        @JoinColumn(name = "Profissao_idProfissao", referencedColumnName = "idProfissao")}, inverseJoinColumns = {
        @JoinColumn(name = "Profissional_idProfissional", referencedColumnName = "idProfissional")})
    @ManyToMany
    private List<Profissional> profissionalList;
    @OneToMany(cascade = CascadeType.ALL, mappedBy = "idProfissao")
    private List<Especialidade> especialidadeList;

    public Profissao() {
    }

    public Profissao(Integer idProfissao) {
        this.idProfissao = idProfissao;
    }

    public Integer getIdProfissao() {
        return idProfissao;
    }

    public void setIdProfissao(Integer idProfissao) {
        this.idProfissao = idProfissao;
    }

    public String getNomeProfissao() {
        return nomeProfissao;
    }

    public void setNomeProfissao(String nomeProfissao) {
        this.nomeProfissao = nomeProfissao;
    }

    @XmlTransient
    public List<Profissional> getProfissionalList() {
        return profissionalList;
    }

    public void setProfissionalList(List<Profissional> profissionalList) {
        this.profissionalList = profissionalList;
    }

    @XmlTransient
    public List<Especialidade> getEspecialidadeList() {
        return especialidadeList;
    }

    public void setEspecialidadeList(List<Especialidade> especialidadeList) {
        this.especialidadeList = especialidadeList;
    }

Classe Especialidade
    @Entity
@Table(name = "especialidade")
@XmlRootElement
@NamedQueries({
    @NamedQuery(name = "Especialidade.findAll", query = "SELECT e FROM Especialidade e")
    , @NamedQuery(name = "Especialidade.findByIdEspecialidade", query = "SELECT e FROM Especialidade e WHERE e.idEspecialidade = :idEspecialidade")
    , @NamedQuery(name = "Especialidade.findByTipoEspecialidade", query = "SELECT e FROM Especialidade e WHERE e.tipoEspecialidade = :tipoEspecialidade")})
public class Especialidade implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "idEspecialidade")
    private Integer idEspecialidade;
    @Size(max = 45)
    @Column(name = "tipoEspecialidade")
    private String tipoEspecialidade;
    @JoinColumn(name = "idProfissao", referencedColumnName = "idProfissao")
    @ManyToOne(optional = false)
    private Profissao idProfissao;

    public Especialidade() {
    }

    public Especialidade(Integer idEspecialidade) {
        this.idEspecialidade = idEspecialidade;
    }

    public Integer getIdEspecialidade() {
        return idEspecialidade;
    }

    public void setIdEspecialidade(Integer idEspecialidade) {
        this.idEspecialidade = idEspecialidade;
    }

    public String getTipoEspecialidade() {
        return tipoEspecialidade;
    }

    public void setTipoEspecialidade(String tipoEspecialidade) {
        this.tipoEspecialidade = tipoEspecialidade;
    }

    public Profissao getIdProfissao() {
        return idProfissao;
    }

    public void setIdProfissao(Profissao idProfissao) {
        this.idProfissao = idProfissao;
    }

ProfissaoDAO
public List<Especialidade> carregarEspecialidade(Profissao profissao){
    List<Especialidade> listaEspecialidade;
    Session session = HibernateUtil.getSessionFactory().openSession();
    String sql = "from Especialidade e WHERE e.idProfissao like :id";
    listaEspecialidade = session.createQuery(sql).setParameter("id", profissao.getIdProfissao()).list();
    session.close();

    return listaEspecialidade;
}

Answer: Tente mudar o setParameter de ProfissaoDAO para:
String sql = "from Especialidade e WHERE e.idProfissao = :id";
listaEspecialidade = session.createQuery(sql).setParameter("id", profissao).list();

Comment: Opa Marcus, tentei mas continua a dá erro: javax.el.ELException: /admin.xhtml @56,88 value="#{administradorBean.listaEspecialidade}": org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: modelo.Profissao
Comment: Vc setou algo na instância Profissao? Ele está dizendo que algo dessa entidade não foi persistido no BD.
Comment: Desculpe, fiz uma alteração no seu sql tb. Tente novamente, por favor.
Answer: Acabei conseguindo resolver da seguinte maneira:
public List<Especialidade> carregarEspecialidade(Profissao profissao){
        List<Especialidade> listaEspecialidade;
        Session session = HibernateUtil.getSessionFactory().openSession();
        String sql = "from Especialidade e WHERE e.idProfissao.id = :id"; // adicionado o .id para retornar o id
        listaEspecialidade = session.createQuery(sql).setParameter("id", profissao.getIdProfissao()).list();
        session.close();

        return listaEspecialidade;
    }

Qualquer dúvida, só consultar:
http://www.mograblog.com/2010/09/javax-persistence-persistence-exception-org-hibernate-property-access-exception-could-not-get-a-field-value-by-reflection-getter.html


Apply CSS to Angular directives (custom or not) with native handle

Question: Let say I have a Angular app with directives like so:
<!doctype html>

    ...

How do I apply CSS to a directive using the Angular directive handle ui-view or any other custom directive, without adding an HTML ID handle.   SO for the "main" section, I dont want the following:
.
I have tried .ui-view#main and ui-view#main.
Answer: If I understand correctly, you want to use the angular directive ui-view as identifier in your CSS?
In your CSS file, you could potentially use
div[ui-view=main] {
    /* styles for main go here, duh! */
}

Seems to work in Chrome (http://plnkr.co/edit/r1fvheUs8S6AJHv4Dm59?p=preview)
If you want conditional styles, you should use


Every infinite recursive set has a recursively enumerable subset which is not recursive.

Question: Is the above statement true? If so, how do I go about proving it?
Another thing: Given two recursively enumerable sets $Q_1$,$Q_2$, I want to prove that $Q_1\backslash Q_2$ isn't necessarily recursively enumerable.
I assume that for this I need the complement of $Q_2$ to be not recursively enumerable, but could someone give a concrete example/way of of constructing a set such that I can prove my claim.
Thank you in advance.
Comment: @see: it is customary jargon to talk about r.e. and recursive *languages* rather than sets when modelling computation with Turing machines, because Turing machines take as their input finite strings of symbols. I imagine you are working with partial recursive functions on the natural numbers. The two approaches are equivalent (see https://en.wikipedia.org/wiki/Μ-recursive_function).
Comment: Quibble: you want to restrict attention to **infinite** recursive sets, otherwise e.g. $\{17\}$ is a counterexample. :P
Comment: @RobArthan: You're totally right, I mixed up recursive and r.e.
Answer: Hint for the first question: you can assume w.l.o.g. that the recursive set is $\Bbb{N}$ (and the question needs qualifying: finite sets are recursive sets that have no non-recursive subsets, so the recursive set has to be infinite).
Hint for the second question: you can get a counter-example in which $Q_1 = \Bbb{N}$.
Both questions reduce to finding an r.e. subset of $\Bbb{N}$ that is not recursive.
If you need more details, then you need to provide some more information about what you've tried so we can know what techniques you are familiar with.
Comment: How does your first hint work?  Isn't the empty set recursive?
Comment: I was trying to jog your memory with examples of r.e. sets that are not recursive that you might have studied already. If you don't know how to prove that such sets exist, then you won't be able to prove either of the results you are asking about.
Comment: @cardboard_box: yes, thanks, good point. The first question requires the recursive set to be infinite. I've pointed this out in my answer.
Comment: @cardboard_box: I don't understand your second comment.
Comment: @Rob Arthan Got the second one thanks to your hint. Regarding the first question: I clarified the title.
Comment: @Rob Arthan Well I know that an infinite subset of the natural numbers has uncountably many subsets, but of those only countably many can be recursive or recursively enumerable. Also by w.l.o.g. you mean using a bijection between the (number-)space $\mathbb{N}^k$ I'm in and the natural numbers?
Comment: The reason you need the recursive set to be infinite is that every finite set is recursive. (You are right that an argument about the uncountability of $\Bbb{P}(\Bbb{N})$ is not useful here.) By "w.l.o.g." I meant that given an inifinite recursive set $X$, there is an effective bijection between $\Bbb{N}$ and $X$. If you can produce a non-r.e. subset of $\Bbb{N}$, then its image under that bijection is a non-r.e. subset of $X$.
Comment: @Rob Arthan I could use a recursive, injective function $f: \mathbb{N}\rightarrow\mathbb{N}$ which isn't strictly monotonically increasing and consider its image (which has to be infinite). It won't be recursive, but recursively enumerable. But for this I need said function.
Comment: Try a function that enumerates Indices of partial recursive functions that are defined at $0$ or a function that enumerates the Goedel numbers of sentences provable in PA.
Comment: @Rob Arthan Hm I didn't consider that I would also have to prove that my set isn't the image of another, possibly strictly monotonically increasing recursive function in my last comment. I'm sorry, but I don't understand your last comment. Seems a bit too advanced for me at the moment.
Comment: @Rob Arthan Alright then. Thank you anyway.


Convert system of second order PDEs to a system of first order PDEs

Question: I am attempting so convert
$$H_t = D_H H_{xx} - vH_x - \alpha H Z$$
$$Z_t = D_Z Z_{xx} + \beta H Z $$
into a system of first order equations. $D_H$, $D_Z$, $\alpha$ and $v$ are constants and $H$ and $Z$ describe the population of humans and zombies which interact as with the equations above.
Following the post from Harry49 in >>here<< I first tried to rewrite the equations as a linear system of balance laws $\mathbf{q_t + A ~ q_x = S ~ q}$ where $\mathbf{q}$ = $(H, H_x, H_t, Z, Z_x, Z_t)^T$.
This gives me
$$\begin{bmatrix} H_t \\ H_{xt} \\ H_{tt} \\ Z_t \\ Z_{xt} \\ Z_{tt} \end{bmatrix} + \mathbf{A} \begin{bmatrix} H_x \\ H_{xx} \\ H_{tx} \\ Z_x \\ Z_{xx} \\ Z_{tx} \end{bmatrix}  = \mathbf{S} \begin{bmatrix} H \\ H_{x} \\ H_{t} \\ Z \\ Z_{x} \\ Z_{t} \end{bmatrix}$$
My next step would be to determine the coefficients of the matrices $\mathbf{A}$ and $\mathbf{S}$, which is where I get confused due to the coefficients that couple the equations. I am not even sure if the approach I chose is a legitimate one for my kind of problem and would appreciate any kind of help!
Thank you very much!
Answer: The basic idea is to introduce new variables $X = H_x$, $Y = Z_x$, that gives directly:
$$
H_t = D_H X_x - v H_x - \alpha H Z \\
X   = H_x \\
Z_t = D_Z Y_x + \beta H Z \\
Y   = Z_x
$$
Comment: @ViennaFormulaTeam Since your system is not hyperbolic, you will not get directly a linear system of balance laws. However, you may be able to do so by introducing a small parameter $\epsilon > 0$ such that $\epsilon X_t + X = H_x$ and $\epsilon Y_t + Y = Z_x$, and then take the limit $\epsilon \to 0$.


Passing a method that return a bool value into a while loop

Question: C# question:
I have a method A(string) that returns a true or false.
I am running a while loop running until method(string) returns true.
The problem is I have these while loops all over the place.
How can I have a single while loop method and pass in the method(string) from anywhere?
Any suggestions would be greatly appreciated. Thanks!!
Comment: Please don't describe your code, *show* it in the form or a [mre] (with emphasis on the minimal part). Also please take some time to read [the help pages](http://stackoverflow.com/help), take the SO [tour], read [ask], as well as [this question checklist](https://codeblog.jonskeet.uk/2012/11/24/stack-overflow-question-checklist/). And please learn how to [edit] your questions to improve them.
Comment: ok thanks will keep that in mind for future posts
Answer: You can use Func<string, bool> as Parameter, please check following code:
<code>internal class Program
{
    private static void Main()
    {
        ManyWhiles1(A);
        ManyWhiles2(A);
    }

    private static bool A(string input)
    {
        return (input == "abc");
    }

    private static void ManyWhiles1(Func<string, bool> a)
    {
        string input = "abc";
        while (a(input))
        {
            Console.WriteLine("Working ...");
        }

        while (a(input))
        {
            Console.WriteLine("Working ...");
        }
    }

    private static void ManyWhiles2(Func<string, bool> a)
    {
        string input = "abc";
        while (a(input))
        {
            Console.WriteLine("Working ...");
        }

        while (a(input))
        {
            Console.WriteLine("Working ...");
        }
    }
}
</code>
Comment: Code-only answers without any kind of explanation about how it solves the problem being asked about, and what the problem actually was, are highly discouraged as they tend to lead to [cargo cult programming](https://en.wikipedia.org/wiki/Cargo_cult_programming). Please take some time to refresh [how to write good answers](https://stackoverflow.com/help/how-to-answer).


How to mock a method of the controller under test in grails 3.3.8

Question: I have a private method in the controller under test that I've exercised and just want to mock in further tests. In grails 2.3.4 the following code worked:
<code>controller.metaClass.method = { a, b -> 'value' }
</code>
But in grails 3.3.8 this doesn't seem to have an effect, and it uses the actual controller method. How do I mock this in grails 3.3.8?
Answer: I finally found a bit of info here:
groovy per instance metaClass method override doesnt work as expected in spock test
and the linked bug report:
https://issues.apache.org/jira/browse/GROOVY-7368.
I tried adding types to the params which didn't seem very groovy and didn't make a difference anyway.
Removing 'private' from the method did allow the metaClass mocking to work and the testcase to pass. I'm not real fond of that solution but right now it's all I've got.


On Ajax submit, vars added in preprocess are lost

Question: I'm currently working on a D8 project and I'm displaying a node edit form in a block. I use template_preprocess_table in order to pass some parameters to my
theme but when I submit the form using ajax the form is reloaded and the parameters are lost so I don't get the correct form format.
Update:
In my MYTHEME.theme file:
function MYTHEME_preprocess_table(&$variables) {

  if($variables['attributes']['id'] == 'field-completion-milestones-values'){
    $element = $variables['rows'];
    foreach( $element as $key => $milestones){
      $completion_milestone = $milestones['cells'][1]['content'];

      if(isset($completion_milestone['field_milestone'])){

        $milestone_id = $completion_milestone['field_milestone']['widget']['#default_value'][0];
        $default_completion_milestone = array('name' => $milestone_id);
        $type_id = milestoneGetTypeId($default_completion_milestone);
        if($type_id == 156) {//Milestones with links - create button
          $variables['rows'][$key]['cells'][1]['content']['test_button'] = TRUE;
        }
        else if($type_id == 155){//Milestones with upload document button
          $variables['rows'][$key]['cells'][1]['content']['test_upload'] = TRUE;
        }
        else if($type_id == 154){//Milestones without link or upload buttons
          $variables['rows'][$key]['cells'][1]['content']['test_plain'] = TRUE;
        }
      }
    }
  }
}

And in my table.html.twig file:
{% set milestone_id = cell.content.field_milestone['widget']['#default_value'][0] %}
{% if(milestone_id) %}

      {{ cell.content.field_milestone['widget']['#options'][milestone_id] }}
        D
        {% if cell.content.field_tip['widget'][0]['value']['#default_value'] %}
            ?
        {% endif %}
        {% if cell.content.test_button %}
             {% set custom_url = cell.content.field_url['widget'][0]['uri']['#default_value'] %}
             {% if cell.content.field_url['widget'][0]['title']['#default_value'] %}
                 {% set link_text = cell.content.field_url['widget'][0]['title']['#default_value'] %}
             {% else %}
                 {% set link_text = cell.content.field_url['widget'][0]['uri']['#default_value'] %}
             {% endif %}
             {{ link_text }}
        {% endif %}
        {% if cell.content.test_upload %}
             {{ cell.content.field_milestone_completion_up }}
        {% endif %}

           {{ cell.content.field_delivery_status }}

{% endif %}

My form submit function:
public static function ajaxFormEntityFormSubmit($form, &$form_state) {
    $entity = $form_state->getBuildInfo()['callback_object']->getEntity();

    // Clear user input.
    $input = $form_state->getUserInput();
    // We should not clear the system items from the user input.
    $clean_keys = $form_state->getCleanValueKeys();
    $clean_keys[] = 'ajax_page_state';
    foreach ($input as $key => $item) {
      if (!in_array($key, $clean_keys) && substr($key, 0, 1) !== '_') {
        unset($input[$key]);
      }
    }

    // Store new entity for display in the AJAX callback.
    $input['entity'] = $entity;
    $form_state->setUserInput($input);

    // Rebuild the form state values.
    $form_state->setRebuild();
    $form_state->setStorage([]);
  }

And my callback:
public static function ajaxFormEntityCallback(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
    // If errors, returns the form with errors and messages.
    if ($form_state->hasAnyErrors()) {
      return $form;
    }
    // Else show the result.
    else {
      $userInputs = $form_state->getUserInput();
      $entity = $userInputs['entity'];
      $entity_type = $entity->getEntityTypeId();
      $configurations = $form_state->getValue('ajax_form_entity');

      $response = new AjaxResponse();

      // Get messages even if not shown.
      $status_messages = array('#type' => 'status_messages');
      $message = \Drupal::service('renderer')->renderRoot($status_messages);

      // Reload the form.
        $response->addCommand(new ReplaceCommand($configurations['form_selector'], $form));

      return $response;
    }
  }

In my hook_form_alter :
    $form['#attributes']['class'][] = $ajax_id;
    $form['actions']['submit']['#submit'][] = 'Drupal\MY_MODULE\Plugin\Form\FormAlter::ajaxFormEntityFormSubmit';
    $form['actions']['submit']['#ajax'] = array(
      'callback' => 'Drupal\MY_MODULE\Plugin\Form\FormAlter::ajaxFormEntityCallback',
      'wrapper' => $ajax_id,
      'effect' => 'fade',
    );
    $form['ajax_form_entity'] = [
      '#type' => 'hidden',
      '#value' => [
        'reload' => '.reload',
        'form_selector' => '.' . $ajax_id,
        'show_message' => TRUE,
      ]
    ];

What I'm doing is to show/hide fields from a field collection field based on a taxonomy term value. Maybe this is not the best solution but I didn't find any other way to solve my problem.
Is it possible to store those vars somehow after ajax submit?
Thanks in advance.
Comment: Paste the whole code, this is not enough information to give nay advice.
Comment: The AJAX are in the form? Which extends FormBase? Something seems off here.
Comment: @Kevin what do you mean? This code works fine for the rest of my forms but when it reloads the form with those hidden fields I have the problem. I  guess that it has to do with the prepossessing as seems like the vars I set are empty when the form reloads.
Comment: @Kevin the form is not just a custom form but a node edit form placed in a custom block.
Answer: I managed to solve this without using template_preprocess_table. Instead I used created a custom module where I extend the twig in oder to have access to a function in my PHP. In my Twig I call that function and I get as a return the values so as I can display properly the fields needed.


Exception creating JSON with LINQ

Question: I am trying to create JSON with the following code:
JArray jInner = new JArray("document");
JProperty jTitle = new JProperty("title", category);
JProperty jDescription = new JProperty("description", "this is the description");
JProperty jContent = new JProperty("content", content);
jInner.Add(jTitle);
jInner.Add(jDescription);
jInner.Add(jContent);

when I get to the jInner.Add(jTitle), I get the following exception:
System.ArgumentException: Can not add Newtonsoft.Json.Linq.JProperty to Newtonsoft.Json.Linq.JArray.
   at Newtonsoft.Json.Linq.JContainer.ValidateToken(JToken o, JToken existing)
   at Newtonsoft.Json.Linq.JContainer.InsertItem(Int32 index, JToken item, Boolean skipParentCheck)
   at Newtonsoft.Json.Linq.JContainer.AddInternal(Int32 index, Object content, Boolean skipParentCheck)

Can anybody help and tell me what am I doing wrong?
Comment: If my answer isn't what you're looking for, please give an example of the JSON you're trying to produce.
Answer: It doesn't make sense to add a property to an array. An array consists of values, not key/value pairs.
If you want something like this:
[ {
  "title": "foo",
  "description": "bar"
} ]

then you just need an intermediate JObject:
JArray jInner = new JArray();
JObject container = new JObject();
JProperty jTitle = new JProperty("title", category);
JProperty jDescription = new JProperty("description", "this is the description");
JProperty jContent = new JProperty("content", content);
container.Add(jTitle);
container.Add(jDescription);
container.Add(jContent);
jInner.Add(container);

Note that I've removed the "document" argument from the JArray constructor call too. It's not clear why you had it, but I strongly suspect you don't want it. (It would have made the first element of the array the string "document", which would be fairly odd.)

Exception creating JSON with LINQ


Unity2D: instantiating multiple prefabs

Question: I have a composite prefab with multiple sprites and a script attached to it. The problem is, when I instantiate it more than once, the instances go crazy:

Their position on the screen is partly OK and partly determined by the prefab's setup in the editor. But Debug.Log reveals that the transform.position variable is set to the same value for all the instances. (It's the value that was used by the last instantiation.)
Their script, when accessed by GetComponent<>, behaves strangely. It doesn't access some members correctly. (Complicated to define.)

Here is a function that instantiates the prefab:
private GameObject SpawnEntity(GameObject p, Vector2 coords)
    {
        Instantiate(p);
        ...
        p.transform.position = coords;
        return p;
    }

It is called like this:
public GameObject humanoid;
...
SpawnEntity(humanoid, new Vector2(-1,-3));

The Unity version is 2018.2.1f1.
Answer: The problem is that you are changing the position of the referenced Gameobject, not the instantiated object. You need to create a new reference to the instantiated object like so:
private GameObject SpawnEntity(GameObject p, Vector2 coords)
    {
        Gameobject myobj = Instantiate(p);
        ...
        myobj.transform.position = coords;
        return myobj;
    }

I imagine this will solve number 2 as well if you are using GetComponent on the returned object, since you were previously returning the original prefab and not the instantiated object.
Comment: It works! Thank you, I can't believe how it was simple!
Comment: I'd like to, but am afraid I have not enough community points for this option. I don't see a button for it anyway.

Unity2D: instantiating multiple prefabs