letting my app talk to google assistant in google home

Question: I have developed an android app that consumes an API. It plays music each time the API sends a request to the app. I want to install this app on the Google home device, In other words, I want the google home device to play the music whenever it receives a request from the API...How can I do that?
Comment: As far as I know, you can't install apps on a Google Home device. You can develop actions which is very different from developing an android app.
Comment: You can't proactively invoke actions on a Google Home through a developer API.
Comment: I read about actions, but the problem is that the action is invoked with voice command...I need to invoke the action from a request from the API...Is that possible? Thank you
Answer: What you're trying to do has a number of problems, and a few involved with your perception of how things work on a Home device and with the Assistant.

The Google Home doesn't run Android, and you can't "install" your app on it. In fact, you don't "install" apps on a Home device at all. Instead, they act more like a web browser and access their Actions that run in the cloud.
The Assistant platform and Actions on Google are mostly conversation driven, and primarily driven by the user initiating the conversation. Notifications are fairly limited. This is to put users in control.
However, Home devices are also Cast enabled devices. So you may be able to have your mobile device be triggered through the API, and have it issue a Cast command to the device begin playback. There are restrictions on how you can initiate casting from a mobile device, however, so this may not be a good solution in your case.


Externalizing route paths using react-router

Question: I have a simple React Router Handler:
var routes = (
    <Route name="main" path="/" handler={require('./main')}>
        <Route name="page1" path="/page1" handler={require('./page1')}/>
        <Route name="page2" path="/page2" handler={require('./page2')}/>
        <Route name="page3" path="/page3" handler={require('./page3')}/>

        <DefaultRoute handler={require('./signin')}/>
    </Route>
);

I'd like to externalize the page1, page2, page3 properties in a separate file (say a json file) and iterate that within the routes. Something like this:
var routes = (
  <Route name="main" path="/" handler={require('./main')}>
    _.each (routes, function(r) {
      <Route name={r.name} path={r.path} handler={require(r.module)}/>
    });

    <DefaultRoute handler={require('./main')}/>
  </Route>
);

Obviously I cannot have such a construct within routes, what is the React way of achieving this?
Or is there a way to alter the routes via an api?
For eg:
routes.addRoute({name: r.name, path: r.path, handler: r.module}) ?

Answer: react-router just added top-level API for defining routes without JSX in version 0.12.2:
Router.createRoute()
Router.createDefaultRoute()
Router.createNotFoundRoute()
Router.createRedirect()

The doc annotations in the Route.js source and the detailed commit note are probably the best places to look while you wait until official docs and examples appear.
Answer: I think you should be able to do it with jsx, but there is an error in your jsx syntax. Try this:
var routes = (
  <Route name="main" path="/" handler={require('./main')}>
    {
     _.each (routes, function(r) {
         return <Route name={r.name} path={r.path} handler={require(r.module)}/>;
     });
    }
    <DefaultRoute handler={require('./main')}/>
  </Route>
);

Comment: Thank you, that syntax did the trick. Though I had to do a slight fix to my original code, because Browserify cannot load require module dynamically (it does static analysis).

See http://stackoverflow.com/questions/26434214/require-in-browserify-doesnt-work-variable-name.

So final syntax is handler={r.module}, where r.module = require('page1')


How to keep Drupal site code in version control in sync with production code when using drush updates on servers?

Question: I have 50 D7 sites I support (none are multisite). We do local development for changes to themes and modules tied to new functionality and bug fixes. Once the update works locally, we check that into git and use automation to push changes to our test servers.
Security and core updates tend to be run directly on our test and production sites using  drush upc --security-only
How can I keep our git repo in sync with the state of production code?
I can request a dump of production code and use a difftool to compare that to the latest commit and then apply those updates to the git repo code and commit, but is there a better way to do this?
Comment: After the security or core update just commit the changes and push them to your origin... you can also use GIT on your server just like you do locally. When you are back on your local environment, just perform a git pull and a drush dbup. That should do the trick.
Answer: You really have two options:

Assuming you are deploying code to your test server by cloning your code base from a service like github then you can always go in the reverse direction for security patches. You can patch your test servers (or even Prod, though thats not recommended) directly, commit the patched changes to your local git repo on your test server and then push that commit to your remote repo on github. On your local development server you can now pull from your remote git repo on github and everything is in sync.
Alternatively (and probably less optimal) you can patch your code on your test server directly AND you can simultaneously apply the same patch to your local code base. This way the same changes should be made in both places. This method is DEFINITLY not as good because it makes A LOT of assumptions about how well you are keeping everything in sync, but it can work.


How can I pass a member function instead of a function in this situation?

Question: I am using an object within a class for its functionalities. The header of this object's class definition contains a typedef, then the class declaration :
typedef void (*Foo)(int arg);
class Bar
{private : double func(Foo f){};}

In my class, I want to create a member function to pass it to func :
class myClass
{
private :
    Bar bar;
    void my_func(int arg);
    void my_caller();
};

In the .cpp :
void myClass::my_caller()
    {
        bar.func(&myClass::my_func);
    }

which returns an error "no matching function for call to Bar::func...".
My understanding is that the type used in the typedef is not "pointer to member function" but "pointer to function". I think I have to change this typedef to change this, but I don't know how.
I am an absolute beginner at C++, so I might be way off track here.
EDIT :
I understand the change I have to bring to the typedef to make a pointer to member function instead. The problem is that this typedef is in a distinct header file, so the compiler returns "'myClass' has not been declared".
Instead, I am going to look into functors and the std::function library.
Comment: I'm not sure what exactly your question is.
Comment: The typedef is a pointer to function, not pointer to member function, beside that I don't see the reason why you want to pass a pointer to member function, why not pass an instance of the class?
Comment: I've edited the title to mention what I'm trying to do.
Comment: The answer to your title is: You can't.
Comment: But the typedef is in the Bar class header file, and I don't know how to write it to take in account the class of the member function.
Comment: Not even by modifying the typedef?
Comment: In general, things get easier if you use `std::function` instead of function pointers.
Comment: @Jans my understanding is that would require me to alter the .cpp of the Bar class, which I don't want to do because it would take time and the class would become too specific to this application.
Answer: A pointer to a function and a pointer to a member function are two different things.  Because the function in question is a member of myClass, the correct function pointer type is:
typedef void (myClass::*Foo)(int arg);


The probability of drawing 7 red balls from an urn containing a total of 10 balls

Question: The urn contains 10 balls, 3 of which are blue and 7 red. Two are arbitrarily drawn from the urn. The task is to calculate the probability of both balls being red. I know nothing about combinations and permutations, so my approach was to start by listing the balls:
$$B_1, B_2, B_3, R_1, R_2, R_3, R_4, R_5, R_6, R_7 \tag{Inventory}$$
We can represent that with the plain natural numbers (starting from 0 to simplify the table):
$$0, 1, \ldots, 9 \tag{Encoding}$$
The idea is that #5 is $R_1$, #1 is $B_2$ and so on. With 2 balls the space of outcomes is this:
$$
        \begin{matrix}
          & \color{blue}{\fbox{0}} & \color{blue}{\fbox{1}} & \color{blue}{\fbox{2}} & \color{red}{\fbox{3}} & \color{red}{\fbox{4}} & \color{red}{\fbox{5}} & \color{red}{\fbox{6}} & \color{red}{\fbox{7}} & \color{red}{\fbox{8}} & \color{red}{\fbox{9}}\\
        \color{blue}{\fbox{0}} & \color{blue}{00}&\color{blue}{01}&\color{blue}{02}& 03&04&05&06&07&08&09\\
        \color{blue}{\fbox{1}} & \color{blue}{10}&\color{blue}{11}&\color{blue}{12}& 13&14&15&16&17&18&19\\
        \color{blue}{\fbox{2}} & \color{blue}{20}&\color{blue}{21}&\color{blue}{22}& 23&24&25&26&27&28&29\\
        \color{red}{\fbox{3}} & 30& 31& 32& \color{red}{33}&\color{red}{34}&\color{red}{35}&\color{red}{36}&\color{red}{37}&\color{red}{38}&\color{red}{39}\\
        \color{red}{\fbox{4}} & 40& 41& 42& \color{red}{43}&\color{red}{44}&\color{red}{45}&\color{red}{46}&\color{red}{47}&\color{red}{48}&\color{red}{49}\\
        \color{red}{\fbox{5}} & 50& 51& 52& \color{red}{53}&\color{red}{54}&\color{red}{55}&\color{red}{56}&\color{red}{57}&\color{red}{58}&\color{red}{59}\\
        \color{red}{\fbox{6}} & 60& 61& 62& \color{red}{63}&\color{red}{64}&\color{red}{65}&\color{red}{66}&\color{red}{67}&\color{red}{68}&\color{red}{69}\\
        \color{red}{\fbox{7}} & 70& 71& 72& \color{red}{73}&\color{red}{74}&\color{red}{75}&\color{red}{76}&\color{red}{77}&\color{red}{78}&\color{red}{79}\\
        \color{red}{\fbox{8}} & 80& 81& 82& \color{red}{83}&\color{red}{84}&\color{red}{85}&\color{red}{86}&\color{red}{87}&\color{red}{88}&\color{red}{89}\\
        \color{red}{\fbox{9}} & 90& 91& 92& \color{red}{93}&\color{red}{94}&\color{red}{95}&\color{red}{96}&\color{red}{97}&\color{red}{98}&\color{red}{99}\\
        \end{matrix}
$$
For this particular problem we confine our attention to the bottom-right partition where both balls are red. There are $N(R) = 7\times 7 = 49$ such balls, and since there are $N(\Omega) = 10 \times 10 = 100$ possible events, the probability should be:
$$P(R) = {N(R) \over N(\Omega)} = {49 \over 100}. \tag{My Answer}$$
The book, however, calculates another number, using the formula $C_n^r = {n! \over r! \cdot (n-r)!}$:
$$C_{10}^2 = {10! \over 2! \cdot 8!} = 45,$$
$$C_{7}^2 = {7! \over 2! \cdot 5!} = 21,$$
$$P(R) = {C_{7}^2 \over C_{10}^2} = {7 \over 15}. \tag{The Answer}$$
I haven't studied permutations and combinations to any degree of satisfaction, so I don't get the intuition behind this approach. I don't doubt of course that $C_{10}^2$ is 45. I'm just not sure what that corresponds to on the table I've made. Maybe the table is completely useless? My questions are:

Question 1. What's wrong with my approach? (Why am I getting 49 instead of 45?)
Question 2. What's the intuition behind the use of the combinations formula here?

This second question may be too broad for this format, so please ignore it if that's the case. I'd appreciate any comments/answers to either of the questions.
Comment: Hint: You can't draw the same ball twice. Don't count the diagonal.
Comment: @GrahamKemp Thank you so much! That makes sense.
Answer: Firstly, the probability of drawing one red ball is $7/10$. The probability of drawing a red ball from an urn with $9$ balls, $3$ of which are blue and $6$ of which are red is $6/9$. Thus, $$P(R)=\frac{7}{10}\cdot \frac{6}{9}$$ $$=\frac{7}{15}.$$
Comment: Using combinations are not necessary for problems like these.
Answer: Hint 1 : you can't draw the same ball twice.  Don't count the diagonal
Hint 2 : Symmetry.  Only you only need to count the proportion in the upper triangle.  The lower triangle has the same proportions.
$$
\begin{matrix}
& \color{blue}{\fbox{0}} & \color{blue}{\fbox{1}} & \color{blue}{\fbox{2}} & \color{red}{\fbox{3}} & \color{red}{\fbox{4}} & \color{red}{\fbox{5}} & \color{red}{\fbox{6}} & \color{red}{\fbox{7}} & \color{red}{\fbox{8}} & \color{red}{\fbox{9}}\\
\color{blue}{\fbox{0}} & ~&\color{blue}{01}&\color{blue}{02}& 03&04&05&06&07&08&09\\
 \color{blue}{\fbox{1}} & ~ &~&\color{blue}{12}& 13&14&15&16&17&18&19\\
