SHINY OUTPUT VARIABLE WITH IF STATEMENT IN RMARKDOWN

Question: I am new to shiny and rmarkdown, I looked for some information on the internet but I cannot understand how to output a variable encompassing a if statement (or similarly a for statement) that is in shiny server into a different rmarkdown document.
For instance, in the following case I would like to print the variable output$price into rmarkdown in a code chunk after the "date", any suggestions?
Shiny code:
<code>library(shiny)

ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(
      textInput("price","Price:", value = "", placeholder = "00.0"),
    ),
    mainPanel(
      h5(textOutput("price")),
    )
  )
)

server <- function(input, output, session){

  output$price <- renderText({
    if(is.na(as.numeric(input$price))){
      stop(safeError("input correct price field"))
    }else{
      return(c("Price:",input$price))
    }
  })
}

shinyApp(ui = ui, server = server)

</code>
Rmarkdowncode:
<code>---
title: ""
output: html_document
date: '2022-03-23'
---

```{r echo=FALSE, results = 'asis'}
cat("Trade Date:",format(Sys.Date(), format="%d-%m-%Y"))```
</code>
Answer: Are you looking for something like this. We could make a reactive value:
---
title: "test"
output: html_document
date: '2022-03-28'
runtime: shiny
---
<code>```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(shiny)
```

```{r eruptions, echo=FALSE}
textInput("price","Price:", value = "", placeholder = "00.0")

output_price <- reactive ({
  if (is.na(input$price)) {
    stop(safeError("input correct price field"))
  } else{
    return(c("Price:", input$price))
  }
})

```

```{r echo=FALSE, results = 'asis'}
cat("Trade Date:",format(Sys.Date(), format="%d-%m-%Y"))
renderText(output_price())
```
</code>
Comment: (Message 1/2) To give a little bit of context, I am working on two different documents. The first is a shiny web app, where the user will select the inputs, the second is a rmarkdown, where the input of the user will be returned in a pdf doc (that will be downloadable from the UI). I would like to have the user select the input in the UI, the input is then "elaborated" in the server or in rmarkdown ( - I don't care), and then returned in the rmarkdown pdf document. I do not want to have the input in the rmarkdown but just the result of the if statement.
Comment: (Message 2/2) I can return in the Rmarkdown document inputs that are not linked with any if or for statement thanks to "cat(input$side)". However, this function does not work when the input linked to any statement
Comment: Update: adding "return((output_price())" and removing the input line in the rmarkdown, I get the output I want. Nevertheless, the output is in the form [1] "Price:" "1000". How can I get just Price: 1000? results = 'asis' in the r chunk is not helping.


Immutable Infrastructure

Question: I'm working on a cloud based solution architecture at the moment and want to take the approach of using an immutable server infrastructure (creating and then deploying new AMIs when updating software, OS, etc). There's plenty of good reading and presentations out there in terms of the approach and the various tooling to use, and I'm aware of the virtues of stateless web/application servers and using the likes of AWS RDS to take away some of the headaches in managing the data tier.
However, I was wondering how to approach some of the management services/servers that sit around the application server estate from an immutable perspective. I can appreciate how the likes of AWS RDS take away some of the complications of maintaining the data tier from an immutable perspective, but how you would approach some of the other 'less stateless' servers/services that typically make up a solution? I'm thinking of things like the CI server e.g. Jenkins, Directory Services, Monitoring/Logging Services, etc. I suppose I could look to engage 3rd party services for some of these things, like the approach with AWS RDS, but what other approaches exit? What alternative approaches are there to maintain these servers and services without deviating widely from the immutable server deployment approach?
Thank you.
Comment: You can't make everything cattle. You will always have some pets.
Answer: in a word - Docker! - this is what Docker was made for and it is the most active open source project on the internet at the moment - it will be supported in Windows Server 2016, has many 'day 2' design considerations and is supported by kubernettes, AWS, OpenStack Magnum, Azure, Stackato, Cloud Foundry, IBM blue Mix, Messos and Docker Swarm
check out Docker Hub and explore, deploy and pass around entire distributed systems as if they were binaries - have dev, production and sandbox all at the very same level, implement a desired state configuration and let kubernettes or messo scale, load balance and version you applications. Docker is so good it's threatening Cloud

Immutable Infrastructure


Qual a diferença entre esses dois meios de obter o PackageName?

Question: Estou com esses dois trechos de códigos, os dois exibem o mesmo resultado, então gostaria de saber, qual a diferença entre eles.
1
jclass cls = (*env)->FindClass(env, "android/content/ContextWrapper");
jmethodID mid = (*env)->GetMethodID(env, cls, "getPackageName", "()Ljava/lang/String;");

jstring packageNamei = (jstring)(*env)->CallObjectMethod(env, context, mid);
const char *nativeString = (*env)->GetStringUTFChars(env, packageNamei, 0);
__android_log_print(ANDROID_LOG_INFO, "--packageName--jni--", "%s", nativeString);

2
jclass context_clazz = (*env)->GetObjectClass(env, context);

jmethodID methodID_pack = (*env)->GetMethodID(env, context_clazz,
"getPackageName", "()Ljava/lang/String;");
jstring application_package = (*env)->CallObjectMethod(env, context, methodID_pack);
const char *str = (*env)->GetStringUTFChars(env, application_package, 0);
__android_log_print(ANDROID_LOG_DEBUG, "JNI", "PackageName: %s\n", str);

Posso usar qualquer um deles, ou algum é mais recomendado?
Comment: O foco é a biblioteca em C, obter o pakage name apenas no C, na library compilada, sei como obter no java, o código que eu estou usando requer o `context`, que só consegui através da `MainActivity.java` talvez essa minha outra [pergunta](http://pt.stackoverflow.com/q/145869/8984) te ajude a entender melhor.
Comment: Porque você quer fazer isso em JNI?
Comment: É para pegar o package name do app android, daria para fazer de outra forma? Estou recebendo o `context` da `MainActivity.java`
Comment: Se tem um *context* pode obter o *Package name* através de `context.getPackageName();`
Comment: Na _library_ @ramaral?
Comment: O que quer dizer com *library*? Só dá se estiver a programar em java.
Answer: No caso 1
FindClass pegará a referência da classe a partir do nome dela, ou seja, pra você pegar a referência da classe você deverá saber o nome dela e sua assinatura completa. Exemplo da classe String:
Nome String
Assinatura completa java.lang.String - porém deve-se substituir os pontos por barras "java/lang/String"
No caso 2
GetObjectClass pegará a referência da classe a partir de um objeto, ou seja, você não precisa saber o nome da classe, o próprio objeto contém essa informação e o GetObjectClass pegará a referência da classe a qual o objeto foi instanciado. Caso a classe, a qual esse objeto pertence, não possuir o método que você está buscando, provavelmente GetObjectClass irá gerar uma exceção NoSuchMethodError. O segundo argumento de GetObjectClass é a referência do objeto:
jclass GetObjectClass(JNIEnv *env, jobject obj);

Especificamente para o trecho de código do seu segundo caso, a função GetObjectClass pode ser usado no caso de o várias classes que possuem o mesmo método, como as classes que herdam um método de uma mesma classe pai. Dessa forma não importa qual classe o objeto instanciado pertence pois todas as classes herdam o mesmo método.
O uso delas vai depender do objetivo de sua função nativa.
Segue link com mais informações sobre as funções de operações de classe: JNI Functions
A partir dessas informações você pode julgar qual delas servirá melhor pra sua necessidade.


Problema AUTO_INCREMENT MySQL

Question: Tive um problema em que a partir do ID 35218, as contas começaram a ser inseridas a partir do ID 400000, porém não lembro de ter mexido no valor do AUTO_INCREMENT. O que posso fazer para as contas voltarem para menor ID vazio?
Comment: O que provavelmente aconteceu é alguma inserção de número alto, provavelmente 400000, que subiu automaticamente o incremento. O autoincrement sempre vai ser maior, nem teria sentido querer voltar para número anterior. Qual é o problema em deixar como está? Autoincrement não foi feito para ser sequencial, e sim único.
Comment: Voltar pra seguir a sequência mesmo.
Answer: Antes de mais nada você deve verificar se existe algum problema na sua inserção, utilizando um bloco de exceção, quando você tenta inserir algo e ocorre algum erro, mesmo assim a sequência muda, é possível modificar a sequencia do auto_increment da sua tabela utilizando o código:
ALTER TABLE nome_da_tabela AUTO_INCREMENT = 352019;

O problema é que se fizer isso vai chegar um momento que ele irá alcançar o número: 400000, e se o campo for uma chave primária você terá problemas, pois estará violando uma chave única.
Comment: Qual a necessidade de converter para o menor número livre, está tabela tem relacionamento com outras tabelas, ou seja, o campo chave é foreign key em outras tabelas? Se sim, aconselho a não mexer nisso...
Comment: Eu já fiz isso, a questão são as linhas que inseriram nesses números maiores, pra converter elas pro menor número livre.
Comment: Porque pretendo mudar o número máximo de IDs para 100.000, e com esses números altos fica estranho

Problema AUTO_INCREMENT MySQL


What's the name for the style of jazz piano with slow rhythmic chords in the left hand

Question: I absolutely love the style of piano where the pianist is alternating low chord, high chord, low chord, high chord in a slow but decidedly rhythmic way. A prime example would be Bobby Floyd in his rendition of Georgia on My Mind (primarily 5:46-6:21).
Is there a name for this style of chording? Are there resources for learning it?
Answer: This looks like a variation of "stride piano", where bass notes are rhythmically alternated with chords some distance away.
Idiomatic stride piano is usually pretty technical due to the sheer velocity of playing -- you'd want to look up Fats Waller and Art Tatum as early pioneers of the style,and more recently people like McCoy Tyner and Hiromi Uehara have continued to push the boundaries of technique.
In the example you gave, the pianist is using the idea of alternating low and high left hand chords at a slow tempo as a way to get the best of both worlds -- deep bass presence, and lush chord voicing, in the context of "comping" for a singer. You'll notice that when he plays more than one note in the low octave, the chord is much more sparse or separated than it is when he plays in the middle octave -- this speaks to the tradeoff you have to make between chord density and positioning (a dense chord in the low octave is not going to sound very clean). In developing this technique, you'd want to start with just a single bass note alternating with middle-register chords at a slow tempo -- which is exactly what you'd be doing if you were practicing stride.


$.9999\dots = 1 $ What's wrong with this Algebra?

Question: This just feels wrong.  My professor is claiming that .999... = 1 with the following proof:
$x = .999\dots$
$10x = 9.999\dots$
$9x = 10x - x = 9.999\dots = 9$
$x = 1$
Is this actually correct and I'm just going crazy?
Comment: The first thing is to sit down and find out/recall, what the notation $0.999\dotsc$ _means_. How is it to be interpreted? The standard interpretation is that it is the sum of the infinite series $$\sum_{k=1}^\infty \frac{9}{10^k},$$ and that sum is $1$.
Comment: Does $1 = (3)(\frac{1}{3}) = (3)(0.333\ldots) = 0.999\ldots$ also feel wrong?
Comment: Its sickening that a horde of "oberlehrers" mark questions dealt with the last time four years ago as duplicates, and so can throw them off the board. For the second time today an answer of mine bringing up new aspects to a question has been killed.
Comment: Nope, those are great explanations, it just felt wrong putting in x on one side and .999... on the other.  This is definitely a duplicate question. Go ahead and close it someone.
Comment: See http://math.stackexchange.com/questions/11/does-99999-1
Answer: Two real numbers are equal, if their difference is 0. The difference between a and b is 0 if $\forall \epsilon>0 \, |a-b|<\epsilon $. This has to do with how real numbers are constructed. There are several ways. One is e.g. that a real-number is a cauchy sequence of rational numbers. Then, two real-numbers $a_n, b_n$ so defined, are equal if the sequence $c_n = a_n - b_n$ has the limit $0$. Decimal numbers are just one way to represent a real number, and as your example suggests, for some numbers there is more than one decimal representation.
Edit:
The proof looks good. The second-last line should read $9x = 10x - x = 9.99999... - 0.99999... = 9$
Comment: The expression  does not mean anything in itself. It is a series of symbols and must be defined.
There are many possible definitions, of which I offer 3:
1. 0.99999… is a string of symbols only.
2. 0.99999… is a limit of the series 0.9 ; 0.99;0.999;0.9999 etc …The limit is obviously 1.

3. It is a so called "actual infinity" of decimal nines following a leading 0. This needs to be defined in turn. It is not by definition the same as the answer 2 (but most persons believe so). There is a problem is related to the implications for the general concept of actual infinity.


Fixable? Or decor?

Question: Is it possible to repair this guitar or just a waste of time. Either way I'm going to try. Just wanted opinion from somewhere else.
Comment: *Decor as in a decoration for around the house. Some people take old guitars and hang them on the wall or stick them in the corner just for the vibe.
Comment: Yes. It can be repaired. Whether or not it is worth it is up to you.
Comment: I can't read the maker - does it actually have any extrinsic value if rebuilt, or would it make more sense to hang a junk-shop relic on the wall instead? Could probably get one for less than the price of new machine heads.
Answer: At worst, if an attempt to repair fails, it can still hang on the wall. A good two-pack epoxy adhesive and some carefully placed clamps will sort out the parting of the ways, but not sure about the electrics side. Without the pup and the circuit, it'll end up as a poor acoustic, and won't even be convincing hiding the damp patch on the wall.
Answer: With a blown out truss rod and a shattered neck heel, I'd say you are going to have difficulty making it playable again. It would be good for practicing your gluing and clamping though. You could cut open or take off the face and put in some shelves for a nice curio display.

Fixable? Or decor?


Marklogic : Multiple XML files created on document on importing a csv. How to get root Document URI path?

Question: I am new to Marklogic, I tried to import my CSV files of 100k records to Marklogic and after import, I found it gets imported to Documents Database by default. Also, I found for each records, I see a XML file generated in the database with incremental number appended to the "documentUri" that I mentioned while importing. For Example: documentUri_1.xml. I understands multiple xml files are created inorder to read the data in a distributed manner.

Question:
  1. How to get the root document URI for this document? which has multiple xml files?
  Question: 2. How do i import the same CSV file to a different database?
  Question: 3. When I use xquery to list all documents in the database, I am getting all the all xml files URI rather just the dummy.xml uri? How do I achieve this?

Note: I was using following command to import:
mlcp.bat import -host localhost -port 8000 -username admin -password admin -input_file_path dummy.csv -mode local -input_file_type delimited_text -uri_id 'dummy.xml'

Can you someone help me on this?
Answer: Question 1) There is no such thing as a "root document".  Every document stands on its own.  But you can group documents together by collection (see below).
Question 2) Use the -database mlcp option.
Question 3) I think you're looking for the mlcp option -filename_as_collection.  This will allow you to find documents by a collection named after the file.  For example, in XQuery:
collection("dummy.csv")

