Underlying functor of tensor product in a closed and symmetric monoidal category.

Question: I will follow, for terminology and notation, G. M. Kelly, Basic Concepts of Enriched Category Theory. For sake of a self-contained exposition, I will try to write here all the needed concepts.
Let then $\mathcal{V}=(\mathcal{V}_{0},\ \otimes,\ I,\ a,\ r,\ l)$ be a monoidal category and let $\mathcal{A}$ be an enriched $\mathcal{V}-$category. Then one can define the underling category of $\mathcal{A}$, denoted as $\mathcal{A}_{0}$, whose objects are those of $\mathcal{A}$ and whose hom-sets $\mathcal{A}_{0}(A,B)$ are $\mathcal{V}_{0}(I,\ \mathcal{A}(A,B))$, for $A,B$ objects of $\mathcal{A}_{0}$. For $f\in\mathcal{A}_{0}(A,B)$ and $g\in\mathcal{A}_{0}(B,C)$, the composite $gf$ is given by the composite
$$
I\overset{l^{-1}}{\longrightarrow}I\otimes I\overset{g\otimes f}{\longrightarrow}\mathcal{A}(B,C)\otimes\mathcal{A}(A,B)\overset{M}{\longrightarrow}\mathcal{A}(A,C),
$$
where $M$ is the composition law in $\mathcal{A}$.
Furthermore, given a $\mathcal{V}-$functor $T\colon\mathcal{A}\to\mathcal{B}$, the underling functor $T_{0}\colon\mathcal{A}_{0}\to\mathcal{B}_{0}$ acts as $T$ on the objects of $\mathcal{A}_{0}$, while it sends $f\in\mathcal{A}_{0}(A,B)$ to $T_{AB}\circ f$, where the composite is taken in $\mathcal{V}_{0}$.
Suppose now that $\mathcal{V}$ is a closed, symmetric monoidal category and call the commutativity isomorphism $c$. Denote also with
$$
\pi\colon\mathcal{V}_{0}(X\otimes Y, Z)\overset{\simeq}{\longrightarrow} \mathcal{V}_{0}(X,[Y,Z])
$$
the adjunction isomorphism. It is then possible to see $\mathcal{V}$ as a category enriched over itself (which we keep on calling $V$): the objects of $\mathcal{V}$ are those of $\mathcal{V}_{0}$, while the hom-object $\mathcal{V}(X,Y)$ is $[X,Y]$. The composition law $M\colon[Y,Z]\times [X,Y]\to [X,Z]$ is the arrow corresponding under $\pi$ to the composite
$$
([Y,Z]\times [X,Y])\times X\overset{a}{\longrightarrow}[Y,Z]\times ([X,Y]\times X)\overset{1\otimes e}{\longrightarrow} [Y,Z]\times Y\overset{e}{\longrightarrow} Z
$$
There is an isomorphism between the underlying category of $\mathcal{V}$ as an enriched category over itself and $\mathcal{V}_{0}$ which, as far as I understand,  should send a morphism $f\colon A\rightarrow B$ in the underlying category (so $f\colon I\rightarrow [A,B]$) to $\pi^{-1}(f)\circ l^{-1}$. Therefore, we can identify those two ordinary categories.
We can also define a $\mathcal{V}-$ functor $Ten\colon \mathcal{V\otimes V}\to\mathcal{V}$. Here $\mathcal{V}\otimes\mathcal{V}$ has object-class given by $\mathcal{V}_{0}\times\mathcal{V}_{0}$ and $(\mathcal{V}\otimes\mathcal{V})((X,Y),\ (X',Y')):= [X,X']\otimes [Y,Y']$. The $\mathcal{V}-$functor $Ten$ sends an object $(X,Y)$ to $X\otimes Y$, while $Ten_{(X,Y),(X',Y')}$ corresponds under $\pi$ to the composite
$$
([X,X']\otimes [Y,Y'])\otimes (X\otimes Y)\overset{m}{\longrightarrow} ([X,X']\otimes X)\otimes ([Y,Y']\times Y)\overset{e\otimes e}{\longrightarrow} X'\otimes X.
$$
Here $m:(W\otimes X)\otimes (Y\otimes Z)\simeq (W\otimes Y)\otimes (X\otimes Z)$ is the middle-four interchange isomorphism and $e\colon [Y,Z]\otimes Y\longrightarrow Z$ is the evaluation morphism associated to $\pi$ (the unit of the adjunction). One gets that $e(Ten\otimes 1)=(e\otimes e)m$.
Finally, here comes the question. It should be true that the ordinary functor $S$ given as the composite
$$
\mathcal{V}_{0}\times\mathcal{V}_{0}\longrightarrow (\mathcal{V}\otimes\mathcal{V})_{0}\overset{Ten_{0}}{\longrightarrow}\mathcal{V}_{0}
$$
is the tensor product $\otimes\colon\mathcal{V}_{0}\times\mathcal{V}_{0}\longrightarrow\mathcal{V}_{0}$. I can not prove this fact.
My attempt, up to now, has been the following. I have found that, on arrows $(f\colon I\rightarrow [A,A'],\ g\colon I\rightarrow [B,B'])$, $S(f,g)$ corresponds, under $\pi$, to $(e\otimes e)\circ m\circ (((f\otimes g)\circ l^{-1})\otimes 1)$. Under the identification between the underlying category of the $\mathcal{V-}$ category $\mathcal{V}$ and the ordinary category $\mathcal{V}_{0}$, $S(f,g)$ should then be $(e\otimes e)\circ m\circ (((f\otimes g)\circ l^{-1})\otimes 1)\circ l^{-1}$. Theoretically speaking, it seems to me that I should then prove this last arrow to be the same as $\otimes (f,g)$, which, under the above identification, should be $(\pi^{-1}(f)\circ l^{-1})\otimes (\pi^{-1}(g)\circ l^{-1})$, but I can not do this.
Any suggestion, as well as complete solutions to the problem, would be greatly appreciated.
Comment: @Turion I admit length might be a problem, but I have tried to mark distinctly the part where the question comes, so that the more expert reader can immediately jump to conclusions. Moreover, it seemed to me that here in MSE there is a sort of implicit rule forcing posters to write down as self-contained questions as possible, especially because, when this is not done, clarifications are usually required by other users.
Comment: The question is clear and well written. Don't shorten it.
Comment: I wonder how many people have actually read this question completely. Can you shorten it somehow? (If necessary, restrict the audience to more experienced people by shortening)
Comment: @MartinBrandenburg Thanks, that was my hope when I wrote down all those lines. Still, the absence of answers made me think a little bit about what Turion asked...
Comment: I made some corrections, in particular, I changed the $×$ into a $\otimes$ at one point, I think this is what you meant. And don't worry about the length. I'm thinking about this question now and maybe I'll write an answer.
Answer: So you have arrows $f:I\to[A,A']$ and $g:I\to[B,B']$. The functor we are interested in and which you called $S$ is the composite
$$
\mathcal V_0\times\mathcal V_0\to (\mathcal{V\otimes V})_0\to \mathcal V_0 \\
\mathcal V_0(I,[A,A'])×\mathcal V_0(I.[B,B'])\to
 \mathcal V_0(I,[A,A']⊗[B,B'])\to \mathcal V_0(I,[A⊗B,A'⊗B']) \\
(f,g)\mapsto (f⊗g)l^{-1}\mapsto \text{Ten}(f⊗g)l^{-1}
$$
We want to show that, under the bijection $\pi$, this arrow corresponds to $f^\sharp l^{-1}⊗g^\sharp l^{-1}:A⊗B\to A'⊗ B'$. But $(\text{Ten}(f⊗g)l^{-1})^\sharp l^{-1}$ is, as you correctly computed, equal to
$$(ε⊗ε)\ m\ (((f⊗g)l^{-1})⊗(1_A⊗1_B))\ l^{-1}$$
which is
$$\begin{align}
& (ε⊗ε)\ m\ ((f⊗g)⊗(1_A⊗1_B))\ (l^{-1}⊗1_{A⊗B})\ l^{-1} \\
& =\  (ε⊗ε)\ ((f⊗1_A)⊗(g⊗1_B))\ (l^{-1}⊗l^{-1}) \\
& =\  ε(f⊗1)l^{-1}⊗ε(g⊗1)l^{-1} \\
& =\  f^\sharp l^{-1}⊗g^\sharp l^{-1}
\end{align}$$


Merging two irregular zoo time-series is messing up the structure

Question: I am working with trade dataset with thousands of rows. Every record has a unique key based on a symbol and date. Trade records for a given symbol are irregular, hence using zoo will be natural choice. I need to use lag and merge to create a new dataset. However, I don't know how to setup multi-column index in zoo in order to use lag function. Below is a sample dataset and intended output.
df = data.frame(
    dt = as.Date(c("2015-01-01", "2015-01-05", "2015-01-06",
                   "2015-01-01", "2015-01-02")),
    id = c("i1", "i1", "i1", "i2", "i2"),
    v1 = c(110, 115, 119, 212, 213),
    v2 = c(100, 170, 180, 202, 210),
    v3 = c(11, 13, 16, 22, 24)
)
df$id = as.character(df$id)

And the output should be
2015-01-01, i1, 110, 100, 11, 2015-01-05, i1, 115, 170, 13
2015-01-05, i1, 115, 170, 13, 2015-01-06, i1, 119, 180, 16
2015-01-06, i1, 119, 180, 16, NA, NA, NA, NA, NA
2015-01-01, i2, 212, 202, 22, 2015-01-02, i2, 213, 210, 24
2015-01-02, i2, 213, 210, 24, NA, NA, NA, NA, NA

Point to note that I need to merge complete rows regardless of number of columns. Following is one possible way to solve the "grouped" lag operation based on zoo which will merge complete rows.
doProcessing = function(df){
  icolnames = colnames(df)
  tt = zoo(df, df$dt)
  tt1 = merge(tt, lag(tt, 1))
  colnames(tt1) = c(icolnames, paste0("lag_", icolnames))
  data.frame(tt1, stringsAsFactors=F)
}
fin_df = do.call(rbind, with(df, by(df, list(id), doProcessing, simplify=F)))

This final output frame has every field as factor, which is different than the original data frame.
> str(df)
'data.frame':   5 obs. of  5 variables:
 $ dt: Date, format: "2015-01-05" "2015-01-01" ...
 $ id: chr  "i1" "i1" "i1" "i2" ...
 $ v1: num  115 110 119 212 213
 $ v2: num  170 100 180 202 210
 $ v3: num  13 11 16 22 24

resultant data frame looks like
> str(fin_df)
'data.frame':   5 obs. of  10 variables:
 $ dt    : Factor w/ 4 levels "2015-01-01","2015-01-05",..: 1 2 3 1 4
 $ id    : Factor w/ 2 levels "i1","i2": 1 1 1 2 2
 $ v1    : Factor w/ 5 levels "110","115","119",..: 1 2 3 4 5
 $ v2    : Factor w/ 5 levels "100","170","180",..: 1 2 3 4 5
 $ v3    : Factor w/ 5 levels "11","13","16",..: 1 2 3 4 5
 $ lag_dt: Factor w/ 3 levels "2015-01-05","2015-01-06",..: 1 2 NA 3 NA
 $ lag_id: Factor w/ 2 levels "i1","i2": 1 1 NA 2 NA
 $ lag_v1: Factor w/ 3 levels "115","119","213": 1 2 NA 3 NA
 $ lag_v2: Factor w/ 3 levels "170","180","210": 1 2 NA 3 NA
 $ lag_v3: Factor w/ 3 levels "13","16","24": 1 2 NA 3 NA

What am I doing wrong and How do I get the correct structure as per original data frame?
I asked this question as per this link multipart index in zoo timeseries
However I messed up that thread badly, hence didn't receive any response. Need to fix this in a correct way as manual fixing is not elegant and not the "R" way of doing things.
Answer: You have an overlap in indexes for the groups. To avoid a lot of missings, a solution is to use a list containing every id as it's own time-series (zoo objects):
>  myTsList <- tapply(1:nrow(df), df$id, function(x) { zoo::zoo(df[x, ], df$dt[x]) } )
>  myTsList
$i1
           dt         id v1  v2  v3
2015-01-01 2015-01-01 i1 110 100 11
2015-01-05 2015-01-05 i1 115 170 13
2015-01-06 2015-01-06 i1 119 180 16

$i2
           dt         id v1  v2  v3
2015-01-01 2015-01-01 i2 212 202 22
2015-01-02 2015-01-02 i2 213 210 24

Then you can easily do the grouped lag as you are talking about:
>  res <- lapply(myTsList, function(x) merge(x, lag(x), suffixes=c("","lag")) )
>  res
$i1
           dt.        id. v1. v2. v3. dt.lag     id.lag v1.lag v2.lag v3.lag
2015-01-01 2015-01-01 i1  110 100 11  2015-01-05 i1     115    170    13
2015-01-05 2015-01-05 i1  115 170 13  2015-01-06 i1     119    180    16
2015-01-06 2015-01-06 i1  119 180 16  <NA>       <NA>   <NA>   <NA>   <NA>

$i2
           dt.        id. v1. v2. v3. dt.lag     id.lag v1.lag v2.lag v3.lag
2015-01-01 2015-01-01 i2  212 202 22  2015-01-02 i2     213    210    24
2015-01-02 2015-01-02 i2  213 210 24  <NA>       <NA>   <NA>   <NA>   <NA>

of course you can then bind the groups if you want to have a data.frame structure, but we need to convert them first because of the overlap in indexes:
> Reduce(rbind, lapply(res, as.data.frame))
                   dt. id. v1. v2. v3.     dt.lag id.lag v1.lag v2.lag v3.lag
2015-01-01  2015-01-01  i1 110 100  11 2015-01-05     i1    115    170     13
2015-01-05  2015-01-05  i1 115 170  13 2015-01-06     i1    119    180     16
2015-01-06  2015-01-06  i1 119 180  16       <NA>   <NA>   <NA>   <NA>   <NA>
2015-01-011 2015-01-01  i2 212 202  22 2015-01-02     i2    213    210     24
2015-01-02  2015-01-02  i2 213 210  24       <NA>   <NA>   <NA>   <NA>   <NA>