\color{blue}{\fbox{2}} & ~&~&~& 23&24&25&26&27&28&29\\
\color{red}{\fbox{3}} & ~& ~& ~& ~&\color{red}{34}&\color{red}{35}&\color{red}{36}&\color{red}{37}&\color{red}{38}&\color{red}{39}\\
\color{red}{\fbox{4}} & ~& ~& ~& ~&~&\color{red}{45}&\color{red}{46}&\color{red}{47}&\color{red}{48}&\color{red}{49}\\
\color{red}{\fbox{5}} & ~& ~& ~& ~&~&~&\color{red}{56}&\color{red}{57}&\color{red}{58}&\color{red}{59}\\
\color{red}{\fbox{6}} & ~& ~& ~& ~&~&~&~&\color{red}{67}&\color{red}{68}&\color{red}{69}\\
\color{red}{\fbox{7}} & ~& ~& ~& ~&~&~&~&~&\color{red}{78}&\color{red}{79}\\
 \color{red}{\fbox{8}} & ~& ~& ~& ~&~&~&~&~&~&\color{red}{89}\\
\color{red}{\fbox{9}} & ~& ~& ~& ~&~&~&~&~&~&~\\
        \end{matrix}$$

For the combinations: There are $^7C_2$ ways to select 2 of the 7 red balls.  There are $^{10}C_2$ ways of picking 2 of all the balls.
$$\frac{^7C_2}{^{10}C_2}=\frac{7\times 6}{\color{gray}{2\times 1}} \frac{\color{gray}{2\times 1}}{10\times 9}$$
Which is the same as saying: there are 7 chances in 10 of picking one red ball, and after that 6 chances in 9 of picking another (from the remaining balls).
Comment: Thank you. Everything was immensely helpful!
Answer: Knowing nothing about combinations or permutations, your approach is perfectly fine. However, you neglected the fact that it is impossible to draw the same ball twice. If you eliminate the entire diagonal and re-visit your method, you'll find that their are 42 ways to choose red balls, and 90 ways to choose balls in general. This will give you 42/90 = 7/15 as you desire.
Comment: Graham's earlier comment about this had already opened my eyes. But thanks for taking time to contribute!


Como passar uma QueryString usando o RegisterStartupScript no asp.net?

Question: Eu tenho este código no meu code behind:
ScriptManager.RegisterStartupScript(this, typeof(string), Guid.NewGuid().ToString().Replace("-", ""), "window.setTimeout(\" $('#" + calendar.ID + "').fullCalendar({header: {left: 'prev,next today',center: 'title',right: 'month,agendaWeek,agendaDay'},aspectRatio: 2.2,editable: true,events: " + sJSON + ", eventClick: function(event) { OpenModal('Novo Compromisso','100%','500px','/agenda/form.aspx?compromissoid=event.id');}});\",100);", true);

Ele pega alguns dados e carrega a propriendade do full calendar. Em eventClick eu quero acessar o valor de event.id para abrir uma janela modal e editar o evento. Mas o valor da querystring está sendo atribuído como 'event.id' literalmente.
Eu chequei o valor de event.id para ver se havia algo ali. O valor existe porque ele aparece na função alert() como visto abaixo:
ScriptManager.RegisterStartupScript(this, typeof(string), Guid.NewGuid().ToString().Replace("-", ""), "window.setTimeout(\" $('#" + calendar.ID + "').fullCalendar({header: {left: 'prev,next today',center: 'title',right: 'month,agendaWeek,agendaDay'},aspectRatio: 2.2,editable: true,events: " + sJSON + ", eventClick: function(event) { alert(event.id); OpenModal('Novo Compromisso','100%','500px','/agenda/form.aspx?compromissoid=event.id');}});\",100);", true);

Então, como eu posso usar o valor de event.id como valor para a querystring?
Answer: Se mais alguém estiver sofrendo com isso está aqui a resposta que me deram no SO em inglês.
Na chamada OpenModal, mude a url '/agenda/form.aspx?compromissoid=event.id' para: '/agenda/form.aspx?compromissoid=' + event.id
ScriptManager.RegisterStartupScript(this, typeof(string), Guid.NewGuid().ToString().Replace("-", ""), "window.setTimeout(\" $('#" + calendar.ID + "').fullCalendar({header: {left: 'prev,next today',center: 'title',right: 'month,agendaWeek,agendaDay'},aspectRatio: 2.2,editable: true,events: " + sJSON + ", eventClick: function(event) { alert(event.id); OpenModal('Novo Compromisso','100%','500px','/agenda/form.aspx?compromissoid=' + event.id);}});\",100);", true);

Tradução livre deste link: https://stackoverflow.com/questions/25185168/how-to-pass-a-querystring-using-registerstartupscript/25185301#25185301
Erro de principiante meu...


Somehow like a two-dimensional intermediate value theorem for the double integral.

Question: Let $f \in L^1(\mathbb{R}^2)$ with respect to the Lebesgue measure $m \times m$ on $\mathbb{R}^2$. Prove that if $$\iint_{\mathbb{R}^2}f(x,y)\,dx\,dy=0,$$then there exits a square $S_{a,b}=\{(x,y)\mid a \leq x \leq a+1, b \leq y \leq b+1\}$, such that $$\iint _{S_{a,b}}f(x,y)\,dx\,dy=0.$$
I tried to show that the integral $$\iint_{[a,a+x]\times [b,b+y]}f(s,t)\,ds\,dt$$ is absolutely continuous by Fubini's Theorem and Fundamental Theorem. And by the countable additivity of integration, I proved the integral on the whole plane is still A.C. However, I could not directly apply a theorem like the IVT for the single variable functions.
Is there any theorem for the two-dimensional case?
Comment: Try applying Fubini's theorem, is the first thing I would think of. I have not worked through the details but it seems as if it could work.
Comment: That's what I have done, but I cannot claim there is a square satisfying what we want.
Answer: Let $g(a,b)=\iint_{S_{ab}} f(s,t) \, ds \, dt$. $g$ is a continuous real valued function on $\mathbb R^{2}$. If it is never zero it is always positive or always negative. [ Because its range is connected in $\mathbb R$].  If it is always positive then $\iint_{\mathbb R^{2}} f(s,t) \, ds \, dt >0$ because this integral is the sum of integrlas over $S_{nm}$ as $n,m$ vary over all integers.
Comment: But for the case some of the integrals are positive and some of them are negative, how can you explian it?
Comment: If some of them are positive and some are negative the function $g$ takes both positive and negative values. By IVP it takes the value $0$ for some $(a,b)$ and this is what you are trying to prove.


External model validation using new data for prediction: How large of a drop in $R^2$ is significant?

