Método de Pagamento divido entre contas

Question: Estou desenvolvendo um E-commerce em que nele terá várias marcas, cada marca terá sua devida integração com PagSeguro, a dúvida em questão é como separar os valores de cada marca no final da compra e trazer apenas uma compra para o usuário final?
Explicando melhor:
Tenho duas marcas na minha loja, cada loja tem 1 produto. Eu como usuário final compro os dois produtos, um de cada marca, no meu cartão vem apenas uma compra (Empresa X). Porém para essas empresas ela recebem o valor de cada produto em seu PagSeguro.
Obrigado.
Answer: Raank, não venho com sua resposta definitiva, mas gostaria de compartilhar contigo um ponto pelo qual você deve se atentar:
Estude a circular 3.682 de 2013 do BACEN. Ela regulamenta sobre liquidação para marketplaces e facilitadoras, talvez você esteja no escopo - e mesmo que não vá se preocupar com isso agora, é uma regulamentação e amanha ou depois você terá que colocar em pratica.
A Moip tem um documento legal sobre isso, veja nesse link. Eles, inclusive, tem um produto que pode te ajudar.
Não, essa não é uma 'resposta propaganda', é apenas um informativo que pode te ajudar.
Com relação ao slip que você precisa fazer - identifique os produtos por empresa, armazene os pedidos e após o pagamento aprovado, faça a divisão do valor atribuindo a cada pedido ao valor correspondente ao deposito em conta das diferentes lojas. Você deve ter sua estrutura de contas para liquidação dos estabelecimentos, não é?
Comment: E essa plataforma tem Lib para Laravel?
Comment: @Raank,

Veja o GitHub deles: https://github.com/moip/moip-sdk-php
Comment: Tem sim, vou usa-lo agora como meio de pagamento para MarketPlace, obrigado!

Método de Pagamento divido entre contas


Asymptotic distribution for MLE of shifted exponential distribution

Question: Suppose we have $X_1,...,X_n$ iid the shifted exponential distribution:
$$f(x)=\lambda e^{-\lambda(x-\theta)}, x\ge \theta$$
I have figured out both the MLE for $\lambda$ and $\theta$, which are $\hat \lambda = \frac{1}{\bar X - X_{min}}$ and $\hat \theta =X_{min}$.
I also found the asymptotic distribution of $\hat \theta$:
$$\sqrt{n}(\hat \theta-\theta) \rightarrow 0$$
Now I'm stuck at deriving the asymptotic distribution of $\hat \lambda$ and showing that it is a consistent estimator. How do you do this?
Thanks!
Comment: The asymptotic distribution of $\hat\theta$ is using the wrong scale: it should be $n$ not $\sqrt n$. [See this answer.](https://stats.stackexchange.com/a/241019/7224)
Answer: For consistency, by the weak law of large numbers $\bar X_n \stackrel{\text p}\to \frac 1\lambda + \theta$ and $X_\min \stackrel{\text p}\to \theta$ so by Slutsky
$$
\bar X_n - X_\min \stackrel{\text p}\to \frac 1\lambda.
$$
By assumption $\lambda > 0$ so the map $x \mapsto x^{-1}$ is continuous, and the continuous mapping theorem finishes the job.

For the asymptotic distribution, by the standard CLT we know $\sqrt n (\bar X_n - \theta -\lambda^{-1}) \stackrel{\text d}\to \mathcal N(0, \lambda^{-2})$. Let $Y_n = \sqrt n (\bar X_n - \theta - \lambda^{-1})$ and consider
$$
\sqrt n (\bar X_n - X_{\min,n} - \lambda^{-1}) = \sqrt n ([\bar X_n - \theta - \lambda^{-1}] - [X_{\min,n} -  \theta])\\
= Y_n - Z_n
$$
where $Z_n := \sqrt n (X_{\min,n} - \theta)$. You already worked out the asymptotic distribution of $Z_n$ so we can use that along with Slutsky again to conclude
$$
Y_n - Z_n \stackrel{\text d}\to \mathcal N(0, \lambda^{-2}).
$$
You can now finish this off with the delta method.
Answer: Although you are also asking about the estimator $\hat{\lambda}$, I am going to note some things about $\hat{\theta}$.  In this particular case it is quite easy to obtain the exact distribution of this estimator.  Since you have a series of shifted exponential random variables, you can define the values $Y_i = X_i - \theta$ and you then have the associated series $Y_1,Y_3,Y_3 ... \sim \text{IID Exp}(\lambda)$.  This gives the exact distribution:
$$\hat{\theta} = X_{(1)} = \theta+ Y_{(1)} \sim \theta + \text{Exp}(n \lambda).$$
Note that this gives the pivotal quantity $n(\hat{\theta} - \theta) \sim \text{Exp}(\lambda)$.  You can prove that $\hat{\theta}$ is a consistent estimator by computing the probability of a deviation larger than a specified level.  For all $\varepsilon >0$ we have:
$$\begin{aligned}
\mathbb{P}(|\hat{\theta} - \theta| < \varepsilon)
= \mathbb{P}(\hat{\theta} - \theta< \varepsilon)
= \exp(-n \lambda \varepsilon). \\[6pt]
\end{aligned}$$
We therefore get the limiting result:
$$\begin{aligned}
\lim_{n \rightarrow \infty} \mathbb{P}(|\hat{\theta} - \theta| < \varepsilon)
= \lim_{n \rightarrow \infty} \exp(-n \lambda \varepsilon) = 0, \\[6pt]
\end{aligned}$$
which is the required condition for weak consistency (i.e., convergence in probability of the estimator to the parameter it is estimating).
Comment: @MaverickMeerkat: The MLE occurs at a boundary point of the likelihood function, which breaks the ordinary regularity conditions.
Comment: any idea why exactly does the asymptotic normality of MLE not hold in this case? Any regularity condition broke?


Arguments to graphql-tools mutation resolver is not an object in v > 0.8.0?

Question: According to the documentation here, the second argument to a resolver function in the graphql-tools library is an object passed into the query
http://dev.apollodata.com/tools/graphql-tools/resolvers.html#Resolver-function-signature
However, if I run graphql-tools with a version of graphql >= 0.8.0, the "object" passed as the second argument is missing some object properties. For example, arg.constructor and arg.hasOwnProperty are undefined.
In the previous version, 0.7.2, both these statements would evaluate to true:
arg.consructor === Object
arg.hasOwnProperty === 'function'

Does anyone know what is actually getting passed as the second argument, or why these properties which usually exist on JS objects are undefined?
edit below:
I can get by this by doing something like this:
async resolverFuncForMutation(root, nonObjArgs, context) {
  const args = Object.assign({}, nonObjArgs);

But I don't want to have to remember how to do that for every resolver function. Does anyone know how to if there's a way to configure that to happen in some kind of pre-resolution hook?
Answer: Looking at the source code, it looks like prior to 0.8.0, the object that was passed to the resolver function was initialized as {}. Now it's being initialized as Object.create(null).
You are still receiving an object, but when Object.create(null) is used, the resulting object doesn't inherit from any prototype, whereas {} inherits from the Object prototype. Methods like hasOwnProperty and toString actually belong to the prototype, not objects themselves. While most objects (little "o") you encounter will be instances of Object (big "O"), this isn't necessarily the case as you've discovered here.
There's some good discussion here around why Object.create(null) is often preferred.
As far as I know, there's no way to modify the arguments before they are passed to the resolver in the way you'd like. However, if you need them to be an Object just to utilize hasOwnProperty, it may be simpler to just refactor your code a little bit, i.e. instead of:
if (foo.hasOwnProperty('bar')) doSomething()

You can just do
if (foo.bar) doSomething()

Comment: Thanks man, that's it!

Unfortunately I had some third party libs calling hasOwnProperty, ect. on the arguments.

Ended up writing a little preprocessor for my resolver functions to traverse the arguments data structure and call something like args = `Object.assign({}, args)`. Worked like a charm


Fitting a line via lm

Question: My code doesn't work. I am trying to find the relationship between 4 set of data briefly by lm function.
My data is as follow
X1,Y1, X2, Y2,X3,Y3
1,2,3,4,5,6
6,5,4,3,2,1
2,3,4,5,6,7
7,6,5,4,3,2

The easiest way is simply
fit=lm(X1,Y1)
summary(fit)

instead of typing fit1, fit2, fit3, i would like to do all at once.
I have also tried get_regression_table(fit[n], print=TRUE)but it still doesn't work
fit[n]<-lm(Yn~Xn,data=mydata)
for (n in 1:3){
  get_regression_table(fit[n], print=TRUE)
}
Comment: @G5W indeed. but even if i change it to 4, it still doesn't work properly. I receive different errors - mainly is Y is not defined yet
Answer: You need to dynamically call the lm function using do.call. And passing the parameters as strings.
data = data.frame(X1 = c(1,6,2,7),Y1 = c(2,5,3,5),X2 = c(3,4,4,5),Y2 = c(4,3,5,4),X3 = c(5,2,6,3),Y3 = c(6,1,7,2))

results = vector("list",3)
for(i in seq(1,3)){
  formula = paste0("Y",i,"~","X",i)
  results[[i]] = do.call("lm",list(formula = formula,data = quote(data)))
}

Each element in results contains the ith fit.
Comment: You dont actually need `do.call` for this. `lm(formula, data)` should work just fine.
Answer: You could use a matrix for storing your values and then use a variable to loop over your needed indexes
mat <- t(matrix(c(1,2,3,4,5,6,6,5,4,3,2,1,2,3,4,5,6,7,7,6,5,4,3,2),6,4))
matfit <- list()
length(fit) <- 3
for(i in 1:3){
  fit[[i]] <- lm(mat[,i*2-1] ~ mat[,i*2])
}

Fitting a line via lm


How do I estimate error when I know a survey is not representative?

Question: Let's say that I have a survey of $n = 1000$ respondents from a population of $N = 3000$.
Moreover, it is known that the ratio of male to female in the population is $50:50$. However, in the sample, $70\%$ were female.
Given that I know that the sample is not representative in terms of sex, how do I calculate the survey error rate?
Comment: Not my area, but here are a couple of thoughts: 1) Perhaps you could calculate first a sex-specific error rate and then then average between the two while weighting for their representation within the sample. 2) Since you know the ratio in the population, you could subsample your data to get a subset with characteristics that match the population, and then do your calculations with this. You could take this further by repeating the process multiple times (bootstrap).
Comment: you could make your data look representative if you give males a weight of 5 and females a weight of 2.142857..  but the probability that you would select less than 301 males out of 1000 draws is something like 8.8 * 10^-38 so you have non-sampling error which will be difficult to quantify.
Answer: I can give some general advice, but a lot of the answer is actually dependent on the design of the survey. I'm going to assume that you made a probability sample (that is, all units had a known probability of being selected). I'm also going to assume you are making estimates of population total - other population quantities are analogous.
Often when we know we need to calibrate to certain general subpopulations that are unidentified before units have responded, we use post-stratified estimation. Generally:
$$
\hat{Y}_{pos} = \sum_{k\text{ post-strata}}\frac{N_k}{\hat{N_k}}\hat{Y}_k
$$
Which means to estimate the total within a population, we estimate the total within each subpopulation, and multiply by an adjustment factor which accounts for the disparity between the known subpopulation representation and the estimated subpopulation representation. The estimates of subpopulation total and size are given by:
$$
\hat{Y}_k = \sum_{i\in s_k}\pi_i^{-1}y_i\\
\hat{N}_k = \sum_{i\in s_k}\pi_i^{-1}
$$
$\pi_i$ is the known probability of selecting unit $i$.
This estimate of population total is biased, but in many cases this is able to be ignored. Ignoring the bias gives us an approximate variance formula of:
$$
Var(\hat{Y}_{pos})\approx\sum_{k\text{ post-strata }}\left[\sum_{i\in s_k}\sum_{j\in s_k}\frac{y_i}{\pi_i}\frac{y_j}{\pi_j}(\pi_{ij}-\pi_i\pi_j)\right]
$$
$\pi_{ij}$ is the probability of both $i$ and $j$ being selected in the sample, and has to be non-zero for all pairs of units in the population. This formula further simplifies rather significantly if the sample is simple random (where all samples of the same size are equally as likely).