EDIT: If you don't need the time-series at all, but only the final output as a data.frame, then inspired by my suggestion you could do something along:
df$ind <- 1:nrow(df)
myTsList <- tapply(1:nrow(df), df$id, function(x) zoo::zoo(df[x, "ind"], df$dt[x])  )
res <- lapply(myTsList, function(x) merge(x, lag(x)) )
newDf<- Reduce(rbind, lapply(res, as.data.frame))
df$ind <- NULL
as.data.frame(cbind(df[newDf[,1],],df[newDf[,2],]))

          dt id  v1  v2 v3         dt   id  v1  v2 v3
1 2015-01-01 i1 110 100 11 2015-01-05   i1 115 170 13
2 2015-01-05 i1 115 170 13 2015-01-06   i1 119 180 16
3 2015-01-06 i1 119 180 16       <NA> <NA>  NA  NA NA
4 2015-01-01 i2 212 202 22 2015-01-02   i2 213 210 24
5 2015-01-02 i2 213 210 24       <NA> <NA>  NA  NA NA

this will also keep the correct classes etc. from the original data.frame.
EDIT* A simpler dplyr solution:
library(dplyr)
merge(
    df,
    df %>% group_by(id) %>% mutate(lag=lag(dt)),
    by.x=c("id","dt"), by.y=c("id","lag"), all.x=TRUE
)

  id         dt v1.x v2.x v3.x         dt v1.y v2.y v3.y
1 i1 2015-01-01  110  100   11 2015-01-05  115  170   13
2 i1 2015-01-05  115  170   13 2015-01-06  119  180   16
3 i1 2015-01-06  119  180   16       <NA>   NA   NA   NA
4 i2 2015-01-01  212  202   22 2015-01-02  213  210   24
5 i2 2015-01-02  213  210   24       <NA>   NA   NA   NA

Comment: output dataframe has all the columns as Factors. How do I get that fixed?
Comment: @JR sorry for delayed acceptance. Lovely (cryptic!!!) code. Does the job beautifully. Thanks
Comment: Think I misunderstood the purpose at first, added a less cryptic approach.
Comment: Please add more text explanation in the answer.


No arbitrage for one period Binomial model option pricing - understanding the return function

Question: I am looking at lecture notes in mathematical finance. The prince $C$ of a European call option with strike $K$ and expiry time $T$ in a one period binomial model is derived via no arbitrage principle. The underlying asset price is $S$ at time $0$ and either $Su$ or $Sd$ at time $1$ and interest rate is $r$. Lecture notes says that the return function $r_{i}(j)$ at present time (time $0$ I assume) is the following:
$$r(1) = \left( \frac{Su - K}{1+r} - C\right)$$
(if asset price moves up), or
$$r(2) = \left( \frac{Sd - K}{1+r} - C\right)$$
if the asset moved down. Then the no arbitrage principle gives equation $p_{1}r(1) + p_{2}r(2) = 0$ from which $C$ is found, where $p_{1,2}$ are risk neutral probabilities.
I don't get how the return function is derived. My understanding would be that, one gets a loan of $(C+K)$ money to purchase the option with price $C$ and also have the ability to pay strike price $K$. But then the accrued interest at time $1$ on the loan is $(1+r)(C+K)$ which we need to pay back; so this equivalently should give the present value return as
$$\tilde{r}(1) =  \left( \frac{Su - K}{1+r} - C - K\right),  \qquad \tilde{r}(2) = \left( \frac{Sd - K}{1+r} - C - K\right) $$
So what's going on?
Answer: You only need a loan of $C$. The $K$ part you obtain by exercising the option. Hence why the value of the option at time $t=1$ is either $Su-K$ or $Sd-K$. Actually, it should be $(Su-K)_{+}$ or $(Sd-K)_{+}$, because in case the underlying is worth less than the strike, you simply will not exercise the option.
Even if you take into account you want to make a loan beforehand to buy the underlying later, you make a loan of $K/(1+r)$ for that and hence that is precisely what is accounted for in the formula already. Which makes your reasoning double count the loan.
At time $t=0$, you make a loan to buy the option, your account looks like this:
$$\begin{array} {r|r} \text{Active} & \text{Passive} \\ \hline \text{Option } & \text{Loan } C + K/(1+r)\\
\text{Current account } K/(1+r) &    \end{array}$$
At time $t=1-\epsilon$, just before exercising your option:
$$\begin{array} {r|r} \text{Active} & \text{Passive} \\ \hline \text{Option} & \text{Loan } C(1+r) + K\\
\text{Current account } K &    \end{array}$$
At time $t=1$ you exercise the option, i.e. buy the underlying for K and sell it for $X$:
$$\begin{array} {r|r} \text{Active} & \text{Passive} \\ \hline  & \text{Loan } C(1+r) + K\\
\text{Current account } X &    \end{array}$$
At time $t=1+\epsilon$ you settle the loan, i.e. using $X$ to pay for it:
$$\begin{array} {r|r} \text{Active} & \text{Passive} \\ \hline  & \text{Loan } C(1+r) + K - X = 0\\
\text{Current account } 0 &    \end{array}$$
So, if you want to settle everything $X-C(1+r)-K=0$.


If $f(x)f(y)+f(xy)\le -\frac{1}{4},\forall x,y\in[0,1)$, show that $f(x)=-\frac{1}{2}$

Question: Let $f:[0,1) \to \mathbb{R}$ be a function such that
$$f(x)f(y)+f(xy)\le -\dfrac{1}{4} \quad \forall\, x,y\in[0,1).$$
Show that
$$f(x)=-\dfrac{1}{2} \quad \forall\, x \in[0,1).$$
I have proved that $f(0)=-\dfrac{1}{2}$: if $x=y=0$, we have
$$f^2(0)+f(0)\le-\dfrac{1}{4}\Longrightarrow \left( f(0)+\frac{1}{2} \right)^2\le 0\Longrightarrow f(0)=-\dfrac{1}{2}.$$
But I can't prove $f(x)$ be constant. Thanks.
Comment: Where is your question from?
Answer: Plugging in $y=0$ gives $f(x) \ge -\frac{1}{2}$ for each $x$.
Let $y=x$ to get $f(x)^2+f(x^2) \le -\frac{1}{4}$. This implies $f(x^2) \le -\frac{1}{4}$ for each $x$, and so $f(x) \le -\frac{1}{4}$ for each $x$. But then $f(x)^2+f(x^2) \le -\frac{1}{4}$ implies $f(x^2) \le -\frac{1}{4}-(\frac{1}{4})^2 = -\frac{5}{16}$, and so $f(x) \le -\frac{5}{16}$ for each $x$. Doing this again gives $f(x) \le -\frac{1}{4}-(\frac{5}{16})^2 = -\frac{89}{256}$ for each $x$. If we keep doing this, we see that, for any $\epsilon > 0$, $f(x) \le -(\frac{1}{2}-\epsilon)$ for each $x$. Therefore, $f(x) \le -\frac{1}{2}$ for each $x$.
Comment: @inequality you started by saying $f$ is defined on $[0,1)$.
Comment: Hello,if $f(x^2)\le -\dfrac{1}{4}$ for each $x$,so I think you only $f(x)\le -\dfrac{1}{4}$ for $x\ge 0$


In how many ways can a king( as in chess ) move from one square to another diagonal square at the end of six moves?

Question: I was able to solve a variant of this in which the king could not move diagonally, but I feel that the method I used for that is not the most efficient one. So, how do I approach this prob?
Comment: Can you define a 'diagonal square' because I don't think it is very clear from the question.
Comment: One square right and one square up
Comment: So you want to count the number of ways a king can spend six moves to get to a specific neighboring diagonal square?
Comment: Yes............
Comment: And the edge of the board is irrelevant, right?
Comment: Yes............
Answer: Brute force is one way:
Let's write, on the chessboard, how many ways there are for a king to get to each square within a specific number of moves. For $0$ moves, we get
$$
\begin{array}{|c|c|c|}
\hline 0&0&0\\
\hline 0&\color{red}1&0\\
\hline 0&0&0\\
\hline
\end{array}
$$
because there is only one square the king can get to, and that's the square he starts at. Now, the way we are going to go from one step to the next is that we are going to pass a "filter" over all these cells. We will draw a new board, and for each cell in this new board, we will look at the corresponding cell in the previous board and add together all the numbers in its $8$ neighboring cells. So, for 1 move we get
$$
\begin{array}{|c|c|c|c|c|}
\hline 0&0&0&0&0\\
\hline 0&1&1&1&0\\
\hline 0&1&\color{red}0&1&0\\
\hline 0&1&1&1&0\\
\hline 0&0&0&0&0\\
\hline
\end{array}
$$
Then for 2 moves we get
$$
\begin{array}{|c|c|c|c|c|c|c|}
\hline 0&0&0&0&0&0&0\\
\hline 0&1&2&3&2&1&0\\
\hline 0&2&2&4&2&2&0\\
\hline 0&3&4&\color{red}8&4&3&0\\
\hline 0&2&2&4&2&2&0\\
\hline 0&1&2&3&2&1&0\\
\hline 0&0&0&0&0&0&0\\
\hline
\end{array}
$$
And finally, for $3$ moves, we get
$$
\begin{array}{|c|c|c|c|c|c|c|}
\hline 1&3&6&7&6&3&1\\
\hline 3&6&12&12&12&6&3\\
\hline 6&12&27&27&27&12&6\\
\hline 7&12&27&\color{red}{24}&27&12&7\\
\hline 6&12&27&27&27&12&6\\
\hline 3&6&12&12&12&6&3\\
\hline 1&3&6&7&6&3&1\\
\hline
\end{array}
$$
I said "finally" because we could keeep going, but it is at this point that I would like to stop. Because we have now spent 3 moves, and must use the remaining 3 moves to get to the goal square. And if we want to count up the number of ways to get from each square to the goal square using $3$ moves, we get the exact same pattern of numbers, only moved one square up and one to the right.
So what we have here is a simple way to calculate the number of ways to spend $3$ moves to get to any specific cell, and then spend $3$ moves to get to our goal square diagonally above our starting square: We take the number in any of the squares above, which represents the number of ways to get there, then multiply with the square diagonally below it, which represents the number of ways to get to the goal square.
Doing this for our entire grid gives us
$$
\begin{array}{|c|c|c|c|c|c|c|}
\hline 1\cdot 0&3\cdot 3&6\cdot 6&7\cdot 12&6\cdot 12&3\cdot 12&1\cdot 6\\
\hline 3\cdot 0&6\cdot 6&12\cdot 12&12\cdot 27&12\cdot 27&6\cdot 27&3\cdot 12\\
\hline 6\cdot 0&12\cdot 7&27\cdot 12&27\cdot 27&27\cdot 24&12\cdot 27&6\cdot 12\\
\hline 7\cdot 0&12\cdot 6&27\cdot 12&\color{red}{24}\cdot 27&27\cdot 27&12\cdot 27&7\cdot 12\\
\hline 6\cdot 0&12\cdot 3&27\cdot 6&27\cdot 12&27\cdot 12&12\cdot 12&6\cdot 6\\
\hline 3\cdot 0&6\cdot 1&12\cdot 3&12\cdot 6&12\cdot 7&6\cdot 6&3\cdot 3\\
\hline 1\cdot 0&3\cdot 0&6\cdot 0&7\cdot 0&6\cdot 0&3\cdot 0&1\cdot 0\\
\hline
\end{array}\\
= \begin{array}{|c|c|c|c|c|c|c|}
\hline 0&9&36&84&72&36&6\\
\hline 0&36&144&314&314&157&36\\
\hline 0&84&314&729&648&314&72\\
\hline 0&72&314&\color{red}{648}&729&314&84\\
\hline 0&36&157&314&314&144&36\\
\hline 0&6&36&72&84&36&9\\
\hline 0&0&0&0&0&0&0\\
\hline
\end{array}
$$
Now we "just" add up all these numbers, and we get our answer. If I haven't made any mistakes, the result is $6180$.
Comment: I think you've made some mistakes in arithmetic.  Your final array should be $$\begin{matrix} 9 &36 &84 &72 &36 &6 \\
36 &144 &324 &324 &162 &36\\
84 &324 &729 &648 &324 &72\\
72 &324 &648 &729 &324 &84\\
36 &162 &324 &324 &144 &36\\
6 &36 &72 &84 &36 &9 \end{matrix}$$ if I understand you correctly, total $6900$.
Answer: Let's say the king starts at $(0,0)$ and ends at $(1,1)$.  If at the $i$th move he moves a signed distance $x_i$ in the $X$ direction and $y_i$ in the $Y$ direction, then we want the number of solutions in integers to
$$x_1+x_2+x_3+x_4+x_5+x_6 = 1 \tag{1}\\
y_1+y_2+y_3+y_4+y_5+y_6 = 1 $$
subject to $-1 \le x_i, y_i \le 1$ and excluding any cases where $x_i=y_i=0$ for some $i$.  (The king must actually move and not remain stationary at any step.)  We will find the number of acceptable solutions via the Principle of Inclusion / Exclusion (PIE).
But first, let's consider the related problem of finding the number of solutions in integers of
$$x_1+x_2+x_3+ \dots +x_n = 1 \tag{2}$$
subject to $-1 \le x_i \le 1$ for $1 \le i \le n$.  We might think of this as finding the number of strings of $n$ symbols, where each symbol is a plus, a minus, or zero, and in which there is one more plus than the number of minuses.  If there are $i$ pluses, then there must be $i-1$ minuses and $n-2i+1$ zeroes, so the number of such strings is the multinomial coefficient
$$\binom{n}{i, i-1, n-2i+1} = \frac{n!}{i! (i-1)! (n-2i+1)!}$$
Then the total number of solutions of $(2)$ is
$$a_n = \sum_{i=1}^{\lfloor (n+1)/2 \rfloor} \binom{n}{i, i-1, n-2i+1}$$
Now back to the problem of determining the number of paths from $(0,0)$ to $(1,1)$.  If we were to disregard the requirement that we can never have $x_i=y_i=0$, the number of paths would be $N = a_6^2$. To find the acceptable number of paths, let's say a solution of $(1)$ has "property $i$" if $x_i=y_i=0$ for $1 \le i \le 6$, and let $S_j$ be the number of solutions with $j$ of the properties, for $1 \le j \le 5$.  If we have $x_i=y_i=0$ for $j$ choices of $i$, then the remaining $(6-j)$ $x_i$'s must still sum to $1$, as must the remaining $(6-j)$ $y_i$'s.  Since there are $\binom{6}{j}$ ways to select the set of "bad" indicies,
$$S_j = \binom{6}{j} a_{6-j}^2$$
By PIE, the number of solutions of $(1)$ with none of the properties, i.e. the number of solutions in which there is no $i$ with $x_i=y_i=0$, is
$$N + \sum_{j=1}^5 (-1)^j S_j = a_6^2 + \sum_{j=1}^5 (-1)^j \binom{6}{j} a_{6-j}^2 = \boxed{6900}$$