Question: I need to validate a model using `external model validation' and I have a question relating to deciding when a drop in $R^2$ when compared to $R_{prediction}^2$ is significant.
DISCLOSURE: This is not a homework question. I am seeking clarification on something that is in the textbook that I am using for an applied regression class (textbook: A second course in statistics: regression analysis).
I have model whose goal is to predict $y$ from a set of covariates. The model has already been fit and I would like to validate the model using new data. My textbook states the following:
FROM MY TEXTBOOK One simple technique is to calculate the percentage of variability in the new data explained by the the model, denoted $R_{prediction}^2$, and compare it to the coefficient of determination $R^2$ for the least squares fit of the final model. Let $y_1, y_2, ..., y_n$ represent the $n$ observations used to build and fit the final regression model and $y_{n+1}, y_{n+2}, ..., y_{n+m}$ represent the $m$ observations in the new data set. Then $$R_{prediction}^2= 1 - \left(\frac{\sum\limits_{i=n+1}^{n+m}\left(y_i - \hat{y_i}\right)^2}{\sum\limits_{i=n+1}^{n+m} \left(y_i - \bar{y} \right)^2}\right)$$ where $\hat{y_i}$ is the predicted value for the $i$th observation using the $\beta$ estimates from the fitted model and $\bar{y}$ is the sample mean of the original data. If $R_{prediction}^2$ compares favorably to $R^2$ from the least squares fit, we will have increased confidence in the usefulness of the model. However if a significant drop in $R^2$ is observed, we should be cautious about using the model for prediction in practice. (Page 316)
MY QUESTION Unfortunately, this is all the textbook says about using this technique and I have no idea how I would go about determining if a significant drop occurred. For my model I have an $R^2$ of 0.8283 and using the technique described in the text, I have a calculated $R_{prediction}^2$ of 0.7444. Could anyone point me into the direction of other sources that would be able to describe the method of determining whether or not this is a significant drop---I performed several google searches but the results have not turned up anything useful.
Thank you for taking the time to read my question.
Answer: This is a good question and one that hasn't really been answered in the literature.  But I would rather emphasize (1) what is the original goal, (2) what is an acceptable final (unbiased) $R^2$, and (3) is our approach good in relationship to other possible modeling approaches, i.e., could someone using the same dataset do significantly better than us?  Related issues include (1) is $Y$ properly transformed and (2) did we assume linearity of the $X$ effects when this assumption was warranted?  In my experience the most frequent assumption violation that matters is the assumption of linearity.
The drop in $R^2$ does tell us about overfitting, and there are some occasions where we rethink a problem when the overfitting is subjectively large.
Note that you are assuming that $m$ is huge (at least several hundred and likely needed to be in the several thousand range).  Unbiased estimates of $R^2$ from data splitting is the most imprecise method of estimating $R^2$, which is why bootstrapping and repeated cross-validation are popular.


Transmitir informação entre telas em ionic com Angular?

Question: Fala pessoal, tudo bem?
Vou descrever o processo que esta me deixando com dúvida.
Tenho uma lista de elementos que é preenchida com com dados que tenho. Na hora que clico em um item da lista, quero que o aplicativo abra uma página de detalhamento referente a lista que eu criei.
Ex:
 - Item 1: BATATA
 - Item 2: BANANA
Ao clicar no item 1, quero uma descrição sobre a batata.
OBS: Quero utilizar apenas uma pagina de detalhes e fazer o templating dela de acordo com um id que transmito através da página de detalhes.
Vejam meu código.
RESULTADO.HTML
 <ion-view view-title="Resultados">
  <ion-content>
    <ion-list>
      <ion-item class="item item-avatar" ng-repeat="item in resultado" ng-click="openOnly(item)" href="#/app/resultado/{{item.id}}">

{{item.nome}}

{{item.endereco}}

        <ion-option-button class="button-positive" ng-click="edit(item)">
          Ligar
        </ion-option-button>
      </ion-item>
    </ion-list>
  </ion-content>
</ion-view>

CONTROLLER.JS
.controller('ResultadosCtrl', function($scope) {
  $scope.resultado = [
    { nome: 'Med Imagem', endereco: 'Rua Paissandu, 1862 - Centro', imagem:'../img/medimagem.jpg', id: 1},
    { nome: 'Clinica Maia', endereco: 'Av. Francisco H. dos Santos, 1190 - JDA', imagem:'../img/user.png', id: 2}
  ];
})

.controller('DetalheCtrl', function($scope, $stateParams) {

});

Espero que consigam entendar..
Forte abraço.
Answer: Vai depender de como voce esta, ou vai obter os dados, mas uma coisa que acredito que vá usar bastate são services https://docs.angularjs.org/guide/services
Service
Usando um service  voce consegue guardar o objeto inteiro, e pegar ele de novo na proxima tela.
Poderia tambem guardar o resultado todo no service e tambem o id ai na proxima tela voce pega o id selecionado no service e atraves dele os detalhes do resultado, quem tambem vai estar no service.
Tem mais 2 soluções, mais ai vai depender das necessidades suas e do projeto.
Route Params
UIRouter
Minha reputação nao deixa eu postar os links :(
Os 2 são bem parecidos, basicamente voce vai poder passar o id nas na url, o que mais uso é o uirouter, que no seu caso ficaria algo bem parecido com o que você ja tem.
<ion-item class="item item-avatar" ng-repeat="item in resultado" ui-sref="resultado(id:item.id)">

Repare que tirei o ng-click, a menos que precise fazer algo antes de mandar para a proxima tela, nao ha necessidade dele.
Answer: Cara, passei por isso esses dias... O que eu fiz, criei um projeto padrão tabs e analisei o código gerado e adaptei para atender minha necessidade... Percebi que teria que passar o código (no seu caso é do item) pela url do projeto, assim configuraria a rota da aplicação.
Por exemplo, passa o id do item pela url e depois use o $stateParams para capturar esse valor e usar em um serviço para que seja feita a consulta.
Crie um projeto padrão de tabs, usando o comando do node: ionic start myApp tabs, depois analise o arquivos app.js, controllers.js e services.js desse projeto criado, se atente aos detalhes que você conseguirá fazer....


Ajuda com query para o problema criado?

Question: Preciso criar uma lista composta pelos campos Estágio Atual e Próximo Estágio ambos nomes de estágio vindos da mesma tabela.
Exemplo do resultado que busco:

Tabela Estágios (fornecedora do nome do estágio)

O query busca na Tabela EstagiosCronologia (abaixo) os nomes dos estágios na tabela Estágios (acima):

Eu posso inclusive ter o mesmo ID para Atual e Próxima.
    SELECT e.Estagio AS Atual,
    (SELECT e.Estagio FROM EstagiosCronologia ec
    INNER JOIN Estagios e ON ec.ProximoEstagioId = e.EstagioId)  AS Proximo
    FROM EstagiosCronologia ec
    INNER JOIN Estagios e ON ec.EstagioAtualId = e.EstagioId

Esse query acima funciona para apenas um item - com a tabela EstagiosCronologia polulada me retorna um erro:
Msg 512, Level 16, State 1, Line 2
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
Como criar essa query?
Tabela EstagiosCronoligia
CREATE TABLE [dbo].[EstagiosCronologia] (
        [CronologiaId]     VARCHAR (36) NOT NULL,
        [EstagioAtualId]   VARCHAR (36) NOT NULL,
        [ProximoEstagioId] VARCHAR (36) NOT NULL,
        PRIMARY KEY CLUSTERED ([CronologiaId] ASC),
        CONSTRAINT [FK_EstagiosCronologia_Estagios] FOREIGN KEY ([EstagioAtualId]) REFERENCES [dbo].[Estagios] ([EstagioId]) ON DELETE CASCADE
    );

Tabela Estagios
CREATE TABLE [dbo].[Estagios] (
    [EstagioId]   VARCHAR (36)    NOT NULL,
    [CursoId]     VARCHAR (36)    NOT NULL,
    [Estagio]     VARCHAR (50)    NOT NULL,
    [Duracao]     INT             NOT NULL,
    [ValorTabela] DECIMAL (10, 2) NOT NULL,
    PRIMARY KEY CLUSTERED ([EstagioId] ASC),
    CONSTRAINT [FK_Estagios_Cursos] FOREIGN KEY ([CursoId]) REFERENCES [dbo].[Cursos] ([CursoId]) ON DELETE CASCADE
);

Dados Cronologia
INSERT INTO [dbo].[EstagiosCronologia] ([CronologiaId], [EstagioAtualId], [ProximoEstagioId]) VALUES (N'7027a044-9530-446f-a60d-9971a206d452', N'508ccd5b-b177-4876-9b7c-987f64ada5ef', N'bb84bd20-4907-4a92-815f-44c08b24410a')
INSERT INTO [dbo].[EstagiosCronologia] ([CronologiaId], [EstagioAtualId], [ProximoEstagioId]) VALUES (N'dc72f06c-470b-4913-b480-4106e05831b4', N'bb84bd20-4907-4a92-815f-44c08b24410a', N'c86516bc-bae2-4edf-9c75-236cdc5fccd8')

Dados Estagios
INSERT INTO [dbo].[Estagios] ([EstagioId], [CursoId], [Estagio], [Duracao], [ValorTabela]) VALUES (N'508ccd5b-b177-4876-9b7c-987f64ada5ef', N'dc72f06c-470b-4913-b480-4106e05831b4', N'Teste', 40, CAST(1589.00 AS Decimal(10, 2)))
INSERT INTO [dbo].[Estagios] ([EstagioId], [CursoId], [Estagio], [Duracao], [ValorTabela]) VALUES (N'bb84bd20-4907-4a92-815f-44c08b24410a', N'dc72f06c-470b-4913-b480-4106e05831b4', N'Nursery Play', 40, CAST(1950.00 AS Decimal(10, 2)))
INSERT INTO [dbo].[Estagios] ([EstagioId], [CursoId], [Estagio], [Duracao], [ValorTabela]) VALUES (N'c86516bc-bae2-4edf-9c75-236cdc5fccd8', N'dc72f06c-470b-4913-b480-4106e05831b4', N'Teste 2', 40, CAST(1500.00 AS Decimal(10, 2)))

Comment: Cada estagio só pode ter um proximo?
Comment: não, cada estágio poderá ter mais que um próximo.
Comment: O erro ta acontecendo pq a subquery retorna mais de uma linha, basicamente vc ta tentenado colocar 2 ou mais registros dentro de um só, se cada estagio só pode ter um `Próximo` tem algo errado com a sua tabela  `EstagiosCronologia `
Comment: Consegue me passar os scripts de criação das tabelas com algum registro pra eu testar?
Comment: Ajuda assim - dessa forma?
Comment: adiciona na pergunta, se não vão apagar
Comment: Respondi, se não for isso que vc quer me avise
Comment: Desculpe Gabriel Oliveira, não vejo a resposta em nenhum lugar... sou novo no StackOverflow. Como faço pra ver a sua resposta?
Answer: Cheguei na resposta.
SELECT e.Estagio AS Atual, (SELECT est.Estagio FROM EstagiosCronologia ecs INNER JOIN Estagios est ON ecs.ProximoEstagioId = est.EstagioId WHERE ecs.EstagioAtualId = ec.EstagioAtualId) As Proximo
FROM EstagiosCronologia ec
INNER JOIN Estagios e ON ec.EstagioAtualId = e.EstagioId

Answer: Bem lógica. Simples.
SELECT ec.*, ea.Estagio AS EstagioAtual, pe.Estagio As ProximoEstagio
FROM EstagiosCronologia ec
JOIN Estagios ea ON ea.EstagioId = ec.EstagioAtualId
JOIN Estagios pe ON pe.EstagioId = ec.ProximoEstagioId

Respondendo a minha própria dúvida.

Ajuda com query para o problema criado?


Android error : com.google.android.gms.persistent E/NetworkScheduler: Invalid component specified

Question: My project android have error when i using admob run in android 5.1
application show log error :

11-15 01:16:13.645 1143-1143/? E/EGL_emulation: tid 1143: eglCreateSyncKHR(1865): error 0x3004 (EGL_BAD_ATTRIBUTE)
11-15 01:16:13.776 2356-21878/com.google.android.gms.persistent E/NetworkScheduler: Invalid component specified.

This is content my build.gradle file:

compileSdkVersion 26
    buildToolsVersion '26.0.0'
    defaultConfig {
        applicationId "com.exam"
        minSdkVersion 21
        targetSdkVersion 26
        versionCode 2
        versionName "2.00"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:26.1.0'
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:design:26.1.0'

    compile 'com.github.bumptech.glide:glide:3.7.0'
    compile 'com.squareup.okhttp3:okhttp:3.5.0'
    compile 'com.facebook.android:facebook-android-sdk:[4,5)'
    compile 'com.android.support:percent:26.1.0'
    compile 'com.squareup.retrofit2:retrofit:2.2.0'
    compile 'com.squareup.retrofit2:converter-gson:2.1.0'
    compile 'com.google.code.gson:gson:2.6.2'
    compile 'com.github.rahatarmanahmed:circularprogressview:2.5.0'
    compile 'com.android.support:cardview-v7:26.1.0'
    compile 'com.android.support:recyclerview-v7:26.1.0'
    compile 'com.afollestad.material-dialogs:commons:0.9.5.0'
    compile 'com.afollestad.material-dialogs:core:0.9.5.0'
    compile 'org.jsoup:jsoup:1.10.2'
    compile 'com.google.firebase:firebase-ads:17.1.0'
    compile 'com.github.ksoichiro:android-observablescrollview:1.6.0'
    compile 'agency.tango.android:material-intro-screen:0.0.5'
    compile 'com.google.firebase:firebase-core:16.0.4'
    compile 'cn.pedant.sweetalert:library:1.3'
    compile 'com.squareup.okhttp3:logging-interceptor:3.8.0'
    compile 'com.github.lzyzsd:circleprogress:1.2.1'
    compile 'com.github.hotchemi:android-rate:1.0.1'
}

apply plugin: 'com.google.gms.google-services'

I tried many solution but it not work
Thank for any can fix it. Please help me!
Comment: I suugest you replace `implemention` with `compile`
Comment: @amir133 i tried as you comment but it not working
Comment: Three question : **1.** can you build and run your project on `android 5.1` **2.** Did you have this problem on every android 5.1 device(maybe your play service is outOfDate). **3.** did android studio offer some warning or error in `build.gradle` if true I suggest you solve them.
Answer: Add below line build.gradle
implementation 'com.google.android.gms:play-services-ads:17.0.0'

If you are using 17+ AdMob sdk you need to specify app id in AndroidManifest.xml file. You can find your app id in Admob App settings
<meta-data
android:name="com.google.android.gms.ads.APPLICATION_ID"
android:value="@string/app_id"/>

after adding above code try uninstalling the app manually and reinstall again without making any changes. Also replace your compile with implementation.
Comment: i tried as you comment above but it not working. i run it on android 5.1 Application not start and show error : "11-16 01:16:28.655 1144-1144/? E/EGL_emulation: tid 1144: eglCreateSyncKHR(1865): error 0x3004 (EGL_BAD_ATTRIBUTE)
11-16 01:16:28.726 1933-2191/com.google.android.gms.persistent E/NetworkScheduler: Invalid component specified."  With device run android 7 Application run ok
Comment: If it's not confidential could you please send complete code to my email address? Here is my email address email@example.com I will check and find out what is the problem.
Comment: So sorry.This is project of my company. i can't send for you source full but
I will try create small project had this error and send for you after complete.
Thanks you very much


Como desenhar uma imagem com Canvas?

Question: Eu tenho esse código e quero desenhar uma imagem:
public void render(){
    BufferStrategy bs = getBufferStrategy();
    if(bs == null)
    {
        createBufferStrategy(3);
        return;
    }

    Graphics g = bs.getDrawGraphics();

    g.dispose();
    bs.show();
}

Answer: Você pode utilizar o método drawImage(Image, int, int, ImageObserver) para desenhar uma imagem no seu Graphics:
public void render() {
    BufferStrategy bs = getBufferStrategy();
    if (bs == null) {
        createBufferStrategy(3);
        return;
    }

    File arquivoComImagem = new File(...);
    BufferedImage img = ImageIO.read(arquivoComImagem );
    Graphics g = bs.getDrawGraphics();
    g.drawImage(img, 0, 0, null);
    g.dispose();
    bs.show();
}

No caso, o primeiro parâmetro do drawImage é a imagem a ser desenhada. Há várias formas de se você obter uma instância de Image, mas uma das mais fáceis é usar o método ImageIO.read(File). Os dois parâmetros int do método drawImage são a posição x e y no Graphics em que você quer desenhar a imagem. O último parâmetro (o ImageObserver) você provavelmente não vai precisar, e você pode sempre passar null lá.

Como desenhar uma imagem com Canvas?


Launch my android app when i open my site in mobile browser

Question: Hey I want my website url to open my android when the user open this url in the browser
What i did is
       <intent-filter>
            <data android:host="www.example.com" />
            <data android:scheme="https" />
            <action android:name="android.intent.action.VIEW"/>
            <category android:name="android.intent.category.BROWSABLE"/>
            <category android:name="android.intent.category.DEFAULT"/>

        </intent-filter>

and my webiste url is www.example.com
but it doesn't work
any way on how to achieve this
Thanks
Comment: http://stackoverflow.com/questions/21663001/launching-custom-android-application-from-android-browser-chrome/21727055#21727055
Comment: what do u mean? u want to open a url from your android app ?
Comment: no i want to launch my android app from browser when i type this url www.example.com
Comment: i tried what provided their but it doesn't work
Comment: I guess you should change `` to , if your site is not secured.
Comment: @KishorPawar my website is secure
Comment: try `www.example.com://` in your mobile browser. This should work.
Comment: @KishorPawar tried this but same result
Comment: add `android:exported="true"` to your Activity in manifest and then type `www.example.com://` in your mobile browser
Comment: tried it same also doesn't work
Answer: Try This:
Add data tag in <intent-filter> with host
<intent-filter>
                <data android:host="www.example.com" />
                <data android:scheme="https" />
                <action android:name="android.intent.action.VIEW"/>
                <category android:name="android.intent.category.BROWSABLE"/>
                <category android:name="android.intent.category.DEFAULT"/>
                <data android:scheme="http"
                      android:host="www.example.com" />
     </intent-filter>