Wordpress Thesis 2 - empty content using Post Box

Question: I'm using Thesis 2.1 on the new Wordpress website I'm developing and unfortunately I'm not able to see any content. I'm using the Post Box -> Content box to display content but nothing shows up. Other boxes like Post Box ->Title and Post Box -> Excerpt work fine, everything just the content.
It doesn't matter whether I try a Post, Page, or Custom Post, always the same case. Everything else seem to work okay.
Any help would be very appreciated.
Answer: The Post Box won't work fully unless it's inside a WP Loop box.  Somehow the excerpt still works, but many of the other variables will come up empty, like content, author, date, etc.
Comment: Appreciate it bro!


Circle Geometry Colinear Points Problem

Question: I was digging through some old questions I had from high school and I came across this circle geometry problem.
.
There were no solutions unfortunately.
How can this be proven?
Here are a few things I've tried:

Pascal's theorem
Proof that $\angle EBF = \angle EAF$
ABDC is a cyclic quadrilateral

I have been unsuccessful with all of these attempts, however I may have missed something when attempting to prove these.
Comment: Which country is this a high school problem from?
Comment: Here are some solutions using polars. https://gogeometry.blogspot.com/2016/02/geometry-problem-1189-circle-tangent.html
Comment: The purpose of this problem is to show the properties of polars and not vice versa. @rae306
Comment: @Aqua I thought so too, but it was the only thing I could find .
Answer: The required claim follows from Problem 30.38.b from the last section of the first volume ("Plane Geometry") of the book "Problems in plane and solid geometry" by Viktor Prasolov.

30.38. a) Through point $P$ all secants of circle $S$ are drawn. Find the locus of the
  intersection points of the tangents to $S$ drawn through the two intersection points of $S$ with
  every secant.
b) Through point $P$ the secants $AB$ and $CD$ of circle $S$ are drawn, where $A$, $B$, $C$, $D$ are the intersection points of the secants with the circle. Find the locus of the intersection points of $AC$ and $BD$.

The proposed solution:

30.38. Let us consider, separately, the following two cases.
1) Point $P$ lies outside $S$. Let us make the projective transformation that sends circle $S$
  into circle $S_1$ and point $P$ into $\infty$ (see Problem 30.17), i.e., the images of all lines passing through $P$ are parallel to each other. Then in heading b) the image of the locus to be found is line $\ell$, their common perpendicular passing through the center of $S_1$, and in heading a) the line $\ell$ with the diameter of $S_1$ deleted.
To prove this, we have to make use of the symmetry through line $\ell$. Therefore, the locus
  itself is: in heading b), the line passing through the tangent points of $S$ with the lines drawn
  through point $P$ and in heading a), the part of this line lying outside $S$.
2) Point $P$ lies inside $S$. Let us make a projective transformation that sends circle $S$ into
  circle $S_1$ and point $P$ into its center, cf. Problem 30.16 a). Then the image of the locus to
  be found in both headings is the infinite line. Therefore, the locus itself is a line.
The obtained line coincides for both headings with the polar line of point $P$ relative to
  $S$, cf. Problem 30.19.
Answer: Let $O$ be a circumcenter of the circle, let $M$ be a midpoint of segment (chord) $AB$ and let circles (blue) around $CHF$ and $DGF$ meet at $N$. Also let line $EF$ meet circle at $X$ and $Y$.
Let us prove that

$ONEM$ is cyclic (yellow) and that
$N$ is the midpoint of a chord $XY$.

This will mean that $\angle OME = 90^{\circ}$ and thus $E$ lies on $AB$.
Lemma $0$. Points $E,F$ and $N$ are collinear.
Proof: Point $E$ is on a radical axsis for circles $(FGD)$ and $(CHF)$: $$Pow(E,(FGD)) = EG\cdot ED = EC\cdot EH = Pow(E,(CHF))$$
 which is $NF$.

Lemma $1$. Points $D,H,N,E$ are concyclic (red circle).
Proof: $$\angle EHN \equiv \angle CHN = \angle CFN = \angle GDN\equiv \angle EDN$$
Lemma $2$. We have $FX\cdot FY = FE\cdot FN$
Proof: $$FX\cdot FY = FH\cdot FD = FE\cdot FN$$
Lemma $3$. We have $EN\cdot EF = EX\cdot EY$
Proof: $$EN \cdot EF = EC\cdot EH = EX\cdot EY$$

Now let us prove that $N$ halves $XY$. Let $FX = s$, $EX= x$, $NE = z$ and $NY = y$.
From lemma 2 we have $$z(x+s)= x(y+z)$$
From lemma 3 we have $$ s(s+x+y+z) = (s+x)(s+x+z)$$
Combining these two (eliminate $s$) we get $y=x+z$ which means that $N$ halves $XY$ and we are done.
Lemma $4$. $ONEM$ is cyclic (yellow).
Proof: $OB\bot BF$ we see that $BF$ is tangent to circle (OMB), so $$FM\cdot FO = FB^2 = FH\cdot FD = FE\cdot FN$$
Answer: Changing notation a bit ...
Given $\bigcirc O$ and a point $P$ with tangent segments $\overline{PA}$ and $\overline{PB}$, introduce $\bigcirc P$ through $A$ and $B$. For $C$ and $D$ on $\bigcirc P$, let the extensions of $\overline{PC}$ and $\overline{PD}$ meet $\bigcirc O$ at points $C'$, $C''$, $D'$, $D''$, as shown:

Calculating the power of $P$ with respect to $\bigcirc O$ in three ways, we have
$$
pow_{\bigcirc O}P = |C'P||C''P| = |D'P||D''P|=|AP|^2 \quad\to\quad \begin{cases}|C'P||C''P|=|CP|^2\\[4pt] |D'P||D''P|=|DP|^2 \end{cases}
$$
Introduce $\bigcirc PC'D''$, and note
$$\begin{align}
pow_{\bigcirc P} C'' &= |C''P|^2-|CP|^2 \\[4pt]
&=|C''P|^2-|C'P||C''P| \\[4pt]
&=|C''P|(|C''P|-|C'P|) \\[4pt]
&=|C''P||C''C'| \\[4pt]
&=pow_{\bigcirc PC'D'}C''
\end{align}$$
Similarly, we have $pow_{\bigcirc P}D'=pow_{\bigcirc PC'D''}D'$. Since the points $C''$ and $D'$ each have the same powers with respect to $\bigcirc P$ and $\bigcirc PC'D''$, they determine the radical axis of these circles. On the other hand, points $C'$ and $D''$, as the endpoints of the common chord of $\bigcirc O$ and $\bigcirc PC'D''$, determine the radical axis of those circles.
Thus, the point $X$, where these axes meet, has the same power with respect to $\bigcirc P$ and $\bigcirc  PC'D''$, and the same power with respect to $\bigcirc PC'D''$ and $\bigcirc O$. Transitively, it has the same power with respect to $\bigcirc P$ and $\bigcirc O$, and so it must lie on the radical axis of these circles, which is the line of the common chord $\overline{AB}$. $\square$
Comment: Nice...........

Circle Geometry Colinear Points Problem


Metro App global variables C#

Question: Im creating my first app for Windows 8 and i have a question. In Windows Phone 7 we can define in App.xaml.cs all global variables and access by App.all_performers for exemple, this works fine with default data types but if i create a List of one object created by me like evento
public static List<evento> eventos_near = new List<evento>();

i have this error:

Inconsistent accessibility: field type
  'System.Collections.Generic.List<UrbaneousTry2.evento>' is less
  accessible than field 'UrbaneousTry2.App.eventos_near'

Anyone can help me? i need Lists and Dictionaries to use in all pages of my app
Answer: The problem you are hitting is that evento isn't a public type yet you've declared it as available in a public location.  If this were legal it would allow a type declared to be not public be accessible from any referencing assembly which effectively makes it public.
You need to either switch evento to be a public type or make the declaration internal
internal static List<evento> eventos_near = new List<evento>();

Answer: You have to make your class eventos public.
Comment: The `eventos_near` declaration is the field while `evento` is the type

Metro App global variables C#


Limpar cache de navegadores com JavaScript

Question: É possível limpar o cache dos navegadores Firefox e Chrome via JavaScript? Com o Internet Explorer já consigo, mas não os citados acima.
Cara, não deu certo, creio que o problema ocorre porque salvo o usuario logado no remember-me ... mas, o problema ocorre só quando eu fecho o browser, se clico em sair funciona normalmente.
Você já viu algo parecido?
Se o usuário marcar o check box lembra eu adiciono um cookie:
if (model.RememberMe)
 {
     Response.Cookies["SistemaLeilao"].Value = model.UserName;
     Response.Cookies["SistemaLeilao"].Expires = DateTime.Now.AddMinutes(5);
 }

Quando clica no sair e o logoff é feito, funciona filé, mas quando fecha a janela do browser sem fazer o logoff fica tudo gravado, e isso que ta me atrapalhando.
Comment: Eu só não estou surpreso que você consiga limpar o cache do IE via JS porque, afinal de contas, segurança nunca foi o ponto forte do IE.
Comment: A resposta é perfeita, fala a realidade, a pergunta e a afirmação estão completamente enganados.
Comment: window.onunload
Comment: Só quis ajudar a um amigo. A pergunta foi pra ele. Não é justificativa isso não, apenas me apoiei na dúvida dele que agora entendi que era minha também. Mas valeu a todos.
Answer: Não é possível, e se fosse seria uma enorme falha de segurança, pensou conseguir limpar o cache de qualquer pessoa que acessasse sua página?
O que você pode fazer é indicar para o navegador não fazer cache da sua página, isso pode ser feito utilizando uma dessas meta tags:
<meta http-equiv="cache-control" content="max-age=0" />
<meta http-equiv="cache-control" content="no-cache" />
<meta http-equiv="expires" content="0" />
<meta http-equiv="expires" content="Tue, 01 Jan 1980 1:00:00 GMT" />
<meta http-equiv="pragma" content="no-cache" />