Comment: thank you for helping me on this. I tried using collection("dummy.csv") and i received "your query returned an empty sequence". the reason i wanted to get the collection of files is to filter the dummy.csv documents from the other set of documents that I inserted to the database. Any thoughts..
Comment: @mani Since this answers the question you asked, you should mark it as accepted and ask another question related to the next issue.
Comment: sure. But the answer doesn't provide the required result.  collection("dummy.csv") provides empty results. Is there a different command to work on?
Answer: The answer does not work because your sample did not include the recommended command option
 -filename_as_collection

Not to be found in:
mlcp.bat import -host localhost -port 8000 -username admin -password admin -input_file_path dummy.csv -mode local -input_file_type delimited_text -uri_id 'dummy.xml'

Comment: got it thanks. let me try to reimport it to a new database. thanks much,
Comment: I tried this following command.. mlcp.bat import -host localhost -port 8000 -username admin -password admin -input_file_path earthquakes.csv -mode local -filename_as_collection "dummy.csv" -database "dummyDB" -input_file_type delimited_text -delimited_root_name profile -delimited_uri_id id -output_uri_suffix _earthquake.xml
as you mentioned. The document go loaded to new database. But I still return empty on calling collection("dummy.csv"). Can you assist me on what I am missing. @DALDEI


Deriving multi-angle addition sin formulaes

Question: There is no derivation I could find anywhere, and is rarely discussed online.
$\sin(A+B+C+\ldots)$ is what is referred as multi-angle sum not $\sin(3x)$ or $\sin(8x)$, as its finite.
$\sin(\theta_1+\theta_2+\theta_3+\ldots)=\cos(\theta_1)\cos(\theta_2)\cos(\theta_3)\cdots(s_1-s_3+s_5-s_7+\ldots)$
where
$s_n=\sum_{\rm cyc}\tan(\theta_1)\tan(\theta_2)\tan(\theta_3)\cdots\tan(\theta_n)$.
https://brilliant.org/wiki/expansions-of-certain-trigonometric-functions/
Comment: Are you asking for what the expression is, or for a derivation of it? Is there a context where you want to apply it?
Comment: Use the two-angle sum case and induction (since, for example $\sin (A+B+C) = \sin ((A+B)+C) $)
Comment: @ConMan derivation without induction
Comment: @Jon  i prefer no induction
Comment: In fact, what you mention can be more or less "recasted" as a  formula for $\tan(\sum \theta_i)$: https://math.stackexchange.com/q/2171738
Answer: The key idea is to use Euler's formula for one angle
$$  e^{i\theta}=\cos(\theta)+i\sin(\theta)=
\cos(\theta)(1+i\tan(\theta)). \tag{1} $$
Thus, for several angles let $\,\theta:=\theta_1+\theta_2+\dots+\theta_n.\,$
Then let $$ E:=e^{i\theta_1} e^{i\theta_2}\cdots e^{i\theta_n}=
e^{i\theta}=\cos(\theta)+i\sin(\theta). \tag{2}$$
From equations $(1)$ and $(2)$ get
$$ E \!=\! \cos(\theta_1)\!\cos(\theta_2)\cdots\cos(\theta_n)
(1\!+\!i\tan(\theta_1))(1\!+\!i\tan(\theta_2))\cdots(1\!+\!i\tan(\theta_n))
. \tag{3}$$
Expand equation $(3)$ and separate the real and imaginary parts to get
$$ \cos(\theta) = \cos(\theta_1)\cos(\theta_2)\cdots\cos(\theta_n)
(e_0-e_2+e_4-\dots) \tag{4} $$ and
$$ \sin(\theta) = \cos(\theta_1)\cos(\theta_2)\cdots\cos(\theta_n)
(e_1-e_3+e_5-\dots) \tag{5} $$
where the $\,e_n\,$ are the $n$-th elementary symmetric polynomials
of the tangents.
Answer: Not a formal answer, but something to consider ...

Compare these trigonographs for the angle-sum formulas involving two and three angles:

It may not be difficult to convince yourself that, for an arbitrary number of angles, the horizontal sides of the diagram (which combine to make the cosine of the total angle) are labeled with all (and only) those products involving an even number of sines of individual angles. Likewise, the vertical sides (for the sine of the total angle) are labeled with products involving an odd number of sines.
That the groupings should be alternately added and subtracted may not be immediately obvious (especially after just two cases), but this might also not take too much convincing.
Comment: wonderful, n how did you draw that crispy diagram?
Comment: @Minikute: I use [GeoGebra](https://geogebra.org) for my diagrams.
Comment: have u also tried algebraically the derivation, is there a book someone said hobb's trigonometry, but i dont have that book.
Comment: @Minikute: I'd be inclined to use induction for an algebraic derivation, but you've commented that you aren't interested in that. (Of course, even this diagrammatic justification requires some inductive thinking.) Maybe a nice identity comes into play when expanding things in terms of complex exponentials; I haven't given that any thought (but it would likely involve induction, anyway). ... I'm afraid I don't have any book recommendations to offer.


Inverse of a modular matrix

Question: I have the matrix$$
\begin{pmatrix}
1 & 5\\
3 & 4
\end{pmatrix} \pmod{26}
$$
and I need to find its inverse. I do it according to this website.
I find the modular multiplicative inverse (of the matrix determinant, which is $1×4-3×5=-11$) with the extended Euclid algorithm (it is $-7 \equiv  19 \pmod{26}$). Then I have $$\frac{1}{19}×\begin{pmatrix}4 & -5\\-3 & 1\end{pmatrix}.$$ I calculate that$$-5 \equiv 21 \pmod{26},\ -3 \equiv 23 \pmod{26}.$$
No matter what I do I am not able to get the solution they have on the website, which is$$\begin{pmatrix}2 & 17\\5 & 7\end{pmatrix}.$$
Can someone help me with this? What am I doing wrong?
Comment: You multiply by the reciprocal of $-11$ (which is $7$) not divide by it.
Answer: The determinant is $-11$, as you mentioned.
The Euclidean algorithm will tell you that the inverse is $7$ or $-19$, since $-11 \times 7 = -77 \equiv 1 \mod 26$.
Now the usual $2 \times 2$ inverse is $\begin{pmatrix}4 & -5 \\ -3 & 1\end{pmatrix}$, and this times $7$ is $\begin{pmatrix}28 & -35 \\ -21
 & 7\end{pmatrix}$,which simplifies $\mod 26$ to $\begin{pmatrix} 2 & 17 \\ 5 & 7\end{pmatrix}$.
Reiterate procedure, for your help. Given a matrix $A$, which you want to invert $\mod m$ (where the inverse of $A$ exists $\mod m$),

First, compute the determinant of the matrix,$\det A$. If $\det A$ is coprime to $m$, then you can be sure that $A$ is invertible $\mod m$.
Find the inverse of $\det A$ modulo $m$. This we denote by $(\det A)^{-1}$ and will be the unique integer between $0$ and $m$ which satisfies $(\det A) \times (\det A)^{-1} \equiv 1 \mod m$.
Next, compute the matrix of cofactors of $A$, call this $B$. So, this is the matrix which would have been the usual inverse of $A$, without division by the determinant.
The matrix $(\det A)^{-1} \times B$ is an inverse to $A$ modulo $m$. You can ensure that all the entries of the above matrix are between $0$ and $m$ for completeness, by division by $26$ and taking the consequent remainder of each entry.
Answer: Doing aritmetic modulo $\;26\;$ all the time, we get that
$$\det A=\begin{vmatrix}1&5\\3&4\end{vmatrix}=4-15=-11=15\implies$$
$$\implies A^{-1}=\frac1{15}\begin{pmatrix}4&-5\\-3&1\end{pmatrix}=7\begin{pmatrix}4&21\\23&1\end{pmatrix}=\begin{pmatrix}2&17\\5&7\end{pmatrix}$$
Answer: The determinant is $-11 \pmod{26}$.
$$(-7)(-11)=77=26\cdot 3-1\equiv -1 \pmod{26}$$
Hence the inverse is suppose to be $7$ rather than $-7$.
$$7 \begin{bmatrix} 4 & -5 \\ -3 & 4\end{bmatrix} \equiv \begin{bmatrix} 2 & 17 \\ 5 & 3\end{bmatrix} \pmod{26}$$

Inverse of a modular matrix


Error in plm random effects Swamy–Arora (swar) estimator with lagged dependent

Question: I am using synthetic data with a model that has a lagged dependent variable. When estimating a random effects model using Swamy–Arora estimator (default) with package plm, I get the error
Error in swar(object, data, effect) :
  the estimated variance of the individual effect is negative

But, if I try with any other of the available estimators (namely, "walhus", "amemiya", "nerlove" or  "kinla"), then everything works fine.
Below is a code that shows the issue.
###########################################################
# Script to show problem with swar estimator of r.e. in plm
# Date: 20151013
###########################################################

# Dependencies
library(MASS) # to sample correlated multinormal
library(plm)

#########################################################################
# CREATE TEST DATA
# This part creates a panel with H individuals and S observations each
# The model has a lagged dependent variable with weight rho
# We also use k multinormal correlated (r) predictors, with weights = 1:k
# We use random effects u = 1:H
# Series start at y0
#########################################################################

k = 5
r = 0.5
S = 1000
R = mat.or.vec(k, k) + r
diag(R) = 1
y0 = 1
rho = 0.9
sigma_e = 3
H = 10

for(h in 1:H){
  # Predictors
  X = mvrnorm(S, rep(0, k), R)

  # Dependent
  y = mat.or.vec(S, 1)
  y[1] = y0
  eps = rnorm(S, 0, sigma_e)

  for(i in 2:S){
    y[i] = rho * y[i-1] + as.numeric(X[i,] %*% 1:k) + eps[i] + h
  }

  # we create a lagged depedendent variable manually to see if this fixes
  # the problem
  temp = data.frame(y[2:S], y[1:(S-1)], X[2:S, ], rep(h, S-1))
  names(temp) = c("y", "y.l", paste("x", 1:5, sep=""), "id")
  temp$t = 1:(S-1)

  if (h == 1) {
    datos = temp
  } else {
    datos = rbind(datos, temp)
  }
}

# Finished

######################################################################
# ESTIMATE THE PANEL
# First we estimate F.E.: it work perfectly
# Then we estimate R.E.
######################################################################

pdatos = pdata.frame(datos, index = c("id", "t"))

# Fixed effects
fitfe = plm(y ~ lag(y, 1) + x1 + x2 + x3 + x4 + x5, data = pdatos)
summary(fitfe) # Beta OK
sqrt(sum(fitfe$residuals ^ 2) / fitfe$df.residual) # sigma_e OK
summary(fixef(fitfe)) # F.E. OK

# Random effects: swar
fitre = plm(y ~ lag(y, 1) + x1 + x2 + x3 + x4 + x5,
            data = pdatos, model = "random", random.method = "swar") # Fails

# manually created lag
fitre = plm(y ~ y.l + x1 + x2 + x3 + x4 + x5,
          data = pdatos, model = "random", random.method = "swar") # Fails

# Random effects: other methods
fitre = plm(y ~ lag(y, 1) + x1 + x2 + x3 + x4 + x5,
            data = pdatos, model = "random", random.method = "walhus") # OK
summary(fitre)
fitre = plm(y ~ lag(y, 1) + x1 + x2 + x3 + x4 + x5,
            data = pdatos, model = "random", random.method = "amemiya") # OK
summary(fitre)
fitre = plm(y ~ lag(y, 1) + x1 + x2 + x3 + x4 + x5,
            data = pdatos, model = "random", random.method = "nerlove") # OK
summary(fitre)
fitre = plm(y ~ lag(y, 1) + x1 + x2 + x3 + x4 + x5,
            data = pdatos, model = "random", random.method = "kinla") # OK
summary(fitre)

# End

Comment: You do know that estimating model with lagged dependent variable gives biased with random effects will give you a biased estimates?
Answer: The error message is correct; this is not an error with the plm package in particular. The default Swamy and Arora (1972) estimator (random.method="swar" is used if not something else is explicitly stated by the user) is not guaranteed to yield positive estimates for the variance.

Wooldridge (2010), p. 296 has some advice:
"As a practical matter, equation (10.37) is not guaranteed to be
positive, although it is in the vast majority of applications. A
negative value for sigma_c^2 is indicative of negative serial
correlation in u_it, probably a substantial amount, which means that
Assumption RE.3a is violated. Alternatively, some other assumption in
the model can be false. We should make sure that time dummies are
included in the model if aggregate effects are important; omitting
them can induce serial correlation in the implied u_it. When the
intercepts are allowed to change freely over time, the effects of
other aggregate variables will not be identified. If sigma_c^2 is
negative, unrestricted FGLS may be called for; see Section 10.4.3."

Sometimes, just adding more control variables or transforming variables also help to overcome this issue (from a technical viewpoint) if you want to stick with the swar estimator.
Comment: Good answer, but it should be noted, that random effects model should not be used for regression with lagged dependent variable.


load image with glide and change image view width base on image width

Question: I am loading image into recycle view with Glide library, with large image every thing is fine but when image size is small I want decrease image view width to avoid low quality view ,I try these lines of code but its not work all time and change all image size when reload image:
<code> Glide.with(context).load(url).listener(new RequestListener<Drawable>() {
                    @Override
                    public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {

                        return false;
                    }

                    @Override
                    public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {

                        ((imageHolder) holder).pb.setVisibility(View.INVISIBLE);
                        final GifDrawable gifDrawable;
                        if (resource instanceof Animatable) {
                            gifDrawable = (GifDrawable) resource;
                            gifDrawable.start();
                        } else {
                            gifDrawable = null;
                        }
                        int imageViewWidth = RelativeLayout.LayoutParams.MATCH_PARENT;
                        if (getScreenWidth() > (2.5 * resource.getIntrinsicWidth())) {
                            imageViewWidth = getScreenWidth() / 2;

                        } else {
                        }
                        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(imageViewWidth, RelativeLayout.LayoutParams.WRAP_CONTENT);
                        ((imageHolder) holder).imageView.setLayoutParams(lp);
                        return false;
                    }
                }).apply(new RequestOptions().placeholder(R.drawable.s).centerInside()).into(((imageHolder) holder).imageView);
</code>
and this my xml:
<code> <ImageView
    android:id="@+id/p_image"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:adjustViewBounds="true"

    />
</code>
and I have to say I can not get Image size without download it.
Answer: Did you try
.centerCrop()?
change centerInside with centerCrop


How to use re.compile with class in BeautifulSoup

Question: I am trying to scrape a page with different css classes as follows:
class="mod result idx0 people"
class="mod result idx1 people"
class="mod result idx2 people"
class="mod result idx3 people"
class="mod result idx4 people"

I am using bs4 and html5lib with Python2.7
Now when I do this for first element above I get the results positively.
soup.find(class_="mod result idx0 people")

However, I want to do this for all the classes.
So I am trying all of them but am still getting an empty list []. What am I doing wrong?
soup.find_all(class_="mod result")
soup.find_all(class_=re.compile("mod result"))
soup.find_all("li",{"class":re.compile("mod result")})
soup.find_all("li",attrs={"class":re.compile("mod result")})
soup.find_all({"class":re.compile("mod result")})

None of them are working :-(
Comment: So someone stupid edited my question - then someone smart changed it again back to what I posted... and in between I get marked down for posting incorrect question --- wow :-)
Answer: According to (Beautiful Soup documentation - Search by CSS class), if you want to search for tags that match two or more CSS classes, you should use a CSS selector.
soup.select('.mod.result')

Comment: Yepiie :-) Thanks again falsetru :-) Never knew classes have to dealt with css. I always preferred find method. But I guess I have to learn this now :-) But it does work. Thank you so much


Given two circles, arc length of the intersection