Comment: i tried it with no luck :(
Answer: You need to combine your <data> elements into one:
<data android:scheme="http" android:host="www.example.com" />

Comment: but my website url scheme is https not http
Comment: @Tony just set it to https instead...
Comment: @Karakuri i tried but it doesn't work also as there any thing else i should use with and handler or something for this intent ?
Answer: You can do it via href, example
 Take a QR code

Link:
https://developer.chrome.com/multidevice/android/intents
Comment: but i can navigate from my website to specific app page and now i want to open my app at the launch of the website
Comment: @Ashish   Are you sure?
Comment: It will be security breach!!,Browser has very limited authorization as compared to an app.
Comment: No man you can launch your app from the browser url
Comment: i think you meant google now not browser
Comment: No, I meant chrome browser
Comment: yes you are right, poor ignorant me : https://developer.chrome.com/multidevice/android/intents
Comment: delete your answer before you get downvotes


Does melody note function change with each chord change in a certain harmonic field?

Question: Lets say the root is G. The chord progression starts with a G minor chord (Tonic) and is in Aeolian mode.
Perfect fifth of it is D. etc..
Does a chord change change the function of the original notes?
If the melody is originally lets say going back and forth between
D (Perfect Fifth) and C (Perfect Fourth) related to the root chord.
Then the same pattern continues but on the next chord that is F Major (Dominant).
Does the function of the notes change during chord changes so that every chord has its own perfect fifth etc. Or is the Interval system overarching in the harmonic field ? I understand that if the notes are a part of the underlying chord, there is a lot more consonance.
---- Basicly I'm asking if the thing below this text, is overarching or related to each individual chord change or both?
1: Perfect consonances: unison, octave, fourth, fifth.
2: Imperfect consonances: major third, minor third, major sixth, minor sixth
3: Dissonances: minor second, major second, tritone, minor seventh, major seventh
Comment: If you play an instrument play a G chord and sing a G note, then keep singing the G note and play a D7 chord, so feel like the G is still stable and nice sounding?
Comment: Can you explain more about what you mean by "melody note function"? I'm not aware of scale degrees of melody notes being considered functional. Leonard Bernstein said that if a melodic phrase is like a noun or a verb, then the chords under it are like adjectives and adverbs - they modify the feeling of the melody. But that's not generally called "function".
Comment: Some theorists consider the perfect 4th a dissonance that resolves to a third otherwise your list of perfect, imperfect, and dissonant intervals is good
Answer: The term that you are looking for to discuss this is qualia. The example that you gave is terrific, but this one may be even more clear:

The example is in C major. In m. 1, the asterisked chord is V (dominant) with a B on top; this is scale-degree 7—also known as the leading tone—and it has a definite urge to resolve back up to tonic, which it does.
But in m. 3, this leading tone is harmonized not with a dominant-functioning V, but with a more enigmatic iii chord. As such, it happily resolves down to scale-degree 6, and we don't get the sense of a non-resolved leading tone like we would had the B in m. 1 not resolved up to tonic.
Thus we recognize that the harmonic context changed this most charged of tendency tones; the change in harmonic environment undoubtedly altered the qualia of this scale degree.
Answer: If I understand the melody notes and chords you describe, I came up with this notation:
X: 1
K: Gm
L: 1/4
%%staves {(RH) (LH)}
V: RH clef=treble
V: LH clef=bass
%
[V: RH] "5th"d/2"nt"c/2 "5th"d/2"nt"c/2 | "nt"d/2"5th"c/2 "nt"d/2"5th"c/2 | "3rd"d2 |
[V: LH] "i"[G,2B,2D2] |"V7/III"[F,2A,2E2] |"III"[B,,2B,2D2]|

The term "function" has a very specific meaning in harmony where we have tonic, pre-dominant, and dominant functions.
"Function" in a melodic context is sort of generic, but a few specific functional melodic ideas apply to your question:

chord versus non-chord tones, various labels are given to melodic tones that do not belong to a chord like appoggiatura, suspension, neighbor tone, etc.
tendency tones, some melody tones have a tendency to move a certain way, for example the ^7 scales degree - the leading tone - has a tendency to move up to the tonic.
chord tone role (I'm not sure role is the best word, but I don't know a standard term) chord tones have names like root, third, fifth, etc. and can receive special consideration depending on the role, for example the third of a chord is general required because it defines the major or minor quality of the chord while the fifth can sometimes be omitted as not absolutely essential for defining the chord.

I labelled the music to show...

neighbor tones (nt)
and chord tones which were fifths and third

To get to your main question...

Does the function of the notes change during chord changes

...the answer is: yes.
Notice of the "C" in the melody is a non-chord tone when played over Gm but becomes a chord tone of the fifth when played over F7. And while the "D" in the melody is a consonant chord tone of a fifth over the Gm it becomes the chord third over the Bb chord.
I made a slight change to the harmonic context you gave and made the second chort a D7 the dominant in G minor.
X: 2
K: Gm
L: 1/4
%%staves {(RH) (LH)}
V: RH clef=treble
V: LH clef=bass
%
[V: RH] "5th"d/2"nt"c/2 "5th"d/2"nt"c/2 | "root"d3/2"7th"c/2  | "3rd"b,2 |
[V: LH] "i"[G,2B,2D2] |"V7"[^F,2A,2D2] |"i"[G,2B,2D2]|

I did this to illustrate a point about tendency tones with the two specific melodic tones you gave: "D" and "C". In your original harmony the "C" isn't a tendency tone. In fact, over the F7 chord it is a stable fifth of the chord. But, when the "C" is played over D7 it becomes the seventh of a dominant seventh chord which is a tendency tone that resolves down to the third for the following Gm tonic chord.
Note that in both examples the second chord is a dominant seventh chord. Merely selecting any dominant didn't determine how the "C" would function. We need to know specifically where each dominant would resolve to truly understand the function of the "C".
By changing the harmony we made the pitch "C" stable in one context but an un-stable tendency tone in another context!
Most harmony textbooks will include sections about non-chord tones, tendency tones, and other functional ideas where melody intersects with harmony. Try to review those topic in a textbook for more examples and explanation.
Answer: Both and more: the scale degree of a pitch class can be thought of as relative to several things:

The current underlying harmony/chord.
The previous one.
In anticipation of the next one.
In anticipation of the ultimate one.
Answer: When we refer to different notes by numbers, there are generally two ways this takes place.  On the one hand, we will refer to a note as a number in the context of a key.  We would generally refer to this as "scale degree #".  On the other hand, notes can be referred to as they relate to a given chord.  It gets a little strange when we start to refer to non-chord tones in relation to a chord.  In some instances, it may not sound right to refer to a note as a number in relation to a chord if it is a non-chord tone but in other instances, it is fairly common.  For example, in Classical theory, we may refer to a non-chord tone in terms of a suspension.  In the context of Jazz, there aren't exactly non-chord tones, per se, so we can usually refer to these notes as numbers but they are usually described as extensions (2=9, 4=11, 6=13), though that isn't always the case (there's a bit too much here to go into a full on example though, so if that is of interest to you, it would best be asked as a separate question.
As far as the consonances and dissonances you are referring to, those are generally referring to intervals.  They are relationships between two notes and are not specific to a given key.  There are some ways that a given note can be described as having a general dissonance within a key even if they are consonant within the current chord, such as the leading tone generally having a sense of dissonance and wanting to resolve to the tonic.


Angular mat-tab and mat-table scrolling problem in FF

Question: I have a table inside a mat-tab that expands to whatever height it needs and does not show a scrollbar when the maximum height of the panel is reached. The mat-tab-group will breach the height of its parent container and the whole page will get a scrollbar just the tab getting a scrollbar.
This does not manifest in Chrome and I can only see it in Firefox so far. Below is some example code I made to reproduce the behavior. The component in which the tab-group is embedded has a max height set. The tabs-panel is supposed to take all remaining space in it (flex: 1)
<mat-tab-group class="tabs-panel">
  <mat-tab label="CoolLabel">
    <mat-table [dataSource]="dswithacouplerows">
      <ng-container matColumnDef="mycol">
        <mat-header-cell *matHeaderCellDef>
        </mat-header-cell>
        <mat-cell *matCellDef="let row">bla</mat-cell>
      </ng-container>

      <mat-header-row *matHeaderRowDef="mycols; sticky: true"></mat-header-row>
      <mat-row *matRowDef="let row; columns: mycols;" class="get-primary-important"></mat-row>
    </mat-table>
  </mat-tab>
</mat-tab-group>

.tabs-panel {
  flex: 1;
  width: 100%;
}

Answer: I had a similar scrolling issue with mat-tab-group in FF/IE and thankfully to this comment in GitHub managed to fix it with setting min-height prop for the mat-tab-group element:
mat-tab-group {
    min-height: 500px;
}


Has a bout stopped during a count ever been reversed?

Question: Has there ever been a reversal of a referee's decision to stop a boxing match?
If you watch this specific bout, shown in this clip, the man knocked down isn't even allowed to come to his feet, and as soon as the ref stops the fight starts trying to tell the ref he's fine. From what we can see, his eyes look straight, and he ends up getting up looking fine. The ref didn't even make it to 6.
I get that it would be unlikely for an outside person to over-rule a match ref, but can the ref himself do it?
Comment: Watching that segment more closely, I have a couple more questions. (I don't know boxing rules, only what I see.) I have gathered that a downed boxer has until the count of five and must be up, or attempting to get up. I also thought the ref wasn't supposed to start counting until the other boxer is in the neutral corner, yet this ref is on four when he turns back and kneels. How did he get to four so quickly? I assume he called the fight because Jacob's hadn't opened his eyes or attempted to get up yet? I still want my title question answered, though.
Answer: That clip is very vague in terms of information regarding the physical state of fighters. I have not watched the fight but as per boxing rules, referee are in the position to decide whether the fighter is fit to continue fighting. Maybe he was getting outclassed terribly. The punch he received was a bad one, and referee can always stop a fight in order to avoid further injuries. Boxing is political, so referee can be pre meditated, there has been controversial statements made in that regard.
And yes, the referee should only start counting, after the other boxer is in neutral corner. But that rule is hardly observed in professional boxing, in an attempt to not give extra seconds to the fallen fighter. If you watch closely the ref looks to the panel, where you see a person standing up and counting. In pro boxing the counting starts as soon as the boxer touches any other part of his body other than his feet, and to answer your first question, to my knowledge no. Refereeing and judge decisions in pro boxing is pretty much ultimate and rules does'nt allow boxer to challenge them. In amateur boxing, a judge's scorecard can be reviewed and overturned if a boxer ask for it and the reversal has happened a lot of times in olympics.
Comment: watch closely..the ref looks to the panel, where you see a person standing up and counting... in pro boxing the counting starts as soon as the boxer touches any other part of his body other than his feet... and to answer your first question, to my knowledge no. Refereeing and judge decisions in pro boxing is pretty much ultimate and rules does'nt allow boxer to challenge them. In amateur boxing, a judge's scorecard can be reviewed and overturned if a boxer ask for it and the reversal has happened a lot of times in olympics.
Comment: Did that just now. Im not that good in editing :)


Exibir ID no form antes de cadastrar php e mysql

Question: Estou fazendo um tela de cadastro , só que eu queria que o sistema já exibisse a ID (id_entidade) que será cadastrado.
Ao salvar, ele vai perguntar se desejo cadastrar documentos, ai se eu clicar em sim, ele vai para um novo form de cadastro de doc que ao salvar no banco de dados tem que levar a id_entidade
Comment: Falta colocar o que já foi feito (código fonte, não tudo, mas o necessário). Do jeito que está fica muito subjetivo para responder adequadamente.
Comment: Coloquei o código que fiz até o momento.
Comment: Robson se o seu código até o momento for NENHUM fica complicado. Está muito ampla a sua pergunta, pois há várias formas de fazer. Aconselho você a pesquisar mais sobre o php e tentar realizar essa aplicaçao. Pesquise sobre o `header` do php, ele ira direcionar o usuario para um outro ambiente se necessario.
Answer: Vamos imaginar uma tabela, chamada de entidade, já criada no seu banco. Então, temos:
+-----------------------------------------------+
|id_entidade integer primary key auto_increment |
|-----------------------------------------------|
|nome varchar(50)                               |
+-----------------------------------------------+

Isso deve servir para o exemplo. Agora é necessario o formulario para cadastrar usuarios, chamemos de form_usuario.php:
<form action="set_user.php" method="post">

Dados Principais

            *Nome
            <input type="text" id="nome" name="nome" class="form-control" placeholder="">

            Sobrenome
            <input type="text" id="sobrenome" name="sobrenome" class="form-control" placeholder="">

        <input type="checkbox" name="novo_documento"> Salvar novo documento

    <input type="submit">
</form>

Mostra o proximo valor de id_entidade é tranquilo, mas é suscetivel a sobre escrita, pois não há como garantir que ninguem vá tentar se cadastrar simultaneamente. De qualquer forma deixei a função para fazer (comentada). Então vamos para a página set_user.php:
<?php
cadastrarUsuario();
//registra novo usuario
function cadastrarUsuario(){
    $conexao = mysqli_connect('127.0.0.1', 'root', '', 'teste');
    $status = mysqli_query($conexao,
    "insert into entidade (nome) values ('". $_POST['nome'] . "')");
    if($status === true){
        //redireciona para o formulario de cadastrar documento
        if(isset($_POST['novo_documento'])){
            ob_get_clean();
            ob_start();
            $ultimo_id = mysqli_insert_id($conexao);
            require_once __DIR__ . '/salvar_documento.php';
            ob_end_flush();

        }else{
            echo 'salvo com sucesso';
        }
    }
    else{
        echo 'erro ao salvar: ' . mysqli_error($conexao);
    }
}
//função para encontrar o proximo id_entidade na tabela entidade
function proximoId(){
    //dados de conexão com o banco, na ordem, host, usuario, senha, e nome do banco utilizado
    $conexao = mysqli_connect('127.0.0.1', 'root', '', 'teste');
    //lista informações da tabela entidade (estrutura), uma delas refere-se ao proximo auto_increment
    $tabela_entidade = mysqli_query($conexao, "SHOW TABLE STATUS LIKE 'entidade'");
    $proximo_id = mysqli_fetch_assoc($tabela_entidade)['Auto_increment'];
    return $proximo_id;
}

Nessa página é obtido o id da ultima entidade inserida (para quando for para a pagina inserir novo documento). Além disso tem as funções ob_get_clean(),
ob_start(), ob_end_flush que são utilizadas para "imprimir" a saida da inclusão do arquivo salvar_documento.php (todo o conteudo html).
E por fim o arquivo salvar_documento.php, consegue "reconhecer" a variavel $ultimo_id, pois foi incluido (require) dentro do arquivo set_user.php (onde foi declarada a variavel $ultimo_id). E foi acrescentado um formulario, com um campo oculto representando o id da entidade criada. Ficou assim:

<form action="algumapagina.php" method="post">

Salvar documento

    O id da entidade criada é <?php echo $ultimo_id; ?>
    <input type="hidden" name="id_entidade" value="<?php echo $ultimo_id; ?>">

            *Nome
            <input type="text" id="nome" name="nome" class="form-control" placeholder="">

            Sobrenome
            <input type="text" id="sobrenome" name="sobrenome" class="form-control" placeholder="">

</form>

Suponha que todos os arquivos estão no mesmo diretorio.
Para uma referencia das funções mysqli_* consulte no w3c.
Comment: Maravilha!! Muito obrigado
Answer:    <form action="set_user.php" method="post">

Dados Principais

                                                    *Nome
                                                    <input type="text" id="nome" name="nome" class="form-control" placeholder="">

                                                    Sobrenome
                                                    <input type="text" id="sobrenome" name="sobrenome" class="form-control" placeholder="">

Comment: Uma observação, quando for adicionar mais detalhes, não poste uma resposta, edite a pergunta.


Simulating speaker distortion with Doppler shift

Question: When a speaker is operating at high volumes, the high frequencies should be frequency modulated by the low frequencies. For the low frequencies the cone moves back and forth slowly but heavily and while doing so it emits the high frequencies. Thus the high frequencies are emitted from a moving sound source and therefor become doppler shifted. The effect should be akin to frequency modulation.
I have little doubt about the above, but my main questions are:

Is this effect audible at all ?
Does it create an impression of "loud"?
Are there any effect devices or plugins which simulate this effect?
Has anybody furnished such an effect e.g with the likes of supercollider or ChucK

Edit: After reading the paper referenced by Dave's post on the phyics side I am no longer convinced that "doppler shift" is correct. It may well be a phase-modulation. But in either case, the effect should not just add higher frequencies (as a nonlinear characteristic would), but also lower frequencies.
Edit Just to make it clear: I am not after a regular Guitar distortion effect. I just want to know if it has some audible effect, like e.g. a Compressor which also creates distortion, but it not percieved as such.
Comment: Your assumptions are incorrect.  The speaker at any given time is moving in response to the sum over all driving frequencies. There is no Doppler Shift taking place. I can see why you might think of the motion that way, but in fact the output pressure vs. time is just a sum of all input waveforms.  Think of the higher frequencies as "riding" on the lower ones, perhaps, rather as the signal on an AM radio "rides" on the carrier frequency.  The "trick" is that the cone driver "knows" that the low-freq cone motion is there, and the proper adjustment to produce a non-Doppler high freq happens.
Comment: From the point you are standing (usually) and the speed of sound, I would say it's not audible (I'm sure someone will claim that s/he can hear it) Note that Doppler shift happens with uniformly dec/increasing distance. Otherwise it's just garbled. It's the same with a fixed tweeter/subwoofer combo and shaking your head.
Comment: The more I think about it, the more I'm confused; so I asked a related question at Physics: http://physics.stackexchange.com/questions/107965/how-to-model-doppler-distortion-of-speakers
Comment: If I take a 0.01Hz signal which makes the diaphragm move by one meter (for the sake of argument) and I add a 1 kHz signal, which makes the diaphrahm move by 1mm and I sum them up and send them to a speaker, there would certainly be a doppler shift, wouldn't it?
Answer: In and of itself, the presence of multiple frequencies does not produce any distortion or frequency modulation.  The idea of the high frequency waves "riding on" (or being "pushed by") the low frequency waves can be misleading in this context.  Intermodulation effects require some non-linearity in the system, i.e. a distortion model.
Most the most basic distortion models only non-linearly transform the amplitude of the signal; this will not model the effect that you've identified.
A model that includes a nonlinear function of both the amplitude and the time-derivative of the amplitude is required to model the effect.
I do not know of any specific models that incorporate this feature, but in terms of the modeling details, the feature that your are looking for is a
distortion model that includes the derivative of the signal as one of its inputs.
ROM of the Effect
Let's just assume that we have a tweeter that is affixed to the cone of a low frequency driver as is envisioned in the question (Note: I'm not sure that this is a good model for single-driver speakers...).  I'll assume a 1mm (=0.001m)
amplitude for the low-frequency driver's amplitude.  In order to get a 0.5% (1.005 factor, just less than 10 cents) Doppler shift, the frequency of the "low" frequency driver would need to be about 330Hz.  This is in the realm of plausibility and perceptability.
Details
A basic (no-memory) non-linear transformation can be represented as