Comment: Parabéns pela resposta ...
Comment: @pnet Talvez seja melhor usar [SessionStorage](http://pt.stackoverflow.com/questions/19384/diferen%C3%A7as-entre-localstorage-vs-sessionstorage) em vez de um cookie então.
Comment: Cara, não deu certo, creio que o problema ocorre porque salvo o usuario logado no remember-me ... mas, o problema ocorre só quando eu fecho o browser, se clico em sair funciona normalmente.

Você já viu algo parecido?
Comment: Você está trabalhando com sessão? O que você quer fazer?
Comment: Se o usuário marcar o check box lembra eu adiciono um cookie:

 if (model.RememberMe)
 {
     Response.Cookies["SistemaLeilao"].Value = model.UserName;
     Response.Cookies["SistemaLeilao"].Expires = DateTime.Now.AddMinutes(5);
 }
Quando clica no sair e o logoff é feito, funciona filé, mas quando fecha a janela do browser sem fazer o logoff fica tudo gravado, e isso que ta me atrapalhando.
Answer: Como dito nesta resposta do Stack-EN, você pode usar:
window.location.reload(true)

para forçar o navegador a recarregar os JS/CSS para a sua página apenas. Limpar o cache do navegador todo não é possível.
Answer: Impedir o browser de utilizar o cache não me pareceu uma boa, pelo menos no meu cenário, então
procurando por uma solução para esta questão, vi muitas pessoas utilizando o formato a seguir:
<link rel="stylesheet" type="text/css" href="meu.css?v=<?=filemtime($file);?>">

Porém no cenário que trabalho, cada vez que o sistema é atualizado no servidor, os arquivos que não foram alterados também são sobrescritos, alterando assim sua data de modificação, forçando o browser a fazer o download do asset mesmo que ele não tenha sido modificado, o que acho bem ineficiente, visto que o uso do cache fica prejudicado.
A solução que encontrei para fazer isso somente se o arquivo foi alterado, é  utilizar uma função de hash, o que só vai alterar o hash se o conteúdo do arquivo for de fato modificado.
<link rel="stylesheet" type="text/css" href="meu.css?v=<?=hash_file('md5', $file);?>">

Estou utilizando tanto para arquivos .js quanto para .css, foi o que achei melhor, pois se o arquivo não foi alterado, é melhor deixar o cache trabalhar, caso contrário, o navegador irá fazer novamente o download do asset.
Answer: Bom, o cache é um importante balanceador de carga e consumo de banda larga, não aconselho como membro do SOpt você utilizar a solução do @Laerte em todos os casos, cada caso deve ser estudado.
Imagine se sua página tivesse fotos de 500 Kb cada, e você quisesse exibir elas sempre em tamanho original, por exemplo, uma galeria de uma rede social. Sempre que o usuário logar na rede social e acessar a sua galeria, seria necessário o browser solicitar essa foto de 500 Kb ( bem como as demais ) já que você teria "feito o navegador não fazer cache da sua página".
Se você tivesse deixado o cache armazenar essas imagens (localmente) seria muito mais rápido o carregamento do site e menor o consumo de banda.
Uma solução, quando você quer forçar algo ser constantemente atualizado e baixado (atualizado no cache), é criar um src de referências a .CSS, .JS, imagens, colocar uma variável via GET atualizada com um valor aleatório (rand). Essa também é uma solução do SOen como citou @user7261.
Apresentei uma solução semelhante aqui: Tratar cache com AngularJS
Comment: Também acho uma boa usar assim `?....`, mas não precisa de `rand()` o legal seria usar um versionamento.
Answer: Aplicações Estáticas ou com cache imutável segundo a especificação RFC8246:
Acrescentar o código abaixo, no inicio da tag ""
<meta name="Cache-Control" content="no-cache">

Alternativamente, usar:
<meta name="Cache-Control" content="max-age=0,must-revalidate">

Aplicações Dinamicas:
As respostas são mentirosas, eu poderia usar um termo mais bonitinho "equivocado", mas sem motivo aparente, são incorretas, principalmente no tocante a "ser impossível" e ainda o parabenizam por uma gambiarra, sim, é gambiarra, pelo que vi no console, versionar não faz absolutamente nada, inclusive, não precisa versionar, basta recarregar a pagina duas vezes seguidas que o próprio navegador verá se existem alterações, eu não achei o que procurava por aqui, mas vou deixar um simples código que eu criei, com base na própria documentação oficial que mostra como se faz: https://developer.mozilla.org/en-US/docs/Web/API/Cache/delete.
Passo 1: Primeiramente, acesse o seu site, abra o console (F12), na parte superior, localize o menu: "Aplicativo", "Application" ou "Applications", clique sobre ele, agora, no menu lateral, localize "Cache", clique em "Armazenamento em cache" ou "Cache storage". (o que vier primeiro)

Anote o nome que você vê por lá, no meu caso: "devsite.pwa_RUNTIME_V3", se não aparecer nada, o seu problema é outro, deve ser com um proxy ou outro intermediador qualquer.
Passo 2: Agora crie um Cookie para todos os usuários que acessarem o seu site, use o nome de "version" e valor "2.0", nada de criptografar, deixe isso para depois, deve ser um cookie comum.
Passo 3: Recorte o seu script e coloque dentro do "else" abaixo, altere "devsite.pwa_RUNTINE_V3" para o nome que você anotou no passo 1, além disso, altere "/assets/css/style.css" para o caminho dos arquivos ou imagens que você deseja atualizar, incluindo o arquivo que você colocará esse código, salve o arquivo, limpe o cache do seu navegador e atualize a pagina.
console.info('script:', 'verificar versão...');
function verify(code){var cookiestring=RegExp(code+"=[^;]+").exec(document.cookie); return decodeURIComponent(!!cookiestring ? cookiestring.toString().replace(/^[^=]+./,"") : "");}

if(verify('version') !== '2.1'){
caches.open('devsite.pwa_RUNTINE_V3').then(function(cache) {
  cache.delete('/assets/css/style.css');
  cache.delete('/assets/js/script.js');
})
localStorage.clear();
console.info('script:', 'confirme a atualização.');
alert("Portuguese: Precisamos atualizar a página, esta é uma versão antiga.\n English: We need to update the page, you are on an old version.\n Español: Necesitamos actualizar la página, estás en una versión anterior.");
console.info('script:', 'recarregando...');
location.reload(true);
} else {
//cole o script aqui.
    }

Se tudo der certo e provavelmente dará, você verá um Alert, não clique em "ok", primeiro altere o valor do cookie que você criou no passo 2, para "2.1", agora sim você pode clicar em "ok", a pagina será recarregada automaticamente e seu cache será limpo.
De nada.

Exemplo de como limpar o cache no Logout
<button class="reset">Sair</button>

Comment: Poderia completar sua resposta mostrando qual é a relação entre a Web API Cache que utilizou na sua resposta com o cache interno do navegador, que é o foco da pergunta? Isso não ficou claro.
Comment: @Woss 10, não tem cache interno nenhum na forma que você se refere, a minha solução segue um caminho semelhante ao já apresentado pela Google em: https://developers.google.com/web/tools/chrome-devtools/manage-data/local-storage#clear-storage, além disso, o problema dele pode ser resolvido com html: https://developer.mozilla.org/pt-BR/docs/Web/HTTP/Headers/Cache-Control, não há nada de complexo aqui.
Comment: Então não entendi. Se o problema da pergunta pode ser resolvido com o cabeçalho Cache-Control, qual é a relação com a API Cache? No próprio MDN é citado que a API Cache não segue os padrões dos cabeçalhos de cache.
Comment: São duas formas de resolver a questão, ali, além da api de cache, limpa também a storage, além disso, é usado a "location.reload(true);", o que faz com que o navegador ignore o cache e carregue novos arquivos, tudo que ele informou é que não deseja o seu painel de controle em cache, você fez complementos que não estão na pergunta, o "cache interno do navegador".
Comment: Inclusive é uma duplicata desta: https://pt.stackoverflow.com/questions/68382/for%C3%A7ar-atualiza%C3%A7%C3%A3o-de-arquivo-javascript-sem-desativar-cache, porem, perguntada de outra forma, a solução buscada é a mesma.
Comment: Mas assim, o SOpt por exemplo cacheia todas as páginas, então elas não deveriam aparecer na opção Aplicação > Cache > Armazenamento em cache do F12, como apontou? Aqui está vazio, mesmo que as páginas estejam cacheadas.
Comment: Vamos [continuar esta discussão no chat](https://chat.stackexchange.com/rooms/119681/discussion-between-macedo-montalvao-and-woss).


Has anyone been successful in implementing google optimize in a SPA React App?

Question: I am fairly new to the Google Analytics Suite and am currently trying to integrate Google Optimize for A/B testing in a react app.
I have gotten to the point where the variant changes display on the desired web page, but only in Preview mode, and am stumped as to how to proceed to viewing the variant changes on a live site.
So far:

google optimize scripts are installed in app

ga tracking is setup using ReactGA
GTM is setup and is firing tags to track
firing google optimize experiments on custom activation event and using dataLayer to push new events
const initializeReactGa = () => {
  console.log('called to initialize react ga');
  ReactGA.initialize(config.gaTag)
  ReactGA.ga('require', config.optimizeTag);
  ReactGA.pageview(window.location.pathname + window.location.search);
}
const googleOptimizeLoader = () => {
  console.log('called google optimize loader');
  if(window.dataLayer) {
    window.dataLayer.push({'event': 'optimize.activate'})
  }
}

The problem

unable to see variant changes in live site (without preview running)

Any help is appreciated.
TIA
Nayyir
[SOLVED]
Was able to determine the issues were not with the setup. The issue was that google optimize's cookie management was unable to set the required cookie for the expirement on localhost:3000, but rather a custom domain pointing to localhost, similar to XXXX.local:3000.
Comment: Hi Can you explain further how you accomplished to do this. I am stuck on the same problem and I don't understand what you mean with these cookies
Answer: This might be what you are looking for
How to Add Google Optimize A/B Testing to Your React App in 10 Lines of Code


How do I perform a proper unsigned right shift in PHP?

Question: Is this possible to get the same results in PHP and Javascript?
Example:
Javascript

output:
1
536870910
16
1073741821
134217727

PHP
function uRShift($a, $b)
    {
        if ($a < 0)
        {
            $a = ($a >> 1);
            $a &= 2147483647;
            $a |= 0x40000000;
            $a = ($a >> ($b - 1));
        } else {
            $a = ($a >> $b);
        }
        return $a;
    }

echo uRShift(10,3)."
";
echo uRShift(-10,3)."
";
echo uRShift(33,33)."
";
echo uRShift(-10,-30)."
";
echo uRShift(-14,5)."
";

output:
1
536870910
0
0
134217727

Is this possible to get the same results?
Closest function to what I want is here:
Unsigned right shift function not working for negative input
Thanks for help.
Comment: Possible duplicate of [Unsigned Right Shift / Zero-fill Right Shift in PHP (Java/JavaScript equivalent)](https://stackoverflow.com/questions/41134337/unsigned-right-shift-zero-fill-right-shift-in-php-java-javascript-equivalent)
Answer: Try this function:
function unsigned_shift_right($value, $steps) {
    if ($steps == 0) {
         return $value;
    }

    return ($value >> $steps) & ~(1 << (8 * PHP_INT_SIZE - 1) >> ($steps - 1));
}

The output, based on your code sample:
1
536870910
16
1073741821
134217727

Comment: PHP gives me results:

1
2305843009213693950
0
1073741823
576460752303423487

why?
Answer: Finally I think I found solution I don't know why but this code works for me:
function uRShift($a, $b)
    {
        if ($b > 32 || $b < -32) {
            $m = (int)($b/32);
            $b = $b-($m*32);
        }

        if ($b < 0)
            $b = 32 + $b;

        if ($a < 0)
        {
            $a = ($a >> 1);
            $a &= 2147483647;
            $a |= 0x40000000;
            $a = ($a >> ($b - 1));
        } else {
            $a = ($a >> $b);
        }
        return $a;
    }


How to display second level menu on another node page

Question: I created a menu by Menu block module. I added a link 'to /news' in the first level. The second level are news categories (taxonomy items). I want to display the categories (2 level) on node page. How to do that?
Answer: Try the Taxonomy Menu Module. It creates you a menu item for each term which you then can place in your menu.
Answer: Try this: menu_block
It allows you to have different levels of your menu in different blocks.
Just create a menu-block for your main navigation(only level 1) and a second for level 2 only. Set the second menu-block only to show up on node* or what ever you need.


ARDL model as remedy for spurious regression?

Question: Suppose there are two non-stationary time series of integrated order 1. The two time series are not cointegrated.
According to conventional econometric theory,

"In general, regression models for non-stationary variables give
spurious results. [The] only exception is if the model eliminates the
stochastic trends to produce stationary results.
For non-stationary variables we should always think in terms of
cointegration. Only look at regression output if the results are
stationary or cointegrate." [1]

Accordingly, in the absense of cointegration between the relevant two I(1) time series, a necessary condition for a correct regression model would be to use the first differences of each variable as input. [2]
Some voices, however, suggest to use an autoregressive distributed lag (ARDL) model in this case: Provided that enough lags for each of the two variables of interest are included, it is possible to use the raw (undifferenced) time series as input without running the risk of spurious regression results. [3, 4] In the example above, one would have to build an ARDL(1, 1) model, i.e. include 1 lag of each variable.
My question is: Can an ARDL(1, 1) model indeed be used as a "treatment" of spurious regression with two I(1) time series variables, which are not cointegrated?

Sources:
[1] http://web.econ.ku.dk/metrics/econometrics2_05_ii/slides/10_cointegration_2pp.pdf
[2] https://www.reed.edu/economics/parker/312/tschapters/S13_Ch_4.pdf
[3] Cointegration - same thing as stationary residuals?
[4] https://mpra.ub.uni-muenchen.de/83973/1/MPRA_paper_83973.pdf
Answer: There is a form of ARDL which works if the variables are integrated of order 1 or 0 (they do not have to be integrated the same). There are specific requirements, however, (essentially they have to be co integrated). Error correction models are used to generate short and long term impact. I did a lot of threads on this in the last few weeks.:) This is one example of the analysis (not the threads I did). http://www.scienpress.com/Upload/JSEM%2FVol%205_4_3.pdf I have never read of an ARDL which did this if they were not co integrated. If they are not co integrated I am not sure how there can be a long term relationship.
Comment: Hi: I haven't read it in detail but check out " error correction methods with political time series" by Grant and Lebo because it seems to atleast try to answer the question of whether error correction is appropriate for non I(1) variables.


How does the guitar demonstrate volume?

Question: I am doing a project in music where we have to make our own instrument and i have chosen to make a guitar. One of the questions we have to answer is; Explain how your instrument demonstrates the following sound qualities?
The one that I'm stuck on is volume...
Can someone help me out??
Comment: I'm guessing that just means you have to show how it can play at different volumes?  Which you do by plucking the strings softer or harder.
Comment: Since you have tagged acoustic guitar, I'll assume that you are building an acoustic guitar. So the volume depends on how hard you strum. Also the sound hole plays a role in maintaining the volume as well.
Answer: Wow.  If you are actually going to make a guitar then I must say that is quite challenging.  I have a friend who is a woodworker who tried to make several guitars - but they just did not work out so well.
Here is what I can share about volume as it relates to guitars.
Let's start with an acoustic guitar (no electronics to amplify the sound).  An acoustic guitar produces sound when a plucked (or otherwise excited) string vibrates the soundboard.  Let's examine this in more intricate detail.
Plucking the string itself will not create much of an audible sound.  So the string by itself does not produce the sound.  Rather the string vibrates at a given frequency (depending on how it's tuned and fretted) which then vibrates the saddle (at that frequency) which sits atop the bridge which is attached to the top - also known as the soundboard. When the soundboard vibrates at the frequency transferred from the vibration of the string, audible sound is produced.  To a lesser extent, the vibrations of the back and sides will also contribute to some sound.  But the top itself is optimized to be the most sensitive to vibration induced by the strings.
Much of the sound created by the top and back and sides emanates through the sound hole, so the size of the soundhole can affect the volume as well (although you can plug the soundhole and still get a great deal of sound).
To a much lesser extent the vibrating string vibrates the nut which in turn vibrates the neck which can send some secondary vibration to the top which contributes to a sound sustaining.
The amount of volume a given acoustic guitar is capable of producing depends on many factors including the type and stiffness of the wood used, they type and design of the bracing, the shape of the guitar, the size of the guitar and the type and gauge of strings used.  Other factors would even include the action or how high the strings sit above the fretboard.
On any given acoustic guitar, the volume is controlled by the velocity of the action used to set the string into motion.  In other words the more forcefully you strike the string with a pick or pluck it with your finger or thumb - the more it will vibrate the top and the louder the sound will be.  The thickness of a pick will affect the picks ability to excite the string (thicker picks will allow for more volume than thinner picks).
The volume can be attenuated by techniques such as palm muting or muting with the fretting hand.  Either type muting can slow or stop the vibration and lower the volume.
An electric guitar depends on electronics and amplification to produce sound.  The string vibration is detected by a magnetic pickup which sends an electrical signal to an amplifier which sends a signal to a speaker in the amplifier.  When the speaker cone vibrates (at a frequency determined by the strings vibration) - audible sound is produced.  The volume of sound on an electric guitar can be controlled similarly to an acoustic but is also controlled by volume knobs on the guitar itself as well as volume and gain controls on the amplifier.
I hope I have provided something you can use and for those not working on a music project - something of interest.
Comment: Excellent answer! Having made various guitars over the years, I'd suggest the OP go with an electric guitar. Acoustic guitars are incredibly difficult to make, as the entire body (shape, choice of wood, thickness of wood, sound holes etc) determines the sound, volume, tone and sustain, whereas an electric guitar can be successfully made from a plank of wood...
Comment: @DrMayhem  I totally agree.  I have another musician friend who regularly builds very nice and very playable electrics that look and sound just like the ones they are modeled after (Fender Strat, Gibson Les Paul, Gibson SG, etc.)  He won't even attempt an acoustic for the reasons you mentioned.  I have another friend who went to a renowned Luthier school for a year and it took multiple failures before he was able to master the art.  Now he owns Hasty Custom Guitars and builds great sounding acoustics - but he's been at it for many years.  Another friend tried acoustics but they all failed.
Answer: Excellent explanation by Rockin Cowboy. On a purely pratical side I would add that volume is a sound property that can be easily measured, at least on relative terms. A number of free APPs for mobile phones are available that measure the sourrounding sound intensity. These are not professional tools, of course, but provide a good enough comparison of intensity for two different instruments, etc.
In my Android phone I use for example Sound Meter (from SMART TOOLS) and SPL Meter (from Keuwlsoft). They are (as many similar other) freeely available on the Google App Store.
Now, these tools measure physical pressure levels caused by sound (hence SPL=Sound Pressure Level :-). Strictly speaking this is not "volume", as "volume" (the perceived loudness) depends on additional factors like the frequencies involved and the average response of the human ear to such frequencies. However, for the purpose of the exercise, I suppose it would be a good enough approximation to demonstrate the sound quality of "volume" by measuring the resulting intensity from plucking a string in a reference frequency (say, A4=440Hz).

How does the guitar demonstrate volume?


Mensagem de erro ao gerar relatório

Question: Estou fazendo um relatório e está dando uma mensagem de erro que não estou conseguindo encontrar solução.
Erro:

Código botão Gerar
   private void btnGerarRelatorio_Click(object sender, EventArgs e)
    {
        SqlCommand cmd = new SqlCommand();
        SqlDataAdapter da = new SqlDataAdapter();
        DataSet dsum = new DataSet();
        DataTable oTable = new DataTable();

        String strReportPath = "";
        try
        {
            strReportPath = @"Report4.rdlc";
            reportViewer1.LocalReport.ReportPath = strReportPath;
            SqlConnection conn = new SqlConnection(@"Data Source=DENILSON-PC;Initial Catalog=dbSistEstoqueEmp;Integrated Security=True");

            cmd.Connection = conn;
            cmd.CommandText = "SELECT * FROM tbEntradaEstoque WHERE cod_peca = @codPeca AND data_ent BETWEEN @dataEnt AND @dataEnt1";
            cmd.CommandType = CommandType.Text;
            conn.Open();
            cmd.Parameters.Add("codPeca", SqlDbType.Int).Value = Convert.ToInt32(txtCodPeca.Text);
            cmd.Parameters.Add("dataEnt", SqlDbType.DateTime).Value = Convert.ToDateTime(maskDataInicial.Text).Date;
            cmd.Parameters.Add("dataEnt1", SqlDbType.DateTime).Value = Convert.ToDateTime(maskDataFinal.Text).Date;

            SqlDataReader oDataReader = cmd.ExecuteReader();
            oTable.Load(oDataReader);
            ReportDataSource myReportDataSource = new ReportDataSource("dbEntSaidaPeca", oTable);
            reportViewer1.Clear();
            reportViewer1.LocalReport.DataSources[0] = myReportDataSource;
            reportViewer1.RefreshReport();

        }
        catch (Exception ex)
        {

            MessageBox.Show(ex.Message);
        }
    }

Answer: O nome do Dataset passado como argumento do ReportDataSource deve ser o mesmo do configurado no arquivo RDLC do report. Então a criação do ReportDataSource deveria ser:
 ReportDataSource myReportDataSource = new ReportDataSource("DataSet1", oTable);

Comment: Obrigado me ajudou muito, deixa eu te perguntar para eu pegar 2 tabelas tbEntradaPeca e tbSaidaPeca como eu faria isso no relatório ? escolheria uma peça cod 1 data inicial e data final e me mostrava todas as entradas e saida no relatorio desta peça, se puder me ajudar eu agradeço preciso entregar isso dia 12 na faculdade.

Mensagem de erro ao gerar relatório


(Euclidean) Norm of a vector with respect to some basis other than the standard basis

Question: We know that if $v=a_1 e_1+\cdots+a_n e_n$ where $(e_{i})$ is the standard basis on $\mathbb{R}^{n}$ that the Euclidean norm is given by
$$\|v\|^2 = a_1^2 +\cdots+a_n^2.$$
Suppose that $v$ were written in component form with respect to some arbitrary basis $(B_i)$.
Is there a formula for the norm of $v$ with respect to the basis $(B_i)$? I'm certain there is, I just can't seem to find it.
Answer: For $$v=a_1 v_1+\cdots+a_n v_n$$ we get $$||v||^2 =  (a_1 v_1+\cdots+a_n v_n).(a_1 v_1+\cdots+a_n v_n)=$$
$$ a_1^2 ||v_1||^2 + 2a_1a_2v_1.v_2 +....+a_n^2 ||v_n||^2$$
As you see the choice of standard basis is a smart choice.


Simple representation for continuous vector fields

Question: I'm a student in my second year of a games programming degree, and our next assignment is to create a rigidbody physics engine. I dislike the standard approach (check every form for intersection against every other form) because it is extremely inefficient; a hundred spheres will produce 10,000 checks every frame (or physics tick, if you have them out of sync).
Instead, I want to implement acceleration as a field and physical interactions as changes to the field; objects would provide repulsions in the field that mirrored their shape and position in the scene at any particular time. Simple collision and torque would then emerge from the interactions between objects and the acceleration at any particular 3D sample of the field.
My problem is that I'm not sure how to represent the field continuously. What I mean is that we can easily represent many figures (spheres, cubes, toruses, discs) as simple mathematical functions (all points on the unit 3D sphere obey the rule $x^2+y^2+z^2 = 1$) that exist independantly of the method you use to rasterize them into a visible medium, and I'm not sure about the equivalent representation for fields.
I need a continuous representation because all of my geometry is galaxy-scale procedural, making it way too expansive to comfortably store in a static 3D texture.
Comment: Another solution might be to partition the space, for example using an octree. Then it's easy to find close bodies.
Comment: I have considered that, but traversing especially dense octrees is actually quite inefficient (which is why my crude voxel sketchboard uses 3D textures instead), and I feel like it would be hard to find an octree resolution that gives good torque/collision results while maintaining performance.
Answer: A vector field in 3-space can be represented as a function that takes a point in 3-space, and returns a 3-d vector. Generally, for each object, it would have such a function representing the force it exerts on every point, and so to calculate the acceleration of an object, you'd have to sum over all other objects to get the total force (which is then a vector field), passing in the position of the object, and divide by the mass of the object.
If you have lots of objects, you'll have to approximate it somehow. For example, if your object is far away from a point cloud, you can approximate the force from that point cloud by a single vector from its center of mass.
Comment: Right, I had to think about it a bit but this definitely makes sense. It wouldn't make any sense for a single magical function to comfortably represent a heterogenous field like I expected :P.

All my geometry is defined through SDF's at the moment (experimenting with ray-tracing). Would it be possible to use the "cloudy" SDF definitions as the source of my exertion data?
Comment: Thinking about it, I don't think there's a direct way to do it, but depending on how the SDF is derived, you may be able to use a similar analysis to derive its center of mass, and how the cloud changes over time (i.e., how its internal forces cause the cloud to change).
Comment: Could I just assume the COM is always at the centre of the SDF? I might be generating more complex forms later but for now I'm just working with evenly dense spheres, cubes, etc.
Comment: Sounds fine to me.


Getting image from clipboard - black when screenshots appear?

Question: I am using WPF to display the image in the clipboard. This works fine when going to Paint and copying something there, but when I hit "Print screen" to take a screenshot, the output there is just a black image, that has the same dimensions as the screen.
How come?
The code for taking data from the clipboard is as follows (yes, I do in fact want to use raw API calls).
<code>...
case CF_BITMAP:
    BitmapSource source = null;
    System.Drawing.Bitmap finalBitmap = null;
    IntPtr destinationHdc = CreateCompatibleDC(IntPtr.Zero);
    if (destinationHdc != null)
    {
        IntPtr sourceHdc = CreateCompatibleDC(IntPtr.Zero);
        if (sourceHdc != null)
        {
            if (OpenClipboard(MainWindow.Handle))
            {
                IntPtr sourceBitmap = GetClipboardData((uint)clipboardFormat);
                SelectObject(sourceHdc, sourceBitmap);

                BITMAP bmp;
                GetObject(sourceBitmap, Marshal.SizeOf(typeof(BITMAP)), out bmp);

                IntPtr destinationBitmap = CreateCompatibleBitmap(destinationHdc, bmp.bmWidth, bmp.bmHeight);
                SelectObject(destinationHdc, destinationBitmap);

                BitBlt(destinationHdc, 0, 0, bmp.bmWidth, bmp.bmHeight, sourceHdc, 0, 0, 0x00CC0020);
                CloseClipboard();

                finalBitmap = System.Drawing.Bitmap.FromHbitmap(destinationBitmap);
            }
            DeleteDC(sourceHdc);
        }
        DeleteDC(destinationHdc);
    }
    if (finalBitmap != null && ((LastData == null || !(LastData is System.Drawing.Bitmap)) || !finalBitmap.EqualsTo((System.Drawing.Bitmap)LastData)))
    {
        source = BitmapToSource(finalBitmap);

        if (LastData == null || source != LastData)
        {
            tile = new ImageTile();
            (tile as ImageTile).Image.Source = source;
            tile.RawData = finalBitmap;
        }
    }
    return tile;
...
</code>
Comment: I seriously doubt anybody is going to volunteer to debug this code for you, especially since you omitted the pinvoke declarations.  It is silly to not use the Clipboard.GetImage() method here.
Comment: The Clipboard.GetImage function is buggy, which has in fact been confirmed, even for .NET 4.0. It will crash for some types of images (for instance images coming off a word document).
Comment: First I heard of it.  Although it inevitably depends on the quality of the code that put the image on the clipboard.  What's wrong with try/catch?
Comment: We're talking about a FatalException, that will crash even the try/catch. It'll seriously shut down the application with NO chance of recovering. It's honestly that critical.
Comment: I think you're better off uninstalling the program that screws up the clipboard like this.  Stops it from crashing .NET programs whose code you don't have.
Answer: I ended up using the inbuilt framework method instead, Clipboard.GetImage(). The WPF version of it seems to work better than the Windows Forms one.


Ideas on collecting payment before form submission?

Question: I have a use case in which I wish to collect payments before users are allowed to fill a form; basically the form is an assessment form for which the provider (offering analysis) would like to charge money.
Currently I have the form setup using webforms, but I couldn't find a decent or well established way of collecting payment with webform submission. I already have Ubercart on the site so, if there is a Ubercart to webform bridge, I would definitely like to know about it as well (I couldn't find any). Lastly I am also open for any other approaches.
My use case is the following.
Users pay for the assessment (service) using Paypal, and then they are given a link to submit a form; the submitted data need to go to the provider.
Do you have any ideas on how this could be implemented? I assume it should be a relatively common use case.
Answer: I believe you are looking for the "Ubercart event registration" technique and the Node Checkout module. Mainly because this technique is associated with "event ticketing" most people do not realize the general nature of what the Node Checkout module provides:
Node Checkout causes a "node creation form" to be presented to a user after adding an item to their cart. The idea being that someone is purchasing an event ticket, so they are presented with a form for capturing their name, address and other info so their identity can be verified at the event's ticket booth.
HOWEVER, this technique provides a few interesting things for developers:
1) these don't have to be event products, the "purchase" can be for anything
2) the information collected is entirely up to you, because you create a new content type for capturing this information, you can put text fields, checkboxes or whatever FAPI or CCK widgets you want on that form
3) due to the nature of how this technique works, you can trigger one or two "purchased item forms": the first one is automatically triggered by the Node Checkout module after the use clicks "add to cart", but part of this technique includes use of a Conditional Action to support identification of abandoned purchases where the "new purchase form" was filled out, but checkout never happened. You can use this Conditional Action moment to trigger a 2nd (or maybe in your case only) node form for collecting this information AFTER their purchase transaction completes.
I think if you only want a form to appear to the customer after the purchase transaction, you may not even need Node Checkout - you can do it all with a custom content type for your information collection, and use Conditional Actions to trigger the display of that form after purchase.
You'll have to do some mental translating to understand this technique, because the best tutorial explaining the technique is purely about event ticketing. But if you have a little imagination, you'll realize how generally useful asking the customers for information after a purchase can be.
Here's the best tutorial I've been able to find on this, step by step too:
http://drupaleasy.com/blogs/ultimike/2009/03/event-registration-ubercart
Answer: Have you tried the Ubercart Webform Checkout Pane module?
You could define a simple product and use the webform as part of the checkout process.
Some more details about this module (from its project page):