Question: If I have the radius of each circle, and the distance between them, how can I calculate the arc length of each arc in their intersection?
Comment: Hint: you can compute the length of the overlap as $(r+r') - d$, where $r,r'$ are the radii and $d$ is the distance between the circle centers.
Comment: @lightxbulb: How does that help?
Comment: Draw an image and see for yourself. The arc length of the intersection is a function of it @TonyK.
Comment: Not to mention that what he's asking is available with a rudimentary google search, with derivations and everything.
Comment: @lightxbulb: But what to search for? It's like when we asked the teacher how to spell a word, and she said "Look it up in the dictionary!" Perhaps [this link](http://mathworld.wolfram.com/Circle-CircleIntersection.html) might help the OP (although it doesn't use your $(r+r')-d$ expression at all).
Comment: @TonyK look closer it does involve it. Everything he had to search for is circles intersection.
Comment: Solve for the angles the triangle formed by the segment between the centers and the two radii to an intersection point.
Comment: I had seen that page, but my attempts to implement it were unsuccessful.
Answer: Let $T$ be one of the intersection points of the circles. By Heron's formula the area of the triangle $O_1TO_2$ is
$$A_{O_1TO_2}=\sqrt{P(P-R_1)(P-R_2)(P-D)},
$$
where $P=\frac{R_1+D+R_2}{2}$ is the semi-perimeter of the triangle.
On the other hand the same area can be written as
$$A_{O_1TO_2}=\frac{1}{2}R_iD\sin\phi_i,
$$
where $\phi_i$ is the angle at $O_i$.
Finally we have:
$$
\Phi_i=2R_i\arcsin\frac{2 \sqrt{P(P-R_1)(P-R_2)(P-D)}}{DR_i};\quad i=1,2,
$$
where $\Phi_i$ is the arc length in question.


How to select a specific row in views-view.tpl.php?

Question: I'm customizing a specific views block and trying to separate the 2 first rows in a "top" div(wrape it)
Comment: Please post code as code block, not image. Also, what exactly do you want to do? Select in what sense? Mark as "selected" for user? Read it's data? What do you need to do with that row?
Comment: Why vote in negative? The question is clear: "I'm trying to separate the 2 first rows in a top div(wrape it)".
Comment: You guys should not vote like that in questions what you dont know what about it is. Again, the question is clear, I have been supported in other sites and it isn't my first time in StackExchange sites.
Comment: Welcome to Drupal SE, sorry you arent feeling supported.  Here are some pieces of information that would make your question easier to read.  1. what is the template filename that you have a screenshot of there  2. why is the displayed code not working for you 3. do you have devel module enabled, or are you able to use it 4. can you add a picture of the views settings in the advanced area mentioned by Daedalus in his answer?
Comment: Hi @DeveloperWeeks the template is views-view.tpl.php like I said. Nevermind, I just found the answer to this question thank to hints of Daedalus and people of Drupal.org and facebook drupal groups.
Comment: @DocKodam "Unclear what you're asking" is **especially** for questions that make it hard for people to know what they are about...
Comment: @Mołot again, if one person understand the "template nesting level" of views/drupal, so he can clearly understand this question like other people already answered me in other places.
Answer: This type of question has come up for me and I found that going a few layers back (or up) and head  towards rows style output solved my issue. If you edit that view you want to override, then go to the Advanced column, expand it, then click on Theme: information. In that overlay window you can see they will suggest what to call a .tpl.php to override the different levels. I would choose the one that has row style output. From there, with a debugger, I am sure you can figure out how to isolate the first two rows. Hope this helps you find the solution you need.


React Bootstrap Validation use validated input in sub component

Question: I am using react-bootstrap-validation that decorates the react-bootstrap Input tag.
The ValidatedInput requires that it is inside a Form component.
When I add my ValidatedInput to a custom sub component I get an error saying it needs to be inside a Form which it is, but I guess it is further down the tree now so can not see the Form.
Is there a way of referencing the parent Form so the ValidatedInput can see the parent.
Looking at the source of the Validation lib I can see that the ValidationInput needs to register to the Form but am not sure how to do this from the sub component.

// Parent render
render(){
   <Form
   className="fl-form fl-form-inline fl-form-large"
   name="customer-details"
   onValidSubmit={this._handleValidSubmit}
   onInvalidSubmit={this._handleInvalidSubmit}
   validationEvent='onChange'>

     <TitleSelect handleChange={this.updateDropDown} value={this.state.form.title} />

   </form>
}

// Sub class containing the ValidatedInput
export class TitleSelect extends React.Component {

    static propTypes = {
      handleChange: React.PropTypes.func.isRequired,
      value: React.PropTypes.string.isRequired
    }

    render(){

        return (
          <ValidatedInput
            name="title"
            label='title'
            type='select'
            value={this.props.value}
            onChange={this.props.handleChange}
            groupClassName='form-group input-title'
            wrapperClassName='fl-input-wrapper'
            validate='required'
            errorHelp={{
              required: 'Please select a title.'
            }}>

            <option value="" ></option>
            <option value="Mr">Mr</option>
            <option value="Mrs">Mrs</option>
            <option value="Master">Mstr.</option>
            <option value="Ms">Ms</option>
            <option value="Miss">Miss</option>
            <option value="Reverend">Rev.</option>
            <option value="Doctor">Dr.</option>
            <option value="Professor">Prof.</option>
            <option value="Lord">Lord</option>
            <option value="Lady">Lady</option>
            <option value="Sir">Sir</option>
            <option value="Master">Mstr.</option>
            <option value="Miss">Miss</option>
          </ValidatedInput>
        )
    }
};
Comment: Look at inspector to get a clue as to how react is parsing your components. That should give you a start.
Answer: At the moment this is impossible to do. It will be possible in a future release once we get proper parent-based contexts in react and I will migrate the component to contexts. But for now I would recommend to split your render() method to couple of smaller ones and reuse them.
Comment: Any progress on "migrating components to contexts"?   In the mean time, could you illustrate your recommendation with a code example?  I can't really fathom how to solve the problem by "splitting `render()`"
Comment: Currently there's no ETA on that feature, sorry. As to splitting `render()` method, consider following example: https://github.com/react-bootstrap/react-bootstrap/blob/master/src/InputBase.js#L184-L207
Answer: Sa @Ваня Решетников said above it's impossible to do it now because of limitations of current design. A solution I went for is this.

Convert subcomponent to plain JS object
TitleSelect = {
  // move prop types to parent
  renderTitleSelect(){
    ...
  }
}

Add new object as a mixin to parent and render a function
mixins: [TitleSelect],
...
render() {
  <Form ...>
    // parentheses are important!
    {this.renderTitleSelect()}
  </Form>
}

Comment: Thanks, I did hear that mixins will be removed at some point so dont want to go down that route. Think I will just move my inputs out of sub components until we can get context introduced.
Comment: I can't see a mention of mixins being removed anywhere (that would be strange to be honest because such mechanism is necessary) and switch to  contexts may take a loooong time
Comment: Read this article about it https://medium.com/@dan_abramov/mixins-are-dead-long-live-higher-order-components-94a0d2f9e750 the author did also mention it in his talk at react Europe. Think I might not use sub components until we can get context sorted.
Comment: Any progress on this?  I read the linked articles, and found it hard to understand how I would use what is describe there to solve this problem.
Comment: I did end up using something like the mixin shown in the answer


Are tonal (sharp, flat and natural) key signatures octave specific?

Question: I recently bought a piano for learning (by myself at the moment) and apart from doing basic exercises, I decided to start learning a piece to get a grip on music sheet reading as I go.
On the sheet I'm trying to play there are 2 sharp key signatures at the start of the line: higher C and higher F (pardon me if terms are not accurate). What caught my attention is that in this piece at higher octave C and F do not sound right without a sharp.
With that in mind, I am wondering if tonal signatures are specific to octave they are written on. For instance, in my case if higher C and F have sharp signatures, would every C and F in the section be a sharp or just the ones on the lines sharp signatures are written on?
Sheet I am trying to play in case my descriptions are hard to read.
Answer: Accidentals in a key signature always apply to any octave you play in.
The human ear hears the same note in neighbouring octaves as almost identical (in fact, many people have a hard time distinguishing them at all). People sing along to a tune in a higher or lower octave with no qualms, and often without noticing. Some instruments, e.g. kettle drums, emit sound that is in fact hard to assign to a particular octave even if you measure it with precision instruments. In brief, it would be majorly unexpected and awkward if an accidental applied only to exactly one particular tone, therefore the rule has always been that it applies to all octaves indifferently.
The specific way the accidentals are arranged on the modern five-line system is merely a convention. It's nice to have because it lets experienced players recognize a key at a single glance, but it's irrelevant to this principle. In fact, when notated in the bass clef many accidentals go in different places, and that makes no difference either.
(Note that individual accidentals inserted into the middle of a piece can in principle break this rule, but it's very rare to combine e.g. an f with an f sharp, and you'll probably go years without ever encountering such an advanced chord.)
Comment: If I understand it correctly accidentals are marked next to a note. While this does help for future reference, right now I am looking at the key signatures at the start of the line.  Do they share the same trait? I am sorry, If I was not specific enough.
Comment: @Zero: Yes, they share the same trait. Every modification applies for all notes regardless of their octave.
Comment: Can you explain a little more what you mean about the kettle drum? Also I don't see what's advanced about an f with an f sharp - that would be found in an f#maj7 chord, for example...?
Comment: @topomorto - F#maj 7 is F# A#C# E#, surely. Not an F in sight.
Answer: Most scales are assumed to be octave-repeating, due to the way that we hear a similarity between notes that are an octave apart (the reason for this being that with many instruments, any note contains harmonic partials at the frequencies of all the overtones of a note an octave below).
This includes the diatonic scale, which is the scale that standard notation assumes and that key signatures are relevant to, and this is why key signatures are read as applying to all octaves.
Incidentally, there do exist scales which are not octave repeating, e.g. http://en.wikipedia.org/wiki/Bohlen%E2%80%93Pierce_scale.
Answer: In principle key signatures apply to all octaves, while individual accidentals apply only to the octave, where they appear. Sometimes score editors are helpful by repeating individual accidentals (courtesy or cautionary accidentals); if these are not especially marked (smaller print, parentheses) it makes the rule more diffcult to recognize for the inexperienced.
In the strict sense, even an accidental in small print (e.g. within an ornamentation) applies to all notes up to the end of the bar.
I revised my answer according to Eduards comment, but even if I found  the information, that individual accidentals on in the octave where they occur in every reference I encountered, I received nothing but astonishment from every professional musician I asked. So I would summarize:
While individual accidentals theoretically apply only to the specific octave, this can't be relied upon: few people (including sheet editors) are aware of the rule, so in case of doubt, use what sounds more appropriate.
Comment: Although it is prudent when editing to add courtesy accidentals, [accidentals normally only apply in their octaves!](https://en.wikipedia.org/wiki/Accidental_(music))


When to report quadratic versus linear relationships

Question: I seem to remember from my graduate statistics course that if higher order variables (i.e., X^2, X^3, etc) are significant in a polynomial regression analysis such as our quadratic regression, then the relationship between the DV and IVs is considered to be the highest order variable.
In other words, when I do a regression in the format of X + X^2, and both the linear (X) and quadratic (X^2) components of the analysis are significant, we report the relationship as quadratic?
Both the X and X^2 predictors are significant in the model
but X is more significant is it still considered to be a quadratic relationship? Note also that a simple linear regression has a lower R^2 than the quadratic regression.
Comment: It's not entirely clear what you mean. If the relationship was quadratic then why would you try and model the two variables using a regression that doesn't include the quadratic term (i.e. a linear regression)?
Comment: What do you mean "more significant"? Do you mean that the p value is bigger for the linear term than the quadratic term? if so, you may want to contemplate the phrase "the difference between significant and not significant is not itself significant"
Comment: I've edited the question to be more clear. My confusion is because the X relationship is more significant then X^2
Comment: Furthermore, the coefficient estimate & p-value for the lower-order effect will depend on the origin used for the scale on which $x$ is measured: it makes no sense to consider it in isolation as a "main effect".
Answer: If this is primarily a linguistic question 'What do I call it?' then I think you use the highest term. So if when you plot it the appearance is almost straight but with a slight curve it is still quadratic.
Some of the other issues about inclusion of terms of various orders have been dealt with extensively on this site, for instance here
Answer: From my personal experience, I would choose one or another depending on two things.
First, depending on the application, the error between the regression line and the data that can be accepted may be different. If choosing just linear regression meets your error requirements, why not keeping it simple. It is usually a tradeoff between the precision of fit and the robustness (the ability to applicate it to other sets of same kind of data).
Second, sometimes we have some a priori knowledge on the data. For example, we know that the relationship between y and x is expected to be linear, or that it might be strongly non linear, etc. This may help also to choose between the regression models.


Como alterar o estilo de um elemento em um iframe a partir da página mãe?

Question: Utilizo um componente que gera um iframe acessando uma página remota.
Exemplo: supondo que no iframe exista uma tabela com alguns TDs com a classe destaque, quero colocar uma borda vermelha nestes "destaques".
Tentei o seguinte código, mas não funciona:
$('iframe tr td.destaque').css('border-color', 'red');

Como alterar o estilo de um elemento em um iframe a partir da página mãe?
UPDATE: Tentando utilizar o contents, conforme resposta de @Rafalages, apresenta o seguinte erro:

jquery-3.1.0.min.js:2 Uncaught SecurityError: Failed to read the 'contentDocument' property from 'HTMLIFrameElement': Blocked a frame with origin "https://192.168.1.15" from accessing a frame with origin "https://www.google.com". Protocols, domains, and ports must match.
Answer: .contents() deve resolver:
$('iframe').contents().find('tr td.destaque').css('border-color', 'red');

https://api.jquery.com/contents/
Comment: Cara, a página tem que estar no mesmo domínio que o seu ou então estar com CORS ativo.
Comment: Agora apresenta o erro: jquery-3.1.0.min.js:2 Uncaught SecurityError: Failed to read the 'contentDocument' property from 'HTMLIFrameElement': Blocked a frame with origin "https://192.168.1.15" from accessing a frame with origin "https://www.google.com". Protocols, domains, and ports must match.
Comment: Se estiver em outro domínio e não estiver com o CORS ativo?


DNS Service not running on a Sandboxed and alienated single Domain controller

Question: we were trying to created a sandboxed test environment; so we promoted a member server to a domain controller and then shut it down moved it to a sandboxed netwrok and cleaned up metadata. Everything was fine untill then but later when we tried to add a workstation to the domain in the sandbox, it failed because DNS lookup failed; Please do advice me how to recover from this? We cant move that DC to live domain again.
Please do let me know of any aditional questions.
Comment: That's what I'm implying, that the DC should use itself for DNS, assuming that the DNS role is also installed on the DC. Additionally, if the DC doesn't have a copy of the AD DNS zone then the workstation isn't going to be able to find the DNS SRV records for the DC in order to communicate with the DC and join the domain. Furthermore, the DC isn't going to function properly if it doesn't hold a copy of the AD DNS zone. Basically, you have no DNS support for the domain in the sandbox. My suggestion would be to start from scratch and follow the advice from MDMarra in his answer.
Comment: Is the DC using itself for DNS? Does it have a copy of the AD DNS zone? Is it authoritative for the AD DNS zone? Are the correct DNS records for the DC registered in the DNS zone? Is the workstation using the DC for DNS? Do the DC and the workstation have layer 2 and layer 3 connectivity between them?
Comment: The DC should use itself for DNS since its the only DC in sandbox; It doesnt have copy of AD DNS zone; all it has is replicated ntds dit and sysvol and it is itself a domaincontroller.
Comment: I actually just installed the DNS role on the DC and then created a forward zone  with domain name; it has host A for the server and Name server and a SOA; is it possoble to just create an SRV to make the workstation find the DC and get added to the domain? there wont be another DC in this sandbox, it will only be 1 DC and 1 Workstation.How can i create the SRV record manually for tricking the workstation?
Answer: This really is not the right way to do what you want to do. If you want to populate a DC with a bunch of accounts to test with, you should promote the DC to a fresh test domain from a fresh OS install. Don't join it to the existing domain and move it. Then you can use a tool like ldifde.exe to export all of the accounts from your existing domain into the test one.
Comment: I don't know if I'd agree with that. There have been multiple migration test scenarios that I've mocked-up using virtual DCs that, initially, started their lives as replicas of a production domain. I think this is a perfectly valid technique, provided you understand how to get the "under glass" copy of the DC working properly and, of course, you understand that it can never be connected to the production network.
Comment: @Evan yes, my only fault was not obtaining the DNS stuff(which is not stored in AD in our domain); so i had to export the whole DNS zone seperately and import it in the sandbox DC and then spoofed one of the DC's ip addreses(In SRV records)  with Sandbox DC IP.
Answer: I fixed it; just exported the DNS zone from our domain using  "DNSCMD /ZONEEXPORT"  and then imported the whole thing in the sandbox using "DNSCMD /ZONEADD" command. Currently i was able to add my workstation to the domain.


Change the link of a view block

Question: Hi I need to change the url path of the view which appears to be a block also,its a button and I want that it redirects to the correct URL, how do I change it?
Please help me..
Answers and directions will highly be appreciated thanks.
Comment: your question is not clear please edit it and make it proper.
Answer: Blocks do not have URLs.  Pages that blocks are on have URLs.
Check the gear icon when you hover over the view area.
If it says configure block, you are on a page created somewhere else and depending on how it was created may need to edit the code where it is defined in hook_menu() or if it is a page node, you can just go to admin/content and search for that page, and at the bottom you will see URL settings.
If it says does not say configure block and only edit view, then that page was likely created by that view you are about to edit.  In this case you can click Edit View and in the middle of the window you will see Page Settings section with a Path field.  You can edit that Path field which is the URL of the view.

Change the link of a view block


Prompt user to close applications on uninstall - WIX

Question: I have a custom action "xxxx" which deletes directory by executing rmdir through command prompt.
ExeCommand="[SystemFolder]cmd.exe /C rmdir /Q /S "[DIR]"" and Execute="deferred"
It is added in InstallExecuteSequence as below
Custom Action="xxxx" After="InstallInitialize"
  (NOT UPGRADINGPRODUCTCODE) AND REMOVE
Custom

If the directory is opened by some other application such as command line, then it throws error.
I read many similar issues. But couldn't figure out on
1) prompt user to close applications - I read adding
UI
  DialogRef Id="FilesInUse"
  DialogRef Id="MsiRMFilesInUse"
/UI

and using custom action Before="InstallValidate" shows prompt to close applications.
2) How to run custom action after services are stopped and prompt user to close applications?
It should run in deferred mode.
3) If I want to run in Execute = deferred, then I can't use InstallValidate. Therefore I can't use FilesInUse.
4) Is there any other good approach? I don't want to reference a dll because I want the installer to delete entire directory on uninstall.
Answer: The big question is why you need to remove that folder because normally you don't need to. That means it must be getting left behind, but that's just a guess, so I'd say that's the problem to deal with - why it's left behind. Your question is about why your solution isn't working. The underlying issue is that InstallValidate will prompt a FilesInUse dialog if Windows decides it needs one, and Windows doesn't need one - you do because of your custom action - that's why FilesInUse UI refs aren't helping.
If you want to remove files or folders, the WiX RemoveFile element is the usual way, and it happens at the right point in the uninstall where everything else has beeen removed:
Wix RemoveFile and RemoveFolder for removing leftovers
If you want to tell an app to shut down, there is the WiX Util CloseApplication.
If you really want to solve the folder issue with your code and a FilesInUse prompt (rather then address the underlying issue of that folder) then a C++ custom action like this will show a FilesInUse dialog, immediate before InstallValidate should work, you'll need some includes of msi.h, msiquery.h:
UINT __stdcall ShowFilesInUse (MSIHANDLE hInstall)
{
PMSIHANDLE hRec = MsiCreateRecord(4);
MsiRecordSetString(hRec, 1, TEXT(" "));
MsiRecordSetString(hRec, 2, TEXT("Please use Task Manager to Terminate these programs:"));
MsiRecordSetString(hRec, 3, TEXT("something else"));
UINT res = 0;
do
{
res = MsiProcessMessage(hInstall, INSTALLMESSAGE_FILESINUSE, hRec);
}
while (res == IDRETRY);
if (IDOK==res) // 1 is the Continue button in VS
   return 0;
if (IDCANCEL ==res) // The Exit button in VS
   return ERROR_INSTALL_USEREXIT;
return 0;
}