out(t) = a0 + a1*in(t)+ a2*[in(t)]^2+a3[in(t)]^3...

If we assume that there are just two frequencies, f1 and f2, you can see that

out(t) = a0
       + a1*(f1(t)+f2(t))
       + a2*[f1(t)+f2(t)]^2 = a2*[ f1^2 + f2^2 + 2*f1*f2 ]
       +...

it's in the quadratic, and higher order terms, of the nonlinear transfer function that produce the frequency modulation.  This type of non-linear amplitude transformation is what is most commonly used in distortion effects simulations.
One aspect of the speaker problem that is less commonly modeled is an explict dependence of the output on the derivative of the input signal:

out(t) = F( in(t), in'(t) )

(in'(t) is the time-derivative of the input signal)
Note that for single-frequency signals the the amplitude of the derivative
of the signal is scaled by the frequency itself -- this is an intrinsic high-frequency boost in the derivative signal.
As with the simple model, one can Taylor expand the transfer function to get the intermodulation products; but this will be systematically different from the simple (amplitude only) non-linear model above due to the fact that the time-derivatives are scaled by the frequency.
Comment: I know that adding signals does not add any distortion. My point is that I believe a speaker is a non-linear device.
Comment: My point is that typical non-linear distortion models cover (most of) the relevant phenomenology.  But now I'll edit to reflect a new (better?) idea of what you are getting at.
Comment: I'm leaving in the initial disclaimer (i.e. that "this doesn't happen") because more than one person mis-interpreted your question along these lines.
Comment: out(t) = F( in(t), in'(t) ) looks odd to me. I would have assumed something like Out(t) = in (F(in(t)), i.e. the modulator affects the time, not the value. This is not distortion caused by a nonlinear characteristic. If that was the case you would only get harmonics, wheras with fm you get additional frequencies below the fundamental. But I am actually more interested in whether this effect has been observed, what it sounds like and if there are audio effects which mimick it,
Answer: One obvious distortion that the overloaded amplifier produces is the saturation: it must already output all voltage is it capable of for a low frequency component and then cannot give any other more for the higher frequency component that should be added to that it is now on the output. Hence the high frequency component is significantly altered (or even fully suppressed) at the peaks of the low frequency component. This effect can be observed in electronics circuitry and probably also on the speaker membrane.
Another type of distortion is when the speaker membrane already cannot go far enough to match the top and bottom peaks of the sine wave of the single tone, producing a different curve at the output. This adds extra tones (mostly overtones, I guess).
These effects do not involve the Doppler shift. They are audible, and while they are normally associated with the loud sound, some tiny speaker can be overloaded without being actually very load.
Answer: Doppler is very unlikely to be audible. I ran the math for a garden variety 12" guitar driver with the playing the low E at full throttle and playing a high E (12th fret, high E) string at the same time. This basically results in the phase modulation of the high note so the pitch of the high note is modulated at the rate of the low note. The overall modulation is really small though: 3mm excursion (= screamingly loud) the maximum pitch shift is only about 7 cents (7/100 of a semitone). That's less than most people can tune to.
Doppler is indeed a non linearity (as it depends on amplitude) and results mainly in intermodulation distortion (not harmonic distortion). You can model this using the power series as Dave  described in his answer but there are actually some closed form solution using Bessel functions that are bit easier.
However intermodulation sounds pretty much always really bad, so it's not a useful effect to model or explore. There are plenty of other non-linearities that can be desirable for guitar but Doppler is not one of them.
Comment: Are you saying: "you cannot hear it, and if you could it would sound bad"? There is no sweet spot in between, where you could tell that it is a loud loudspeaker without noticing a distortion?
Comment: Yep, pretty much. This is very non-harmonic whereas "good" distortion such as tube, overdrive, etc. are typically odd order harmonic.


Como plotar um gráfico de colunas agrupados com ggplot

Question: como posso fazer um gráfico de colunas agrupados por ano? Tenho um banco de dados extenso com várias variáveis e gostaria de plotar um gráfico com separado por ano.
Como fazer? Para algumas variáveis o gráfico está ficando assim, mas ainda não consegui ajustar por ano:

Até o momento meu código está assim:
ggplot(data=espacial, aes(x=AREAURB_2018, y=microrregião, fill=microrregião))+
    geom_bar(aes(fill=microrregião), stat="identity", position="dodge")

Aqui só tem o Efetivo Bovino (Pastebin):
CodMun;microrregião;MUNIC;EFETIVOBOV_2000;EFETIVOBOV_2001;EFETIVOBOV_2002;EFETIVOBOV_2003;EFETIVOBOV_2004;EFETIVOBOV_2005;EFETIVOBOV_2006;EFETIVOBOV_2007;EFETIVOBOV_2008;EFETIVOBOV_2009;EFETIVOBOV_2010;EFETIVOBOV_2011;EFETIVOBOV_2012;EFETIVOBOV_2013;EFETIVOBOV_2014;EFETIVOBOV_2015;EFETIVOBOV_2016;EFETIVOBOV_2017;EFETIVOBOV_2018
1500404,00;Santarém;Alenquer(PA);96000,00;99778,00;120000,00;106080,00;137164,00;151468,00;161306,00;167401,00;112400,00;147352,00;170396,00;166052,00;160908,00;168444,00;191140,00;189902,00;190903,00;188400,00;213741,00
1500503,00;Almeirim;Almeirim(PA);12031,00;18728,00;20600,00;21630,00;22170,00;23278,00;23976,00;25395,00;33108,00;34763,00;36501,00;38326,00;39475,00;25312,00;24124,00;21853,00;21100,00;23414,00;28110,00
1500602,00;Altamira;Altamira(PA);202965,00;203066,00;272839,00;291061,00;314217,00;339517,00;365034,00;402340,00;399512,00;413625,00;555324,00;688901,00;668541,00;711028,00;687535,00;628481,00;657436,00;656430,00;707958,00
1500859,00;Altamira;Anapu(PA);48950,00;83407,00;68747,00;95149,00;118600,00;139260,00;172456,00;280321,00;175384,00;177857,00;171721,00;175023,00;225093,00;270460,00;262642,00;251681,00;267860,00;202400,00;237584,00
1501006,00;SãoFelixdoXingu;Aveiro(PA);14300,00;15000,00;15300,00;19957,00;23450,00;25604,00;30540,00;37329,00;35447,00;37229,00;37736,00;37202,00;31160,00;43637,00;42160,00;45668,00;47187,00;50942,00;50227,00
1501253,00;SãoFelixdoXingu;Bannach(PA);152313,00;191673,00;171374,00;171342,00;257085,00;201557,00;193461,00;165102,00;142813,00;171387,00;192965,00;195272,00;211401,00;193334,00;240905,00;231288,00;240080,00;258244,00;248230,00
1501451,00;Altamira;Belterra(PA);10000,00;11200,00;12650,00;13477,00;21017,00;17730,00;15700,00;9491,00;12200,00;23835,00;21765,00;20729,00;24136,00;26490,00;23843,00;23405,00;20842,00;21310,00;23810,00
1501725,00;Altamira;BrasilNovo(PA);139905,00;196187,00;195748,00;213054,00;245507,00;263254,00;259546,00;225866,00;219847,00;222722,00;206099,00;211000,00;217881,00;235712,00;241027,00;233652,00;240470,00;223901,00;230385,00
1502764,00;SãoFelixdoXingu;CumarudoNorte(PA);195110,00;197062,00;200017,00;213118,00;611151,00;549673,00;550712,00;447412,00;440378,00;588925,00;638983,00;683072,00;749278,00;821185,00;743174,00;772554,00;808396,00;846495,00;807787,00
1502855,00;Santarém;Curuá(PA);11960,00;13395,00;14735,00;22000,00;25000,00;18674,00;26646,00;29868,00;28286,00;26020,00;32647,00;34034,00;32109,00;32181,00;34433,00;37187,00;37148,00;44068,00;44924,00
1503002,00;Óbidos;Faro(PA);3890,00;3306,00;4138,00;5793,00;6372,00;7646,00;8500,00;13937,00;9226,00;7934,00;7457,00;871,00;1019,00;12149,00;10966,00;11318,00;12109,00;13102,00;9757,00
1503606,00;Itaituba;Itaituba(PA);146000,00;140000,00;151200,00;168641,00;180160,00;243759,00;270698,00;174318,00;267526,00;270657,00;309894,00;325567,00;337737,00;360703,00;344197,00;331381,00;328979,00;368776,00;343981,00
1503754,00;Itaituba;Jacareacanga(PA);22700,00;25000,00;26250,00;30187,00;5165,00;6802,00;8467,00;26789,00;26250,00;27038,00;12992,00;12993,00;15602,00;16085,00;15396,00;14716,00;14468,00;80476,00;81350,00
1503903,00;Óbidos;Juruti(PA);40500,00;46575,00;46575,00;50000,00;48500,00;32000,00;43627,00;38906,00;43254,00;37198,00;29758,00;30137,00;40996,00;21745,00;28441,00;27872,00;31486,00;40347,00;42608,00
1504455,00;Altamira;Medicilândia(PA);49175,00;70323,00;105443,00;111910,00;124373,00;137864,00;157128,00;143359,00;135117,00;134380,00;103939,00;123212,00;133885,00;143371,00;152562,00;158768,00;165016,00;166100,00;147540,00
1504802,00;Santarém;MonteAlegre(PA);100000,00;106761,00;114706,00;171865,00;174302,00;177451,00;196200,00;128412,00;191680,00;191680,00;186473,00;192242,00;205728,00;214596,00;219112,00;221942,00;214361,00;236968,00;244500,00
1505031,00;Itaituba;NovoProgresso(PA);155974,00;185000,00;183568,00;231741,00;378573,00;463784,00;561628,00;105989,00;412400,00;763088,00;636227,00;680671,00;687142,00;632521,00;590273,00;567077,00;579218,00;618365,00;618876,00
1505106,00;Óbidos;Óbidos(PA);85681,00;100681,00;120817,00;126857,00;120000,00;128394,00;124526,00;127768,00;125428,00;113090,00;120713,00;127269,00;127687,00;127269,00;129823,00;133551,00;133989,00;143462,00;143128,00
1505304,00;Óbidos;Oriximiná(PA);102184,00;78638,00;82842,00;91486,00;104000,00;131563,00;123430,00;131525,00;130485,00;139852,00;135156,00;125350,00;147748,00;159623,00;140549,00;141576,00;140340,00;148328,00;139429,00
1505437,00;SãoFelixdoXingu;OurilândiadoNorte(PA);156078,00;188993,00;194656,00;207877,00;202944,00;216980,00;198936,00;103510,00;173569,00;158221,00;181515,00;191113,00;194935,00;187148,00;191441,00;181074,00;186959,00;204229,00;192522,00
1505486,00;Altamira;Pacajá(PA);97345,00;138319,00;166542,00;250643,00;283204,00;313579,00;334595,00;256420,00;370333,00;415724,00;400216,00;358037,00;432578,00;492442,00;536460,00;573471,00;585925,00;643200,00;620785,00
1505650,00;Santarém;Placas(PA);68000,00;62000,00;50142,00;62756,00;66257,00;74174,00;78658,00;59450,00;87605,00;90381,00;90823,00;72122,00;102831,00;116124,00;127830,00;132387,00;135286,00;140977,00;140480,00
1505908,00;Almeirim;PortodeMoz(PA);9516,00;12850,00;17850,00;18742,00;20451,00;20241,00;20853,00;47913,00;48215,00;51107,00;53662,00;56077,00;57759,00;20278,00;50030,00;46670,00;51433,00;52918,00;46893,00
1506005,00;Santarém;Prainha(PA);62609,00;63861,00;65138,00;66440,00;79581,00;95497,00;100986,00;102125,00;113821,00;115630,00;121412,00;127482,00;131306,00;114548,00;119353,00;110494,00;114728,00;123652,00;110253,00
1506195,00;SãoFelixdoXingu;Rurópolis(PA);50000,00;50000,00;57962,00;59599,00;88226,00;105872,00;115984,00;117821,00;102000,00;112044,00;114000,00;116907,00;123990,00;136626,00;142087,00;145251,00;152471,00;159930,00;158534,00
1506807,00;Santarém;Santarém(PA);105332,00;100000,00;95000,00;106088,00;153115,00;133218,00;126935,00;104529,00;130613,00;116503,00;132008,00;118861,00;138911,00;129954,00;132300,00;115052,00;113620,00;118897,00;120537,00
1507300,00;SãoFelixdoXingu;SãoFélixdoXingu(PA);682407,00;1030019,00;1157707,00;1264991,00;1527017,00;1581518,00;1596411,00;1653231,00;1812870,00;1912009,00;2022366,00;2101726,00;2143760,00;2282445,00;2213310,00;2222949,00;2200338,00;2240496,00;2256734,00
1507805,00;Altamira;SenadorJoséPorfírio(PA);12742,00;21385,00;26938,00;30900,00;36546,00;45432,00;57396,00;60899,00;48105,00;52427,00;44467,00;57029,00;64208,00;68790,00;70379,00;73405,00;71425,00;70300,00;79920,00
1507979,00;Óbidos;TerraSanta(PA);41541,00;47772,00;57326,00;60192,00;50000,00;52000,00;35000,00;40000,00;47178,00;39157,00;38373,00;25000,00;27325,00;36672,00;35419,00;30133,00;33442,00;36177,00;29557,00
1508050,00;SãoFelixdoXingu;Trairão(PA);20400,00;25000,00;27000,00;28753,00;36686,00;44053,00;53815,00;68497,00;46972,00;65262,00;77972,00;86865,00;86478,00;96839,00;96562,00;95934,00;102281,00;108399,00;106543,00
1508084,00;SãoFelixdoXingu;Tucumã(PA);344136,00;341604,00;355781,00;349637,00;372073,00;359975,00;315622,00;175778,00;291651,00;284979,00;268172,00;274254,00;282481,00;282064,00;283818,00;284593,00;305524,00;329551,00;332269,00
1508159,00;Altamira;Uruará(PA);95345,00;125207,00;158723,00;193905,00;232912,00;250739,00;295527,00;293640,00;291868,00;297341,00;290513,00;288172,00;298960,00;308125,00;313523,00;310109,00;280603,00;205800,00;271258,00
1508357,00;Altamira;VitóriadoXingu(PA);127520,00;166720,00;195642,00;235526,00;245590,00;250002,00;220292,00;195201,00;193924,00;195155,00;169964,00;152217,00;175376,00;166290,00;156564,00;146937,00;135543,00;121600,00;122015,00
;;;;;;;;;;;;;;;;;;;;;

Answer: Este tipo de problema geralmente está relacionado à reformatação dos dados. O formato deve ser longo e os dados estão em formato largo. Veja esta postagem sobre como reformatar os dados do formato largo para o longo.
No código abaixo segui os seguintes passos.

Filtrar as colunas sem microrregião;
Reformatar os dados para o formato longo;
Criar um gráfico base e guardá-lo na variável p.

Depois é só acrescentar a geom_* requerida (geom_col ou geom_bar) e melhorar o aspeto final, tal como pedido neste comentário à resposta do @abreums. A rotação dos anos no eixo dos x vem dessa resposta.

Reformatar os dados e criar o objeto gráfico.
library(tidyverse)

espacial %>%
  filter(microrregião != "") %>%
  pivot_longer(
    cols = starts_with("EFETIVOBOV"),
    names_to = "Ano",
    values_to = "Efetivo"
  ) %>%
  mutate(Ano = str_extract(Ano, "\\d+")) %>%
  ggplot(aes(x = Ano, y = Efetivo, fill = microrregião)) +
  labs(y = "Efetivo Bovino") -> p

Barras sobrepostas.
p + geom_col() +
  theme_bw() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))

Barras lado a lado.
p + geom_col(position = position_dodge()) +
  theme_bw() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))