This module allows you to define Webform nodes as checkout/order panes in Ubercart.
This is useful if you want to collect additional information during the checkout process. For example, you may want a quick survey or require additional fields that apply to the entire order.
Using the Webform module allows for many advantages: the forms/fields can easily be modified by an end-user; less development time is required to create database tables and code to store/retrieve the data; and the form will remember the user's previous answers.
Furthermore, this module now provides tokens for every field in each of your enabled webforms, making it easy for you to insert the submitted values into confirmation emails, invoices, etc.
Answer: If I understand you correctly you could use Ubercart Event Registration. It creates a product class that is also a webform content type. The user fills in the webform first and then is taken to their cart. There's a hidden component in the webform for the payment status that gets updated automatically when payment's received, so it would be easy to filter out those who hadn't paid.


Skip apt faster if already installed using ansible

Question: I'm using ansible to deploy to a server.
The apt stage (it is Ubuntu) takes a long time to run even if the correct version is already installed (I'm guessing it just runs and sees that nothing needs to be installed)
Example command:
- name: set up apt packages
  action: apt pkg=nginx=1.4.6-1ubuntu3.3 state=present update_cache=yes

(I have quite a few of those, so it takes quite some time)
Is there a way ansible can "figure out" pkg is already installed and run/skip this command faster?
Answer: If you set update_cache=yes Ansible will run apt-get update at every run of the play.
Ansible documentation

Run the equivalent of apt-get update before the operation. Can be run as part of the package installation or as a separate step.

By removing update_cache=yes the task should run a lot faster, because Ansible won't need to wait for apt to update its repositories.
Another option would be to register some file or path create by the package using the stat module. Something like this:
- stat: path=/etc/nginx/nginx.conf
  register: st

- name: set up apt packages
  action: apt pkg=nginx=1.4.6-1ubuntu3.3 state=present update_cache=yes
  when: not st.stat.exists

See Ansible documentation for more examples. But I would recommend just to remove the update_cache=yes parameter.


Identity Server 3 After login looping issue

Question: We have issue with the following code

public void Configuration(IAppBuilder app)
        {
            AntiForgeryConfig.UniqueClaimTypeIdentifier = IdentityServer3.Core.Constants.ClaimTypes.Subject;
            JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary<string, string>();
            app.Map("/identity", idsrvApp =>
            {
                idsrvApp.UseIdentityServer(new IdentityServerOptions
                {
                    SiteName = "Authentication Server",
                    SigningCertificate = LoadCertificate(),
                    IssuerUri = "https://localhost:44305/",
                    Factory = new IdentityServerServiceFactory()
                                .UseInMemoryUsers(Users.Get())
                                .UseInMemoryClients(Clients.Get())
                                .UseInMemoryScopes(Scopes.Get()),
                    //EnableWelcomePage = false,
                    RequireSsl = true,
                    AuthenticationOptions = new IdentityServer3.Core.Configuration.AuthenticationOptions
                    {
                        EnablePostSignOutAutoRedirect = true,
                        IdentityProviders = ConfigureIdentityProviders
                    },
                });
            });

            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
            {
                Authority = "https://localhost:44305/identity",
                RedirectUri = "https://localhost:44305/",
                ClientId = "mvc",
                Scope = "openid",
                ResponseType = "id_token token",
                SignInAsAuthenticationType = "Cookies",
                UseTokenLifetime = false,
                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    SecurityTokenValidated = async n =>
                    {
                        var nid = new ClaimsIdentity(
                            n.AuthenticationTicket.Identity.AuthenticationType,
                            IdentityServer3.Core.Constants.ClaimTypes.GivenName,
                            IdentityServer3.Core.Constants.ClaimTypes.Role);

                        // get userinfo data
                        var userInfoClient = new UserInfoClient(
                            new Uri(n.Options.Authority + "/connect/userinfo"),
                            n.ProtocolMessage.AccessToken);

                        var userInfo = await userInfoClient.GetAsync();
                        userInfo.Claims.ToList().ForEach(ui => nid.AddClaim(new Claim(ui.Item1, ui.Item2)));

                        // keep the id_token for logout
                        nid.AddClaim(new Claim("id_token", n.ProtocolMessage.IdToken));

                        // add access token for sample API
                        nid.AddClaim(new Claim("access_token", n.ProtocolMessage.AccessToken));

                        // keep track of access token expiration
                        nid.AddClaim(new Claim("expires_at", DateTimeOffset.Now.AddSeconds(int.Parse(n.ProtocolMessage.ExpiresIn)).ToString()));

                        // add some other app specific claim
                        nid.AddClaim(new Claim("app_specific", "some data"));

                        n.AuthenticationTicket = new AuthenticationTicket(
                            nid,
                            n.AuthenticationTicket.Properties);
                        var data = ClaimsPrincipal.Current.Identity;

                    },

                    RedirectToIdentityProvider = n =>
                    {
                        if (n.ProtocolMessage.RequestType == Microsoft.IdentityModel.Protocols.OpenIdConnectRequestType.LogoutRequest)
                        {
                            var idTokenHint = n.OwinContext.Authentication.User.FindFirst("id_token");

                            if (idTokenHint != null)
                            {
                                n.ProtocolMessage.IdTokenHint = idTokenHint.Value;
                            }
                        }

                        return Task.FromResult(0);
                    },
                }
            });

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = "Cookies",
                            });

        }

        public static X509Certificate2 LoadCertificate()
        {
            return new X509Certificate2(
                string.Format(@"{0}\bin\identityServer\idsrv3test.pfx", AppDomain.CurrentDomain.BaseDirectory), "idsrv3test");
        }