what is there equivalent to rollback transaction of SQL in c#?

Question: if in a transaction any error occurs
sql will rollback the process.
BEGIN TRANSACTION

 COMMIT

 IF @@TRANCOUNT > 0
        ROLLBACK

END TRANSACTION

How i can do the same in asp.net C#?
Comment: By the way, the code yo posted looks like it will always commit the transaction, because COMMIT is called before the if check.
Comment: What do you want to rollback?
Comment: Take a look at the [TransactionScope Class](http://msdn.microsoft.com/en-us/library/system.transactions.transactionscope%28v=vs.110%29.aspx)
Comment: @Tim It starts with "BEGIN TRANSACTION", so it commits the nested transaction, then possibly rolls back the outer transaction. (This is horribly confusing, so don't do it.)
Comment: @hvd - Ah, thanks.  I forgot about nested transactions.
Answer: Check below to see how to implement Implicit Transaction using Transaction Scope which will give you transaction in C#. If you call the Complete method for the TransactionScope it will be commited otherwise rolledback.
http://msdn.microsoft.com/en-us/library/ee818746(v=vs.110).aspx
Answer: The following snippet shows the general idea:
using (SqlConnection connection = new SqlConnection("connection string"))
using (SqlTransaction transaction = connection.BeginTransaction())
using (SqlCommand command = new SqlCommand("command text", connection) { Transaction = transaction })
{
    connection.Open();
    try
    {
        command.ExecuteNonQuery();
        transaction.Commit();
    }
    catch
    {
        transaction.Rollback();
        throw;
    }
}

If the command fails to execute and throws any exception, the transaction will be rolled back.
Answer: I don't really find your question clear enough. Here is something I would like to share. I assume you are asking this.
In SQL, imagine something like this (not really syntax):
begin transaction
insert into table X y= 1, z =2
insert into table A b =1, c =2
commit

Now, imagine there is no column b in table A so this transaction would not work.
To do same in ASP.Net where you have close to no control over actual DB transactions, combination of try/catch and transaction is what I will suggest. Not because it is the right way but just because it can do what you want.
Again, this is not the right way. Tell more about your problem and more people can help.


If $a+b=1$ then $a^{4b^2}+b^{4a^2}\leq1$

Question: Let $a$ and $b$ be positive numbers such that $a+b=1$. Prove that:
$$a^{4b^2}+b^{4a^2}\leq1$$
I think this inequality is very interesting because the equality "occurs" for $a=b=\frac{1}{2}$ and also for $a\rightarrow0$ and $b\rightarrow1$.
I tried to work with a function of one variable, but the derivative is not easy.
I also don't get something solvable by Taylor series.
Comment: A typical start should be $\,a=\sin^2{\theta}\,$: $$ \left(\sin{\theta}\right)^{8\cos^4{\theta}}+\left(\cos{\theta}\right)^{8\sin^4{\theta}}\le1\quad\colon\,\theta\in\left[0,\frac{\pi}{2}\right] $$
Comment: Intriguing inequality, where does it come from ?
Comment: To clarify what I meant in that last comment: We can sandwich the line $x+y=1$ in our interval between the curves $x^2+y^2 = 1$ and $x^2+y^2=\frac{1}{2}$, both of which satisfy the inequality. With a bit of work we might be able to massage a proof out of this.
Comment: @MichaelRozenberg I have a proof wich is long but interesting if you want I can post it next week end.
Comment: Sorry, I made a silly mistake. I should delete it.
Comment: Looking at this yields the arguably tighter problem of $x^2+y^2 = 1 \implies x^{4y^2} + y^{4x^2} \le 1$ when $x,y >0$
Comment: Using this method, all we have to solve is $$u+v = 1 \implies u^{2v}+v^{2u}\le1 \tag{1}$$ and an extremely similar second problem, then show that $x+y=1$ is strictly sandwiched between the two. I can post a solution using this method when I have time unless someone spots a blatant error with it. In the mean time, if anyone has a clever idea for solving $(1)$ please share... I'm thinking about just brute forcing it, which would be simpler to do than the original problems but still not very fun.
Comment: One method might be to parametrize the same way we would with $x^y+y^x$ and seek an answer in terms of the $W$ function. Inequalities/Derivatives would then be easier.... I think?
Comment: I find that with a=2 and b=-1, the condition is violated.  Perhaps you need to specify that a and b are in the interval [0, 1].
Comment: One could also define $f(x,y) = x^{4y^2} + y^{4x^2}$ and find its critical point with the constraint $x+y=1$ and prove that it's a maximum and it is equal to $1$.
Comment: The answer to my $(1)$ above can be found on MathOverflow [here](http://mathoverflow.net/q/17189/83537), which explains that $(1)$ is non-trivial. Using that link as a reference proof I can probably show this inequality holds later today. I might also try a proof using Lagrange Multipliers, since that seems to be sorely lacking
Comment: @MichaelRozenberg May I ask where did you get it? Interesting place it must be where you can find such problems!:)
Comment: @MichaelRozenberg I have finished. Please now attack my post as viciously and rigorously as possible until any potential issues are ironed out.
Comment: You mention [here](https://math.stackexchange.com/questions/2176571/if-ab-1-so-a4b2b4a2-leq1#comment6430362_3120958) that you have a proof  now– why don't you post it as an answer?
Comment: @MathArt  $a^{4b^2}\leq a$ is wrong.
Answer: We define $f(x,y)=x^{4y^2}+y^{4x^2}$.
This is my plan to solve the problem:

Since $x+y=1$, we replace $y$ by $1-x$.
We make a new function: $g(x)=x^{4(1-x)^2}+(1-x)^{4x^2}$
Therefore, we must find the maximum on the range $x \in [0,1]$ of $g$ so that we can see the maximum is less than or equal to $1$.

This will be troublesome:
$$g(x)=x^{4(1-x)^2}+(1-x)^{4x^2}$$
Set $g_{1}(x) = x^{4(1-x)^2}$ and $g_{2}(x) = (1-x)^{4x^2}$. Therefore, we can break it up like so:
$$g'(x) = g_{1}'(x)+g_{2}'(x)$$
$$g_{1}'(x)=g_{1}', g_{2}'(x)=g_{2}'$$
$$\ln(g_{1})=\ln \left(x^{4(1-x)^2}\right)$$
$$\ln(g_{1})={4(1-x)^2} \cdot \ln \left(x\right)$$
$$\frac{g_{1}'}{g_{1}}= 4 \cdot \left((1-x)^2 \right)' \cdot \ln(x)+\frac{4(1-x)^2}{x}$$
$$\frac{g_{1}'}{g_{1}}= 4 \cdot -2 \cdot (1-x) \cdot \ln(x)+\frac{4(1-x)^2}{x}$$
$$\frac{g_{1}'}{g_{1}}= 8(x-1)\ln(x)+\frac{4x^2-8x+4}{x}$$
$$\frac{g_{1}'}{g_{1}}= 8(x-1)\ln(x)+4x-8+\frac{4}{x}$$
$$g_{1}'= x^{4(1-x)^2} \cdot \left(8(x-1)\ln(x)+4x-8+\frac{4}{x}\right)$$
Alright. Deep breath. Let's keep going.
$$\ln(g_{2})=4x^2\ln(1-x)$$
$$\frac{g_{2}'}{g_{2}}=8x\ln(x-1)+\frac{4x^2}{x-1}$$
$$g_{2}'= (1-x)^{4x^2}\left(8x\ln(x-1)+\frac{4x^2}{x-1}\right)$$
$$g_{1}'= x^{4(1-x)^2} \cdot \left(8(x-1)\ln(x)+4x-8+\frac{4}{x}\right)$$
$$g'(x)=x^{4(1-x)^2} \cdot \left(8(x-1)\ln(x)+4x-8+\frac{4}{x}\right) + (1-x)^{4x^2}\left(8x\ln(1-x)+\frac{4x^2}{x-1}\right)$$
The maximum appears (according to the closed interval method), either at:
$$g(0)=1$$
$$g(1)=1$$
Or at the $x$-value(s) of the solution of:
$$0=x^{4(1-x)^2} \cdot \left(8(x-1)\ln(x)+4x-8+\frac{4}{x}\right) + (1-x)^{4x^2}\left(8x\ln(1-x)+\frac{4x^2}{x-1}\right)$$
Therefore, if we set $x_{1}$, $x_{2}$, $x_{3}$ ... to be the solutions to the equation above in the interval $x_{n} \in [0,1]$, we have reduced the problem to proving that:
$$g(x_{1}),g(x_{2}), g(x_{3})... \leq 1$$
Through some graphing of $g(x)$, we see that there exists $x_{1}$, $x_{2}$, and $x_{3}$, where $x_{2}$ is $0.5$ and the others are not easily calculatable or are irrational.
It can easily be seen that $g'(0.5) = 0$ and that $g(0.5)=1$ (a maximum of the function). Since we now have proof that $g(x_{2}) \leq 1$ and we see that there does not exist an $x_{n}$ s.t. $n>3$ and $g'(x_{n})=0$, we can reduce our previous problem to:
Prove that:
$$g(x_{1}), g(x_{3}) \leq 1$$
Through Newton's Method, we obtain approximations of $x_{1}$ and $x_{3}$ accurate to 10 decimal places. We state them below:
$$x_{1} \approx 0.281731964017$$
$$x_{3} \approx 0.718268035983$$
Note that:
$$g'(x_{1}) \approx g'(0.281731964017)=7.349676423 \cdot 10^{-14}$$
$$g(x_{1}) \approx g(0.281731964017)=0.973494223187$$
We now have that $g(x_{1})$ is a minimum of the function and that $g(x_{1}) \leq 1$
Finally:
$$g'(x_{3}) \approx g'(0.718268035983)=-7.349676423 \cdot 10^{-14}$$
$$g(x_{3}) \approx g(0.718268035983)=0.973494223187$$
We now have that $g(x_{1})$ is also a minimum of the function and that $g(x_{1}) \leq 1$
We now have that:
$$g(x_{1}), g(x_{2}), g(x_{3}) \leq 1$$
Q.E.D
I took a very head-on brute-force approach to the problem, but I am happy with the rigorousness of the result and the final proof. We also now have the minimums of the function, which if anyone is curious, is $\approx 0.973494223187$
Comment: hmm. Basically brute forcing the problem. Works well enough, but based on the beautiful visual in @masnuhuey's answer I feel like we should be able to do this so much more simply. If only we could rotate our main function 45 degrees counter-clockwise... our line $x+y=1$ becomes $y =\frac{1}{\sqrt{2}}$ but I'm not sure how to parametrize our inequality.
Comment: You get the same root equation using a Lagrange multiplier, although the algebra is a bit simpler. I don't see an obvious analytical solution for the root.
Comment: @Robin Aldabanx Thank you for your trying, but for me it's not proof. I am sorry. I am looking for an human proof, which we can use during the competition. My congratulations for $+200$.
Comment: @Robin Aldabanx You claim "we see that there does not exist an $x_n$ s.t. $n>3$ and $g'(x_n)=0$". Isn't that just like saying "we plotted g and see that $g \leq 1$"? I don't think that this is a valid proof.
Comment: And wow Brevan Ellefsen's comment that is way easier to prove.
Comment: Btw, you mentioned my comment without tagging me with the @ symbol so I just noticed it by chance. I don't immediately see how to solve the problem $x^2+y^2=1$, but it felt like a cleaner start because we could bound with a cleaner curve. Note that if we solve the problem for $x^2+y^2=\frac{1}{2}$ as well we can probably pull out a cleaner proof, as $x+y=1$ is sandwiched between the two
Comment: what is the "closed interval method"?
Comment: (One of) the interior maximum is at the middle of the interval, with the value 1
Comment: @EwanDelanoy it states that for a one-variable function $f(x)$ defined, continuous, and differentiable on a closed interval $[a, b]$, the maximum and minimum of $f(x)$ either appear at $a$, $b$, or when $f'(x)=0$
Comment: @BradyGilg That's why I used Newton's method. Yes, that is true, although I don't feel perfectly comfortable using Lagrange multipliers yet. I will admit that the constraint $x+y=1$ makes it perfect for that Lagrange multipliers technique. I probably could've simplified this tremendously using that technique.
Comment: Thank you, I will fix it right away.
Comment: It has been fixed, thank you.
Comment: @MichaelRozenberg I have actually pretty much already written up a human proof. I couldn't get it in time for the bounty (not that I care too much about rep anyway, as long as the math gets done!). I'll try to post it soon. I rely on the existing result $a+b=1 \implies a^{2b}+b^{2a} \le 1$, which is relatively well known in the literature. I don't think any trivial solutions are known, though a Taylor Series approach gives the answer fairly quickly. I wouldn't expect your answer to have a trivial solution if this 'simpler problem' doesn't have one.
Comment: @MichaelRozenberg I will probably try to write it up tomorrow (this has simply been a busy week for me... no time for MSE). Before I do so, is there anything I should know about the limits you are imposing about "doing this by hand"?? Also, am I allowed to reference existing proofs about $a+b=1 \implies a^{2b}+b^{2a}\le1$ to conclude the result?
Comment: @Brevan Ellefsen I think I have a proof of your inequality.
Comment: @MichaelRozenberg Thanks! I'm glad you liked my attempt, and wish I could've come up with a more analytical and rigorous solution, especially something that doesn't require a calculator.
Comment: @BrevanEllefsen You said $a+b=1 \implies a^{2b}+b^{2a} \le 1$ is pretty known in the literature; just curious, is there some inequality literature? Or in the Analysis literature (as far as I know, Analysis is the field which deals most with inequalities, but please correct me if I'm wrong).
Comment: @Ovi hmmm. Interesting question. Honestly, I have no idea where I first saw the result, it just comes up often enough I considered it a more common inequality. While I could point you towards some beginning references, inequalities are not my field of study (I focus more on where complex analysis and operator theory meet). Honestly, I'd ask the the OP Michael Rosenberg. He's probably asked and answered more inequality questions on this site than anyone, and could point you in the right direction far better than I.
Comment: @Ovi your question does remind me that I never finished my answer here. My attempt had some serious flaws at the start, which were actually a result of one of my references having a faulty proof of a lemma I needed! I still think the method of attack I was trying was a lot cleaner than the more numeric approaches currently posted. Perhaps I'll have to revisit this post and give it more thought.
Answer: Let $f \colon [0,1] \rightarrow \mathbb{R}$ be the function given by $$f(x) = x^{4 (1-x)^2}.$$
We will show that if $x \in [0,\frac{1}{2}]$ then $f(x) + f(1-x) \leq 1$.
If $x=0$ then it is clear that $f(0)+f(1)=1$.
Claim 1. If $x \in (0, \frac{71}{200}]$ then $f(x) + f(1-x) \leq 1$.
Proof. Let $x \in (0, \frac{71}{200}]$. By Bernoulli's inequality we have
$$f(1-x) = (1-x)^{4x^2} \leq 1-4x^3.$$
Therefore
\begin{align}
&f(x) + f(1-x) \leq 1
\\ &\impliedby f(x) \leq 4x^3
\\ &\iff \log x^{4 (1-x)^2} \leq \log4x^3
\\ &\iff (3-4 (1-x)^2) \log x\ + \log 4 \geq 0.
\end{align}
The $\log x$ is a problem here. We use the following trick to factor our expression.
Since the global maximum of $z \mapsto - z \log z$ is $\mathrm{e}^{-1}$, we have $(-\mathrm{e}\, x \log x) \log 4 \leq \log 4.$ It follows that
\begin{align}
&(3-4 (1-x)^2) \log x\ + \log 4 \geq 0
\\ &\impliedby (3-4 (1-x)^2 -(\mathrm{e}\ \log 4)\, x) \log x\ \geq 0
\\ &\iff 3-4 (1-x)^2 -(\mathrm{e}\ \log 4)\, x \leq 0
\\ &\impliedby x \leq \frac{71}{200} < \frac{1}{4} \left(4-\mathrm{e} \log 2-\sqrt{12+\mathrm{e}^2 \log ^2 2-8 \mathrm{e} \log 2}\right).
\end{align}
We used the quadratic formula in the last step.
$$\tag*{$\Box$}$$
Claim 2. If $x \in (\frac{71}{200}, \frac{73}{200}]$ then $f(x) + f(1-x) < 1$.
Proof.
Let $z \in (0,1)$. Since $\log(z) \leq z-1$, we have
\begin{align}
f'(z) &= x^{4 (1-z)^2} \left(\frac{4 (1-z)^2}{z}-8 (1-z) \log z\right)
\\ &\geq x^{4 (1-z)^2} \left(\frac{4 (1-z)^2}{z}+8 (1-z)^2\right) \geq 0.
\end{align}
Thus $f$ is monotonically increasing on $(0,1)$. We have
$$f(x) + f(1-x) \leq  f\left(\frac{73}{200}\right) + f\left(1-\frac{71}{200}\right) \approx 0.9985 < 1$$
for all $x \in (\frac{71}{200}, \frac{73}{200}]$.
$$\tag*{$\Box$}$$
We need some lemmata for $(\frac{73}{200}, \frac{1}{2}]$.
Let $\varphi \colon (-\frac{1}{2},\frac{1}{2}) \rightarrow \mathbb{R}$ be the function given by $\varphi(z) = \log \left(\frac{1}{2}-z\right).$
Lemma 3.1. If $z \in (-\frac{1}{2},\frac{1}{2})$ then $\varphi(z) \leq -\log 2 -2 z-2 z^2-\frac{8}{3}z^3$.
Proof. Let $z \in (-\frac{1}{2},\frac{1}{2})$. Since $\log$ is real analytic, we have
\begin{align}
\varphi(z) &= \sum_{k=0}^{\infty} \frac{\varphi^{(k)}(0)}{k!}z^k
\\&=-\log 2 -2 z-2 z^2-\frac{8}{3}z^3 + \sum_{k=4}^{\infty} \frac{\varphi^{(k)}(0)}{k!}z^k.
\end{align}
By the Lagrange form of the remainder there is a $\zeta \in (-\frac{1}{2},\frac{1}{2})$ such that
$$\frac{\varphi^{(4)}(\zeta)}{4!}z^4 = \sum_{k=4}^{\infty} \frac{\varphi^{(k)}(0)}{k!}z^k.$$
We have
\begin{align}
\varphi(z) &= -\log 2 -2 z-2 z^2-\frac{8}{3}z^3 + \frac{\varphi^{(4)}(\zeta)}{4!}z^4
\\ &= -\log 2 -2 z-2 z^2-\frac{8}{3}z^3 -\frac{1}{4\left(\frac{1}{2}-\zeta\right)^4} z^4
\\ &\leq -\log 2 -2 z-2 z^2-\frac{8}{3}z^3.
\end{align}
$$\tag*{$\Box$}$$
Let $\gamma \colon (-\frac{1}{2},\frac{1}{2}) \rightarrow \mathbb{R}$ be the function given by $$\gamma(z) = 4 \left(z+\frac{1}{2}\right)^2 \left(-\log 2 -2 z-2 z^2-\frac{8}{3}z^3\right).$$
Lemma 3.2. If $z \in [-\frac{27}{200},\frac{27}{200}]$ then $$-\frac{1}{2}\left(\frac{\gamma(z)-\gamma(-z)}{2}\right)^2-\log 2\geq \frac{\gamma(z)+\gamma(-z)}{2}.$$
Proof.
The inequality is equivalent to
$$-128 z^8-448 z^6+z^4 (-440-96 \log 2)+z^2 (-42-168 \log2)+18-18 \log ^2 2 -9 \log 2 \geq  0.$$
We substitute $u = z^2$ and use the quartic formula to calculate the roots of the polynomial. The real roots are near $-0.136139$ and $0.136139$. We have $$-0.136 < -\frac{27}{200} < \frac{27}{200} < 0.136.$$
We calculate that the inequality holds at $z=0$, thus it must hold for all $z \in [-\frac{27}{200},\frac{27}{200}]$.
$$\tag*{$\Box$}$$
Let $\psi \colon \mathbb{R} \rightarrow \mathbb{R}$ be the function given by $$\psi(z) = \exp\left(-\frac{z^2}{2}\right)(\exp(z) + \exp(-z)).$$
Lemma 3.3. If $z \in \mathbb{R}$ then $\psi(z) \leq 2$.
Proof. For all $z \in [0, \infty)$ we have
\begin{align}
\exp\left(\frac{z^2}{2}+z\right)\psi'(z) &= -1 -z -(z-1)\exp(2 z)
\\ &= -1 -z -(z-1) \sum_{k=0}^{\infty}\frac{2^k z^k}{k!}
\\ &= -1 -z - (z-1) \sum_{k=0}^{\infty}\frac{2^k z^k}{k!}
\\ &= -1 -z + \sum_{k=0}^{\infty}\frac{2^k z^k}{k!} - \sum_{k=1}^{\infty}\frac{2^{k-1} z^{k}}{(k-1)!}
\\ &= -z + \sum_{k=1}^{\infty}2^{k-1}\left(\frac{2}{k!} - \frac{1}{(k-1)!}\right) z^k
\\ &= -z + \sum_{k=1}^{\infty}2^{k-1}\left(\frac{2 (k-1)!-k!}{(k-1)! k!}\right) z^k
\\ &= \sum_{k=3}^{\infty}2^{k-1}\left(\frac{2 (k-1)!-k!}{(k-1)! k!}\right) z^k.
\end{align}
Since $2 (k-1)! < k!$ for all $k > 2$, we have $\psi'(z) \leq 0$. Thus $\psi$ is monotonically decreasing on $[0,\infty)$. We have $\psi(0) = 2$, thus $\psi(z) \leq 2$ for all $z \in [0,\infty)$. Since $\psi(z) = \psi(-z)$ for all $z \in \mathbb{R}$, we have $\psi(z) \leq 2$.
$$\tag*{$\Box$}$$
Claim 3.4. If $x \in (\frac{73}{200}, \frac{1}{2}]$ then $f(x) + f(1-x) \leq 1$.
Proof. Let $x \in (\frac{73}{200}, \frac{1}{2}]$ and $z = \frac{1}{2} - x \in [0, \frac{27}{200})$. We have
\begin{align}
f(x) + f(1-x)
 &= f\left(\frac{1}{2}-z\right) +f\left(\frac{1}{2}+z\right)
\\[10pt] &= \exp \left(4 \left(\frac{1}{2}+z\right)^2 \varphi(z)\right)
    + \exp \left(4 \left(\frac{1}{2}-z\right)^2 \varphi(-z)\right)
\\ \text{By Lemma 3.1:}
\\[7pt] &\leq \exp \left(\gamma(z)\right)
    + \exp \left(\gamma(-z)\right)
\\[10pt] &= \exp \frac{\gamma(z)+\gamma(-z)}{2} \left(\exp \frac{\gamma(z)-\gamma(-z)}{2} + \exp \frac{\gamma(-z)-\gamma(z)}{2}\right)
\\ \text{By Lemma 3.2:}
\\[7pt] &\leq \exp \left(-\frac{1}{2}\left(\frac{\gamma(z)-\gamma(-z)}{2}\right)^2-\log 2\right) \left(\exp \frac{\gamma(z)-\gamma(-z)}{2} + \exp \frac{\gamma(-z)-\gamma(z)}{2}\right)
\\[10pt] &= \frac{1}{2}\, \exp \left(-\frac{1}{2}\left(\frac{\gamma(z)-\gamma(-z)}{2}\right)^2\right) \left(\exp \frac{\gamma(z)-\gamma(-z)}{2} + \exp \frac{\gamma(-z)-\gamma(z)}{2}\right)
\\[10pt] &= \frac{1}{2}\, \psi\left(\frac{\gamma(z)+\gamma(-z)}{2}\right)
\\ \text{By Lemma 3.3:}
\\[7pt] &\leq 1.
\end{align}
$$\tag*{$\Box$}$$
Comment: Impressive solution. The use of Lemma 3.3 particularly nice; here is an alternative proof. We need $(1-z)e^{2z}\leq 1+z$, which is clear for $z>1$. For $z\in[0,1]$ we use
$$\ln\left(\frac{1+z}{1-z}\right)=2\left(z+\frac{z^3}3+\frac{z^5}5+\cdots\right)\geq2z.$$
Answer: I offer a complete, self-contained solution below that can be checked without computer/calculator assistance.
The main tools that we will use (abuse?) are logarithmic differentiation and symmetry, to greatly simplify the exponentials that we are dealing with.
We may assume that $0<a\leq\frac12\leq b<1$. We split into the following two cases.
Case 1: $a\leq\frac13$
By Bernoulli's inequality we have $b^{4a^2}=(1-a)^{4a^2}\leq1-4a^3$, so it suffices to show that
$$a^{4(1-a)^2}\stackrel?<4a^3.$$
Let $h(a)=(4(1-a)^2-3)\ln(a)$; we want to show that $h(a)\stackrel?<\ln4$. Now
$$h'(a)=\frac{4(1-a)^2-3}a-8(1-a)\ln(a)$$
can clearly be seen to be decreasing on $a\in[0,1]$ (edit: in fact this is false as stated, but writing $\frac{4(1-a)^2-3}a=\frac{(2a-1)^2}a-4$ we see that $h'(a)$ is decreasing for $a\in[0,\frac12]$). Hence
$$h'(a)\geq h'(\frac13)=\frac{16\ln3-11}3>\frac{16-11}3>0,$$
so $h(a)$ is increasing on $a\in[0,\frac13]$. Thus
$$h(a)\leq h(\frac13)=\frac{11}9\ln3<\ln4,$$
since $4^4=256>243=3^5$ implies $\frac{\ln4}{\ln3}>\frac54>\frac{11}9$, as desired.
Case 2: $\frac13\leq a\leq\frac12$
Substitute $a=\frac12-x$ and $b=\frac12+x$, so $x\in[0,\frac16]$ and
$$b^{4a^2}+a^{4b^2}=\left(\frac12+x\right)^{(1-2x)^2}\!\!\!+\left(\frac12-x\right)^{(1+2x)^2}\!\!\!=F(x)+F(-x),$$
where
$$F(x)=\left(\frac12+x\right)^{(1-2x)^2}\!\!\!.$$
Write $F'(x)=F(x)G(x)$ (so $G$ is the logarithmic derivative of $F$). It is clear that $F(x)$ is increasing on $x\in[-\frac16,\frac16]$, so $F(x),F'(x)>0$ implies $G(x)>0$ on $x\in[-\frac16,\frac16]$.
Now $F(0)+F(-0)=1$, so
\begin{align*}
F(x)+F(-x)\stackrel?\leq1
&\:\Longleftarrow\:\frac d{dx}(F(x)+F(-x))\stackrel?\leq0\\
&\iff F'(x)\stackrel?\leq F'(-x)\\
&\iff\frac{F(x)}{F(-x)}\stackrel?\leq\frac{G(-x)}{G(x)}.
\end{align*}
We now prove this last inequality on $x\in[0,\frac16]$ in the following steps.
Step 1
We will show that $\ln\left(\dfrac{F(x)}{F(-x)}\right)$ is concave up on $x\in[0,\frac16]$, ie.
\begin{align*}
\frac{d^2}{dx^2}\ln\left(\dfrac{F(x)}{F(-x)}\right)&=\frac d{dx}(G(x)+G(-x))\\
&=G'(x)-G'(-x)\stackrel?\geq0.
\end{align*}
It suffices to show that $G'(x)$ is increasing on $x\in[-\frac16,\frac16]$. Now
\begin{align*}
G(x)&=\frac d{dx}\ln(F(x))\\
&=(1-2x)\left(\frac{1-2x}{\frac12+x}-4\ln\left(\frac12+x\right)\right),\\
G'(x)=\cdots&=\frac43\cdot\frac{-4+9(x+\frac16)^2}{(\frac12+x)^2}+8\ln\left(\frac12+x\right),\tag{*}
\end{align*}
so (by some miracle!) $G'(x)$ can be clearly seen to be increasing on $x\in[-\frac16,\frac16]$.
Hence the graph of $\ln\left(\dfrac{F(x)}{F(-x)}\right)$ lies below the line joining $(0,0)$ and $\left(\dfrac16,\ln\left(\dfrac{F(\frac16)}{F(-\frac16)}\right)\right)$, ie.
$$\ln\left(\dfrac{F(x)}{F(-x)}\right)\leq6\ln\left(\dfrac{F(\frac16)}{F(-\frac16)}\right)x=2Cx,\quad C:=\frac{4\ln54}3.$$
Step 2
We are left to show that $\dfrac{G(-x)}{G(x)}\stackrel?\geq e^{2Cx}$ on $x\in[0,\frac16]$.
A little manipulation gives
\begin{align*}
\frac{G(x)}{\sqrt{1-4x^2}}&=\sqrt{\frac{1-2x}{1+2x}}\left(2\,\frac{1-2x}{1+2x}-4\ln\left(\frac12+x\right)\right)\\
&=u(2u^2+4\ln(1+u^2)):=H(u),
\end{align*}
under the substitution $u=\sqrt{\dfrac{1-2x}{1+2x}}$, $x=\dfrac12\,\dfrac{1-u^2}{1+u^2}$.
Now the desired inequality is equivalent to
$$\frac{H(\frac1u)e^{-Cx}}{H(u)e^{Cx}}=\frac{G(-x)e^{-Cx}}{G(x)e^{Cx}}\stackrel?\geq1\quad\text{for }x\in[0,\tfrac16]\iff u\in[\tfrac1{\sqrt2},1].$$
Note that $u$ is decreasing in $x$, and the transformation $x\to-x$ is equivalent to $u\to\frac1u$. Thus it is sufficient to show that $H(u)e^{Cx}$ is increasing on $u\in[\frac1{\sqrt2},\sqrt2]$ (this is less than clear; I have gotten the sign wrong several times myself), ie.
\begin{align*}
\frac d{du}\ln(H(u)e^{Cx})&=\frac d{du}(Cx+\ln H(u))\\
&=C\frac{dx}{du}+\frac{H'(u)}{H(u)}\\
&=-2C\frac u{(1+u^2)^2}+\frac1u+\frac{2u+\frac{4u}{1+u^2}}{u^2+2\ln(1+u^2)}\stackrel?\geq0\\
\iff\frac{2C}{1+u^2}&\stackrel?\leq\frac{1+u^2}{u^2}+\frac{2(3+u^2)}{u^2+2\ln(1+u^2)}.
\end{align*}
We substitute $t=u^2$ and use the inequality $\ln(1+t)\leq\ln2+\frac{t-1}2$ (by convexity of $\ln(t+1)$; RHS is tangent line at $t=1$) to reduce the above to
$$2+\frac1t+\frac{7-2\ln2}{2t+2\ln2-1}\stackrel?\geq\frac{2C}{1+t}.\tag{**}$$
This will fall to Cauchy-Schwarz (in the Engel form $\sum\dfrac{a_i^2}{b_i}\geq\dfrac{(\sum a_i)^2}{\sum b_i}$), if we can find the correct weights. With some (okay, a lot) of inspiration, we obtain the following:
\begin{align*}
&\phantom{{}={}}2+\frac1t+\frac{7-2\ln2}{2t+2\ln2-1}\\
&\geq\frac{94}{47}+\frac{18}{18t}+\frac{101}{36+7t}\\
&\geq\frac{(\sqrt{94}+\sqrt{18}+\sqrt{101})^2}{54(1+t)}\geq\frac{2C}{1+t},
\end{align*}
which is what we wanted.
Hence we are left with the following (zero-variable!) inequalities that we used above:
$$\ln2\stackrel?\leq\frac{25}{36},\qquad\frac{(\sqrt{94}+\sqrt{18}+\sqrt{101})^2}{54}\stackrel?\geq2C.$$
Most people should be content with checking these by calculator. For the purists, here is a sketch of how to get these by hand.
Step 3 (Optional?)
Firstly, note that for $x>0$, we have
\begin{align*}
\ln\left(\frac{1+x}{1-x}\right)&=2\left(x+\frac{x^3}3+\frac{x^5}5+\frac{x^7}7+\cdots\right)\\
&\leq2\left(x+\frac{x^3}3+\frac{x^5}3+\frac{x^7}3+\cdots\right)\\
&=2\left(x+\frac{x^3}{3(1-x^2)}\right).
\end{align*}
Taking $x=\frac13$ gives the first inequality. In addition, taking $x=\frac15$ gives
$$54(2C)=54\times\frac83\left(3\ln\frac32+\ln2\right)\leq72\left(3\times\frac{73}{180}+\frac{25}{36}\right)=\frac{2876}5.$$
Let $(a,b,c,d)=(101,94,18,\frac{2876}5)$, and $n=\frac12(c+d-a-b)$. We are left to check that
\begin{align*}
\sqrt a+\sqrt b+\sqrt c&\geq\sqrt d\\
\iff a+b+2\sqrt{ab}&\geq c+d-2\sqrt{cd}\qquad(\because\sqrt a+\sqrt b>0)\\
\iff\sqrt{ab}&\geq n-\sqrt{cd}\\
\iff ab&\geq n^2+cd-2n\sqrt{cd}\qquad(\because\sqrt{ab}>0)\\
\iff2n\sqrt{cd}&\geq n^2+cd-ab\\
\iff4n^2cd&\geq(n^2+cd-ab)^2,\qquad(\because2n\sqrt{cd}>0)
\end{align*}
which after substitution becomes $\dfrac{205212545208}{125}\geq\dfrac{16402832101681}{10000}$, something that I consider to be close to the limits of what I can do by hand.
QED. Phew!
Remarks

Yes, this might be a long proof, and perhaps it doesn't give much insight as to why the original inequality holds. However, I hope that the tricks used in the solution (and there are many!) are of independent interest.
I have optimised the solution as presented above to minimise the effort of hand calculations. Some parts of the solution have feasible alternatives, eg. at $(*)$ we can compute $G''(x)=\dfrac{16(7+8x+4x^2)}{(1+2x)^3}$, and check that the numerator is positive on $x\in[-\frac16,\frac16]$; at $(**)$ we essentially need $P(t)\geq0$ for some cubic $P$, and we can proceed by showing
$$P(t)\geq k(t-\lambda)(t-\mu)^2+Q(t)$$
for good choices of $k,\lambda,\mu\in\mathbb R$ and $Q$ a quadratic in $t$.
How human is this solution? It is certainly human-checkable, but I have serious doubts as to whether a human can come up with a proof along these lines without computer assistance. As many previous answers have noted, the original inequality is very tight, and we cannot afford to lose more than $0.03$ in total throughout our proof.
In addition, I can count about 8 places in Step 2 alone where I used the irreversible $\Leftarrow$ implication, ie. "to prove A it is sufficient to prove B." This is disastrous if B turns out to be false! I personally needed extensive computer aid to explore the problem space and avoid dead ends of this type --- this proof was made possible by around 2000--3000 Mathematica commands.
For these two reasons, I doubt that there can be an unassisted proof using the normal tools of calculus (such as those in the above solution), let alone in a competition setting. Of course, maybe we just need some radical new insight or perspective. (I have not looked at the $W$ function closely, so maybe...?)

Cheers.
Comment: Thank you for your trying!
Comment: In Case 1, you claim $h'$ is clearly decreasing for $a\in(0,1]$. First of all, this is false. A plot of $h''$ reveals positive output for $a$ just below $1$, so $h'$ is increasing a little bit toward the end of $(0,1]$.

You might respond by restricting the claim to $(0,1/3]$. But then it's still not "clear" than $h'$ is decreasing. Trying to prove something like that is the crux of this whole endeavor. It's trying to prove an inequality involving a hybrid polynomial logarithmic function.
Comment: @alex.jordan Thanks for catching that, I have edited the solution to include an easy fix.
Answer: Update
I want to share some thought. Consider the more general problem
$$
a^{n b^2} + b^{n a^2} \leq 1
$$
A key observation is the symmetry of the two terms $a^{n b^2} $ and $b^{n \
a^2} $. Due to the constraint $a + b = 1 $,
the two terms are just $a^{n (1 - a)^2} $ and $ (1 -
      a)^{n a^2} $. So a substitution of $a \rightarrow 1 -
  a$ changes one term to the other.
    Conclusion : The LHS is a sum of two terms symmetric around the $a =
 1/2 $.
Lemma W.l.o.g, suppose a function $f (x) $ in interval $[0,
  1] $.If the function is monotonic and convex around $x=1/2$,
then the "mirror average function" $g (x) = (f (x) + f (1 - x))/2 $ has a maximum at $x =
  1/2 $.
Proof Just calculate to show $g' (1/2) = 0 $ and $g'' (x) = f'' (x)$
Corollary for concave $f(x)$ follows directly. This analysis does not answer the question, but hopefully will introduce some abstractness and shed more light on it.
Old Post
This should be a comment, but then I won't be able to post pictures. For the more general inequality:
$$
a^{n b^2}+b^{n a^2}\leq1
$$
I draw pictures for n = 0, 1, ..., 7. Each one has green dashed contour highlighting where the equality is satisfied. And of course, each one is overlaid with $a+b=1$. It's interesting to note only $n = 4$ is tightly bounded by the green contour, so it is a really special $n$ value.
Answer: This is indeed a hard nut, since convexity cannot be invoked to close the case. The following plot shows that the function
$$f(x):=(1-x)^{4x^2}+x^{4(1-x)^2}\qquad(0\leq x\leq 1)$$
in fact never drops below $0.97\>$! (Compare Robin Aldabanx' answer)

At the moment I'm just able to show that $f(x)$ behaves as claimed near $x=0$ (and, by symmetry, near $x=1$) and near $x={1\over2}$.
If $0\leq x\leq{1\over2}$ then $0\leq4x^2\leq1$, and Bernoulli's inequality gives
$$(1-x)^{4x^2}\leq1-4x^3\ .$$
On the other hand
$$x^{4(1-x)^2}=x^4\cdot x^{-8x+4x^2}=:x^4\> h(x)$$
with $\lim_{x\to0+}h(x)=1$. It follows that there is a $\delta>0$ with
$$f(x)\leq 1-4x^3+2x^4=1-4x^3\>\left(1-{x\over2}\right)<1\qquad (0<x<\delta)\ .$$
For $x\doteq{1\over2}$ we consider the auxiliary function
$$g(t):=f\left({1\over2}+t\right)\qquad\bigl(|t|\ll1\bigr)$$
which is analytic for small $|t|$. Mathematica computes its Taylor series as
$$g(t)=1+\left(-8+4\log 2+8\log^2 2\right) t^2+\ ?\>t^3\ .$$
The numerical value of the relevant coefficient here is $\doteq-1.38379$, and this tells us that $f$ has  a local maximum at $x={1\over2}$.
Comment: Your first estimate works for $0 < x  \le \frac 14$ (unless I made an error), because $x^{4(1-x)^2} \le  x^{-8x} x^4 \le 16 x^4$ on that interval, so that $f(x) \le 1 - 4x^3 + 16 x^4 = 1 - 4x^3(1-4x) \le 1$.
Comment: "This is a hard nut ..." as a teenager, I did not view this maturely.
Answer: Too long for a comment .
It's just to propose one methods on power series .
Method  (Power series)
First we have two inequalities ($\forall x\in[\frac{42}{100},\frac{1}{2}]$)

$$(1-x)^{4x^2}\leq \frac{1}{2}+\frac{2}{5} (\frac{1}{2}x-x^2)+ (\frac{-(2+4\ln(\frac{1}{2}))}{2}+\frac{18}{10}) (\frac{1}{2}-x)\quad(1)$$

And

$$x^{4(1-x)^2}\leq \frac{1}{2}+\frac{2}{5} (\frac{1}{2}x-\frac{1}{4})+ (\frac{-(2+4\ln(\frac{1}{2}))}{2}+\frac{18}{10}+\frac{2}{5}(x-\frac{1}{2}))(x-\frac{1}{2})$$

proof of $(1)$ :
Taking logartihm on both side then  making the difference  and differentiate and using :
$$8x\ln(1-x)\geq (0.5-\frac{2235}{1000}(0.5-x))\ln(0.5)$$
We get a fourth degree polynomial with a roots at $x=0.5$.Remains to study a third degree polynomial wich is not hard .
The proof of $(2)$ is similar .
For the case $\forall x\in[0,\frac{1}{3}]$ we can use the Bernoulli's inequality as in others answer . Remains just to prove the inequality on $[\frac{1}{3},\frac{45}{100}]$.I continue to explore this .
Another approach :
We use a form of the Young's inequality wich is a somewhere a generalization of the Bernoulli's inequality :
Let $a,b>0$ and $0<v<1$ then we have :
$$av+b(1-v)\geq a^vb^{1-v}$$
Taking account of this theorem and putting :
$a=x^{2(1-x)}$$\quad$$b=1$$\quad$$v=2(1-x)$ we get $0.5\leq x<1$:
$$x^{4(1-x)^2}\leq x^{2(1-x)}2(1-x)+1-2(1-x)$$
Now the idea is to show :
Let $$(1-x)^{4x^2}\leq 1-(x^{2(1-x)}2(1-x)+1-2(1-x))$$
Or :
$$(1-x)^{4x^2}\leq2(1-x)(1-x^{2(1-x)})$$
Or:
$$(1-x)^{4x^2-1}+2x^{2(1-x)}\leq 2$$
Now by Bernoulli's inequality we have :
$$2x^{2(1-x)}\leq 2-4(1-x)^2$$
So :
$$(1-x)^{4x^2-1}+2-4(1-x)^2\leq 2$$
Or :
$$(1-x)^{4x^2-3}\leq 4$$
It's not hard to show it on $[0.65,1)$
As you can see here we can improve the reasoning above and get the inequality on $[0.61,1]$
Update 20/04/2021
We can improve the reasoning using the inequality :
$$(1-v)a+vb\geq a^{1-v}b^{v}+\min{(1-v,v)}(\sqrt{a}-\sqrt{b})^2$$
Found in this article (Proposition 1.1) https://arxiv.org/pdf/1001.0535.pdf
Edit :
We have the inequality for $0<x\leq 0.55$
$$\left(\frac{1}{1-\left(1-\frac{1}{1-\left(1-x\right)^{2\left(x\right)}}\right)\left(2^{-y}x^{-y}\right)}\right)\geq x^{4\left(1-x\right)^{2}}\quad (I)$$
Where $y=\frac{-(2+4\ln(\frac{1}{2}))}{2}+1$
We have also $0<x<1$:
$$r(x)=\left(\left(\frac{1}{1+\left(\frac{g\left(x\right)}{1-\left(1-x\right)^{2x}}-g\left(x\right)\right)2^{-f\left(x\right)}x^{-f\left(x\right)}}\right)^{-1}-1+g\left(x\right)\right)^{-1}\geq x^{4\left(1-x\right)^{2}}$$
Where :
$f(x)=-\frac{\left(2+4\ln\left(0.5\right)\right)}{2}+1$
And :
$g\left(x\right)=x^{2\left(1-x\right)}+\left(1-x\right)^{2x}$
To finish we have for $\frac{1}{4}\leq x\leq \frac{3}{4}$:
$$r(x)+r(1-x)\leq 1$$
A good start to show the inequality $(I)$ see WA.The same idea can be applied to the next inequality.
To simplify a little bit $(I)$ we have the inequality for $0.47\leq x\leq 0.53$ :
$$\left(1+\left(\frac{1}{1-\left(2^{\left(2\left(1-x\right)+1\right)}\cdot\left(1-x\right)^{2}\cdot x\right)}-1\right)\cdot2^{-\left(-\frac{\left(2+4\ln\left(0.5\right)\right)}{2}+1\right)}\cdot x^{-\left(-\frac{\left(2+4\ln\left(0.5\right)\right)}{2}+1\right)}\right)\cdot x^{4\left(1-x\right)^{2}}\leq 1$$
Last edit :
It seems we have on $x\in[0.45,0.55]$ :
$$\frac{\left(2^{-\left(2\left(1-x\right)\right)^{2}}\cdot x\right)}{1-2^{\ln\left(2\right)}\left(\left(1-x\right)\cdot2\cdot x\right)^{\left(\ln\left(2\right)+1\right)}}\geq x^{\left(2\left(1-x\right)\right)^{2}}$$
Edit 21/09/2022 :
We have the inequality for $x\in(0,0.75]$:
$$\left(\left(x\right)^{b}\cdot\frac{1}{1-\left(\left(1-x\right)^{b}-1\right)\left(x^{b}-1\right)}\right)^{a}\geq f(x)=1-\left(\left(1-x\right)^{b}\cdot\frac{1}{1-\left(\left(1-x\right)^{b}-1\right)\left(x^{b}-1\right)}\right)^{a}\geq x^{4\left(1-x\right)^{2}}$$
Where $$a,b=-\frac{\ln\left(2-2^{\frac{1}{a}}\right)}{\ln\left(2\right)}$$
And $a$ is choose as :
$$f'(1/2)=1+2\ln2$$
We can also improve it for $a,b$ as above and $x\in[1/3,1)$ :
Choosing :
$$f\left(x\right)=\left(\left(1-x\right)^{b}\cdot\frac{1+4\left(\left(x-0.5\right)\left(x-1\right)x\right)^{2}}{1-\left(\left(1-x\right)^{b}-1\right)\left(x^{b}-1\right)+4\left(\left(x-0.5\right)\left(x-1\right)x\right)^{2}}\right)^{a}$$
Comment: @The.old.boy Some months ago, I came up with a proof. However, it is not better than the available solutions, so I did not post it. You shall continue to pursue it.
Comment: @RiverLi have you an idea to complete my comment ?I mean on $[\frac{1}{3},0.37]$ ?Thanks .
Comment: So apparently you mean $37/100$, not $37/10$.
Comment: @MartinR yes thanks .Good day .
Comment: @RiverLi Can you confirm there are no counter-example ? Thanks have a good day .
Comment: @The.old.boy Your bound is fine.
Comment: @RiverLi I go further do you want to check my proof ?
Comment: @ErikSatie How did you get $f(x)\leq f(0.5)+f'(0.5)(x-0.5)+0.5f''(0.5)(x-0.5)^2$ from its Taylor expansion $f(x)=f(0.5)+f'(0.5)(x-0.5)+0.5f''(0.5)(x-0.5)^2+O((x-0.5)^3)$?
Comment: @RiverLi Well it involves an absolute value and here I'm stuck in fact...
Comment: @ErikSatie  One may take logarithms and derivatives.
Comment: @RiverLi Yes I try it without success... What do you think about my 'another approach'?Thanks dear RiverLi.
Comment: @ErikSatie It is nice.
Comment: @RiverLi I have almost proof now . Can you say if it's right ? Thanks a lot :-)
Comment: @ErikSatie  You need to give a complete rigorous proof since there are quite a few proofs here.
Answer: Again too long for  comment
The inequality is equivalent to on $(0,0.5)$:
$$f(x)=\left(\left(x^{-\left(2\left(1-x\right)\right)^{2}}\right)-1\right)\left(\left(1-x\right)^{-\left(2x\right)^{2}}-1\right)\geq1$$
Now define :
$$u(x)=1+\frac{\left(\sqrt{1+0.0025\left(\frac{\left(\ln\left(m\left(x\right)\right)\right)}{\ln\left(2\right)}\right)^{\frac{\ln\left(64\right)}{3}}\cdot\left(\ln\left(\frac{m\left(x\right)}{2}\right)\right)^{2}}\right)-1}{0.00125\left(\ln\left(\frac{m\left(x\right)}{2}\right)\right)^{2}}$$
Where $m(x)=x^{-\left(2\left(1-x\right)\right)^{2}}$ and $g\left(x\right)=\left(\left(1-x\right)^{-\left(2x\right)^{2}}-1\right)$
We have the inequalities :
$$f(x)+(u(x)-1)g(x)\geq 2$$
$$f(x)\geq \frac{\left(\left(u\left(1-x\right)\right)\cdot\left(u\left(x\right)\right)\right)^{0.25}}{\sqrt{2}}\geq 1$$
This kind of method is valid for a generalisation when the higher exponent (here $2$ in $f(x)$) is greater or equal to $2$.
Comment: @RiverLi what do you think about ? Thanks !
Comment: Do you have a rigorous complete proof? If so, I will look at it.


How javascript allows object key type syntax without including ir inside a literal and also variable declaration inside it?

Question: While running these statement in chrome console or inside script tag what I found is that the below syntax which I thought is invalid is working and all the varaibles were exposed globally which I understand could be due to curly braces are interpreted as block but that key: in front is what confuse me. But I am not sure why and looking for an explaination.
    foo: {
      a = 5,
      b = 6
    }

    console.log(a) output --->  5
    console.log(b) output --->  6

    foo: {
      a = 5;
      b = 6;
    }

    console.log(a) output --->  5
    console.log(b) output --->  6

    foo: {
      a: 5;
      b: 6;
    }

    console.log(a) output --->  5
    console.log(b) output --->  6

Comment: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/label
Comment: thanks @jonrsharpe for the reference I was looking for same but was unable to find it.
Answer: That's because foo: is interpreted as a label and your "ObjectLiteral" get's interpreted as block and the statements inside get executed.
Your code boils down to the following.
a = 5,
b = 6

Since you don't have any declaration like var, let, or const you're setting a global variable a and b
Answer: If you declare a variable by just assigning to it  (without using let, const, var or as a function parameter), then it is global.
The labels do nothing because you have no loop to continue (or similar) from.
The blocks do nothing because you aren't using let or const which would scope variable to blocks.


Chart.js More than 1 charts on same web page

Question: I am looking to put 2 or more charts on the same page, but everytime I put the 2nd, the second chart dissapears. What is the correct method to add 2 or more charts?

      <canvas id="1" width="800" height="450"></canvas>
      <canvas id="2" width="800" height="450"></canvas>

var ctx = document.getElementById("myChart");
var myChart = new Chart(document.getElementById("1"), {
    type: 'bar',
    data: {
  labels: ["name1", "name2"],
  datasets: [
    {
      label: "1",
      backgroundColor: "#01cc90",
      data: [20,50]
    }
  ]
},
options: {
  title: {
    display: false,
    text: 'Name'
  }
}
}

 );

Answer: HTML
<canvas id="chartOneContainer" width="600" height="400"></canvas>

<canvas id="chartTwoContainer" width="600" height="400"></canvas>

.
JAVASCRIPT
var optionsOne = {
  type: 'line',
  data: {
    labels: ["Red", "Blue", "Yellow"],
    datasets: [
            {
                label: 'Colors One',
                data: [7, 11, 5],
                borderWidth: 1
            }
        ]
  },
  options: {
    scales: {
        xAxes: [{
        ticks: {
                    display: true
        }
      }]
    }
  }
}

var optionsTwo = {
  type: 'line',
  data: {
    labels: ["Green", "Purple", "Orange"],
    datasets: [
            {
                label: 'Colors Two',
                data: [8, 3, 7],
                borderWidth: 1
            }
        ]
  },
  options: {
    scales: {
        xAxes: [{
        ticks: {
                    display: true
        }
      }]
    }
  }
}

var ctxOne = document.getElementById('chartOneContainer').getContext('2d');
new Chart(ctxOne, optionsOne);

var ctxTwo = document.getElementById('chartTwoContainer').getContext('2d');
new Chart(ctxTwo, optionsTwo);

.
Example on JSFiddle
https://jsfiddle.net/u4gs1ttm/


Importar descrição de outra tabela

Question: Olá pessoal eu tenho o seguinte código:
SELECT COUNT(*) AS categorias_total, v_lctos_despesa.id_categorias
FROM 'v_lctos_despesa'
INNER JOIN categorias ON (v_lctos_despesa.id_categorias = categorias.id_tipo)
GROUP BY v_lctos_despesa.id_categorias

porém o resultado dele não está correto, gostaria que ele trouxesse a descrição da categoria e não a id:

categoria1 = 10
categoria2 = 15

ele está trazendo:

1 = 10
2 = 15

Answer: Não seria o caso apenas você alterar o campo de retorno?
SELECT COUNT(*) AS categorias_total, v_lctos_despesa.desc_categorias --valida o nome do campo
FROM 'v_lctos_despesa'
INNER JOIN categorias ON (v_lctos_despesa.id_categorias = categorias.id_tipo)
GROUP BY v_lctos_despesa.desc_categorias

obs: repare que fazendo isso, você precisa alterar também o campo do group by, que deve ser igual ao trazido no select.

Importar descrição de outra tabela


How do I change the color of an SF Symbols icon in Swift?

Question: I realize this question has been asked here twice but none of the solutions provided are working for me. My icon is showing up but it is showing with a blue outline rather than the red I have requested. Swift is telling me that setting the foreground color is not an option
let largeConfig = UIImage.SymbolConfiguration(pointSize: heartPointSize)

let emptyHeartIcon = UIImage(systemName: "heart", withConfiguration:largeConfig)?.withTintColor(.systemRed) // this did not work

emptyHeartIcon?.withTintColor(.systemRed) // this also did not work
emptyHeartIcon!.withTintColor(.systemRed) // thought maybe it was because I wasn't unwrapping it but this also didn't work

If you're so inclined here's the context of the symbol :)
func levelUpsShown(){

    let levelUpShownStackView = UIStackView(arrangedSubviews: [])
    levelUpShownStackView.frame = CGRect(x: 15, y: 15, width: levelUpsShownView.bounds.width - 30, height: levelUpsShownView.bounds.height - 30)

    let heartPointSize = (levelUpsShownView.bounds.width - 30)/8
    let heartLocation = (levelUpsShownView.bounds.width - 38)/12

    (0..<6).forEach { (levelUpsBucket) in
        let largeConfig = UIImage.SymbolConfiguration(pointSize: heartPointSize)
        let emptyHeartIcon = UIImage(systemName: "heart", withConfiguration: largeConfig)
        let emptyHeartView = UIImageView(image: emptyHeartIcon)

        let levelUpSegment = UIView()
        levelUpSegment.addSubview(emptyHeartView)

        emptyHeartView.center = CGPoint(x: heartLocation, y: 40)

        levelUpShownStackView.addArrangedSubview(levelUpSegment)
    }
    levelUpShownStackView.distribution = .fillEqually
    levelUpShownStackView.spacing = 4
    levelUpsShownView.addSubview(levelUpShownStackView)
}

Answer: Try to change the tint of the UIImageView instead of the UIImage.
emptyHeartView.tintColor = .systemRed

If you don't want an UIImageView, check this post;
https://stackoverflow.com/a/19152722/8258494
Basically applying a mask on your image.
Comment: This worked! Thanks, I'll accept when the time limit is over. The extra context is much appreciated as well, I'll check it out.


Usando opção única com radio button

Question: Não estou conseguindo criar uma opção única para seleção via radio-button. Quando clico em duas opções, ele seleciona as duas, quando o ideal seria ou uma ou outra.

Base Anterior<input name="b_ant" type="radio" value="S" />

Base na Grade<input name="b_grade" type="radio" value="S" />

Base em Veículos Novos<input name="b_novos" type="radio" value="S" />

Comment: os names devem ser iguais
Answer: O name dos inputs devem ser o mesmo. Veja o exemplo abaixo:

    Base Anterior
    <input id="ant" name="base" type="radio" value="S" />

    Base na Grade
    <input id="grade" name="base" type="radio" value="S" />

    Base em Veículos Novos
    <input id="novo" name="base" type="radio" value="S" />

Answer: Com HTML puro somente conforme consta no meu comentário na sua pergunta os names devem ser iguais
Quando uma opção RADIO é marcada, esta só será desmarcada quando outra opção RADIO com mesmo NAME for selecionada
Se for necessário manter os names diferentes, considere usar jquery. exemplo:

$(document).ready(function () {
    $('input[type=radio]').change(function() {
        $('input[type=radio]:checked').not(this).prop('checked', false);
    });
});

Base Anterior<input name="b_ant" type="radio" value="S" />

Base na Grade<input name="b_grade" type="radio" value="S" />

Base em Veículos Novos<input name="b_novos" type="radio" value="S" />

not()  seleciona todos os elementos, exceto o elemento especificado.
prop() prop('checked', false) usado para desmarcar.
not(this).prop('checked', false); vai desmarcar todos os inputs radios exceto o selecionado
Comment: Conseguiria dar um exemplo de quando seria necessário ter vários elementos *radio* que representam o mesmo campo, porém com nomes distintos?
Comment: @AndersonCarlosWoss, não é o foco do post avaliar uma ou outra situação, estou apenas respondendo a uma pergunta. Isto vc deve perguntar ao autor do post.
Comment: É que como sugeriu a solução, achei que saberia, mas obrigado.
Comment: É como eu disse na resposta - Se for necessário manter os names diferentes - o uso te tal situação só o AP pode explicar. Entendo que você fez essa pergunta inadequadamente com segundas intenções.

Usando opção única com radio button


How do I properly interpret an external SVG file for use with two.js?

Question: If the object tag is not really suitable, then is there a more preferable method for grabbing an SVG file and manipulating it directly with two.js?  Or will I have to go into the SVGs and just add them inline?
Using this question's code and some of my own edits I can't get my object to rotate, Chrome gives me the error: Uncaught TypeError: Cannot read property 'x' of undefined
HTML
<object type="image/svg+xml" data="./images/face.svg" id="face"></object>

JS
    $(function(){
    var svgObject = document.getElementsByTagName('object')[0];
        svgObject.onload = function(){
            var mySvg = svgObject.contentDocument.getElementsByTagName('svg')[0];
            var two = new Two({
                fullscreen:false,
                autostart: true
            }).appendTo(document.body);
            var shape = two.interpret(mySvg);
            console.log(shape);
            two.update();
            two.bind('update', function() {
                shape.rotation += 0.01;
            });
        };
    });

Since the code in the referenced question seems to have worked for the individual, I assume I just have a syntax error.  Any ideas as to what's going on?
EDIT: With Francis' help, I was able to get my own SVG parsed for use with the for loop Francis mentioned in order to access the elements inside, but it seems to be considering the nested G tag within the following SVG to be null...for some reason:
<svg id="svg2" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns="http://www.w3.org/2000/svg" height="280" width="280" version="1.1" xmlns:cc="http://creativecommons.org/ns#" xmlns:dc="http://purl.org/dc/elements/1.1/"><g id="layer1" transform="matrix(0.99999301,0,0,1,-400.71477,-954.83987)"><g id="g3836" transform="matrix(-0.08567939,-0.08567939,0.08567939,-0.08567939,574.3717,1199.1604)"><path id="path3801" fill="#3b5998" d="m805.17-1221.6c-902.43,902.43-902.43,2365.6,0.00003,3268l517.13-517.1c-616.83-616.83-616.83-1616.9,0-2233.8z"/><path id="rect3822" fill="#FFF" d="m266.93,336.2c0.15806,60.722,23.582,102.66,103.93,102.66h44.694v62.567h71.844v-62.57h184.55v-73.089h-184.55v-62.849l-71.844-8.5959v71.445h-44.69c-20.309,0-35.863-7.2042-35.863-35.676v-38.658h-64.869c-2.0284,15.729-3.2307,30.752-3.1941,44.765z"/></g></g></svg>

Also, Chrome throws the following errors on load:
'Uncaught TypeError: Cannot read property 'nodeName' of null' on line 68, in the handler() function (this is what I assumed to be the nested G being considered null):
xmlDocValue.value+=XMLdoc.childNodes.item(1).nodeName +"\n"

'Uncaught TypeError: Cannot read property 'childNodes' of undefined' in the aforementioned for loop, which I assume is because of the fact that the null element is considered null:
myGElems = XMLdoc.childNodes.item(0).childNodes

Answer: The parent html cannot access the <object>'s content. I assume you want to access the svg's elements in your file, and use their nodeName and attributes to create two.js elements. If so, The best way would be to use XMLHttpRequest to load the svg as XML and then DOMParser to get nodeName and attriutes of the elements. The responseText can also be loaded directly into a DIV's innerHTML.
Try this:
create an SVG file, called mySVG.svg as below:
<svg width="400" height="400" id="mySVG" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" ><circle id="myCircle"   r="100" cx="150" cy="150" fill="red" /><rect id="myRect" x="200" y="260" width="120" height="100" fill="blue" /></svg>

Then run the following HTML file:
   <!DOCTYPE html>

    <title>Parse SVG Elements via XML DOM</title>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">

Parse SVG Elements via XML DOM

    Load svg files as XML via XMLHttpRequest. use DOMParser to parse the XML Document Element to create a client's svg elements.

mySVG.svg:
    <textarea id=svgValue style='width:90%;height:200px;font-size:120%;font-family:lucida console;'></textarea>
    SVG Inline

<button onClick=loadSVGXML()>load svg as xml</button>

    XML Doc
    <textarea id=xmlDocValue style='width:90%;height:100px;font-size:120%;font-family:lucida console;'></textarea>

Comment: Running your HTML works fine for your supplied SVG, and gives me tagNames I'd expect to see.  but when using my own SVG I only get "#text" in the XML doc box (don't know why that's showing up since I have no text or any objects with said tag in my SVG), and Chrome throws: 'Uncaught TypeError: Object # has no method 'getAttribute' (index):59
handler' as an error.  Thanks for your help!
Comment: When you 'hand-craft' svg files, you tend to use carriage returns to make it pretty. These are interpreted as #text elements. Therefore remove carriage returns or filter out the #text element.
Comment: @EnMod: Also, spaces between elements will cause #text elements.
Comment: Thanks I had no idea about that, after putting all of the elements on what was essentially one line in the SVG your parser appears to have parsed it correctly.  However, what appears in the XML doc box is g (which I think I should expect) and null, and that's it.  What exactly does that mean?
Comment: I would expect that means your svg has a single  element with a bunch of elements contained in the . Therefore myGElems=XMLdoc.childNodes.item(0).childNodes Then just iterate through the myGElems to access them. e.g. for(var k=0;k<myGElems.length;k++){ var myElem=myGElemes.item(k) ...}
Comment: Updated question with some more info...my apologies for leaving that out after my previous comment.
Comment: Also thank you for that snippet, I think it will prove useful; I'm extremely new at accessing external objects using JS, even more so with SVG.  Please see my edit for the latest issue I'm having: this goes to anyone reading this.
Comment: This is slightly tangential, but if you have jQuery it's pretty easy to asynchronously load an svg file: `$.get('path-to-file.svg', function(resp) { var result = two.interpret($(doc).find('svg')[0]); });` as in this: http://jonobr1.github.io/two.js/examples/animate-stroke.html
Comment: Wow, the creator of two.js himself? Good to see you.  there have been some developments since my last comment.  Some new info:

-My SVGs are Optimized SVGs from Inkscape
-When I use my SVGs with the samples from two.js (by replacing the sample SVG code with my own), there are JS errors: c is undefined, v is undefined...I have a feeling this has  to do with the Optimized SVG exporting from Inkscape.
-A sample SVG of mine that doesn't work with your examples, throwing errors, is [here](http://pastebin.com/4pNkC21J)

I'm at my wit's end...weren't there issues with Inkscape Optimized SVGs?


como receber / imprimir o conteudo em json de uma API

Question: OLA, sou novo na area de API e estou consumindo uma API de previsão do tempo.
consegui "conectar" na api, recebi o resultado 200 ok mas agora quero saber como receber os dados em json da api.
eu sei que para receber os dados do endpoint tenho que passar os parametros de cidade e país. (desculpa se usei termos que não fazem sentido).
URL url = new URL("https://reqbin.com/echo");
         HttpURLConnection http = (HttpURLConnection)url.openConnection();
         http.setRequestProperty("Accept", "*/*");
         http.setRequestProperty("Authorization", "Bearer 9c40e8ea24eaabf937f16e0fbb7ff186");
         System.out.println(http.getResponseCode() + " " + http.getResponseMessage());

         String contentType = http.getContentType();
         System.out.println(contentType);

         http.disconnect();

Comment: Isto responde à sua pergunta? [Conversão de string JSON para objeto Java](https://pt.stackoverflow.com/questions/6046/convers%c3%a3o-de-string-json-para-objeto-java)
Comment: na vdd não haha :(
Comment: O que você quer tirar de dúvida, especificamente?
Answer: Junior, também sou iniciante, mas assim como capturou o contentType, você pode pegar o body retornado pela API.
Eu usei o java.net.http e a API da IMDB, ficou assim:
 URI apiIMDB = URI.create("https://imdb-api.com/en/API/Top250Movies/" + apiKey);

    HttpClient client = HttpClient.newHttpClient();
    HttpRequest request = HttpRequest.newBuilder().uri(apiIMDB).build();

    HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
    String json = response.body();

Pronto o JSON está ai na váriavel como uma String.
Essa é uma forma de fazer direto sem recursos externos, ja que o java.net.http esta incluso no java 11+
Pode usar as bibliotecas Jackson e Gson também. São bem famosas e bem tem muito conteúdo espalhado pela rede!
Comment: salve man, entao mas ai o problema ainda é o mesmo, por exemplo eu queria
 retornar apenas a temperatura, ou a velocidade do vento, não queria ver toda a lista json


JPA / Hibernate "simple" OneToMany Unidirictional / Clear of set does not work

Question: I don't know what I am doing wrong, but apparently I am not able to create a simple OneToMany relationship with hibernate.
Here are my tables how they look in DB:

I will only show relevant part, so the question does not get to bloated.
My User Looks like
@Entity(name = "CORE_USER")
public class User extends AbstractPersistentObject {

    ...

    @ManyToMany(cascade=CascadeType.ALL,fetch=FetchType.LAZY)
    @JoinTable(name = "CORE_USER_TO_ROLE",
        joinColumns = { @JoinColumn(name = "USER_ID") },
        inverseJoinColumns = { @JoinColumn(name = "ROLE_ID") })
    private Set<UserRole> roles = new HashSet<UserRole>();

    @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    @JoinColumn(name = "USER_ID")
    private Set<UserRoleParam> userRoleParams = new HashSet<UserRoleParam>();

    ...(getter and setters)

}

Here Core user role param entity
@Entity(name = "CORE_USER_ROLE_PARAM")
public class UserRoleParam extends AbstractPersistentObject {

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "ROLE_ID")
    private UserRole userRole;

    @Column(name = "ROLE_PARAMETER")
    private String paramter;

    ...(getter and setter)....
}

UserRole entity
@Entity(name="CORE_USER_ROLE")
public class UserRole  extends AbstractPersistentObject {

    @Enumerated(EnumType.STRING)
    @Column(name = "ROLE_NAME", length = 30, nullable=false, unique=true)
    private UserRoleEnum roleName;

    ...(getter and setters)
}

When I do this in my test:
@Test
@Transactional(propagation = Propagation.NEVER)
public void saveUserRoleParametersTest() throws Exception {

    // load an user which exists and check params is zero
    UserDTO userDTO = userService.getUserDTO(Users.DE678_ACTIVE_ALLROLES.getObject().getId());
    Assert.assertNotNull(userDTO);
    Assert.assertNotNull(userDTO.getUserRoleParams());
    Assert.assertEquals(0, userDTO.getUserRoleParams().size());

    Map<UserRoleEnum, List<String>> userRoleParams = new HashMap<>();
    userRoleParams.put(UserRoleEnum.BASIC, new ArrayList<>());
    userRoleParams.get(UserRoleEnum.BASIC).add("BASIC_PARAM");

    // save params to user
    userService.saveUserRoleParameters(Users.DE678_ACTIVE_ALLROLES.getObject().getId(), userRoleParams);

    userDTO = userService.getUserDTO(Users.DE678_ACTIVE_ALLROLES.getObject().getId());
    Assert.assertNotNull(userDTO);
    Assert.assertNotNull(userDTO.getUserRoleParams());
    Assert.assertEquals(1, userDTO.getUserRoleParams().size());
    Assert.assertEquals(1, userDTO.getUserRoleParams().get(UserRoleEnum.BASIC).size());
    Assert.assertTrue(userDTO.getUserRoleParams().get(UserRoleEnum.BASIC).contains("BASIC_PARAM"));

    // delete params of user
    userService.saveUserRoleParameters(Users.DE678_ACTIVE_ALLROLES.getObject().getId(), null);

    userDTO = userService.getUserDTO(Users.DE678_ACTIVE_ALLROLES.getObject().getId());
    Assert.assertNotNull(userDTO);
    Assert.assertNotNull(userDTO.getUserRoleParams());
    Assert.assertEquals(0, userDTO.getUserRoleParams().size());
}

here is also the user service method which I invoke:
@Override
public void saveUserRoleParameters(final String userId, final Map<UserRoleEnum, List<String>> userRoleParams) throws UserNotFoundException {
    User user = userDAO.get(userId);

    if (user == null) {
        throw new UserNotFoundException(userId);
    }

    if (userRoleParams == null || userRoleParams.isEmpty()) {
        user.getUserRoleParams().clear();
    } else {
        List<UserRole> roles = userDAO.getUserRolesByEnums(userRoleParams.keySet());
        Map<UserRoleEnum, UserRole> enumToEntity = new HashMap<>();
        roles.stream().forEach(r -> enumToEntity.put(r.getRoleName(), r));

        for (Entry<UserRoleEnum, List<String>> entry : userRoleParams.entrySet()) {
            UserRoleParam urp = new UserRoleParam(enumToEntity.get(entry.getKey()), entry.getValue().stream().collect(Collectors.joining(";")));
            user.getUserRoleParams().add(urp);
        }
    }
    userDAO.saveOrUpdate(user);
}

The problem is that my test fails on first service method call of saveUserRoleParameters which is (EDIT: now with sql log enabled):
DEBUG [main] 12.05.17 08:46:50.264  org.hibernate.engine.jdbc.spi.SqlStatementLogger@logStatement: select user0_.id as id1_0_0_, user0_.version as version2_0_0_, user0_.ACTIVE as ACTIVE1_38_0_, user0_.APP_LANG as APP_LANG2_38_0_, user0_.DEFAULT_MODULE as DEFAULT_3_38_0_, user0_.ORGA_UNIT as ORGA_UNI4_38_0_, user0_.USER_FULL_NAME as USER_FUL5_38_0_, user0_.USER_NAME as USER_NAM6_38_0_ from CORE_USER user0_ where user0_.id=?
DEBUG [main] 12.05.17 08:46:50.270  org.hibernate.engine.jdbc.spi.SqlStatementLogger@logStatement: select userrole0_.id as id1_0_, userrole0_.version as version2_0_, userrole0_.ROLE_NAME as ROLE_NAM1_41_ from CORE_USER_ROLE userrole0_ where userrole0_.ROLE_NAME in (?)
DEBUG [main] 12.05.17 08:46:50.287  org.hibernate.engine.jdbc.spi.SqlStatementLogger@logStatement: select userrolepa0_.USER_ID as USER_ID3_0_0_, userrolepa0_.id as id1_42_0_, userrolepa0_.id as id1_0_1_, userrolepa0_.version as version2_0_1_, userrolepa0_.ROLE_PARAMETER as ROLE_PAR1_42_1_, userrolepa0_.ROLE_ID as ROLE_ID2_42_1_ from CORE_USER_ROLE_ROLE_PARAM userrolepa0_ where userrolepa0_.USER_ID=?
DEBUG [main] 12.05.17 08:46:50.290  org.hibernate.engine.jdbc.spi.SqlStatementLogger@logStatement: insert into CORE_USER_ROLE_PARAM (version, ROLE_PARAMETER, ROLE_ID, id) values (?, ?, ?, ?)
WARN  [main] 12.05.17 08:46:50.291  org.hibernate.engine.jdbc.spi.SqlExceptionHelper@logExceptions: SQL Error: 23502, SQLState: 23502
ERROR [main] 12.05.17 08:46:50.291  org.hibernate.engine.jdbc.spi.SqlExceptionHelper@logExceptions: NULL nicht zulässig für Feld "USER_ID"
NULL not allowed for column "USER_ID"; SQL statement:
insert into CORE_USER_ROLE_ROLE_PARAM (version, ROLE_PARAMETER, ROLE_ID, id) values (?, ?, ?, ?) [23502-175]
WARN  [main] 12.05.17 08:46:50.291  org.hibernate.engine.jdbc.spi.SqlExceptionHelper@logExceptions: SQL Error: 23502, SQLState: 23502
ERROR [main] 12.05.17 08:46:50.292  org.hibernate.engine.jdbc.spi.SqlExceptionHelper@logExceptions: NULL nicht zulässig für Feld "USER_ID"
NULL not allowed for column "USER_ID"; SQL statement:

Shouldn't jpa put the UserId where it belongs? What I want is a Unidirectional relationship where User knows about UserRoleParams but not the other way around. Like in the example here http://www.objectdb.com/api/java/jpa/annotations/relationship
EDIT#2:
I found a solution. I added following on User Entity:
@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinColumn(name = "USER_ID", nullable = false)
private Set<UserRoleParam> userRoleParams = new HashSet<UserRoleParam>();

Now I have the issue that clearing the set will not be persisted. My test fails as the second check if the Set is empty fails. It shows that the Parameters are still set.
Comment: You haven't put `mappedBy="user"` on the `User.userRoleParams` field, since that is a BIDIRECTIONAL relation
Comment: Please enable debugging and show some sql statements
Comment: Save the user before you save the CORE_USER_ROLE_PARAM
Comment: @Stimpson: The user which I load is already existent as you can see in the beginning of the test where I load the user to check if the parameters are empty.
Comment: Then you save the user with id = null. Do you have autoincrement turned on or are you using a sequence for the id?
Comment: @StimpsonCat the user exists. I do not want to save to user with a new id. As the test shows. I get the user with an id and want to update the retrieved user.
Answer: The fields User.userRoleParams and UserRoleParam.user are part of a bidirectional relation. To do that you must add
mappedBy="user" to the @OneToMany side.
You cannot have those two parts as independent relations (i.e unidirectional 1-N and unidirectional N-1) reusing the same FK column ("USER_ID").
As for your documentation you linked to in the comments, the only use of unidirectional 1-N has no field on the other side (and you do have a field on the other side of the relation).
User has changed their question since this answer! Why do I bother?
Comment: You cant help, if the questions are changeing ;)
Comment: you are right... in that case... that was when I was playing around and I accidentally posted the wrong code. What I want is a UNIDIRECTIONAL relation on the JPA Mapping side
Comment: It has its own column in the table CORE_USER_ROLE_PARAM which is USER_ID. I would appreciate if you either cold have more patience or stop yelling (write with capitalized letters)
Comment: you are right... I made a mistake by copying a wrong code into the question. And I do not want to open a new question if I solved the old problem


Is it safe to use the django safe filter in text only emails?

Question: When crafting the text only version of an email, is it safe to use the 'safe' filter on untrusted content?
<code> # text_email.txt
 Dear User,

 Please see below some user-submitted content:

 {{ untrusted_content|safe }}

 Yours, etc.
</code>
Comment: why not? it's just a text.
Answer: Yes.
As long as you are enforcing that the email is sent as text, then any HTML (or other unsafe content) should not be rendered by email clients, but instead the source will just be shown as text.


Text chatting website in python

Question: I aspire to create a text chatting website with some extra features. As for the core text chatting part, is python an appropriate language for such a kind ? If so, is their any libraries which help in this process.
I would also require real time data being pushed back to the browser, implying i would be using the web-sockets also. Is tornado the appropriate choice of server ? I am a newbie in terms of network based application or website.
Comment: I'm sorry, but I think your question is too vague and overly broad to be answered here on SO; see the [FAQ#dontask]. If you have more concrete problems (preferably involving some code), feel free to ask those!
Comment: I was looking for an answer with supported libraries or examples of projects.
Answer: Tornado is a non block webserver with a chat demo already created.
https://github.com/facebook/tornado/tree/master/demos/chat
From the tornado website:

The framework is distinct from most mainstream web server frameworks
  (and certainly most Python frameworks) because it is non-blocking and
  reasonably fast. Because it is non-blocking and uses epoll or kqueue,
  it can handle thousands of simultaneous standing connections, which
  means it is ideal for real-time web services. We built the web server
  specifically to handle FriendFeed's real-time features — every active
  user of FriendFeed maintains an open connection to the FriendFeed
  servers. (For more information on scaling servers to support thousands
  of clients, see The C10K problem.)

Sounds like it would be worth the time to look into.
Answer: You can create your own simple chat engine. In any case it's not bad to see the next libraries:
http://docs.python.org/library/asynchat.html,
http://docs.python.org/library/socketserver.html.
The links contain examples.
An example of usage: start it on some port and access it from javascript.

Text chatting website in python


"(" and ")" Replace in C#

Question: So I am trying to replace the characters below from a users input which relates to a SQL column in a table.
Example:
User creates a field called My(first)try. In SQL this comes up as Myfirsttry.
I am currently write code to replace the users input with our and I am stuck.
I have this so far.
  itemreplace = itemreplace.Replace("(", "");

This however, doesn't do the trick. Thoughts, comments, suggestions?
Comment: So what *does* it do?  What is the result of running that line of code?
Comment: This smells like your asking for a SQL injection attack... Please tell me you aren't trying to clean up input from the user and make a query out of the text...
Comment: If you did the same thing again for the closing bracket would life be better?
Comment: itemreplace is a string, right? That certainly should work.

Post your actual code. I just tried that in a quick dirty console application and it properly replaces the open parenthesis with an empty string.
Comment: Basically an exact duplicate of this question from two days ago (parenthesis and all): http://stackoverflow.com/questions/19280553/how-do-i-remove-multiple-offending-characters-from-my-string
Comment: possible duplicate of [Remove characters from C# string](http://stackoverflow.com/questions/7411438/remove-characters-from-c-sharp-string)
Answer: I feel like the real-world case is more complicated, and you're not indicating that, but to handle your example text My(first)try you could just chain the Replace statements:
itemreplace = itemreplace.Replace("(", "").Replace(")", "");

However, it seems like the real-world case is more along the lines of leveraging a Regex like this:
^[a-zA-Z0-9_@#][a-zA-Z0-9@$#_]*$

and here is a Regex 101 that would prove that.
Then using that might look like this:
var valid = Regex.IsMatch("My(first)try", pattern);

I did reference this post, What special characters are allowed in T-SQL column name?, to determine the allowed characters for a column name.
Comment: Thanks everyone. I did try searching but I guess I had no idea what I was searching for to begin with.
Answer: First option:
String itemreplace = new String("My(first)try");
String charsToRemove = new String[] {"(", ")"};
foreach (char c in charsToRemove)
{
    itemreplace = itemreplace.Replace(c, string.Empty);
}

Second option:
itemreplace = itemreplace.Replace("(", string.Empty).Replace(")", string.Empty);

"(" and ")" Replace in C#


Apache Named Virtual Hosts and HTTPS

Question: I have an SSL certificate which is valid for multiple (sub-) domains. In Apache I have configured this as follows:
In /etc/apache2/apache2.conf
NameVirtualHost <my ip>:443

Then for one named virtual host I have
<VirtualHost <my ip>:443>
    ServerName ...

    SSLEngine on
    SSLCertificateFile ...
    SSLCertificateKeyFile ...
    SSLCertificateChainFile ...
    SSLCACertificateFile ...
</VirtualHost>

Finally, for every other site I want to be accessible over HTTPS I just have a
<VirtualHost <my ip>:443>
    ServerName ...
</VirtualHost>

The good news is that it works. However, when I start Apache I get warning messages
[warn] Init: SSL server IP/port conflict: Domain A:443 (...) vs. Domain B:443 (...)
[warn] Init: SSL server IP/port conflict: Domain C:443 (...) vs. Domain B:443 (...)
[warn] Init: You should not use name-based virtual hosts in conjunction with SSL!!

So, my question is: how should I be configuring this? Clearly from the warning messages I am doing something wrong (although it does work!), however, the above configuration was the only one I could get to work. It is somewhat annoying as the configuration files have an explicit dependence on my IP address.
Answer: The configuration is right.
Apache barks because it thinks it is a mistake on your part to have more SSL VirtualHosts with the same certificate (because most of the time, configurations like this manifest as a certificate error on the client). You can ignore the warning messages, mostly because, like you said, it works the way you want.
If you want the config to be independent from the IP address, you can specify
<VirtualHost *:80>

in your config files. Naturally, you'll have to have the corresponding NameVirtualHost entry:
NameVirtualHost *:80

Answer: you can use the same certificate into each VirtualHost directive and define as well your server configuration - basically combine what you wrote above.
the NameVirtualHost directive is used for NON ssl traffic when you want apache to look at the incoming headers and route based on the Host string sent by the client to the actual virtual server.
Answer: You can only have a https site per socket, so you have to change the VHost port and associate it with the new certificate. If all those sites need to run on 443 port you need more IPs.
Comment: Abject nonsense ;) You are limited to one certificate per IP, however, a certificate can be valid for multiple domains, hence allowing virtual hosts to be used.
Answer: You can use nginx instead of or in front of apache.
Most web servers (apache, iis, etc.) don't work properly with named ssl hosts because they determine the virtual website before determining which ssl cert to use, negotiating, etc..  The SNI thing is sort of a hack that doesn't work with lots of browsers.
nginx, however, does name based SSL hosts gracefully, because it allows you to associate the cert with the IP/port and then inspect the host header to determine where to route the request.  The destination can be served by nginx or reverse proxied to apache, iis, other machines, whatever.. It's the swiss army knife of incoming tcp/ip requests.  It has many of the same capabilities of ssl offloading and redirecting commonly done with hardware load balancers, including simple load balancing.

Apache Named Virtual Hosts and HTTPS


Evaluation of Standard Normal Integral

Question: I have always wondered how we calculate the percentiles of the Standard Normal Distribution given that the CDF cannot be obtained in closed form:
$$F(x)=\int_{-\infty}^{x} \frac{1}{\sqrt{2\pi}} e^{-\frac{t^2}{2}} $$
Do we approximate the function somehow? I have seen some texts that employ the Taylor Series of $e^x$, i.e. $e^x = \sum_0^{\infty} \frac{x^n}{n!} $ but this is not very practical. Is there another way to approximate the integral at a satisfactory level? Thank you.
Comment: You may want to check http://en.wikipedia.org/wiki/Error_function
Comment: @LordSoth What you are saying is that we normally calculate the Standard Normal percentiles by approximating the Error Function and then using the relation between those two?
Comment: Yes, that may be one way to do it as $\mathrm{erf}(\cdot)$ is a quite well-studied function.
Comment: Right. What about numerical integration techniques though? Are any applicable for this case?
Answer: You may want to take a look at some of the approximations of the error function in Abramowitz and Stegun.  Some of these may be derived by guessing the approximate form and fitting coefficients of the form to various numerically derived data points.  This is evident in formulae 7.1.25-7.1.28.  Unfortunately, much of applied mathematics can be a little on the ugly side like this; the results, however, are incredibly practical.
Comment: @Ioannis: well, sure, but you need to be careful not to go too high in order: you end up assuming more crazy behavior than is warranted with a gaussian.  The thing is, the error function is so well-known and cheap to compute, there are a hundred ways to do it.  If you do not have access to a black box code, then the polynomials I referred to work beautifully.  Otherwise, just use a black box error function.  Unless you are learning about the structure of the function, there is really no need to reinvent the wheel.
Comment: Thank you. I am feeling a bit overwhelmed though. Other than the Error Function do you think that any of Newton's numerical integration formulas are applicable?
Comment: Thanks again. I still have a lot to learn.

Evaluation of Standard Normal Integral


Disable unused Subversion features

Question: My organization uses Subversion for source control as usual, but there's been an interest in using Subversion to store non-software related documents - specifically, engineering drawings.
The users would be engineers who need a secure and versioned repository for their technical drawings. These would be binary files, so we're aware it wouldn't be the most efficient use of Subversion. Also they won't need branching, tagging, merging, etc. - just the versioning capabilities.
The users aren't software engineers, and this will be their first use of Subversion, and - well, engineers like to take things apart. I'd like to prevent them from breaking anything. What I'd like to know is whether I can turn off, at the server, the features they won't be using, so that nobody will be tempted to play...
Thanks a bunch.
Answer: You can't do it on server (except "recompile" option), but you can prepare minified client-side GUI (if Windows)
Comment: I think TortoiseSVN lets you customize the contextual menu - you can't really disable features but you can certainly hide them.
Comment: Yeah, we're using Windows. Is there such a GUI that I can use?

Disable unused Subversion features