Comment: Rui, deu certinho para todas as variáveis. Obrigada pela explicação!!!
Answer: ...
library(tidyverse)
library(scales)

dt <- read_csv2("ImportacaoR.txt")

# é preciso "pivotar" / "rodar" os dados
# para que haja uma coluna com os anos e outra com os efetivos
dt <- dt %>%
  pivot_longer(EFETIVOBOV_2000:EFETIVOBOV_2018,
               names_to = "ano",
               values_to = "efetivo")

# vamos subtrair "EFETIVOBOV" da coluna "ano" (criada acima)
# e transformar em inteiro
dt <- dt %>%
  mutate(ano = as.integer(str_sub(ano, -4, -1)))

# gráfico empilhando os efetivos por ano para todos os municípios
dt %>%
  ggplot(aes(x = ano,
             y = efetivo,
             group = microrregião,
             fill = microrregião)) +
  geom_col() +
  # limita os "breaks" do eixo x
  scale_x_continuous(breaks = c(2000, 2004, 2008, 2012, 2016)) +
  # acrescenta separador nos valores do eixo y
  scale_y_continuous(labels = scales::comma_format(big.mark = ".",
                                                   decimal.mark = ",")) +
  # inclinação para o texto do eixo x + ajuste horizontal
  theme(
    axis.text.x = element_text(angle = 45, hjust = 1)
  ) +
  labs(
    title = "Aumento do efetivo de cabeças de gado no PA",
    subtitle = "2000 - 2018",
    x = "Ano",
    y = "Efetivo"
  )