Issue is like when login successed that time identity goes to looping.
Answer: How are you trying to access the site in the first place? I think you are accessing it over HTTP. The result is a cookie problem that is set for HTTPS and not HTTP and it will keep trying to redirect to itself.
I explained this in depth with an answer here: OWIN and Azure AD HTTPS to HTTP Redirect Loop
Comment: I am using Asp.net WebFroms and Identity Server 3.Webconfig set authorization and its directly go for Identity Server login page and after login successed its not work.
Comment: The technology is not really relevant. It should work with any of them. Take a look at the linked answer.
Comment: Same structure works into MVC side.its working fine in MVC


ggplot2 ggallin Error in `as.trans()`: ! `trans` must be a character vector or a transformer object

Question: I was able to use ggallin::pseudolog10_trans() to plot log10 x-scale with negative numbers a week ago, but now I am getting the error message:
Error in `as.trans()`:
! `trans` must be a character vector or a transformer object

At this point, the scripts available from the help page do not work:
set.seed(1234)
ggplot(data.frame(x=rnorm(100),y=runif(100)),aes(x=x,y=y)) +
  geom_point() +
  scale_x_continuous(trans=ssqrt_trans)
Error in `as.trans()`:
! `trans` must be a character vector or a transformer object

Suggestions?
Answer: Please go and get the latest version on github -> packageVersion("ggallin") = 0.1.1.1001.
Using install.packages("ggallin") causes the error (package version 0.1.1).
# get snapshot from github (may be buggy)
if (require(devtools)) {
  install_github('shabbychef/ggallin')
}