Equation with fractions

Question: If $P=\frac{h}{1-h}$ then $h$ is equal to?
Answer is: $\frac{P}{1+P}$
I understand that $\frac{P}{1+P}$ is the right answer for when I replace $\frac{P}{1+P}$ for h the answer solves the equation, but what I can't do is find the answer by myself, how do I get to $\frac{P}{1+P}$?
Answer: Hint: Multiply both sides by $1-h$ and solve for $h$. This tactic (multiplying by the denominator) works in many cases when you want to solve problems with variables in the denominator; in the future it should be one of the first things you try.
Answer: $$P = \frac{h}{1-h}$$
Cross-multiplying you get
$$(1-h) \cdot P = h$$
After this, simply work to get the expression in terms of h.
$$P - P\cdot h = h$$
$$P = h + P \cdot h$$
$$P = (1 + P) \cdot h \implies h = \frac{P}{1 + P}$$
Answer: P = h/1-h --> (1-h)P = h;
P - Ph = h;
P = h + Ph;
P = h(1 + P);
P/(1+P) = h

Equation with fractions


Como verificar se uma data já está no formato correto em php?

Question: Estou pegando uma data em formulário e no firefox o campo DATE se comporta como um campo de texto normal. Ai, caso a pessoa digite um data no formato dd/mm/yyyy, tenho uma função que converte essa data pra salvar no MariaDB(MySql).O problema é que no chrome a data já vem formatada,ai nao precisa dessa formatação!
O que eu quero é fazer a verificação pra ver se esta data já no formato certo, pois se estiver quero ignorar a formatação.
segue a função:
function traduz_data_para_banco($parametro){

    if($parametro === null){
        echo "data nula";
        return;
    }
    $data_picada = explode("/",$parametro);
    $data_USA = "{$data_picada[2]}" . "-" . "{$data_picada[1]}" . "-" . "{$data_picada[0]}";

    return $data_USA;

}

Comment: Pq não explicar em formato brasileiro?
Answer: A melhor forma de validar datas no PHP é utilizando a classe DateTime().
Acredito que o mais importante não seja verificar se a data já vem no formato americano, mas se o usuário está informando a data corretamente
$data = '10/08/2017';
echo validarData($data, 'd/m/Y');