# outro gráfico separando os efetivos por município
# em gráficos diferentes - facet_wrap
dt %>%
  # alguns registros não contém informação de microrregião,
  # por isso incluimos este filtro para evitar o facet de NA
  filter(!is.na(microrregião)) %>%
  ggplot(aes(x = ano,
             y = efetivo,
             group = microrregião,
             fill = microrregião)) +
  geom_col() +
  scale_x_continuous(breaks = c(2000, 2004, 2008, 2012, 2016)) +
  # acrescenta separador nos valores do eixo
  scale_y_continuous(labels = scales::comma_format(big.mark = ".",
                                                   decimal.mark = ",")) +
  theme(
    # inclinação para o texto do eixo x + ajuste horizontal
    axis.text.x = element_text(angle = 45, hjust = 1),
    # esconde a legenda
    legend.position = "none"
  ) +
  labs( title = "Aumento do efetivo de cabeças de gado no PA",
        subtitle = "2000 - 2018",
        x = element_blank(),
        y = element_blank()) +
  facet_wrap(~ microrregião)

Comment: Obrigada pela resposta! Queria tirar uma dúvida, é possível organizar os rótulos abaixo do gráfico (o de anos)? Eles ficaram sobrepostos
Comment: Depois eu vi que vc queria por microrregião e eu fiz por município... arrumei isto também.
Comment: ótimo, abreu! Aqui ficou com duas colunas, ao invés de 18, você sabe o que pode ter ocorrido? Abraços
Comment: Talvez porque estamos usando bases diferentes. Acrescentei a linha que usei para ler o arquivo q vc enviou. Eu precisaria de mais informações para poder ajudar mais.
Comment: Obrigada mesmo Abreu!


O que é IPC (Inter Process Communication)?