library(ggplot2)
library(ggallin)

set.seed(1234)
ggplot(data.frame(x=rnorm(100),y=runif(100)),aes(x=x,y=y)) +
  geom_point() +
  scale_x_continuous(trans=ssqrt_trans)


Alternately Multiplying and Dividing Within Pascal's Triangle

Question: I recently noticed that, if you take the $(2n)$th row of Pascal's triangle, and alternately multiply and divide the numbers that crop up, almost everything cancels. For example, the 4th row (1 4 6 4 1) becomes $1/4 \times 6/4 \times 1$, which simplifies to $3/8$. I performed the same procedure for some later rows, and got $5/16$, $35/128$, $63/256$, $(3 \times 7 \times 11)/(2^{10})$, and $(3 \times 11 \times 13)/(2^{11})$.
All of the denominators seem to be powers of 2, which I don't know how to prove. Also, the fractions seem to me to be (very) slowly approaching 0, which I also don't know how to prove (if it's even true). Any assistance with either question would be greatly appreciated- I'm not very well versed in methods of proof.
Comment: 4th row the way mathematicians count them.
Comment: Okay. I'll switch that, then.
Answer: We can simplify each individual ratio:
$$ \frac{\displaystyle \binom{2n}{0}}{\displaystyle \binom{2n}{1}}\frac{\displaystyle \binom{2n}{2}}{\displaystyle \binom{2n}{3}}\cdots\frac{\displaystyle\binom{2n}{2n-2}}{\displaystyle \binom{2n}{2n-1}} = \frac{1}{2n}\frac{3}{2n-2}\cdots\frac{2n-1}{2} $$
Reorder the factors in the denominator, then square them while interlacing them up top:
$$ \frac{1\cdot2\cdot3\cdot4\cdots(2n-1)(2n)}{2^2\cdot 4^2\cdot6^2\cdots (2n)^2} =\frac{(2n)!}{\big[2^n n!\big]^2}=\frac{1}{4^n}\binom{2n}{n}. $$
Comment: Yes, see [central binomial coefficient](https://en.wikipedia.org/wiki/Central_binomial_coefficient) for estimates and elementary inequalities. In particular, $$\frac{1}{4^n}\binom{2n}{n}\sim \frac{1}{\sqrt{\pi n}}. $$ Not sure off the top of my head of an elementary proof of a sufficient inequality.
Comment: Apply Stirling's formula
Comment: And $\frac{1}{4^n}\binom{2n}{n}$ approaches 0 as n approaches infinity?


Proper regression model for ratio data

Question: I've been thinking about a regression model with dependent variable a ratio in the range [0-600+]. About 50%+ are 0 values though, 40%+ values [0-5], and a very small percentage of the values are higher than 5, so the picture is quite skewed.
I've been wondering what kind of transformation I need to do in order to linearize the model. Is the natural log transformation appropriate?
Comment: If you take the log of the dependent variable, then you lose all observations with zero, i.e., 50%+. I wouldn't do that. What is the ratio exactly? Maybe you can multiply with the denominator, thus making everything linear.
Comment: What are the numerator and denominator of the ratio? Are they counts? Why are they divided?
Comment: I've been interested in the success rate of a crowdfunding campaigns, that why I am taking the ratio beteen the actual pledge and the goal. The ratios do not have the same denominator, thus multipling wont work :(
Answer: One answer is no transformation at all. Poisson regression in fact can give the best of both worlds, the ability to cope with observed zeros and a logarithmic link. The point is that the mean response is modelled as positive, so that it can be logged, and that can be consistent with some observed values being zero. You don't transform the response. In effect the software takes a logarithmic view of the data but returns predictions on the original scale. (This is one kind of generalized linear model.)
See http://blog.stata.com/2011/08/22/use-poisson-rather-than-regress-tell-a-friend/ for one encouraging discussion. By the way, it's a myth that Poisson regression requires counted data or even a marginal Poisson distribution for the response. The leading idea is simply that a non-negative response and a functional form $Y = \exp(X\beta)$ just as the leading idea of classical regression is $Y = X\beta$ and assumptions of Gaussian distributions are far less crucial, just nice if they are accurate.
Much, however, depends on those zeros and whether they are all comparable. For example, number of alcoholic drinks per day is a response that could be zero, but if the population mixed people who never drink alcohol at all and people who in some cases just drank no alcohol on some days, then there is heterogeneity that might require explicit modelling. The best way I can think of putting this is that the simplest situation is that the zeros you observe are all sampling zeros, so that in principle they could have been different. If some are structural zeros, i.e. zeros by necessity or definition, your situation is more complicated.
Comment: Even if they're all sampling zeros, don't you think he might run into an excess zeros problem using Poisson with 50% or more zeros?
Comment: @Nameless Could well be. But the mean being very low and near zero is consistent with Poisson regression. Also, I would always try Poisson first before trying something more exotic such as a zero-inflated Poisson.
Comment: The zeroes are sampling zeroes, however the sample is random and I do not expect to be that different from the whole population. I do not believe I will run into unobserved heterogeneity problem.

I am still not sure how to proceed, probably I will read more about Poisson. Just to clarify...ln transformation is not an option, right?
Comment: ln(0) is indeterminate, so a ln() transformation is, as already stated, emphatically not an option for you. You can find literature using ln(x + 1) as a work-around, on which there are threads in this forum. I advise against, but there are different views.
Comment: What you think about using Gamma GLM since the distibution is heavily skewed? I am mostly concerned about the academic support for the use of Poisson in similar situations.
Comment: That's going in the wrong direction. Gamma-distributed variables can't be zero, at least not in the standard two-parameter version. I think you need to be more explicit about your concern about "academic support".
Comment: @NickCox, thank you, I will certainly take that points.

Proper regression model for ratio data


Não consigo apresentar a mensagem de erro Spring

Question: Estou tentando validar uns campos com anotações, mas não consigo trazer as mensagens para o jsp da página:
Usuario.java
mport java.util.Calendar;

import javax.validation.constraints.Email;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

public class Usuario {

private String nome;
private String sobrenome;
private String cpf;
private String identidade;
@NotNull(message="{usuario.email.nulo}")
@Email(message="{usuario.email.invalido}")
private String email;
@NotNull(message = "{usuario.senha.nula}")
@Size(min = 6, message="{usuario.senha.pequena}")
private String senha;
private Endereco endereco;
private Calendar dataNascimento;

Tem uma classe Cliente que estende de Usuario:
E tem ClienteController.java
package br.com.wlsnprogramming.loja.controller;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;

import br.com.wlsnprogramming.loja.model.usuario.Cliente;

@Controller
@RequestMapping("cliente")
public class ClienteController {

@RequestMapping("login")
public String formLogin() {
    return "cliente/login";
}
@RequestMapping("efetuarLogin")
public String efetuarLogin(@Valid Cliente cliente, BindingResult result, HttpSession session) {
    if(result.hasFieldErrors("email") || result.hasFieldErrors("senha")) {
        System.out.println(result.getFieldError("senha").getDefaultMessage());//Aqui em fiz o teste para ver se recuperava a mensagem, ate aqui deu certo
        return "redirect:login";
    }
    //faz a verificação aqui
    return "redirect:meusPedidos";
}
}

login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<!DOCTYPE html>

<meta charset="utf-8"/>
<title>Inicio</title>
<link rel="stylesheet" href="../resources/styles/login.css" type="text/css"/>
<link rel="stylesheet" href="../resources/styles/style.css" type="text/css"/>

<c:import url="../header.jsp"/>

Entrar na Conta

Ainda não tem uma conta? Crie já!

    <form id="login" method="post" action="efetuarLogin">
        E-mail:
        <input type="email" name="email" id="email" required="true" />
        Senha:
        <input type="password" name="senha" id="senha" required="true" />

<form:errors path="cliente.senha" cssStyle="color:red"/>

        <input type="submit" value="Entrar"/>

Esqueceu a sua senha? Estão recupere clicando aqui!

    </form>

<c:import url="../fooder.jsp"/>

Já tentei colocar de tudo no path, mas não funciona.
Answer: Já descubri o erro, parece que tem fazer o redirecionamento no lado do servidor:
return "cliente/login";// direcionando diretamente para o jsp

ou
return "forward:login";// direcionado para a função, mas do lado do servidor

Não pode usar o redirect para redirecionar no lado do cliente.
Answer: Basta apenas inserir a dependência de validação do Spring no projeto!
Spring-Boot-Starter-Validation.

    org.springframework.boot
    spring-boot-starter-validation
    2.4.0
Answer: Tente colocar a dependencia no pom. No spring boot funcionou.

    org.springframework.boot
    spring-boot-starter-validation


Rounding issue in laravel blade

Question: I've continued trying different variations of number_format and float on a certain column in my blade template, but no matter what I still end up with numbers like 514.238054 instead of 514.24
I'm currently using this format:
<code>{{ (number_format((float)$item['test']['category'], 2, '.', '')/number_format((float)$item['new']['category'], 2, '.', ''))*100 }}
</code>
Is there another method I can try with this that would keep it down to two decimal places properly?
Comment: its the result you should format, not the divident or the devisor
Comment: Be very careful doing any arithmetic on floating-point numbers. I strongly suggest using a library to handle this for you. Something like https://github.com/moneyphp/money has been tested well.
Comment: Having code like this in your view is fairly ugly. You should define an accessor on the model and do the math there, or at least put it in the controller.
Answer: It's the result you should format, not the dividend or the divisor.
So if anything it should look something like this
<code>{{(number_format(((float)$item['test']['category']/(float)$item['new']['category']), 2, '.', '')) * 100}}
</code>
Comment: That makes sense now, I plugged this in and it worked perfectly, thanks! I'll make sure to only format the result from now on
Answer: This Php Code Works Just Fine For Above Explained Task!
I've Tried It On My Php Ide!
Actual Code:
<code>
$flo= 514.238054;

echo number_format((float)$flo, 2, '.', '');

</code>
Ide Screenshot Before Execution:
Before Execution Code
Output Ide Screenshot:
After Executing The Code
Comment:  Please, easy on the ALL CAPS. It's considered YELLING.
Comment: This doesn't really help the OP because they had the syntax right but were doing an additional calculation which produced another float.
Comment: noone is questioning that it works, but you're not contributing anything new to the topic, it's the order of things that is creating undesired effects. Not how he uses the function

Rounding issue in laravel blade


How to submit without having a submit button on the form?

Question: Can I have a submit  in <% using (Ajax.BeginForm("ChangePassword", new AjaxOptions { OnComplete = "ChangePasswordComplete" }))  without having a submit button on the form?
I yes, how? Let's say I want to submit the above when a user click on an input of type button simply?
Answer: You'd have to use Javascript to post back the form, jQuery has a submit method you can use.
$("#FormId").submit();

But really, an input of type button is the same as submit, only it submits automatically so you might as well use that.
Progressive Enhancement
Alternatively, you can use the jQuery Form plug-in to post a standard form (using Html.BeginForm or manually outputting the <form />) and that will work for people who don't have Javascript enabled on their browser.
Comment: Where do I include the form Id in the above?
Comment: Either inspect it in the browser to see it's id/ name or provide one using the htmlAttributes (http://msdn.microsoft.com/en-us/library/dd493048(v=VS.100).aspx). You can also give it a class and use the jQuery class selector `.FormClass`, again, use the htmlAttributes to provide the class name like this `new { @class = "form-class-name" }` (the @ is required in C# as class is a keyword)


Passing the same props while rendering different elements conditionally in React.js

Question: I have a React Component named Chart. I want to render different charts in it based on the prop passed from their parent, but having the exactly same config. What is the best way to do it?
class Chart extends Component {

  static propTypes = {
    type: PropTypes.string.isRequired
  }

  state = {
    chartData: {
      // some data here
    }
  }

  render(){
    return(
      this.props.type === 'line' ?
      { <Line
        data={this.state.chartData}
        options={{
          title: {
            display: true,
            text: 'Cities I\'ve lived in',
            fontSize: 25
          },
          legend: {
            display: true,
            position: 'right',
            labels: {
              fontColor: '#000'
            }
          }
        }}
      /> } : this.props.type === 'bar' ?
      { <Bar
          //same stuff here as <Line />
        />
      } : this.props.type === 'pie' ?
      { <Pie
          //same stuff here as <Line />
        /> }
      }
    );
  }
}

Don't think it matters since the question is generic, but I'm using react-chartjs-2 / chart.js 2 library for rendering charts.
Note: I've tried using a variable name in place of Line/Bar/Pie, but it doesn't work if I'm using JSX or rendering a non-html tag. Better ways to solve it while using JSX and non-html tags are also welcome.
Answer: Two things:

Use stateless component, in your example you are not using state.
Use switch instead of if statements.

Your new component, ...chart are the destructured props. Read more about destructuring on MDN.
// Chart.js - new component

export const Chart = ({ type, ...chart }) => {
  switch(type) {
    case 'line':
      return <Line {...chart} />
    case 'bar':
      return <Bar {...chart} />
    case 'pie':
      return <Pie {...chart} />
    default:
     return null;
  }
}

Example usage
// App.js

render() {
  return (

      <Chart type="line" options={optionsObject} whateverProp="whatever" />
      <Chart type="bar" options={optionsObject} whateverProp="whatever" />
      <Chart type="pie" options={optionsObject} whateverProp="whatever" />

  )
}

Answer: import React, { Component } from 'react';

class Chart extends Component {
  components = {
    Line: Line,
    Bar: Bar,
    Pie: Pie
  };
  render() {
    const TagName = this.components[this.props.tag || 'Line'];
    return
      <TagName
        data={this.state.chartData}
        options={{
        title: {
          display: true,
          text: 'Cities I\'ve lived in',
          fontSize: 25
        },
        legend: {
          display: true,
          position: 'right',
          labels: {
            fontColor: '#000'
          }
        }
      }}
    />
  }
}
export default Chart;

// Call MyComponent using prop tag with required prop Line or Bar or Pie
<Chart tag='Line' />

NOTE:- You could create it as a stateless functional component as well.
Answer: I prefer to have each chart as a component, so you can do chart's specific configuration in that component and your code will be more close to React codes modularity goal, so for Line chart as example:
class LineChart extends Component {

const chartLegend = {
            display: true,
            position: 'right',
            labels: {
              fontColor: '#000'
            }};

const chartTitle = {
            display: true,
            text: 'Cities I\'ve lived in',
            fontSize: 25
          };
const chartOptions = {
          title: chartTitle ,
          legend: chartLegend
        }

  render(){
    return(
      <Line
        data={this.props.chartData}
        options={chartOptions }
      />
    );
  }
}

Now for chat Component as container component you can use switch case or guard conditions as @loelsonk also said, I prefer to have guard conditions besides switch:
class Chart extends Component {

  static propTypes = {
    type: PropTypes.string.isRequired
  }

  state = {
    chartData: {
      // some data here
    }
  }

  render(){
    if (this.props.type === 'line')
      return <LineChart chartData={...}/>;
    if (this.props.type === 'bar')
      return <BarChart chartData={...}/>;
    if (this.props.type === 'pie')
      return <PieChart chartData={...}/>;
  }
}

this way you can easily replace any chart implementation any time that needed.


Como retornar diferentes estruturas em uma função com um valor definido em runtime?

Question: Olá, estou trabalhando em um projeto para Windows que possui uma estrutura(do próprio Windows) que muda conforme a arquitetura do sistema(x86/x64), como retornar a estrutura correta por uma função baseado na informação de qual arquitetura do Windows o usuário está usando?
Por exemplo:
struct s_arch_x86
{
    uint32_t    callback0;
    uint32_t    flags;
    uint32_t    callback1;
};

struct s_arch_x64
{
    uint64_t    callback0;
    uint32_t    flags;
    uint32_t    flags2;
    uint64_t    callback1;
};

template < typename T1, typename T2 >
auto get_struct_based_on_arch(uint32_t arch, uintptr_t address)
{
    return arch == 32 ? reinterpret_cast<T1>(address) : reinterpret_cast<T2>(address);
}

get_struct_based_on_os_arch<s_arch_x86*, s_arch_x64*>(get_os_arch(), ptr)->callback1 = 0;

No MSVC com C++17 tenho o seguinte erro ao compilar o código acima: error C2446: ':': no conversion from 'T2' to 'T1'
Comment: É pra todas essas versões? (não que precise de  nenhuma, provavelmente no pior caso `#ifdef` resolve em todas)
Comment: Não, qualquer uma
Answer: Acho que está complicado demais...
A não ser que exista alguma razão para usar templates (eu pelo menos não estou vendo nenhuma) eu faria algo assim:
if (get_os_arch() == 32)
{
  s_arch_x86* x86 = (s_arch_x86*)ptr;
  x86->callback1 = 0;
}
else
{
  s_arch_x64* x64 = (s_arch_x64*)ptr;
  x64->callback1 = 0;
}

Esse é só um código ilustrativo, nem sei se está totalmente correto, mas o importante, para mim, seria não usar aquela complicação de templates...
Encapsulando em uma função:
void resetCallback(uintptr_t ptr)
{
  if (get_os_arch() == 32)
  {
    s_arch_x86* x86 = (s_arch_x86*)ptr;
    x86->callback1 = 0;
  }
  else
  {
    s_arch_x64* x64 = (s_arch_x64*)ptr;
    x64->callback1 = 0;
  }
}

Comment: O problema é que lotaria o código de condicionais if/else e de blocos
Comment: então é só encapsular em uma função...
Comment: Não é simples assim, essa estrutura muda conforme a arquitetura, versão e build do Windows, é uma estrutura relacionada a windows driver, existe varias builds diferentes no windows 10(10240, 10586, 14393, 15063, 16299, 17134, 17763, 18362, 18363), lotaria o código de if/else if ou switch de qualquer forma, acredito que não tenha uma forma melhor
Comment: como eu disse acima, é só encapsular em uma função para evitar a repetição de if/switch
Answer: Não consegui achar o uso pra isso, mas você pode receber por template a arquitetura que quer utilizar.
Link com um exemplo: https://godbolt.org/z/MKWTcV.
#include <cstdint>

struct s_arch_x86
{
    uint32_t    callback0;
    uint32_t    flags;
    uint32_t    callback1;
};

struct s_arch_x64
{
    uint64_t    callback0;
    uint32_t    flags;
    uint32_t    flags2;
    uint64_t    callback1;
};

template <typename ARCH>
auto getArchStructure(std::uintptr_t address)
{
    return reinterpret_cast<ARCH*>(address);
}

int main()
{
    auto x32 = getArchStructure<s_arch_x64>(0xFFFFFF);
    auto x64 = getArchStructure<s_arch_x86>(0xFFFFFF);

    x32->callback1 = 0;

    x64->callback1 = 0;

    return 1;
}


Call a Rmarkdown report in the shiny application

Question: I have a shiny application that read a csv file and clean the data and add few columns, ... (I used this example to create the app). At the end the application save the cleaned data (output.csv) in the log folder within the application folder.
I also design a Rmd file which is in the shiny application folder. The Rmd file uses the output file (log/output.csv).
I would like to call the Rmd file to show the report after saving the (output.csv), How can I do it?
Comment: I tried your suggestion and it doesn't work!
Answer: I found the solution as follow. Just include the following code lines in your application:
uo.R:
mainPanel(
      uiOutput("report")
    )

server.R:
output$report <- renderUI({
    includeMarkdown("Report1.Rmd")
  })


How to make two Elastic Beanstalk environments share one database instance

Question: I have a rails elastic beanstalk application with two environments, staging and production. When creating the application and staging environment with eb init i created a database instance. I used the eb console to create the production environment and created a new database instance which i perceive is obviously a wrong move.
How do i make my two environments share the same database instance? If that happens, how about when i update the database migrations in my app and deploy to the staging; it means my users would see it because the same database is used by staging environment.
How to i handle this issue?
I also noticed git aws.push doesn't overwrite my database but it doesn't remove rolled back migrations. Am i missing something?
Answer: I would recommend to you following option: Create rds instance outside of the elastic beanstalk environment. Create separate schemas for production and staging. Pass connections strings to your EBS application. Shared rds instance between EBS environments will help to you:

Decrease cost of your environment, because to have several rds instances running is expensive.
Help to you isolate production and staging environments.
Comment: You can add to your application folder .ebextentions with config files which will contain configuration settings like connection string to db and scripts to run migrations. I would suggest to read article: http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create_deploy_Ruby_custom_container.html
Comment: I will try to explain my idea one more time be steps: 1. You can manually create rds instance and schemas for production and staging. 2. You can add to your application elastic beanstalk configuration files, where you can define connection string for current database related with staging or production, also you can define here commands for running migrations. 3. To do git aws.push :)
Comment: If i want to agree with you, how do i push my database from localhost independently to the new RDS instance? Remember its rails and a git aws.push does the deployment but with your solution not anymore. So how?


Modal view before UITabBarController

Question: Im trying to present a modal view controller from subclass of UITabBarController. I present it from viewDidLayoutSubviews method. Everything works fine on iOS 7 but in iOS 8 when app stars i still breafly see TabBarControllers first tab.
TabBarController is set as initial view controller in storyboard.
Is this even a good way to present it or there is something for iOS 8 that i dont know?
Answer: I don't have the rep to post a comment, so I'll seek clarification and provide guidance through this answer.
Is the intention that the modally presented view controller will be the first thing people see when they launch the app? And then I suppose it gets dismissed, and behind it will be the tabbar controller? How is your storyboard currently set up for the modal view controller if the tabbar is set to be the initial view controller?
One place to start could be to move to code to viewWillLoad or viewDidLoad rather than viewDidLayoutSubviews. I could also suggest to just make the modal VC the initial view controller

Modal view before UITabBarController


Nginx proxy pass real ip doesn't work

Question: I run a nginx reverse proxy server in the docker container. And the backend is a apache server running on the host, which is listening 10082 port. Laravel handle the request. And I use
$request->getClientIp()
to get real ip. However, the result of visiting the server by http://myip:10082 directly without proxy conflicts with the result of visiting it by reverse proxy.
The test code in laravel:
echo $request->ip().'
';
echo $request->headers->get('X-Real-IP').'
';
echo $request->getClientIp().'
';

The result with proxy:
192.168.80.2
126.96.36.199
192.168.80.2

The result without proxy(the XX.XXX.236.29 is my real ip):
XX.XXX.236.29

XX.XXX.236.29

The configuration of nginx:
server {
    listen       80;
    server_name  myserver.com;

    access_log  logs/myserver.access.log  main;

    location / {
        proxy_pass http://myip:10082;
        proxy_set_header   Host    $host;
        proxy_set_header   X-Real-IP   $remote_addr;
        proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
    }

}

I'm so confused. Could someone help me solve it. Thanks!
Comment: Check out: http://stackoverflow.com/a/41748592/7377984 and https://github.com/fideloper/TrustedProxy
Answer: Since you have set the X-Real-IP header in your nginx proxy, it's the real ip.
Answer: I've had the same issue and spent quite some time on it.
The problem is triggered is by the request having to pass the docker-proxy on its way to your containers. The IP is changed and basically you'll receive the gateway IP for your docker-network instead of the physical server one.
The latest editions of Laravel includes TrustProxies, but that helps nothing if the REMOTE_ADDR you receive isn't your server IP.
Hardcoding it isn't a solution either, since that IP can change the next time you reboot your server/recreate the containers.
I've solved this for myself by assuming that - when my server IP has 3 bytes in common with the REMOTE_ADDR and the latter ends with .1, it is safe to use as a trusted proxy:
In your TrustProxies-middleware's handle()-function:
$remoteAddr = $request->server->get('REMOTE_ADDR');
$serverAddr = $request->server->get('SERVER_ADDR');
if ($serverAddr && $remoteAddr) {
   $lastDot = strrpos($serverAddr, '.');
   if ($lastDot !== false &&
       substr($remoteAddr, $lastDot) === '.1' &&
       strpos($remoteAddr, substr($remoteAddr, 0, $lastDot+1)) === 0) {
      $this->proxies[] = $remoteAddr;
   }
}

Nginx proxy pass real ip doesn't work


Equations of the image of a curve with elimination theory

Question: I've been trying to solve the next problem but I can't complete the last step.
The problem is:
Considering the image of the circle $$V=\{  (x_1,x_2): x_1^2+x_2^2=1  \}$$ given by the map $$\rho: V \rightarrow \mathbb{A}^2(\mathbb{R})$$ $$(x_1,x_2) \longmapsto (\frac{x_1}{1+x_2^2}, \frac{x_1x_2}{1+x_2^2})$$ Compute the equations of the image.
My attemp: The map $\rho$ is well defined over the open set $$U=\{(x_1,x_2)\in V: g=(1+x_2^2)(1+x_2^2) \neq 0\}=V$$ so we can take the affine variety $ Y:=\mathbb{A}^2(\mathbb{R})_g \subset  \mathbb{A}^3(\mathbb{R})$ given by $$Y:=\{(x_1,x_2,z):zg(x_1,x_2)-1=0\}=\{(x_1,x_2,z):z(1+x_2^2)^2-1=0\}$$ and a morphism $\phi: Y \rightarrow W $ such that $\phi(Y)= \rho(V)$.
$$ $$
Calling $ \Gamma_\phi$ to the graph of $\phi$ in $ \mathbb{A}^3(\mathbb{R}) \times  \mathbb{A}^2(\mathbb{R})$, we have that: $$I(\Gamma_\phi)=\langle  z(1+x_2^2)^2-1, y_1-x_1 (1+x_2^2), y_2-x_1x_2(1+x_2^2)  \rangle$$
Now we have to compute a Gröbner basis of that ideal and, after that, use elimination theory to quit all the expresions in that basis that depend on $x_1,x_2,z$. The remaining equations will be those asked in our problem.
I've tried this last part many times but I always get all the equations depending on $x_1,x_2,z$. I'd really appreciate if someone could help me in this last part.
Thanks in advance.
Answer: Solving equations $y_1=\frac{x_1}{1+x_2^2}$ and $y_2= \frac{x_1x_2}{1+x_2^2}$ for $x_1$ and $x_2$ and substituting into $x_1^2+x_2^2=1$, I get $y_1^3+y_2^2y_1+y_2^2=y_1^2$. Does that help?
Comment: Thank you very much, @user72694. This is a possible solution but I've been asked to solve the problem using elimination theory, so I need to compute Gröbner basis $\mathfrak{G}$ and, after that, take the generators of $\mathfrak{G} \cap k[y_1,y_2]$, and is here where I can't continue.


How to loop through mismatched data

Question: So I have been trying to think of how this would be possible, but nothing comes to mind.
I have 2 csv files with dates and data in them. The dates, however, are mismatched. I want to be able to write a code that allows me to loop through all the data, find the matching dates, and then create a text document with the date in common and the 2 data values from the separate sheets. The other alternative is matching them myself in excel.
Any suggestions?
Ex. of what I am trying to accomplish:
Say I have this file1:
01/01/01 | 1
01/02/01 | 2
01/03/01 | 3
01/04/01 | 4
01/05/01 | 5
01/06/01 | 6
01/07/01 | 7
01/08/01 | 8

and this file2:
01/05/01 | 9
01/06/01 | 22
01/07/01 | 33
01/08/01 | 44
01/09/01 | 55
01/10/01 | 66
01/11/01 | 77
01/12/01 | 88

What I would hope to have returned is (after running a loop):
01/05/01 | 5 | 9
01/06/01 | 6 | 22
01/07/01 | 7 | 33
01/08/01 | 8 | 44

Any help would be appreciated, thanks!
Answer: I think pandas join logic is well suited for this task since you are effectively asking for an inner join as keyed by date.
First define a parsing function for your dates (which I added in case you needed to treat these as actual dates for further processing in python). Then load each csv file into a separate dataframe. Finally join and drop NaN values to get the inner join you seek (or just explicitly inner join by setting how parameter in join function). You can also easily drop the outptut dataframe into a csv file with the to_csv function.
If you are looking to get a little more creative with aggregating or joining then pandas is the way to go.
import pandas
parser = lambda date: pandas.datetime.strptime(date.strip(), '%y/%m/%d')
dt = pandas.read_csv('H:\\one.csv', parse_dates = [0], date_parser = parser, index_col=0, delimiter="|", names = ["date", "val"])
dt2 = pandas.read_csv('H:\\two.csv', parse_dates = [0], date_parser = parser, index_col=0, delimiter="|", names = ["date", "val2"])
dt.join(dt2).dropna().to_csv("H:\\output.csv")

This would also work but you lose all of the date-specific functionality within python:
import pandas
dt = pandas.read_csv('H:\\one.csv', index_col=0, delimiter="|", names = ["date", "val"])
dt2 = pandas.read_csv('H:\\two.csv', index_col=0, delimiter="|", names = ["date", "val2"])
dt.join(dt2, how='inner').to_csv("H:\\output.csv")

Answer: Use a defaultdict of lists to store the data from the CSV files, then find those items in the dict that have more than one value in the list.
import csv
from collections import defaultdict

merged = defaultdict(list)

for filename in 'f1.csv', 'f2.csv':
    with open(filename) as f:
        for date, value in csv.reader(f, delimiter='|'):
            merged[date].append(value)

with open('out.csv', 'w') as f:
    w = csv.writer(f, delimiter='|')
    for date in sorted(merged):
        if len(merged[date]) > 1:
            w.writerow([date] + merged[date])

This will (almost) produce the file that you require, the only difference being that the delimiter is a single | instead of | (with surrounding spaces). I also assumed that the input files are similarly delimited.
Answer:
Read the first record from each file, r1 and r2
Extract dates d1 and d2
while there's remaining data in both files:

if d1 == d2:

merge records and print
get next line of each file (new r1 and r2)

else if d1 < d2

get next r1

else

get next r2

Briefly, you're stepping through both files, keeping a "bookmark" in each.  If the records match, merge them and print; advance both files.  Otherwise, advance the bookmark that's "behind" in the date.
Answer: Using CSV module to read out both files, convert them to a dictionary which maps date => list[values], then prints them.
import csv

# Extract CSV
csv1 = []
with open('first.csv', 'r') as f1:
    csv_reader = csv.reader(f1)
    for row in csv_reader:
        csv1.append(row)

csv2 = []
with open('second.csv', 'r') as f2:
    csv_reader = csv.reader(f2)
    for row in csv_reader:
        csv2.append(row)

# Initialize dict which will map dates to values
d = {}

# Map dates to values by getting a default array and appending the values
for row in csv1:
    v = d.get(row[0], [])
    v.append(row[1])
    d[row[0]] = v

for row in csv2:
    v = d.get(row[0], [])
    v.append(row[1])
    d[row[0]] = v

# Print results
for k, v in d.items():
    values = ' | '.join(list(map(str, v)))
    print(f'{k} | {values}')

How to loop through mismatched data