echo PHP_EOL; // Apenas quebra alinha

$data = '2017/08/10';
echo validarData($data, 'Y/m/d');

function validarData($date, $format = 'Y-m-d') {

    $d = DateTime::createFromFormat($format, $date);

    if ($d && $d->format($format) != $date) {
        echo 'Data Inválida';
    }

    return $d->format('Y-m-d');
}

E recomendo sempre usar a função para validar data, mesmo que o chrome retorne a data no formato banco, pois se um dia isso mudar, seu sistema já estará preparado para esta alteração.
Answer: $data = explode('/', $vigenciac);
                if (!checkdate($data[1], $data[0], $data[2])):
                    $mensagem .= 'Formato da Data do início da vigência inválido.';
                endif;
eu utilizo essa função e funciona perfeitamente para entrada de data.


Directive ngChange fires as many times as combobox options

Question: I have a Countries dropdown, nothin' fancy.  My only oddball requirement is that I want to be able to pass in an OnChange function from my controller so the Directive can run it.  Here is a Plunker
In the Plunker, I have this basic template:

    Country
    <select id="countryDirective" ng-model="country" ng-Change="countryChanged()" ng-options="obj.value as obj.name for obj in countries">
        <option value="">Choose Your Country</option>
    </select>
    {{country}}

The only difference between the On-Page HTML and the Directive Template is that I added ng-Change onto the On-Page HTML.
One point of note is in my Directive, I am using require: '^ngChange'.
I don't know why it isn't documented very well, but it works wonders and gets around all of the problems posed by other questions relating to change event firing before the scope is updated and other change issues.
However, the price for this elegance is that my countryChanged() function is being fired x times, where x is the number of items in the drop-down.  I assume because items are being observed one at a time and so changes keep happening?
So my main question is: How do I keep this elegance, but make the ng-Change only fire once per change?
Edit: Turns out switching to select ngOptions instead of option ngRepeat fixes my issue with them not sync'ing, but not the main issue of why my ngChange is firing x times in the Directive.
Comment: Try to replace your `ng-repeat` inside your option tag for an `ng-options` inside your `select` tag. Not sure if it'll fix your n calls problem but it might, and it's the recommended way to do what you want.
Comment: That doesn't fix the issue, but it is more elegant.  Sometimes I don't jump into the `ngOptions` before I finish a select because I'm more comfortable with `ngRepeat`.  But I went ahead and took that step and updated my Plunkr.  Still, didn't stop the onChange method from firing multiple times times.  But it did fix my second question and keeps them in sync for some reason.
Answer: I guess the issue was setValue: '=ngChange'
I changed it to setValue: '&ngChange' and added ng-change="setValue()" to <select/>
Now its triggering only once when you change it (verify console log).
I have updated plunker https://plnkr.co/edit/xYi4uoNLeJVvKAoZhjbH?p=preview
Comment: Good Catch.  I hadn't seen this answer in the last hour, and came to the conclusion, but since you posted it first, I certainly give you points.  Thanks for answering!


How to emulate shm_open on Windows?

Question: My service needs to store a few bits of information (at minimum, at least 20 bits or so, but I can easily make use of more) such that

it persists across service restarts, even if the service crashed or was otherwise terminated abnormally
it does not persist across a reboot
can be read and updated with very little overhead

If I store this information in the registry or in a file, it will not get automatically emptied when the system reboots.
Now, if I were on a modern POSIX system, I would use shm_open, which would create a shared memory segment which persists across process restarts but not system reboots, and I could use shm_unlink to clean it up if the persistent data somehow got corrupted.
I found MSDN : Creating Named Shared Memory and started reimplementing pieces of it within my service; this basically uses CreateFileMapping(INVALID_HANDLE_NAME, ..., PAGE_READWRITE, ..., "Global\\my_service") instead of shm_open("/my_service", O_RDWR, O_CREAT).
However, I have a few concerns, especially centered around  the lifetime of this pagefile-backed mapping.  I haven't found answers to these questions in the MSDN documentation:

Does the mapping persist across reboots?
If not, does the mapping disappear when all open handles to it are closed?
If not, is there a way to remove or clear the mapping?  Doesn't need to be while it's in use.

If it does persist across reboots, or does disappear when unreferenced, or is not able to be reset manually, this method is useless to me.
Can you verify or find faults in these points, and/or recommend a different approach?

If there were a directory that were guaranteed to be cleaned out upon reboot, I could save data in a temporary file there, but it still wouldn't be ideal: under certain system loads, we are encountering file open/write failures (rare, under 0.01% of the time, but still happening), and this functionality is to be used in the logging path.  I would like not to introduce any more file operations here.
Answer: The shared memory mapping would not persist across reboots and it will disappear when all of its handles are closed.  A memory mapping object is a kernel object - they always get deleted when the last reference to them goes away, either explicitly via a CloseHandle or when the process containing the reference exits.
Try creating a registry key with RegCreateKeyEx with REG_OPTION_VOLATILE - the data will not preserved when the corresponding hive is unloaded.  This will be at system shutdown for HKLM or user logoff for HKCU.
Comment: Thanks for confirming that my current approach is flawed; I was coming to that conclusion but put it to test yet.  `REG_OPTION_VOLATILE` in `HKLM` looks like a good fit, I just have to work around some in-house registry wrappers.
Answer: sounds like maybe you want serialization instead of shared memory? If that is indeed appropriate for your application, the way you serialize will depend on your language. If you're using c++, check out boost::serialize. C# undoubtedly has lots of serializations options (like java), if that's what you're using.
Comment: Serialization is not the problem; the problem is getting the lifetime of the serialized data exactly right.

How to emulate shm_open on Windows?


How to remove lemon oil from guitar parts where it doesn't belong

Question: I recently had a little mishap while cleaning the fredboard and spilled almost half a bottle of lemon oil over my guitar. Unfortunately lemon oil has the word "oil" in it, therefore it takes a lot of patience wiping it off with just a moist cloth.
How can I, without harming the materials, remove the excess lemon oil from the following guitar parts:

String posts (makes the strings slip when tuned too strong),
Strings (makes the fingers slip) and
Body (just doesn't look good)

The guitar in question is a Yamaha CX40 classical guitar with plastic string posts and flatwound strings.
Comment: Just a paper towel and/or a paper towel with a little mild dish soap and water on it - just so it's damp, not fully wet.
Comment: Sounds like you need some Lemon aid! Sorry, couldn't help myself. Try a small absorbent camping towel.
Answer: Body & string posts...
Microfibre cloths*, one wetted then squeezed as dry as you can get it, the other completely dry. Wipe over with the damp one, then dry with the dry. Repeat gently rather than scrub.
If that isn't completely effective [it should be with patience rather than elbow grease] then add a squirt of clear window cleaner to the wet cloth.
Strings...
...Discard.
[or if you must try it, boil in water with washing up liquid, which I've never found to be successful]
*The best microfibres for this type of task are actually the cheapest ones, available from any supermarket. They have lots of 'fluffy loops' that cling to your fingers when you pick them up [weird feeling, like picking up tiny velcro]. The specialist glass-cleaner cloths with a smooth finish can be too harsh on softer surfaces.
Comment: I admit, i was hoping for a miracle solution, but there is problably no way around several wet and dry microfibre cloths and a little patience (especially on the hard-to-reach string posts). A pity for the strings though, they are new and expensive.
Comment: I had a late thought of electrical degreaser spray for the posts. Shouldn't harm the varnish, but be sparing.


Css na condicional (somente com JQuery)

Question: Estou tentando colocar o color dentro do condicional, porém não estou conseguindo. PS: São três cores diferentes e somente pode ser feito com JQuery.

Para que a tabela criada seja adicionada na pagina, você devera criar um elemento, exemplo:

jQuery Referências

append
css
text
Comment: Então, o ponto é que eu não posso utilizar o CSS comum, mas sim apenas JQuery.
Comment: Entendi, então [edite](https://pt.stackoverflow.com/posts/248425/edit) sua pergunta, e informe mas sobre o seu problema.
Comment: Veja agora, como ficou

Css na condicional (somente com JQuery)


Erro ao obter token em interceptor - Type 'Promise>>' is not assignable to type 'Observable>'

Question: Estou criando um interceptor para enviar o token juntamente com as requisições para a Api.
Eu uso @ionic/storage para guardar as informações do meu usuário. Porém, quando eu tento obter o token no construtor para guardar em uma variável (ex: private token: string), o meu interceptor não consegue obter esse valor mesmo o token existindo. Creio que isso acontece pq o intercept é executado antes da função this.storage.get finalizar.
Como posso corrigir isso?
Já tentei colocar a função this.storage.get dentro do intercept, porém da erro de retorno:
"Type 'Promise>>' is not assignable to type 'Observable>'.  Property '_isScalar' is missing in type 'Promise>>'."
Vejam o código:

Agradeço a ajuda.
Answer: A resposta veio de um usuário do stackoverflow.com
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
var promise = this.storage.get('token')
    .then((token) => {
        if (token) {
            const newRequest = req.clone({ setHeaders: { 'Authorization': `Bearer ${token}` } });

            return next.handle(newRequest);
        } else {
            return next.handle(req);
        }
    })
    .catch((error) => {
        //TODO: Trata erro
        throw error;
    })
return Observable.fromPromise(promise);

}


Connect two mikrotik LAN

Question: I got two RB951G-2HnD and two RBSXTG-5HPnD-HGr2.

(clientsOfLan1) ))> RB1 <---> SXT1 ))> <(( SXT2 <---> RB2 <((
  (clientsOfLan2)

I need to 'connect' two LAN's around 951.
I can't figure out how to 'bridge' those two networks that clientsOfLan1 could see clientsOfLan2 on L2 layer.
RB1/2 is in ap bridge
SXT1 is station pseudobridge
SXT2 is ap bridge
I am quite lost. Can anyone suggest how to achieve this? I need same L2 (ethernet) network on both sides best possible latency and bandwidth. I want use/setup SXT1 and SXT2 to simulate a 'wire' that I connect between those two routerboards.
Comment: Don't bridge two IP networks through a pseudobridge. Pseudobriding is only suitable for bridging a single layer 2 device.
Comment: Are LAN1 and LAN2 on the same subnet?
Comment: They are both on 10.0.0.0/24 (L3). But I dont know to setup SXT's to create 'switching' (L2) network.
Answer: (clientsOfLan1) ))> RB1 <---> SXT1 ))> <(( SXT2 <---> switch <(( (clientsOfLan2)
if you want LAN1 and LAN2 use the same subnet, just make RB1 as the main router.
LAN1 and LAN2 assign DHCP from RB1.
i did it on my office.
thank you.
Answer: I think the best way to do this is to use WDS mode= dynamic on SXT routers, wds-bridge=bridge1 and to create bridge1 between eth and wlan interfaces on those SXT int. Set up mode of SXT1 to AP bridge and to SXT2 to Station-Wds.
This link will be the same as you connect ethernet cable between the two RB951.
Even the ip addresses you will give to those SXT devices does not have to be on the same network as the net of the two RB951.

Connect two mikrotik LAN


Let $G$ be a nilpotent group, $H\subsetneq G$. How to prove $H \subsetneq N$, where $N$ is a normalizer of $H$?

Question: Let $G$ be a nilpotent group, $H\subsetneq G$. How to prove $H \subsetneq N$, where $N$ is a normalizer of $H$?
I tried to use induction. It's easy to show the property works when nilpotency is equal to $1$, but I've got stuck moving further.
Comment: Please don't repost [closed questions](https://math.stackexchange.com/q/3835662/10513). Instead, you should edit them to improve them.
Comment: @user1729 ok, thanks
Answer: Hint: since $G$ is nilpotent it has a central series $\{N_i: 0 \leq i \leq r \}$ and $N_0=1 \subseteq H$ and $N_r=G$ which is not contained in $H$ obviously. So, there must be an index $i$ with $N_i \subseteq H$ and $N_{i+1} \nsubseteq H$. Try to show $N_{i+1} \subseteq N_G(H)$. Then $H \lt N_G(H)$.

 Observe that we have a central series here, and centers are always contained in normalizers, so $$N_{i+1}/N_i \subseteq Z(G/N_i) \subseteq N_{G/N_i}(H/N_i) \subseteq N_G(H)/N_i.$$ It follows that $N_{i+1} \subseteq N_G(H)$.
Comment: Sort of right track, but see spoiler.
Comment: I tried to work with commutators. [G,N$_{i+1}$] $\subseteq$ N$_i$ $\subseteq$ $_G$() then N$_{i+1}^G$ N$_{i+1}$ $\subseteq$ $_G$() . Am I going the right way?
Comment: Thanks a lot! But why do we have N$_{G/N_i}$(H/N$_i$) $\subseteq$ N$_G$(H)/N$_i$ ? Is it some property I forgot about? :)
Comment: No this is just computations in a factor group: let overbar $\bar{.}$ denote modding out by $N_i$. Let $\bar{g} \in N_{\overline{G}}(\overline{H})$. Then $\bar{g}^{-1}\bar{h}\bar{g}=\bar{k}$, for some $k \in H$. That is, $g^{-1}hg=kn$ for some $n \in N_i$. But $N_i \subseteq H$, and this implies $g \in N_G(H)$. Hope it is clear now!


SQL SELECT : map columns to new column

Question: I have a table with two columns of integers. I would like to select data from it (in some standard way) and add a new column by rule:

if number on left is bigger, new column is 1
if number on left is smaller, new column is -1
if numbers are equal, new column is 0

Example:
16 | 15 | 1
20 | 28 |-1
11 | 11 | 0
28 | 14 | 1
...

Answer: SELECT X,Y,
    CASE WHEN X > Y THEN 1
         WHEN X < Y THEN -1
         ELSE 0 END AS "Z"
FROM table_name

Comment: Is this "CASE" in standard? I was thinking about joining with (SELECT -1/0/1) ON (one of 3 conditions) and grouping it somehow...
Comment: Yes, it is standard SQL. See the answers to [this question](http://stackoverflow.com/questions/4622/sql-case-statement-syntax).
Answer: Sounds like you want the SIGN Function
SELECT Col1, Col2, SIGN(Col1 - Col2) AS Col3
FROM   T

SQL SELECT : map columns to new column


Jquery changing .live to .on,

Question: I am trying to change all my .live() to .on() as the prior is now deprecated.
I am struggling to understand how it works though. Before I used this code and it worked fine...
$('#lightBoxClose').live('click', function() {
    $('#lightBox').fadeOut();
});

So I tried changing it to,
$('#lightBoxClose').on('click', function() {
    $('#lightBox').fadeOut();
});

But it doesn't work can anyone please explain what I am supposed to be doing thanks.
Comment: Possible duplicate : http://stackoverflow.com/questions/8042576/whats-the-difference-between-jquery-live-and-on
Comment: See example at the bottom of http://api.jquery.com/on/
Answer: You have to bind to an element that already exists at the time of the binding, passing the target selector as the second argument. That element must be an ancestor of the eventual click target, so it can catch the bubbled event. This technique is called delegation.
For example, using the document element:
$(document).on('click', '#lightBoxClose', function() {
    $('#lightBox').fadeOut();
});

Comment: Really? That's so disappointing.  Why doesn't it just bind to the window by default?
Comment: @Anthony, because `.on()` does not just replace `.live()`, it's now the standard way to bind all events. So it cannot force delegation by assuming you always want to bind to `document`. (Note: you can't bind to the `window` object, because DOM events won't reach it.)
Comment: @ bfavaretto : if that's the case, will binding shorthand functions like `.click()` work if it's appended to an existing element? Like `$(document).$('.my_controllers').click("blah")`? It just seems like a bit much to a) have to establish in advance a parent when everyone is going to use `document` if it's not crucial to a specific panel and b) have to lose the event-specific shorthand methods that make jquery easier to look at and write. Seems like it's moving away from the lazy and weak ways I so identify with.
Comment: @Anthony, the shorthand methods like `.click()` are not deprecated, I use them all the time. It's just that `.on()` now combines the power of live, bind and delegate, so they're encouraging its use.
Comment: They may not be deprecated, but they are (and never have been) dynamically binding to new elements, and with this being in higher and higher demand as jquery gets more sophisticated, two things happen 1) less experienced developers hit their heads on the wall when the event methods don't work and 2) more experienced developers will always use `.on()` as a habit. Don't get me wrong, it's better to have one future-binding method over three, I just wish the listener list was a live node list instead of a subscription model.
Answer: Please use the search before posting, as it's posted all around SO.
See: JQuery switching application from "live" to "on" method
$(document).on('click', '#lightBoxClose', function() {
    $('#lightBox').fadeOut();
});

Jquery changing .live to .on,


Strange behaviour

Question: I have the following script which works kind of...
$(document).ready(function(){
    // add or remove from favorites
    $("input:checkbox").change(function() {
        if($(this).is(":checked")) {
            $.ajax({
                url: 'favorite.aspx',
                type: 'POST',
                data: { ID:$(this).attr("id"), State:"1" }
            });
        } else {
            $.ajax({
                url: 'favorite.aspx',
                type: 'POST',
                data: { ID:$(this).attr("id"), State:"0" }
            });
        }
    });

    // search on keyup
    $(".txtSearchBox").keyup(function()
    {
        $.ajax({
            url: 'search.aspx',
            type: 'POST',
            data: { strPhrase:$(".txtHeaderSearch").val() },
            success: function(results)
            {
                $("#divSearchResults").empty();
                $("#divSearchResults").append(results);
            }
        });
    });
});

When the page loads for the first time after clearing browser cache, favorites function works fine and so does the search function.  However, after loading the page after a page refresh, if I perform a search first, then try to tag a favorite, the favorite will not get inserted into the database, I have to click the reload browser button, then add a favorite.
Why is this happening?
Comment: you have a syntax error at " url: favorite.aspx',"  you let out the single quote before the favorite.aspx
Answer: You need to use live() as you are trying to act on stuff in the dom which you are inserting using ajax.
http://api.jquery.com/live/
Answer: Live is an answer, but I've had problems with change event with live and Internet Explorer, at least with select fields. I've solved the problem by using the livequery plugin.
jQuery delegate should also work if you don't want to install plugins.

Strange behaviour


Adjusting row height according to text in selected column

Question: I couldn't find the answer to this and thought the answer may be adaptable to be useful for other things and other people.
In cell G1 is a dropdown list, in columns out to the right are over 300 rows of text, with the header of each column making up what's in the dropdown list (G1). Depending on what is selected in the dropdown list, all other columns are hidden except the column that matches the dropdown list selection.
As there are varying amounts of text (most of it now hidden), with wrapped text and row.autofit turned on, the row heights for the visible column will be much larger than they need to be if one of the hidden columns has a lage amount of text in those particular rows.
I'd like to run a macro that adjusts the row height according to the row heights required for that selected column. Most of it will be single line (15), with around a dozen needing to be made larger. I'd like to set them all the 15 to begin with then find the rows that need a bigger height and adjust the height accordingly.
I understand from other posts that there is no easy solution (I'm using Excel 2007), although I liked the idea of copying the cell content, pasting it to a blank area of the worksheet, using autofit on that row to get the proper row height then applying that row height to where text was copied from.
This is my first post and very much a beginner at this so let me know if I'm doing something wrong in terms of how I pose the question. Below is where I've gotten so far, but I'm getting a type mismatch error on the line beginning If Not..
Option Explicit
Sub AdjustRowHeights()

    ' below code to adjust row height for selected comments

    Dim strSearch As String
    Dim aCell As Range
    Dim r As Integer

    strSearch = "G1"

    ' to set all rows to single row height
    Rows("9:331").Select
    Selection.RowHeight = 15

    ' to find the column currently on dislplay (header matching cell G1)
    Set aCell = Rows(5).Find(What:=strSearch, LookIn:=xlValues, LookAt:=xlWhole)

    ' cycle through rows checking active comments column for text and adjust row height if necessary
    For r = 9 To 331
    If Not Cells(r, aCell) Is Nothing Then
        Cells(r, aCell).Select
        Selection.Copy
        Cells(350, aCell).Select
        ActiveSheet.Paste
        Rows("350:350").EntireRow.AutoFit
        Rows("r:r").Select
        Selection.RowHeight = Rows("350:350").RowHeight
    End If
    Next r
End Sub

Answer: You are getting a type mismatch error because Cells expects Long or Integer arguments for the row and column. Try something like:
Cells(r, aCell.Column)


Bayesian Decision theory

Question: A person randomly chooses a coin with probability 0.5: Tossing coin 1 yields a head with a probability P(X1=H)=.3 (and tail with P(X1=T)=.7). Tossing coin 2 yields a head with a probability P(X2=H)=.6 (and tail with P(X2=T)=.4). You earn 1 dollar if you correctly guessed the coin and 0 dollars otherwise. Design the optimum decision rule and estimate your average earning.
Can anybody explain me ,how should i go about solving this problem?
Comment: Is this a homework question? If so, please add the `self-study` tag.
Comment: what is your experiment? is it one toss? or $n$ tosses, and you decide based on number of heads?
Comment: Could the user share his findings on this question? I am new to Bayesian and trying to understand this problem as homework. It would be really helpful if the user shares the whole answer to this question.
Comment: @user277892 - Can you let me know exactly which part you find unclear or need further help with? Then I can expand my answer to help you out.
Answer: Given that you know all the probabilities that govern your system, I don't think you need to apply anything "Bayesian" for this. You can simply calculate the probability of heads as
$$P(H) = P(H | X1) P(X1) + P(H | X2) P(X2)$$
You can use a similar calculation to calculate the probability of tails. Now that you have these probabilities, you can compute the expected earnings if you guess heads and if you guess tails, and base your decision rule on this calculation.
Please let me know if any of this is unclear.
Edit:
When you know $P(H)$ and $P(T)$ you can compute the expected earnings as
$$ E(\mathrm{earnings}) = P(H)*[\mathrm{earnings\ in\ case\ of\ }H] + P(T) *[\mathrm{earnings\ in\ case\ of\ }T]$$
Now the earnings in case of heads and tails depend on your decision rule, so you should compute the expected earnings for every possible decision you can make and then make the decision with the highest expected earnings.
Comment: I calculated the probabilities but i'm not able to figure out how should i compute the expected earnings...
Comment: I edited my answer so that you can hopefully solve your problem now.

Bayesian Decision theory


Do I need to adjust the degrees of freedom returned by pool.compare() in MICE?

Question: I am analyzing a multiply imputed dataset produced from the MICE package in R. To assess the overall significance of my linear model, I am using pool.compare() to compare my "full" model to an intercept only "restricted" model. However, the degrees of freedom (residual) returned by pool.compare() seem very highly inflated (I have set m = 50 imputations). I'm aware that 50 imputations is high, but it's needed for my dataset. I've given an example below of the same issue using the nhanes2 dataset from the MICE package. I have two questions:
1) Why are the degrees of freedom returned by pool.compare() so high?
2) Is it appropriate to use the adjustment to the degrees of freedom suggested by Barnard and Rubin (1999) and described in section 2.3.6 of Stef van Burren's Flexible Imputation of Missing Data textbook?
The R code below shows the issue I'm asking about using the nhanes2 dataset. This dataset has 25 observations and the example fits a linear model with one categorical predictor (age) with three levels and one continuous predictor (chl).
# load package and data
library("mice")
data(nhanes2)

# impute missing values, m = 50
imp <- mice(nhanes2, m = 50, seed = 1, print = FALSE)

# produce the models to compare, a full model and
# an intercept only restricted model
fit.imputed.full <- with(imp, lm(bmi ~ age + chl))
fit.imputed.res <- with(imp, lm(bmi ~ 1))

# compare models using pool.compare()
pooled.comparison <- pool.compare(fit.imputed.full, fit.imputed.res)

# given that the original dataset had 25 observations, and we have a
# linear model with three predictors (age is a factor with three levels)
# I'd expect the degrees of freedom (residual) for the comparison to be at
# most 24. The df for the numerator comes as expected:

pooled.comparison$df1
[1] 3

# the df for the denominator comes out a much larger than the
# maximum of 24:

pooled.comparison$df2
[1] 1374.457

# by way of comparison, the same analysis conducted on a single
# hypothetically complete dataset gives the expected degrees of freedom

nhanes2CCA <- complete(imp, 1)
attach(nhanes2CCA)
fit.CCA.full <- lm(bmi ~ age + chl)
fit.CCA.res <- lm(bmi ~ 1)
detach(nhanes2CCA)
anova(fit.CCA.full, fit.CCA.res)

Model 1: bmi ~ age + chl
Model 2: bmi ~ 1
  Res.Df    RSS Df Sum of Sq      F  Pr(>F)
1     21 293.60
2     24 477.23 -3   -183.62 4.3778 0.01525 *
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

In the end, it seems strange that an analysis conducted on a hypothetically complete dataset returns 24 degrees of freedom, while an analysis conducted on 50 multiply imputed datasets returns over 1000 degrees of freedom. Why is there this large difference in degrees of freedom?
My second question relates to the correction proposed by Barnard and Rubin(1999). Is it appropriate to use that correction here? Because this is a multi-parameter test, doing so requires, I guess, an estimate of lambda which is averaged across the parameters being estimated.
The figures I've used in this example are:
v_old = 1374.457
v_com = 25-1 = 24
average lambda = 0.329
v_obs = 14.91
v (adjusted degrees of freedom) = 14.75
Applying this correction in this instance returns a corrected degrees of freedom of 14.75, which is more than the df that would be returned by analyzing only complete cases (12) and less than the df that would be returned by analyzing a hypothetically complete dataset (24). Which seems reasonable.
Thank you all for your assistance.
Matt.
Answer: You posed two questions, so I will simply comment on them in order:
Question 1: High degrees of freedom:
Such high degrees of freedoms are normal with pool.compare. The function implements the procedure by Meng & Rubin (1992), in which the denominator degrees of freedom for the test statistic $D_m$ are derived under the assumptions that the complete-data degrees of freedom are infinite (see also Rubin, 1987).
Thus, the procedure will estimate the degrees of freedom smaller than in the hypothetical complete-data (i.e., smaller than infinity), which often results in relatively large denominator degrees of freedom in MI. Sometimes this is inappropriate, especially in smaller samples.
Question 2: Correction formula of Barnard & Rubin:
The correction formula in Barnard & Rubin (1999) adresses the aforementioned problem, but not for multiparameter tests (as done in pool.compare) but for tests for scalar estimands (e.g., a single regression coefficient).
Therefore, this correction formula is not the way to go here. Luckily, there is also a correction formula available for multiparameter tests. That formula was proposed by Reiter (2007) and was originally developed for the procedure by Li, Raghunathan, and Rubin (1991).
However, these two procedures are asymptotically identical in many cases, and the expression for the degrees of freedom is the same in $D_1$ and $D_3$. Therefore, I would suggest you apply Reiter's correction formula to the results in pool.compare. The formula is not much more difficult to apply than that of Barnard & Rubin, and it is also implemented in a couple of R packages.
You can find some very readable applications of Reiter's correction formula in the article by van Ginkel and Kronenberg (2014), who apply the procedure of Li et al (1991) with Reiter's corrections to the ANOVA (recall that Meng & Rubin, 1992, and Li et al., 1991, can be thought interchangeable in this case).
Edit:
However, it is not unlikely that you will observe no big difference. The outcome of your hypothesis test will likely remain the same.
Comment: SimonG thanks for your answer and apologies for the delay in getting back to you - I've been OS and working on another project since July. Much appreciated.


visualvm fails with "No jdkhome found" on Ubuntu 15.10 with Oracle JDK

Question: I installed Oracle JDK from the webupd8team/java PPA, and then installed the visualvm package. When starting visualvm, I get the following error message:
[beni:~]$ visualvm
No jdkhome found

My $JAVA_HOME is set correctly to /usr/lib/jvm/java-7-oracle.
Also, when starting visualvm with the jdkhome property set, I get the same error:
[beni:~]$ visualvm --jdkhome $JAVA_HOME
No jdkhome found

Answer: visualvm checks the following three directories for a JDK:

/usr/lib/jvm/java-7-openjdk-$ARCH
/usr/lib/jvm/java-8-openjdk-$ARCH and
/usr/lib/jvm/default-java

From the /usr/bin/visualvm start script:
visualvm_jdkhome=
for j in /usr/lib/jvm/java-7-openjdk-$ARCH /usr/lib/jvm/java-8-openjdk-$ARCH /usr/lib/jvm/default-java; do
    if [ -x $j/bin/javac ]; then
       visualvm_jdkhome=$j
       break
    fi
done

So make /usr/lib/jvm/default-java a symlink to $JAVA_HOME, and visualvm will find the right JDK.
cd /usr/lib/jvm
sudo ln -Tsf java-7-oracle default-java

Comment: As a matter of fact, I've encountered that exact problem yesterday : on one machine, `default-java`  was a symlink to openjdk-7 and `visualvm`  refused to start because of that. I wasn't able to find the correct Debian-specific script managing that link (I assume there *is* such a script) -- so I've updated it manually.
Comment: You need the `-T` and `-f` options of `ln` since the `default-java` symlink probably already exists. I've updated the answer accordingly. Please feel free to revert if you disagree.
Comment: Thanks Sylvain. Although from my understanding, you only get the `No jdkhome found` error if the `default-java` does not yet exist.
Comment: Ah okay, makes sense. Let's keep it with `ln -Tsf` then. Thanks for your input!
Answer: In my case even the symlink of default-java didn't fixed the problem.
To fix, I did:
Edited jvisualvm and add any "trash" into jdkhome variable

$ sudo vi /usr/bin/jvisualvm

jdkhome=/tmp
Then started the program passing parameter:

/usr/bin/jvisualvm --jdkhome /usr/lib/jvm/myJava7

Note: today (2016), with my version is working only with java7
Update:now, in 2017, using version 1.3.8, it's working with Java 8. But I needed to add visualvm_jdkhome=/tmp, in /usr/bin/visualvm
Comment: I got "Your are running VisualVM using an unsupported Java version: 1.8." Is this same for the upstream version?


How to return a value from class with events

Question: I need a class that uses WebBrowser to retrive some data, and then returns that data to another class. Problem is that WebBrowser is asyncronous and uses events, so the method that returns the data has ended before WebBrowser.DocumentCompleted -event is fired, and no data is returned. I have to use WebBrowser instead of WebClient, because I need to interact with the web page.
How can I create a class that returns the data after all events are fired, and for example some boolean flag has been set?
Answer: Ideally you should expose another event in your class that will be triggered by the WebBrowsers's DocumentCompletedEvent. This will provide the consumers of your class the possibility to subscribe to this event as well. Otherwise you will have to block the caller's thread waiting for the webbrowser to complete which is not a good thing to do.


Ios Swift TableView limpada ao retornar a tela

Question: Estou implementando duas telas... na primeira tenho um tableview a ao clicar em uma das celulas, envio dados para a segunda tela...
Porem quando clico no botao de voltar que é uma segue para a primeira tela...os dados que carreguei na tableView, são perdidos...
Como faço pra retornar a primeira tela, sem modificar os dados que estão na tableview?
Obrigado
Comment: Como você está chamando a segunda tela e em seguida voltando para a primeira? Poste o código para que possamos ajuda-lo.
Comment: Você esta fazendo via navigation?
Answer: Pelo que entendi, você está utilizando outra segue para voltar para a pagina. Isso faz que recrie a pagina novamente, dando start no viewDidLoad se não me engano. Como não tem imagens do seu código, estou supondo que esteja utilizando o reloadData da tabela no viewDidLoad. Por isso que está recriando a tabela novamente. Sugiro que estude navegação entre telas.Um exemplo seria o dismissViewControllerAnimated , utilizando para voltar para a pagina anterior.