Question: Numa discussão com experientes programadores aqui do site a respeito de controle de concorrência, surgiram os termos semáforos, mutex, memória compartilhada, monitor, e ainda outros, os quais estou começando a entender agora.
Toda essas minhas dúvidas começaram quando perguntei sobre processos assíncronos, onde percebi que eu não estava entendendo muito bem sobre o termo assíncrono e acabei aprendendo sobre bifurcação de processos.
No meio disso tudo, comecei a pesquisar muitas coisas a respeito de processos de sistemas operacionais. E foi aí que aprendi mais um termo: IPC — que disseram que significa inter process communication.
Mas o que é IPC mais detalhadamente?
De que forma ele se relaciona com os termos que eu citei acima, sobre os quais disse que eu estava discutindo?
Comment: Não é que as perguntas estão mal formuladas, é que você está encavalando um monte de pergunta relacionada. Talvez desse pra fundir algumas delas. Mas também não sou especialista na área, pode ser que não dê. A minha dica é só pra segurar um pouco o ritmo ;)
Comment: Talvez seja o caso de você consolidar um pouco mais o que sabe antes de formular as perguntas... Porque tenho a impressão de que as respostas vão ter muita sobreposição. A propósito, acho que cabe a tag [tag:multithreading] nessas perguntas todas.
Comment: IPC seria a [Comunicação entre processos] (https://pt.wikipedia.org/wiki/Comunica%C3%A7%C3%A3o_entre_processos)
Comment: Por curiosidade, o que você está tentando implementar? Como eu disse, não entendo muito do assunto, mas pensaria duas vezes antes de lidar com múltiplas threads ou processos com PHP. Não parece a linguagem adequada para isso.
Comment: @bfavaretto pensa num cara que dessa vez realmente não sabe nada sobre o assunto? Sou eu. A maioria das vezes que pergunto no site, é porque já sei a resposta, mas dessa vez foi diferente. Peço desculpas se acabei formulando alguma coisa de maneira ruim, mas é que não vi nada no site falando diretamente sobre o assunto.
Comment: @bfavaretto eu tava querendo até perguntar o que era System V, porque nunca tinha ouvido falar disso antes.
Comment: @bfavaretto se for o caso, podemos fechar as perguntas. Eu não me importo com isso. Eu geralmente realmente gosto de separar cada termo em uma pergunta. Mas talvez possamos pelo menos marcar como duplicada, para ter mais referências.
Comment: @bfavaretto realmente estou "cavalgando". Estou correndo pra lá e pra cá igual doido pra saber o que está por trás daquela pergunta que fiz sobre [msg_ em php](https://pt.stackoverflow.com/questions/211357/qual-%C3%A9-o-objetivo-dessas-fun%C3%A7%C3%B5es-prefixadas-por-msg-em-php). Não quero tentar implementar nada sem saber direitinho se o que estou pensando sobre as funções está certo.
Comment: @bfavaretto concordo com você. PHP na verdade tem várias limitações quando a controle de processos (quando se usa Apache principalmente). A ideia mesmo era compreender como funciona aqueles *message queues* nativos do php que mostrei na outra pergunta, e como isso se relaciona com os termos : System V, IPC, shared memory, semaforos e afins...
Comment: Encontrei esse [link](http://www.ece.eng.wayne.edu/~gchen/ece5650/lecture5.pdf). Vou dar uma olhadinha depois.
Comment: Como usar IPC de forma errada: https://pt.stackoverflow.com/a/45330/64969
Answer: Sistemas operacionais multiprocessados são sistemas operacionais que são capazes de executar mais de um processo de uma vez. Exemplos são os sistemas UNIX, Windows da versão 95 em diante, e MacOS Classic (MacOS X também é multiprocessado, mas está incluído sob a rubrica UNIX já citada).
Uma característica muito importante dos sistemas multiprocessados é que eles implementam os chamados espaços de endereços virtuais, em que cada processo que executa enxerga a si próprio como se fosse o único processo executando na memória. Isso facilita muito o desenvolvimento dos programas, porque o programador não precisa se preocupar em acidentalmente ler, sobrescrever ou até executar dados ou código de um outro processo sem relação consigo, mas que calhe de estar rodando ao mesmo tempo.
Então o SO se preocupa em montar essa ficção de que cada processo é o único executando na máquina, e os processos simplesmente executam como se fossem os únicos no mundo. Isso funciona muito bem para programas simples, mas eventualmente um processo vai precisar se comunicar com outro — por exemplo, um programa gráfico vai querer se comunicar com o X/Wayland num ambiente UNIX. Como fazer neste caso?
Aí entram os mecanismos chamados de Comunicação Interprocesso (IPC, na sigla em inglês). Como os processos não podem conversar entre si acessando a memória um do outro, eles precisam de algum tipo de mecanismo — e existem vários — para conversar entre si quando isso for necessário. E como quem implementa essa separação entre os processos é o SO, então é responsabilidade do SO implementar esses mecanismos também.
O mecanismo mais simples de IPC é simplesmente o uso de arquivos. Isso era usado na época dos compiladores C antigos, em que o preprocessador pegava o código fonte e escrevia um arquivo com esse código preprocessado, e então o compilador pegava esse código e escrevia um programa assembly correspondente, o montador pegava o programa assembly e emitia o código objeto, e finalmente o link-editor juntava os códigos objeto e gerava o executável.
Um refinamento disso é o conceito de pipe, que é um arquivo que só existe enquanto os programas enquanto os programas em cada lado do pipe executam e só é visível para eles; outro maior são as soquetes de domínio UNIX (UNIX Domain Sockets), usadas pelo Wayland para fazer IPC; o uso de soquetes TCP/IP, COM, DCOM, CORBA, mapeamento de memória, mensagens Win32, são numerosos outros.
Um dos mecanismos de comunicação interprocesso é realmente estabelecer uma área de memória que os dois (ou mais) processos comunicantes conseguem acessar ao mesmo tempo, o que é simples e eficiente, mas pode causar problemas se mais de um processo tentar escrever a mesma região ao mesmo tempo. Neste caso, é preciso estabelecer algum tipo de protocolo para definir quem pode escrever onde e quando. Este protocolo são os semáforos, mutexes e aliados.
Em resumo, o conceito de IPC é um conceito que surge naturalmente a partir do conceito de isolamento de processos. Os métodos de se concretizar esse conceito são inúmeros; cada um tem características, vantagens e desvantagens próprias. Qual é mais apropriada para o seu caso específico depende de você.
Answer: IPC: inter process communication. A parte mais fácil da pergunta já foi respondida, mas ela abrange muito mais por baixo.
Vou tomar a liberdade aqui e falar que processo é tudo aquilo que ocupa o processador para simplificar o entendimento, ok?
Os níveis de IPC variam de acordo com a tecnologia usada e a técnica para se fazer a comunicação. Vamos discutir um sistema computacional MIMD/processador com escalonamento de processos, do nível que eu considero mais desacoplado até o que eu considero mais acoplado.
Como estamos falando de múltiplos processos falando entre si, esses múltiplos processos não necessariamente precisam estar na mesma máquina. Vamos começar pelo caso de que eles estão na mesma máquina.
Interfaces de comunicação

Resumo:
  Plexidade? Uniplex, half-duplex ou full duplex
  Tipo de dado? Generalizado
  Ativo/passivo? Ativo
  Duração: Arbitrário/lifetime

São interfaces fornecidas pelo próprio sistema operacional. Podem ser uniplex, half duplex e full duplex. O exemplo mais típico de uma comunicação por interface uniplex é o pipeline, mais brevemente conhecido por pipe, ou até mesmo por | para os íntimos. Como isso funciona?
Tome um exemplo básico de shell script:
echo "furiosas ideias verdes dormem furiosamente" | sed -e 's/(^| )[aeiou][^ ]* /  /g' |
    sed 's/  */ /g' | tr -d aeiou

Aqui, cada processo funciona de modo suficientemente separado um do outro. Não há compartilhamento de memória, nem um processo sabe da existência um do outro. Por baixo, o bash está imprimindo a frase de efeito, então alimentando o primeiro sed (que remove palavras começadas por vogais, deixando um espaço no lugar), que então alimenta o segundo sed (que remove excesso de espaços) que, só então, lança para o tr deletar as vogais da entrada. A saída desse script é:

frss vrds drmm frsmnt

Passo a passo do exemplo
echo "furiosas ideias verdes dormem furiosamente"
Entrada:

Saída:

furiosas ideias verdes dormem furiosamente

sed 's/[aeiou][^ ]* / /g'
Entrada:

furiosas ideias verdes dormem furiosamente

Saída:

furiosas  verdes dormem furiosamente

sed 's/  */ /g'
Entrada:

furiosas  verdes dormem furiosamente

Saída:

furiosas verdes dormem furiosamente

tr -d aeiou
Entrada:

furiosas verdes dormem furiosamente

Saída:

frss vrds drmm frsmnt

Outras comunicações interprocesso por interfaces
Foi apresentado já o pipe. Esse pipe também é conhecido como pipe anônimo, pois ele não foi nomeado. Também existe o pipe nomeado. Em sistema Unix, você cria um pipe nomeado através do comando mkfifo, então você põe um processo para escrever no pipe e outro para ler dele, como se fosse um arquivo do sistema de arquivos tradicional.
Outro modelo também é o socket. Um programa abre um socket e entra em modo de escuta, então outro programa se conecta e os dois passam a se falar pelo socket.
MPI

Resumo:
  Plexidade? Full duplex
  Tipo de dado? Generalizado
  Ativo/passivo? Ativo
  Duração: Arbitrário/lifetime

MPI é uma espécie de interface de comunicação, mas aqui há uma coesão maior, há um acoplamento mais intenso. Também pode-se dizer que isso aqui é multi computador, mas funciona muito bem com um computador só.
Imagine que você precisa saber como uma molécula se estrutura dado o pH e a temperatura do sangue humano (resquícios da época em que trabalhava no CENAPAD-UFC). Essa molécula é grande demais, com partes quase independentes entre si, então você pode computar separadamente o comportamento de suas estruturas, chegar numa posição de estabilidade eletro-quântica e, então, atualizar a informação obtida pelo outro processamento para refinar seu posicionamento.
Essa troca de valores comumente se faz através de um envio de mensagens em um processamento tipo BSP.

BSP em quinze segundos: grandes pedaços de processamento independentes que de quando em quando são sincronizados e trocam informação entre si.
  Exemplo do BSP nesta resposta, através dos processos nas redes de ordenação.

Memória compartilhada

Resumo:
  Plexidade? Full duplex
  Tipo de dado? Generalizado
  Ativo/passivo? Passivo
  Duração: Arbitrário

Aqui dois ou mais processos compartilham parte da memória do computador. Eles escrevem na área comum, eles leem da área comum, mas também tem sua área privada. MPI pode ser montado em cima disso.
Normalmente é nesse nível que o programador começa a se preocupar com semáforos/mutex/monitores propriamente ditos. Antes, ele simplesmente sabe que essas coisas existem.
Esse compartilhamento de dados permite maior agilidade na execução, porém também é preciso mais controle do programador. Diferente de comunicação por interface, isso aqui não permite lançar um evento para que o outro processo tome uma ação: aqui, a comunicação é totalmente passiva.
Eu não preciso nem devo falar para o outro processo: olhe, dados! O outro processo simplesmente pega os dados.
Variáveis compartilhadas

Resumo:
  Plexidade? Full duplex
  Tipo de dado? Generalizado
  Ativo/passivo? Passivo
  Duração: Lifetime

Ok, alguns iriam argumentar que isso é um tipo de Memória Compartilhada, outros iriam argumentar que eu estou inventando esse nome. E, de fato, não lembro qual o nome correto, mas esse nome vem bem a calhar.
Aqui, não só há um espaço de memória compartilhado entre diversos processos, como de fato toda a memória é compartilhada. A partilha é tão grande que até pelos mesmos nomes as variáveis atendem. Esse é o modelo de IPC em threads.
Envio de sinais

Resumo:
  Plexidade? Uniplex
  Tipo de dado? Sinal/byte
  Ativo/passivo? Ativo
  Duração: Momento

Quem nunca recebeu um SIGSEGV quando programou em C?
SIGSEGV também é conhecido por segmentation fault, ou falha de segmentação. Esse é um sinal Unix enviado pelo sistema operacional falando que você acessou uma área de memória fora do esperado (acabou por violar o segmento de memória do programa).
Tem outros sinais muito característicos que usamos:

sinal de pausa (CTRL+Z no terminal; SIGSTOP)
sinal de interromper (CTRL+C no terminal; SIGINT)
sinal de morte (já deu kill -9 <PID> em algum processo? SIGKILL)

Alguns sinais podem ser interceptados, outros não. SIGKILL e SIGSTOP, se não me engano, não são interceptáveis. Não me lembro se é possível enviar sinais de qualquer programa para qualquer programa, mas tenho certeza de que todo programa ancestral pode enviar um sinal para qualquer um de seus descendentes. Wtrmute mostra de modo excelente nesta resposta como usar o envio de mensagens dentro da árvore de processos, de ancestral para descendente e vice-versa.
Tem uma pergunta específica sobre sinais
Via arquivo

Resumo:
  Plexidade? Half-duplex
  Tipo de dado? Generalizado
  Ativo/passivo? Passivo
  Duração: Arbitrário

Escreve num arquivo, espera que outro processo leia. Porco e direto ao assunto. Se o arquivo for residente da RAM (RAM-FS), vai ser mais rápido.
Também poderia funcionar bem no caso de o SO demorar para fazer flush e permitir "leitura" do que estiver no cache de arquivos por outros processos, pode não ser tão ruim de performance.
A vantagem desse método é que a informação da comunicação fica persistida no caso de término abrupto do processo leitor.
Via banco de dados

Resumo:
  Plexidade? Half-duplex
  Tipo de dado? Generalizado
  Ativo/passivo? Passivo
  Duração: Arbitrário

Semelhante ao IPC por arquivo, mas o SGBD pode otimizar para a tabela ficar na RAM enquanto se realiza a escrita/leitura de maneira mais eficiente do que a leitura no cache do arquivo antes do flush.
Arquivo de trava

Resumo:
  Plexidade? Uniplex
  Tipo de dado? Booleano
  Ativo/passivo? Passivo
  Duração: Arbitrário

Lembrei-me desse tipo de comunicação ao escrever essa resposta.
Em suma: quando você está em um ambiente multitarefa e precisa garantir a integridade de algum arquivo no sistema, não tendo nenhum servidor fixo para controlar essa situação, é criado um arquivo de trava.
O seguinte trecho exemplifica como funciona essa estratégia no ambiente git:

No caso, como não há servidor esperando ouvir uma mensagem, um processo git precisa decidir por si só, observando o ambiente (SO incluso como parte do ambiente) se ele pode realizar mudanças críticas ou não. Então, ele faz a seguinte chamada ao sistema operacional:

SO, por favorzinho, cria para mim o arquivo .git/index.lock? Me retorna sucesso se é somente se eu fui quem conseguiu criar esse arquivo, ou se ele já existir me retorne falha

Para o qual, há duas respostas que o SO pode fornecer:

Tá aqui, pequeno git, você criou o arquivo

Ou então, no caso de o arquivo já existir (ou que acabou de ser criado por outro processo em paralelo):

Ô, animalzinho! Esse arquivo já existe!

Caso o arquivo exista previamente (e portanto ocorreu o erro), o git aborta graciosamente com essa mensagem que você foi recebido.
Caso o arquivo tenha sido criado (e portanto sucesso), o git segue feliz em seu processamento e, quando tiver terminado a atividade requerida, vai remover o arquivo de trava.

Variável de ambiente

Resumo:
  Plexidade? Uniplex
  Tipo de dado? Texto
  Ativo/passivo? Passivo
  Duração: Criação do processo filho

No shell-script, em diversos cantos precisamos fazer coisas assim:
export PATH=/bin:/usr/bin:$HOME/bin
./meu_script.sh

Isso é um jeito de passar para o programa meu_scrpit.sh a variável $PATH. Nota: se o export for omitido, o valor da variável alterado não será passado para o processo filho.
Essas variáveis só são passadas do processo pai para o processo filho, e se não me engano os valores são definidos na hora de fazer o fork.
Código de retorno

Resumo:
  Plexidade? Uniplex
  Tipo de dado? Byte
  Ativo/passivo? Passivo
  Duração: Término do processo filho

Quando um processo filho termina, ele pode notificar ao pai se deu tudo normal ou se deu alguma falha durante a execução. O padrão é retornar 0 quando não há erro (execução com sucesso) e com um código diferente de 0 quando há erro, sendo que cada valor corresponderia a um erro diferente.
Isso permite a um programa chamador tomar decisões de fluxo de execução condicionado ao sucesso ou fracasso do programa filho. O código de erro permite, também, informar ao programa chamador qual foi o problema encontrado (ou à pessoa que está executando na mão o programa).


How can a foreign key be mapped onto an object field in SQLite-Net Extensions?

Question: Context:
We are using SQLite-Net Extensions for local data caching with Xamarin. We plan on deploying to iOS, Android and Windows Phone. We have existing data structures used throughout our system (all implementing a common interface) that we would like to store in this manner.
Problem
As shown in the code sample, the [ManyToOne] attribute is used to signify a relation field. This does not work. As described on the BitBucket Developer Page the [ForeignKey] attribute can be used to specify the foreign key relation. This seemingly only supports an int. Can we easily adapt our structure to support these relations without duplicating the properties for the Id field. e.g. the following is undesirable.
    [ForeignKey(typeof(Address))]
    public int AddressId { set; get; }

    [ManyToOne]
    public Address Address
    {
        set { address = value; }
        get { return address; }
    }

Code Sample
using SQLite.Net.Attributes;
using SQLiteNetExtensions.Attributes;

namespace Data
{
    [Table("Client")]
    public class Client : IData
    {
        private int id = -1;
        private Address address = null;

        public Client() { }

        public Client(int id)
        {
            this.id = id;
        }

        [PrimaryKey, AutoIncrement, Column("_id")]
        public int Id
        {
            set { id = value; }
            get { return id; }
        }

        [ManyToOne]
        public Address Address
        {
            set { address = value; }
            get { return address; }
        }
    }

    [Table("Address")]
    public class Address : IIdentifiable
    {
        private int id = -1;
        private string someFields = "";

        public Address() { }

        public Address(int id)
        {
            this.id = id;
        }

        [PrimaryKey, AutoIncrement, Column("_id")]
        public int Id
        {
            set { id = value; }
            get { return id; }
        }

        public string SomeFields
        {
            set { someFields = value; }
            get { return someFields; }
        }
    }
}

Answer: SQLite-Net Extensions is a thin layer over SQLite-Net, and it uses sqlite database for the storage. Relational databases store relations using foreign keys, and sqlite is no different in this aspect. Therefore, SQLite-Net and SQLite-Net Extensions also uses the foreign key mechanism for declaring relationships.
As an alternative, you could use intermediate tables to store relationships, the same way ManyToMany relationships work, but limit one of the ends to one. This way you would mimic a OneToMany, ManyToOne or even OneToOne relationship using ManyToMany relationships and intermediate tables. For example:
[Table("Client")]
public class Client {

    [PrimaryKey, AutoIncrement, Column("_id")]
    public int Id { get; set; }

    [Ignore] // This property shouldn't be persisted
    public Address Address { get; set; }

    // This relationship is in fact a ManyToOne relationship,
    // but we model it as a ManyToMany to avoid adding foreign key to this entity
    [ManyToMany(typeof(AddressesClients))]
    public Address[] Addresses {
        get { return Address != null ? new []{ Address } : Address; }
        set { Address = value.FirstOrDefault(); }
    }
}

[Table("Address")]
public class Address
{
    [PrimaryKey, AutoIncrement, Column("_id")]
    public int Id { get; set; }

    public string SomeFields { get; set; }

    [ManyToMany(typeof(AddressesClients), ReadOnly = true)]
    public List<Client> Clients { get; set; }
}

// Intermediate table that defines the relationship between Address and Client
class AddressesClients {
    [PrimaryKey, AutoIncrement]
    public int Id { get; set; }

    [ForeignKey(typeof(Client))]
    public int ClientId { get; set; }

    [ForeignKey(typeof(Address))]
    public int AddressId { get; set; }
}

Of course, this would have some performance penalties.
As for the PrimaryKey, you can use any supported type, and you have to use the exact same type for the opposite ForeignKey, i.e. if you use Guid as primary key, the foreign key that points to that class must be a Guid too . In the demo project we're already using int (the most performant), string and even UUID.
Comment: Although this isn't the solution we chose, it is similar. In our case we forked the sqlite-net-extensions repository and modified it. We added a new custom attribute to indicate a foreign key. We then modified the internal read/write operations so that every time the attribute is detected, it writes to a custom Relations table, storing: source table, field, object id and the target object id.