text:
Q: $\int_0^{\pi/2}\log^2(\cos^2x)\mathrm{d}x=\frac{\pi^3}6+2\pi\log^2(2)$??? I saw in a paper by @Jack D'aurizio the following integral
$$I=\int_0^{\pi/2}\log^2(\cos^2x)\mathrm{d}x=\frac{\pi^3}6+2\pi\log^2(2)$$
Below is my attempt.
$$I=4\int_0^{\pi/2}\log^2(\cos x)\mathrm{d}x$$
Then we define
$$F(a)=\int_0^{\pi/2}\log^2(a\cos x)\mathrm{d}x$$
So we have
$$F'(a)=\frac2a\int_0^{\pi/2}\log(a\cos x)\mathrm{d}x$$
Which I do not know how to compute. How do I proceed? Thanks.

A: Let $$I(a)=\int_0^{\frac {\pi}{2}} (\cos^2 x)^a dx$$
Hence we need $I''(0)$.
Now recalling the definition of Beta function we get $$I(a)=\frac 12 B\left(a+\frac 12 ,\frac 12\right)=\frac {\sqrt {\pi}}{2}\frac {\Gamma\left(a+\frac 12\right)}{\Gamma(a+1)}$$
Hence we have $$I''(a) =\frac {\sqrt {\pi}}{2}\frac {\Gamma\left(a+\frac 12\right)}{\Gamma(a+1)}\left(\left[\psi^{(0)}\left(a+\frac 12 \right)-\psi^{(0)}(a+1)\right]^2 +\psi^{(1)}\left(a+\frac 12 \right)-\psi^{(1)}(a+1)\right) $$
Substituting $a=0$ in above formula yields the answer.

A: Differentiation of the Beta function is a viable approach, but since we are dealing with a squared logarithm and not higher powers, it is faster to just exploit the Fourier (cosine) series of $\log(\cos^2\theta)$ and Parseval's theorem. Given
$$-\log(\cos^2\theta)=2\log 2+2\sum_{k\geq 1}\frac{(-1)^k}{k}\cos(2k\theta),\tag{1} $$
since $\int_{0}^{\pi/2}\cos(2jx)\cos(2kx)\,dx =\frac{\pi}{4}\delta(j,k)$, we immediately have
$$ \int_{0}^{\pi/2}\log^2(\cos^2\theta)\,d\theta = 2\pi\log^2 2+\pi\zeta(2).\tag{2}$$
Since the LHS equals $\int_{0}^{1}\frac{4\log^2 x}{\sqrt{1-x^2}}\,dx$, we have just found the value of the hypergeometric series
$$ 8\sum_{n\geq 0}\frac{\binom{2n}{n}}{4^n(2n+1)^3}=8\cdot\phantom{}_4 F_3\left(\tfrac{1}{2},\tfrac{1}{2},\tfrac{1}{2},\tfrac{1}{2};\tfrac{3}{2},\tfrac{3}{2},\tfrac{3}{2};1\right)\tag{3} $$
which also equals $\int_{0}^{+\infty}\frac{\log^2(1+t^2)}{1+t^2}\,dt$ or $\frac{1}{2}\int_{0}^{1}\frac{\log^2(x)}{\sqrt{x(1-x)}}\,dx$.

A: \begin{align}J=\int_0^{\frac{\pi}{2}} \ln^2\left(\cos x\right)\,dx\end{align}
Observe that,
\begin{align}I&=4J\\
J&=\int_0^{\frac{\pi}{2}} \ln^2\left(\sin x\right)\,dx\\
\int_0^{\frac{\pi}{2}} \ln\left(\sin x\right)\,dx&=\int_0^{\frac{\pi}{2}} \ln\left(\cos x\right)\,dx
\end{align}
(change of variable $y=\dfrac{\pi}{2}-x$  )
\begin{align}
K&=\int_0^{\frac{\pi}{2}} \ln^2 \left(2\sin x\cos x\right)\,dx\\
&=\int_0^{\frac{\pi}{2}} \ln^2 \left(\sin\left(2x\right)\right)\,dx\\
\end{align}
Perform the change of variable $y=2x$,
\begin{align}
K&=\frac{1}{2}\int_0^{\pi} \ln^2 \left(\sin x\right)\,dx\\
&=\frac{1}{2}\int_0^{\frac{\pi}{2}} \ln^2 \left(\sin x\right)\,dx+\frac{1}{2}\int_{\frac{\pi}{2}}^\pi \ln^2 \left(\sin x\right)\,dx\\
\end{align}
In the latter integral perform the change of variable $y=\dfrac{\pi}{2}-x$ and recall $\sin\left(\pi-x\right)=\sin x$ for $x$ real,
\begin{align}
K&=\int_0^{\frac{\pi}{2}} \ln^2 \left(\sin x\right)\,dx\\
&=\int_0^{\frac{\pi}{2}} \ln^2 \left(\cos x\right)\,dx\\
&=J
\end{align}
On the other hand,
\begin{align}
K&=\int_0^{\frac{\pi}{2}}\left(\ln 2+\ln(\sin x)+\ln(\cos x)\right)^2 \,dx\\
&=\frac{\pi}{2}\ln^2 2+\int_0^{\frac{\pi}{2}}\ln^2(\sin x)\,dx+\int_0^{\frac{\pi}{2}}\ln^2(\cos x)\,dx+2\ln 2\int_0^{\frac{\pi}{2}}\ln(\cos x)\,dx+\\
&2\ln 2\int_0^{\frac{\pi}{2}}\ln(\sin x)\,dx+2\int_0^{\frac{\pi}{2}}\ln(\sin x)\ln(\cos x)\,dx\\
&=\frac{\pi}{2}\ln^2 2+2J+4\ln 2\int_0^{\frac{\pi}{2}}\ln(\cos x)\,dx+2\int_0^{\frac{\pi}{2}}\ln(\sin x)\ln(\cos x)\,dx\\
\end{align}
\begin{align}L&=\int_0^\infty \frac{\ln^2 x}{1+x^2}\,dx\end{align}
Perform the change of variable $x=\tan y$,
\begin{align}L&=\int_0^{\frac{\pi}{2}} \ln^2\left(\tan x\right)\,dx\\
&=\int_0^{\frac{\pi}{2}}\left(\ln\left(\sin x\right)-\ln\left(\cos x\right)\right)^2\,dx\\
&=2J-2\int_0^{\frac{\pi}{2}}\ln(\sin x)\ln(\cos x)\,dx\\
\end{align}
Therefore,
\begin{align}K+L&=\frac{\pi}{2}\ln^2 2+4J+4\ln 2\int_0^{\frac{\pi}{2}}\ln(\cos x)\,dx
\end{align}
Therefore (recall $K=J$),
\begin{align}J&=\frac{1}{3}L-\frac{\pi}{6}\ln^2 2-\frac{4}{3}\ln 2\int_0^{\frac{\pi}{2}}\ln(\cos x)\,dx\end{align}
On the other hand,
\begin{align}L&=\int_0^1 \frac{\ln^2 x}{1+x}\,dx+\int_1^\infty \frac{\ln^2 x}{1+x}\,dx\end{align}
In the latter integral perform the change of variable $y=\dfrac{1}{x}$,
\begin{align}L&=2\int_0^1 \frac{\ln^2 x}{1+x}\,dx\end{align}
But it is well known that,
\begin{align}\int_0^1 \frac{\ln^2 x}{1+x^2}\,dx&=\frac{\pi^3}{16}\\
\int_0^{\frac{\pi}{2}}\ln(\cos x)\,dx&=-\frac{1}{2}\pi\ln 2
\end{align}
Therefore,
\begin{align}J&=\frac{\pi^3}{24}-\frac{\pi}{6}\ln^2 2-\frac{4}{3}\ln 2\times -\frac{1}{2}\pi\ln 2\\
&=\boxed{\frac{\pi^3}{24}+\frac{1}{2}\pi\ln^2 2}\\
\end{align}
PS:
See: https://math.stackexchange.com/a/2942594/186817
(in this post i assume only the value of $\zeta(4)$ )

A: Since $$\sum_{n=0}^{\infty}\frac{H_n}{n+1} x^{n+1} =\frac{\log^2(1-x)}{2}$$ with $x \mapsto \sin^2 x$. and hence on integrating we obtain $$\int_0^{\frac{\pi}{2}}\log^2(\cos^2 x) dx = \pi\sum_{n=1}^{\infty}\frac{H_{n-1}}{n4^n}{2n\choose n}=\pi\sum_{n=1}^{\infty}\frac{H_n}{n4^n}{2n\choose n} -\pi\sum_{n=1}^{\infty}\frac{1}{n^24^n}{2n\choose n}$$ since the latter series $\mathcal{LS}$ is known whose value is $\displaystyle \zeta(2)-2\log^2(2)$ which is easily do able by computing the following integral $$2\int_0^1 \log\left(\frac{2}{\sqrt {1-x}+1}\right)\frac{dx}{x}=\zeta(2)-2\log^2(2)$$. Below I have derived the generating function for $\displaystyle \sum_{n\geq 1}{2n\choose n}\frac{y^n}{n^24^n}$

and to evaluate the former series $\mathcal{FS}$, we use the elementary integral $\displaystyle \int_0^1 x^{n-1} \log(1-x)dx =-\frac{H_n}{n}$ and generating function of central binomial coefficients $\displaystyle \sum_{n\geq 1} \frac{x^n}{4^n}{2n\choose n}=\frac{1}{\sqrt{1-x}}-1$ which we too use to calculate the latter series. Now, we just need to divide both sides by x, multiply $\log(1-x)$ and integrating from 0 to 1 gives $$-\mathcal{FS} =\int_0^1\frac{\log(1-x)}{x\sqrt{1-x}}dx-\int_0^1\frac{\log(1-x)}{x}dx=4\int_0^{\frac{\pi}{2}}\frac{\log(x)}{1-x^2} dx+\zeta(2)$$  since $$\int_0^1\frac{\log(1-x)}{x\sqrt {1-x}} dx=2\int_0^1\frac{\log\left(\sqrt{1-x}\right)}{x\sqrt{1-x}}dx\stackrel{\rm \sqrt{1-x}\mapsto x}{=}4\int_0^1\frac{\log(x)}{1-x^2}dx=-\frac{\pi^2}{2}$$ so $$\displaystyle -\pi\mathcal{FS}=\frac{\pi^3}{3},\; \pi\mathcal{LS} =\frac{\pi^3}{6}-2\pi\log^2(2)$$ and hence $-\pi\mathcal{FS}-\pi\mathcal{LS} =\frac{\pi^3}{6}+2\pi\log^2(2)$.

A: Getting rid of the first roadblock:
Use the fact that $$\log(a\cos x) = \log a + \log\cos x$$
along with the result that
$$
\int_0^{\pi/2} \log\cos x\,dx = -\frac{\pi}{2}\log 2
$$
to get
$$
F'(a) = \frac{\pi\log a}{a} -\frac{\pi}{2a}\log 2
$$

A: $\newcommand{\bbx}[1]{\,\bbox[15px,border:1px groove navy]{\displaystyle{#1}}\,}
 \newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack}
 \newcommand{\dd}{\mathrm{d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
 \newcommand{\ic}{\mathrm{i}}
 \newcommand{\mc}[1]{\mathcal{#1}}
 \newcommand{\mrm}[1]{\mathrm{#1}}
 \newcommand{\pars}[1]{\left(\,{#1}\,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,}
 \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
 \newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$

$\ds{I \equiv
\int_{0}^{\pi/2}\ln^{2}\pars{\cos^{2}\pars{x}}\,\dd x =
{\pi^{3} \over 6} + 2\pi\ln^{2}\pars{2}:\ {\LARGE ?}}$.

\begin{align}
I & \equiv
\bbox[10px,#ffd]{\int_{0}^{\pi/2}\ln^{2}\pars{\cos^{2}\pars{x}}\,\dd x}
\,\,\,\stackrel{x\ \mapsto\ \pi/2\ -\ x}{=}\,\,\,
4\int_{0}^{\pi/2}\ln^{2}\pars{\sin\pars{x}}\,\dd x
\\[5mm] & =
\left.4\,\Re\int_{x\ =\ 0}^{x\ =\ \pi/2}\ln^{2}\pars{{1 - z^{2} \over 2z}\,\ic}\,{\dd z \over \ic z}
\,\right\vert_{\ z\ =\ \exp\pars{\ic x}}
\\[5mm] & =
\left.4\,\Im\int_{x\ =\ 0}^{x\ =\ \pi/2}\ln^{2}\pars{{1 - z^{2} \over 2z}\,\ic}\,{\dd z \over z}
\,\right\vert_{\ z\ =\ \exp\pars{\ic x}}
\\[1cm] & \stackrel{\mrm{as}\ \epsilon\ \to\ 0^{+}}{\sim}\,\,\,
-\, 4\,\
\overbrace{\Im\int_{1}^{\epsilon}\ln^{2}
\pars{1 + y^{2} \over 2y}\,{\dd y \over y}}^{\ds{=\ \large 0}}
\\[2mm] & \phantom{\stackrel{\mrm{as}\ \epsilon\ \to\ 0^{+}}{\sim}\,\,\,\,\,\,\,} -
4\,\Im\int_{\pi/2}^{0}\bracks{\ln\pars{1 \over 2\epsilon} + \pars{{\pi \over 2} - \theta}\ic}^{2}\,\ic\,\dd\theta
\\[2mm] & \phantom{\stackrel{\mrm{as}\ \epsilon\ \to\ 0^{+}}{\sim}\,\,\,\,\,\,\,\,}
-4\,\Im\int_{\epsilon}^{1}\bracks{\ln\pars{1 - x^{2} \over 2x} + {\pi \over 2}\,\ic}^{2}{\dd x \over x}
\\[1cm] & =
4\int_{0}^{\pi/2}\bracks{\ln^{2}\pars{2\epsilon} -
\pars{{\pi \over 2} - \theta}^{2}}\,\dd\theta
-4\pi\int_{\epsilon}^{1}\ln\pars{1 - x^{2} \over 2x}
{\dd x \over x}
\\[5mm] & \stackrel{\mrm{as}\ \epsilon\ \to\ 0^{+}}{\sim}
\bracks{2\pi\ln^{2}\pars{2\epsilon} - {\pi^{3} \over 6}} -
\bracks{4\pi\int_{0}^{1}{\ln\pars{1 - x^{2}} \over x}\,\dd x -
4\pi\int_{\epsilon}^{1}{\ln\pars{2x} \over x}\,\dd x}
\\[5mm] & =
\bracks{2\pi\ln^{2}\pars{2\epsilon} - {\pi^{3} \over 6}} -
\bracks{2\pi\int_{0}^{1}{\ln\pars{1 - x} \over x}\,\dd x +
2\pi\ln\pars{\epsilon}\ln\pars{4\epsilon}}
\\[5mm] & \stackrel{\mrm{as}\ \epsilon\ \to\ 0}{\to}
\bbx{{\pi^{3} \over 6} + 2\pi\ln^{2}\pars{2}} \approx
8.1865
\end{align}

Note that
  $\ds{\int_{0}^{1}{\ln\pars{1 - x} \over x}\,\dd x =
-\,\mrm{Li}\pars{1} = -\,{\pi^{2} \over 6}}$.

A: Noting that $$
\int_{0}^{\frac{\pi}{2}} \ln ^{2}\left(\cos ^{2} x\right) d x=4 \int_{0}^{\frac{\pi}{2}} \ln ^{2}(\cos x) dx
$$
Let $$
I:=\int_{0}^{\frac{\pi}{2}} \ln ^{2}(\cos x) d x \stackrel{x\mapsto\frac{\pi}{2}-x}{=} \int_{0}^{\frac{\pi}{2}} \ln ^{2}(\sin x) d x
$$
Using the identity $$[\ln (\sin x)+\ln (\cos x)]^{2}+[\ln (\sin x)-\ln (\cos x)]^{2}
=2\left[\ln ^{2}(\sin x)+\ln ^{2}(\cos x)\right],$$
we have $$
4 I=\underbrace{\int_{0}^{\frac{\pi}{2}} \ln ^{2}\left(\frac{\sin 2 x}{2}\right)}_{J} d x+\underbrace{\int_{0}^{\frac{\pi}{2}} \ln ^{2}(\tan x) d x}_{K}
$$
For the first integral, using $\int_{0}^{\frac{\pi}{2}} \ln (\sin x) d x=-\dfrac{\pi}{2} \ln 2$ yields
$$
\begin{aligned}
J &=\int_{0}^{\frac{\pi}{2}}[\ln (\sin 2 x)-\ln 2]^{2} d x \\
&=\int_{0}^{\frac{\pi}{2}} \ln ^{2}(\sin 2 x) d x-2 \ln 2 \int_{0}^{\frac{\pi}{2}} \ln (\sin 2 x) d x +\frac{\pi \ln ^{2} 2}{2} \\
& \stackrel{x\mapsto 2x}{=}  \frac{1}{2} \int_{0}^{\pi} \ln ^{2}(\sin x) d x-\ln 2 \int_{0}^{\pi} \ln (\sin x) d x+\frac{\pi \ln ^{2} 2}{2} \\
& \stackrel{symmetry}{=}  I-\ln 2(-\pi \ln 2)+\frac{\pi \ln ^{2} 2}{2} \\
&=I+\frac{3 \pi \ln ^{2} 2}{2}
\end{aligned}
$$
For the second integral, letting $y=\tan x $
and using the post, yields $$
\int_{0}^{\infty} \frac{\ln ^{2} y}{1+y^{2}} d y=\frac{\pi^{3}}{8},
$$
then
$$
4I=I+\frac{3 \pi  \ln ^{2} 2}{2}+\frac{\pi^{3}}{8} \Rightarrow I=\frac{\pi^{3}}{24}+\frac{\pi \ln ^{2} 2}{2}
$$
Hence
$$\boxed{\int_{0}^{\frac{\pi}{2}} \ln ^{2}\left(\cos ^{2} x\right) d x= \frac{\pi^{3}}{6}+2 \pi \ln ^{2} 2}$$


text:
Q: 16bit to bcd conversion I'm trying to make a 16bit to BCD conversion.
I have found this link for a 8 bit and I'm trying to convert it to 16 bits.
http://vhdlguru.blogspot.nl/2010/04/8-bit-binary-to-bcd-converter-double.html
I don't know what im doing wrong the rpm_1000 keeps changing and the rpm_100 stays at 4. Does anyone have a idea what i did wrong?
process (Hex_Display_Data)
        variable i : integer:=0;
        variable bcd : std_logic_vector(19 downto 0) := (others => '0');
        variable bint : std_logic_vector(15 downto 0) := Hex_Display_Data;

    begin
        for i in 0 to 15 loop  -- repeating 16 times.
        bcd(19 downto 1) := bcd(18 downto 0);  --shifting the bits.
        bcd(0) := bint(15); -- shift bit in
        bint(15 downto 1) := bint(14 downto 0); --removing msb
        bint(0) :='0'; -- adding a '0'

        if(i < 15 and bcd(3 downto 0) > "0100") then --add 3 if BCD digit is greater than 4.
        bcd(3 downto 0) := bcd(3 downto 0) + "0011";
        end if;

        if(i < 15 and bcd(7 downto 4) > "0100") then --add 3 if BCD digit is greater than 4.
        bcd(7 downto 4) := bcd(7 downto 4) + "0011";
        end if;

        if(i < 15 and bcd(11 downto 8) > "0100") then  --add 3 if BCD digit is greater than 4.
        bcd(11 downto 8) := bcd(11 downto 8) + "0011";
        end if;

        if(i < 15 and bcd(15 downto 12) > "0100") then  --add 3 if BCD digit is greater than 4.
        bcd(15 downto 12) := bcd(15 downto 12) + "0011";
        end if;

    end loop;

    rpm_1000    <= bcd(15 downto 12);
    rpm_100     <= bcd(11 downto 8);
    rpm_10      <= bcd(7 downto 4);
    rpm_1       <= bcd(3 downto 0);

end process ;

A: Note four BCD digits can be wholly contained in 14 bits of input (your Hex_Display_Data) and unused bcd 'bits' (19 downto 16) will get eaten during synthesis along with all the add 3's that can't occur because their upper two bits are '0's (not > 4).
If you constrain your bcd value to 4 hex digits, and your loop iteration to 14 bits:
library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;

entity bin2bcd is
    port (
        input:      in   std_logic_vector (15 downto 0);
        ones:       out  std_logic_vector (3 downto 0);
        tens:       out  std_logic_vector (3 downto 0);
        hundreds:   out  std_logic_vector (3 downto 0);
        thousands:  out  std_logic_vector (3 downto 0)
    );
end entity;

architecture fum of bin2bcd is
    alias Hex_Display_Data: std_logic_vector (15 downto 0) is input;
    alias rpm_1:    std_logic_vector (3 downto 0) is ones;
    alias rpm_10:   std_logic_vector (3 downto 0) is tens;
    alias rpm_100:  std_logic_vector (3 downto 0) is hundreds;
    alias rpm_1000: std_logic_vector (3 downto 0) is thousands;
begin
    process (Hex_Display_Data)
        type fourbits is array (3 downto 0) of std_logic_vector(3 downto 0);
        -- variable i : integer := 0;  -- NOT USED
        -- variable bcd : std_logic_vector(15 downto 0) := (others => '0');
        variable bcd:   std_logic_vector (15 downto 0);
        -- variable bint : std_logic_vector(15 downto 0) := Hex_Display_Data;
        variable bint:  std_logic_vector (13 downto 0); -- SEE process body
    begin
        bcd := (others => '0');      -- ADDED for EVERY CONVERSION
        bint := Hex_Display_Data (13 downto 0); -- ADDED for EVERY CONVERSION

        for i in 0 to 13 loop
            bcd(15 downto 1) := bcd(14 downto 0);
            bcd(0) := bint(13);
            bint(13 downto 1) := bint(12 downto 0);
            bint(0) := '0';

            if i < 13 and bcd(3 downto 0) > "0100" then
                bcd(3 downto 0) :=
                    std_logic_vector (unsigned(bcd(3 downto 0)) + 3);
            end if;
            if i < 13 and bcd(7 downto 4) > "0100" then
                bcd(7 downto 4) :=
                    std_logic_vector(unsigned(bcd(7 downto 4)) + 3);
            end if;
            if i < 13 and bcd(11 downto 8) > "0100" then
                bcd(11 downto 8) :=
                    std_logic_vector(unsigned(bcd(11 downto 8)) + 3);
            end if;
            if i < 13 and bcd(15 downto 12) > "0100" then
                bcd(11 downto 8) :=
                    std_logic_vector(unsigned(bcd(15 downto 12)) + 3);
            end if;
        end loop;

        (rpm_1000, rpm_100, rpm_10, rpm_1)  <=
                  fourbits'( bcd (15 downto 12), bcd (11 downto 8),
                               bcd ( 7 downto  4), bcd ( 3 downto 0) );
    end process ;
end architecture;

Note the use of aliases to enable your names to be used in an existing otherwise compatible Minimal, Complete and Verifiable Example which your question did not provide.
Aggregate signal assignment is also taken from the original, your assignment to the individual digits should work just fine.
There are two changes besides limiting the conversion to 14 bits and the number of BCD digits to match the number of digits output.
The bcd and bint variables are now cleared every time the process is resumed (sensitive to updates to Hex_Display_Data). These were causing causing your otherwise unverifiable errors more than likely.
Extraneous parentheses have been removed.
You didn't supply context clauses. The code shown uses package numeric_std as opposed to the -2008 numeric_std_unsigned offering compatibility with earlier revisions of the standard while using IEEE authored packages.
You'll get something that works, provable with a testbench:
library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;

entity bin2bcd_tb is
end entity;

architecture foo of bin2bcd_tb is
    signal input:      std_logic_vector (15 downto 0) := (others => '0');
    signal ones:       std_logic_vector (3 downto 0);
    signal tens:       std_logic_vector (3 downto 0);
    signal hundreds:   std_logic_vector (3 downto 0);
    signal thousands:  std_logic_vector (3 downto 0);
begin
DUT:
    entity work.bin2bcd
        port map (
            input => input,
            ones => ones,
            tens => tens,
            hundreds => hundreds,
            thousands => thousands
        );
STIMULUS:
    process
    begin
        for i in 0 to 1001 loop
            wait for 20 ns;
            input <= std_logic_vector(to_unsigned(9999 - i, 16));
        end loop;
        wait for 20 ns;
        wait;
    end process;
end architecture;

Some other stimulus scheme can be used to toggle BCD digit roll over of all four digits.
This testbench provides input values starting at 9999 and decrementing 1001 times to show all four digits transitioning:

I can easily be modified to prove every transition of every BCD digit.
In summary the errors you were encountering appear to have come from the difference in elaboration for variables in a subprogram, where bcd and bint would be dynamically elaborated and initialized every function call, and in the process where they would be only initialized once.
From examining Xilinx's User Guide 901 Vivado Design Suite User Guide, Synthesis (2015.3), Chapter 4: VHDL Support, Combinatorial Processes, case Statements, for-loop Statements, the for loop appears to be supported for synthesis and has been reported to be synthesis eligible in other double dabble questions on stackoverflow. The issue would be support for repetitive assignment to variables in repeated sequences of sequential statements, which should be supported. There are is at least one other double dabble question on stackoverflow where successful synthesis had been reported using such a for loop.
Note that constraining the input value you deal with to 14 bits doesn't detect the effects of larger  binary numbers (> 9999) which your process does not otherwise do either providing only 4 BCD output digits. You could deal with that by checking if the input value is greater than 9999 (x"270F").
The + 3 represents 1 LUT depth in an FPGA (4 bit input, 4 bit output), there are some number of them layered in depth based on the size of the converted number (the range of i). Allowing time for conversion propagation through ADD3's is offset by the rate at which the display can be visually interpreted. If you updated Hex_Display_Data in the millisecond range you likely could not tell the difference visually.

A: Running the loop 16 times will cause the value in the BCD registers to be multiplied by 65536 (mod 100000) and added to the value in the binary registers.  Say the value is 4000.  Then 4000x65536 yields 44000.  44000x65536 yields 84000.  84000x65536 yields 24000.  24000x65536 yields 64000.  And 64000x65536 yields 4000.
To make the algorithm work, you must start out by clearing the BCD registers.  It also wouldn't hurt to fix the comment about how many times your loop runs.
Incidentally, a practical implementation of a binary to BCD converter should generally accept a clock input, and perform one step for each active clock edge.  If your VHDL is running entirely in simulation the complexity of the resulting logic won't matter, but trying to perform everything at once in real hardware will be rather expensive.  By contrast, the hardware to do a simple shift of the binary number and a multiply-by-two of the BCD number will be much simpler.  Note that if you do things "all at once", the most significant bit of the output will depend upon the second-least-significant bit of the input, meaning the input signal will have to propagate through all the logic in one step.  By contrast, if you shift by one bit per clock cycle, each bit of the output will depend only upon at most four bits of the input (since each digit will be in the range 0-9 before the adjustment phase, adding 3 will never cause a carry out).
Also, the "double dabble" algorithm requires that the adjustment be performed before the BCD shifts, but it looks as though the code is performing the adjustment after.  Doing the adjustment after is fine if one looks at bit
ranges 16..13, 12..9, 8..5, and 4..1 rather than 15..12, etc.  Alternatively, one could specify that the value of bits 19..17 should be the value of bits 18..16, the value of bits 16..13 should be either the value of bits 15..12 (if less than 5) or the value of bits 15..12, plus three (if greater), etc.  Such a formulation would set the value of each bit in exactly one place, which would make it easier to see how it should be rendered into hardware.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why does this xpath fail using lxml in python? Here is an example web page I am trying to get data from.
http://www.makospearguns.com/product-p/mcffgb.htm
The xpath was taken from chrome development tools, and firepath in firefox is also able to find it, but using lxml it just returns an empty list for 'text'.
from lxml import html
import requests

site_url = 'http://www.makospearguns.com/product-p/mcffgb.htm'
xpath = '//*[@id="v65-product-parent"]/tbody/tr[2]/td[2]/table[1]/tbody/tr/td/table/tbody/tr[2]/td[2]/table/tbody/tr[1]/td[1]/div/table/tbody/tr/td/font/div/b/span/text()'

page = requests.get(site_url)
tree = html.fromstring(page.text)
text = tree.xpath(xpath)

Printing out the tree text with
print(tree.text_content().encode('utf-8'))

shows that the data is there, but it seems the xpath isn't working to find it. Is there something I am missing? Most other sites I have tried work fine using lxml and the xpath taken from chrome dev tools, but a few I have found give empty lists.

A: The xpath is simply wrong
Here is snippet from the page:
<form id="vCSS_mainform" method="post" name="MainForm" action="/ProductDetails.asp?ProductCode=MCFFGB" onsubmit="javascript:return QtyEnabledAddToCart_SuppressFormIE();">

Home >

You can see, that element with id being "v65-product-parent" is of typetableand has subelementtr`.
There can be only one element with such id (otherwise it would be broken xml).
The xpath is expecting tbody as child of given element (table) and there is none in whole page.
This can be tested by
>>> "tbody" in page.text
False

How Chrome came to that XPath?
If you simply download this page by
$ wget http://www.makospearguns.com/product-p/mcffgb.htm

and review content of it, it does not contain a single element named tbody
But if you use Chrome Developer Tools, you find some.
How it comes here?
This often happens, if JavaScript comes into play and generates some page content when in the browser. But as LegoStormtroopr noted, this is not our case and this time it is the browser, which modifies document to make it correct.
How to get content of page dynamically modified within browser?
You have to give some sort of browser a chance. E.g. if you use selenium, you would get it.
byselenium.py
from selenium import webdriver
from lxml import html

url = "http://www.makospearguns.com/product-p/mcffgb.htm"
xpath = '//*[@id="v65-product-parent"]/tbody/tr[2]/td[2]/table[1]/tbody/tr/td/table/tbody/tr[2]/td[2]/table/tbody/tr[1]/td[1]/div/table/tbody/tr/td/font/div/b/span/text()'

browser = webdriver.Firefox()
browser.get(url)
html_source = browser.page_source
print "test tbody", "tbody" in html_source

tree = html.fromstring(html_source)
text = tree.xpath(xpath)
print text

what prints
$ python byselenimum.py
test tbody True
['$149.95']

Conclusions
Selenium is great when it comes to changes within browser. However it is a bit heavy tool and if you can do it simpler way, do it that way. Lego Stormrtoopr have proposed such a simpler solution working on simply fetched web page.

A: 1. Browsers frequently change the HTML
Browsers quite frequently change the HTML served to it to make it "valid". For example, if you serve a browser this invalid HTML:

bad paragraph

Note that cells and rows can be unclosed (and valid) in HTML

To render it, the browser is helpful and tries to make it valid HTML and may convert this to:

bad paragraph

      Note that cells and rows can be unclosed (and valid) in HTML

The above is changed because
aragraphs cannot be inside
s and
s are recommended. What changes are applied to the source can vary wildly by browser. Some will put invalid elements before tables, some after, some inside cells, etc...
2. Xpaths aren't fixed, they are flexible in pointing to elements.
Using this 'fixed' HTML:

bad paragraph

      Note that cells and rows can be unclosed (and valid) in HTML

If we try to target the text of  cell, all of the following will give you approximately the right information:
//td
//tr/td
//tbody/tr/td
/table/tbody/tr/td
/table//*/text()

And the list goes on...
however, in general browser will give you the most precise (and least flexible) XPath that lists every element from the DOM. In this case:
/table[0]/tbody[0]/tr[0]/td[0]/text()

3. Conclusion: Browser given Xpaths are usually unhelpful
This is why the XPaths produced by developer tools will frequently give you the wrong Xpath when trying to use the raw HTML.
The solution, always refer to the raw HTML and use a flexible, but precise XPath.
Examine the actual HTML that holds the price:

                        Price:
                        $149.95

            <input type="image" src="/v/vspfiles/templates/MAKO/images/buttons/btn_updateprice.gif" name="btnupdateprice" alt="Update Price" border="0"/>

If you want the price, there is actually only one place to look!
//span[@itemprop="price"]/text()

And this will return:
$149.95

A: I had a similar issue (Chrome inserting tbody elements when you do Copy as XPath). As others answered, you have to look at the actual page source, though the browser-given XPath is a good place to start. I've found that often, removing tbody tags fixes it, and to test this I wrote a small Python utility script to test XPaths:
#!/usr/bin/env python
import sys, requests
from lxml import html
if (len(sys.argv) < 3):
     print 'Usage: ' + sys.argv[0] + ' url xpath'
     sys.exit(1)
else:
    url = sys.argv[1]
    xp = sys.argv[2]

page = requests.get(url)
tree = html.fromstring(page.text)
nodes = tree.xpath(xp)

if (len(nodes) == 0):
     print 'XPath did not match any nodes'
else:
     # tree.xpath(xp) produces a list, so always just take first item
     print (nodes[0]).text_content().encode('ascii', 'ignore')

(that's Python 2.7, in case the non-function "print" didn't give it away)


text:
Q: add tkinter variable via function to dictionary I created a function to add labels (or other tkinter elements to a specific frame). The same function also adds a tkinter variable to a dictionary for better access within the program. Now, there are more than  200 variables within the dictionary and i decided to split them to settings and parameters.
How can i tell the function to eiter add the variable to the settings-dict (my_settings) or to add it to parameters-dict (my_params)?
import tkinter as tk

masterframe = tk.Tk()

my_settings = dict()    # unused
my_params   = dict()

def add_label(frame, key, default=None):
    my_params[key] = tk.StringVar()
    my_params[key].set(default)
    inputframe=tk.Frame(frame)
    inputframe.pack(side='top', padx=5, pady=5, fill='x')
    label = tk.Label(inputframe, text=key, width=10)
    label.pack(side='left')
    label = tk.Label(inputframe, textvariable=my_params[key], width=10)
    label.pack(side='left')

add_label(masterframe, 'a', '123')
add_label(masterframe, 'b', '456')
add_label(masterframe, 'c', '789')

masterframe.mainloop()

A: You can do this by adding a group parameter to add_label. I've used 'p' for params and 's' for settings, but it can be anything. It then uses an if statement to determine which dictionary to add it to.
def add_label(frame, key, group, default=None):
    if group == 'p':
        d = my_params
    elif group == 's':
        d = my_settings
    d[key] = tk.StringVar()
    d[key].set(default)
    inputframe=tk.Frame(frame)
    inputframe.pack(side='top', padx=5, pady=5, fill='x')
    label = tk.Label(inputframe, text=key, width=10)
    label.pack(side='left')
    label = tk.Label(inputframe, textvariable=d[key], width=10)
    label.pack(side='left')

add_label(masterframe, 'a', 'p', '123')
add_label(masterframe, 'b', 's', '456')
add_label(masterframe, 'c', 's', '789')

A: Are you trying to do something like this?:
import tkinter as tk

masterframe = tk.Tk()

my_settings = dict()
my_params   = dict()

def add_label(frame, key, default=None, setting=False):
    # If the keyword setting is True, `my_settings` will be updated. Otherwise `my_params` will be updated.
    var = tk.StringVar()
    var.set(default)
    inputframe=tk.Frame(frame)
    inputframe.pack(side='top', padx=5, pady=5, fill='x')
    label = tk.Label(inputframe, text=key, width=10)
    label.pack(side='left')
    label = tk.Label(inputframe, textvariable=var, width=10)
    label.pack(side='left')

    # Append it to the dict
    if setting:
        my_settings.update({key: var})
    else:
        my_params.update({key: var})

add_label(masterframe, 'a', '123')
add_label(masterframe, 'b', '456')
add_label(masterframe, 'c', '789')
add_label(masterframe, 'setting', '789', setting=True)

print(my_params)
print(my_settings)

masterframe.mainloop()

I think you should look at some dict tutorials.


text:
Q: Looking to format column names to dates after reading in a CSV When I read in data from a CSV file, the column names return in this format:
X2017.04, X2017.05, X2017.06

I'm looking to format it as (or something similar to):
April-2017, May-2017, June-2017

Currently, I've tried for loops to iterate through the entire data set and reformat everything using as.Date() or as.yearmon and some of them have worked, kinda.
as.yearmon returned 1997.333333333 and similar looking floats. The as.Date code I tried returned blank values.
I'm relatively new/novice level in R and could use some help.
Thank you!

A: Using as.yearmon you can try :
names(df) <- zoo::as.yearmon(names(df), 'X%Y.%m')

Or in base R pasting an arbitrary date :
names(df) <- format(as.Date(paste0(names(df), '.01'), 'X%Y.%m.%d'), '%b-%Y')

As an example :
x <- c('X2017.04', 'X2017.05', 'X2017.06')
format(as.Date(paste0(x, '.01'), 'X%Y.%m.%d'), '%b-%Y')
#[1] "Apr-2017" "May-2017" "Jun-2017"

A: We can use
library(lubridate)
format(ymd(sub('^X', "", x,), truncated = 2), '%b-%Y')
#[1] "Apr-2017" "May-2017" "Jun-2017"

data
x <- c('X2017.04', 'X2017.05', 'X2017.06')


text:
Q: CKEditor file upload with wrong file encoding (not UTF-8) I am using PHP 5.6 on Windows IIS. When creating a link and uploading a file for that link through ckeditor, file name on server is not with special characters like: ČĆŽŠĐ. Problem is only when uploading files through ckeditor. When uploading text to database, there is no problem with the encoding. How can I make ckeditor to maybe tell server the right encoding, maybe to include encoding i request, or whatever I need to do to make it work? This PHP encoding is a nightmare!
I've fixed it with this:
iconv("utf-8", "cp1250", $_FILES['upload']['name'])

But, is there no way I can tell PHP to just treat everything as UTF-8? I've tried setting every single setting regarding encoding and codepage in php.ini to UTF-8 and it did not help. It really seems inconsistent and finicky. Any PHP experts that can tell me the simple solution to this mess?
These are the upload headers:
POST https://nsdmup-a.hr/cms/news_fileupload.php?CKEditor=fullText&CKEditorFuncNum=1&langCode=en HTTP/1.1
Host: nsdmup-a.hr
Connection: keep-alive
Content-Length: 1069214
Cache-Control: max-age=0
Origin: https://nsdmup-a.hr
Upgrade-Insecure-Requests: 1
Content-Type: multipart/form-data; boundary=----WebKitFormBoundarysc0FA4jsjDe2Z4s8
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
Referer: https://nsdmup-a.hr/cms/news_add.php?editId=293
Accept-Encoding: gzip, deflate, br
Accept-Language: hr-HR,hr;q=0.9,en-US;q=0.8,en;q=0.7,sr;q=0.6,bs;q=0.5,ja;q=0.4
Cookie: PHPSESSID=45iuc1r017sb75bte57dl0te71

------WebKitFormBoundarysc0FA4jsjDe2Z4s8
Content-Disposition: form-data; name="upload"; filename="511-D-022-2018. dopis ministru - zapšljavanje namještenika2.pdf"
Content-Type: application/pdf

This is the file name he wrote to disk:
"511-D-022-2018. dopis ministru - zapšljavanje namještenika2.pdf"

A: To my experience, this is a problem with Windows and all PHP versions up until v7.0
So, either you continue using iconv function or upgrade PHP to at least v7.1 (changelog regarding Windows)
You can also create a helper function with contents like this:
if (version_compare(phpversion(), '7.1.0', '<') and strtoupper(substr(php_uname('s'), 0, 3)) === 'WIN')
{
    // Windows and PHP 7.0 or less. Use iconv
    return iconv('utf-8', 'cp1250', $filename);
}
else
{
    // Should be all good
    return $filename;
}


text:
Q: Обработка запросов Flask В процессе работы возник вопрос, а как Flask обрабатывает запросы. Точнее может ли быть такая ситуация, что одновременно обрабатываются несколько запросов или они берутся из очереди и выполняются последовательно? Стоит ли при работе с базой данных учитывать случай, когда начинает выполняться два параллельных запроса?

A: Вот тут можно найти более детальное объяснение: http://flask.pocoo.org/docs/1.0/reqcontext/
Но:
 1. Параллельно, каждый запрос в своем котексте.
 2. Да, если 2 пользователя одновременно запросили данные по адресу.
 3. Только если вы пишете данные и возможно состояние коллизии. Если вы, например, добавляете временную сессию пользователя и индексное поле в БД имеет тип autoincrement или просто проверяяете логин пароль, то не обязательно. Или если несколько пользователей никогда не будут работать с одним набором данных.
Но вообще лучше всегда использовать транзации, в случае update/delete.


text:
Q: Reformat my paper from one LaTex format to another LaTex format I am very new to LaTex. One reason I switched to it was to have an easy way to reformat my papers based on the templates provided by different publishers.
Then I don't know yet, laTex provide that convenience for me or not. For example Suppose I have a paper based on the laTex template by IEEE. Then I want to send it to another journal named IJCA, the IJCA give me their specific laTex template.
What is the easiest way to convert my paper (in IEEE format) to XXX format? Is there any automatic conversion tool for that? I just began to use WinEDT and can edit and compile latex files, what is the next step?
I give an example of two templates
IEEE:
\author{\IEEEauthorblockN{Michael Shell}
\IEEEauthorblockA{School of Electrical and\\Computer Engineering\\
Georgia Institute of Technology\\
Atlanta, Georgia 30332--0250\\
Email: http://www.michaelshell.org/contact.html}
\and
\IEEEauthorblockN{Homer Simpson}
\IEEEauthorblockA{Twentieth Century Fox\\
Springfield, USA\\
Email: homer@thesimpsons.com}
\and
\IEEEauthorblockN{James Kirk\\ and Montgomery Scott}
\IEEEauthorblockA{Starfleet Academy\\
San Francisco, California 96678-2391\\
Telephone: (800) 555--1212\\
Fax: (888) 555--1212}}

IJCA:
\author{
   \large 1st Author \\[-3pt]
   \normalsize 1st author's affiliation  \\[-3pt]
    \normalsize 1st line of address \\[-3pt]
    \normalsize 2nd line of address \\[-3pt]
    \normalsize 1st author's email address \\[-3pt]
  \and
   \large 2nd Author \\[-3pt]
   \normalsize 2nd author's affiliation  \\[-3pt]
    \normalsize 1st line of address \\[-3pt]
    \normalsize 2nd line of address \\[-3pt]
    \normalsize 2nd author's email address \\[-3pt]
\and
   \large 3rd Author \\[-3pt]
   \normalsize 3rd author's affiliation  \\[-3pt]
    \normalsize 1st line of address \\[-3pt]
    \normalsize 2nd line of address \\[-3pt]
    \normalsize 3rd author's email address \\[-3pt]
}
.......
\section{USING THE  ijca Article  CLASS FILE}

If the file \verb ijcaArticle.cls  is not already in the appropriate system directory
for \LaTeX{} files, either arrange for it to be put there or copy
it to your working directory. The \verb ijcaArticle  document class is implemented
as a complete class, not a document style option. In order to
use the \verb ijcaArticle  document class, replace \verb article  by \verb ijcaArticle  in the
\verb \documentclass  command at the beginning of your document:
\vskip 6pt
\begin{centering}
    \verb \documentclass{article}  \end{centering}
\vskip 6pt
replace by
\vskip 6pt
 \verb \documentclass{ijcaArticle}  \vskip 6pt
In general, the following standard document \verb style  options should
{ \itshape not} be used with the {\footnotesize \itshape article} class file:
\begin{enumerate}
\item[(1)] \verb 10pt,  \verb 11pt,  \verb 12pt   – unavailable;
\item[(2)] \verb twoside  (no associated style file) – \verb twoside  is the default;
\item[(3)] \verb fleqn, \verb leqno, \verb titlepage – should not be used;
\end{enumerate}

\section{Additional Document Style Options}
\label{sec:additional_doc}
%

I don't know much the latTex tags, then I prefer an automatic conversion tool which matches the tags and convert them to each other. At least does a preprocessing on them.

A: The conversion could be as automatic as change (manually) article by paper in the first line, or  a nightmare, or really impossible. The automatic conversion, in general, is impossible.
Let go with a simple example as proof-of-concept of the problem, with the very standard class book:
\documentclass{book}
\begin{document}
\chapter{Hello}
\end{document}

Work perfectly. Now, imagine that you want change the format to another very standard class:
\documentclass{article}
\begin{document}
\chapter{Hello}
\end{document}

But that simple document cannot be compiled. The reason is a  "undefined control sequence" error reading \chapter. That is, LaTeX do not know nothing about the supposedly well-know command \chapter. It is not hard coded in the TeX engines but defined in the document class book.
This is a big problem for a conversion tool. What to do if the command of one class (book) is not defined in another (article)? Just pass the  definition to the new template? In this case have not sense. Well, then ... Ignore it? Down the header one level? Left as bold font?
This mean that the tool must have a predefined solution for every command in every new class.
Moreover, in this case the control sequence (command) is defined (directly or not) in the document class (.cls files),  but the definition could be located also in any of the included packages (.sty files), or children .tex files (using \input{} in the preample, for example) or directly in the preamble.
Think about known only the uncountable number of control sequences of the  thousands of  packages in  CTAN ... And what to do with user-defined control sequences like \def\myowncommand{Hello}?
A template conversion only can be compiled when all the definitions of the  commands used in the old document (even the dull  \myowncommand) are maintained or redefined in the new template.
Some commands works in all type of documents because they are hard coded in the LaTeX engine. These are mainly TeX primitives and some others that you can use even in a "unclassified document". For example, With  pdfLaTeX document you can make a PDF with only some like:
% This is no a code chunk, but a complete MWE
\def\normalsize{\normalfont}
\begin{document}
Hello, {\em World}\par
Try me without a document class.
\end{document}

Here we must define \normalsize in some way to avoid an error in the initialization process, since there are not any \documentclass, but then we can use the commands that obviously do not pertain to any class or package.
The minimal class do not make much more than a (re)definition of  \normalsize, so is  hidden in minimal.cls. The the above MWE is almost equivalent to:
\documentclass{minimal}
\begin{document}
Hello, {\em World}\par
Try me without a document class.
\end{document}

This class have no utility for any real work, but show you what is not a "universally accessible" command. You may be surprised that commands as \section{} cannot be used here. Then \section{} is a control sequence specific of some type of document, without operating warranty in any  template.
Said that, the conversion often is very easy. With very specific (user-defined) commands you must be careful in maintain any auxiliar file like mymacros.tex, the row of the preample with \input{mymacros} in the main document or the preamble definitions starting with   \newcommand, \def and so on.
Most time, the problem of a undefined but well-known command is that you have lost in the conversion some package. That is, a undefined \includegraphics mean that you have lost \usepackage{graphicx} in the preamble, so it is a problem easy to solve.
The plight  become more obscure when the package was not loaded directly  but through another package or even the document class of the original template, but the after some research about the real origin, the solution is the same.
The worst problem is the command is defined at the document class level, like \chapter{}, because you cannot load a book class inside an article document, for example. Fortunately, most usual  commands like \section{}are defined in almost all any document class, so the problem in practice is limited to a few commands of less standard clases, like \institution{} of paperclass, that are not defined in article and other common clases.
Then the solution for a undefined command, for example said the command  \xxx{}  with one argument, could be:

*

*Remove, comment o replace  manually every \xxx{} with another command to follow  strictly the new template. Probably the best solution.

*Copy the original definition \xxx from the old document class and use it in your custom class, package, preamble or children file. But this is only part of the problem. The other is make this without breaking anything else and ruin the layout. Do not try if you do not know what are you doing.

*Define \xxx as something simple and inoffensive. For example:

*

*\newcommand\xxx{} (do nothing)

*\newcommand\xxx[1]{#1} (print the argument as plain text). After check the result, try to modify your own definition with a more elaborated format of the argument (some like \newcommand\xxx[1]{\par\bfseries #1\par\bigskip} if really is needed.

Finally, take into account that probably the editor of a journal will not be happy with the second or third solution.

A: In general each template writer can do pretty much whatever they want. For example I know one that forced a special paragraph command between each of their paragraphs. So in the worst case scenario it can be a pain.
In practice though I think you will find that it is mostly enough to just change document class and maybe do some other minor things.
But I don't think there are any general answers to this question.


text:
Q: how to add css code on jquery? i have a part of css code, how can i add this css with jquery ?
div#menu li:hover>div {
    visibility: visible;
}

A: Although Sarfraz and Anthony's answers would work there are a couple of points to note.
1) To hide/show you are better just using the hide() and show() mothods available on a jQuery object.
So,
$("div#menu li:hover>div").show();

2) Try to use css classes instead, rather than direct use of the .css() function
3) With your selector, div#menu is pointless. An id selector is faster. All you do when you put the element selector div in front of it is slow it down:
$("#menu li:hover>div").show();

Also, start accepting answers and voting. It good courtesy - It earns people points, which they like, and makes them more inclined to help you in future.

A: If I'm not mistaken, the following should work with the newest version of jquery:
 $("div#menu li:hover>div").css("visibility","visible")

A: ........
 $('selector').css('visibility', 'visible')

A: Please check this link
http://remysharp.com/2008/10/17/jquery-really-visible/
The Problem with :visible
The :visible selector works fine if you're asking whether the particular element has been set to invisible (either via the display or visibility CSS style).
However, if the element is hidden because a parent element is set to hidden, the :visible selector returns a false positive.


text:
Q: Crystal for ATMEGA32u4 Not Working I have been trying to make a watch circuit, but have ran into the issue of how to setup the crystal. I believe it is the crystal that is the problem because when I messed with the crystal contacts the microcontroller starting completing the blink program I had put in it. It made me believe that the crystal was not oscillating and I don't know why. I am totally confused on how to fix it because all the circuits look like they just have the resonator and the capacitors. Thanks in advance!

Wiring for the Crystal


text:
Q: How to use workflow to send a link to a specific page in an email I am building an approval workflow which will send an email to a named individual, directing them to a specific project to review the work done there.
I am having trouble embedding a link to the site homepage in the email. It cannot be hard-coded as the site to be approved will change with each iteration of the workflow so it needs to be a lookup.
The approval workflow runs against a list containing data about the project. When the workflow is invoked by a change to the list item it needs to embed a link to the homepage of the site into an email.

A: Create variable: 'ProjectName' and fill it with a CurrentItem:Property a project Name (if its as URL) you you should have something in the list item as unique identifier.
You can use link only to the Web without the Page.aspx, like : https://SP.company.com/projects/0010 because HomePage will be loaded automatically.
Use In Link this Variable to complete URL:

It will send email with Link to project on its running.
I Used SharePoint Workflow 2010.


text:
Q: For Bigquery table schemas, how do I change a column's mode from NULLABLE to REQUIRED? I have a table in BigQuery and want to change the mode of a column from NULLABLE to REQUIRED.
According to the Google documentation for modifying BigQuery table schemas the only way to do this goes as follows: "You can manually change a column's mode by exporting your table data to Cloud Storage, and then loading the data into a new table with a schema definition that specifies the correct mode for the column. You can also use the load job to overwrite the existing table." (https://cloud.google.com/bigquery/docs/manually-changing-schemas#changing_a_columns_mode).
I have 2 questions about that.

*

*What does this last sentence "You can also use the load job to overwrite the existing table" mean? Does this mean I can somehow make this schema change in the existing table and don't actually have to make a new table?

*I want to avoid creating a new table and just make schema changes to my existing table. Is there a way to change the mode of a column from NULLABLE to REQUIRED in my existing table? For other modifications like deleting a column from a table schema or changing a column's data type it is possible to use a query job for that (option 1 in the doc). Is there also a query job I can do to change a column's mode? BigQuery does not seem to support something like "ALTER TABLE [Table] ALTER COLUMN [Column] INTEGER NOT NULL".
Any help is appreciated!

A: *

*Given the documentation no you will have to create a new table in that scenario.

*There is no way to change the definition of a column (data type or mode)

What you could alternatively do is add a new column that has the new definition and update the column with the values from the old column.
See Mikhail's answer to this post:
Big Query - Convert a int column into float

A: The important part of the documentation you need to read is Modifying Table schemas, more precisely the section Relaxing a column mode. In there you can see this two key lines:

*

*Currently, the only supported modification you can make to a column's mode is changing it from REQUIRED to NULLABLE.

*Caution: Changing a REQUIRED column to NULLABLE cannot be undone.
Meaning, there is no way to change a NULLABLE column to REQUIRED but you can change a REQUIRED column to NULLABLE.
I tried anyway to proceed with the change, all schema changes, as shown in the aforementioned official documentation can be done using bq update, calling table.patch method or with a client library. I described it more extensively in this other post. In any case, when modifying the column in the schema from NULLABLE to REQUIRED and trying to update, one is met with the error:
BigQuery error in update operation: Provided Schema does not match Table <project-id>:<dataset-id>.<table-id>. Field <field-name> has changed mode from NULLABLE to REQUIRED
Confirming this is not supported.
However, you can follow your workaround mentioned in your first question, i.e. loading the data overwriting the same named table.
Basically, the steps are:

*

*Export to GCS

*Load the data overwriting the same table

I performed a quick experiment to double-check it works properly.

*

*I exported the data to a CSV file in GCS using the UI.

*I overwrote the table following Appending to or overwriting a table with CSV data. Basically I used the command:

bq load \
--source_format=CSV \
--replace \
--max_bad_records=3 \
<dataset-id>.<table-id> \
gs://<MyBucket>/<myexportedfile> \
<mymodifiedschemafile>

As a result I had the same table I had before but with the field changed from NULLABLE to REQUIRED, confirming this workaround works properly!


text:
Q: SQL DISTINCT when combining LEFT JOIN with subquery I have the following two SQL tables for storing movie titles, and the dates I've seen them:
CREATE TABLE movies (
  id int(10) unsigned NOT NULL AUTO_INCREMENT,
  title varchar(90) NOT NULL,
  year varchar(7) DEFAULT NULL,
  watchAgain enum('0', '1') NOT NULL DEFAULT '0',
  PRIMARY KEY (id)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=3 ;

INSERT INTO movies (id, title, year, watchAgain)
  VALUES (1, 'Wall Street', '1987', '1'), (2, 'Wag the Dog', '1997', '1');

CREATE TABLE movies_seen (
  object_id int(10) NOT NULL DEFAULT '0',
  date varchar(10) CHARACTER SET utf8 COLLATE utf8_unicode_ci
    NOT NULL DEFAULT '0',
  seen_again enum('0', '1') NOT NULL DEFAULT '0',
  PRIMARY KEY (object_id, date)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

INSERT INTO `movies_seen` (object_id, date, seen_again)
  VALUES (1, '1156187700', '0'), (1, '1218395700', '0'), (2, '0', '0');

To find movies I should watch again, I ask the database for titles with seen_again == 1, or if seen_again == 0 and it is not stored in movies_seen:
SELECT m.year, m.title, s.date AS last_seen
FROM movies m
LEFT JOIN movies_seen s ON m.id = s.object_id
WHERE
     (
     m.watchAgain = '0'
     AND m.id NOT IN (SELECT s.object_id
                      FROM movies m
                      INNER JOIN movies_seen s ON m.id = s.object_id)
    OR m.watchAgain = '1'
    )
ORDER BY m.title

This basically works, but when the movies_seen table has 2 entires for the same title, it shows up duplicated in the results:
year    title           last_seen
1997    Wag the Dog 0
1987    Wall Street 1156187700
1987    Wall Street 1218395700

It works with DISTINCT if I only fetch the title, but as I need additional columns, this obviously fails. Ideas?

A: In MySQL a GROUP BY clause can do the same task as a DISTINCT
SELECT m.year
  , m.title
  , s.date AS last_seen
FROM movies m
LEFT JOIN movies_seen s ON m.id = s.object_id
WHERE (m.watchAgain = '0'
  AND m.id NOT IN (SELECT s.object_id
                   FROM movies m
                   INNER JOIN movies_seen s ON m.id = s.object_id)
  OR m.watchAgain = '1')
GROUP BY m.title /*<<--- this will do a distinct on title only*/
ORDER BY m.title

AFAIK, this only works on MySQL.
BTW: Since you are grouping on m.title MySQL does a sort on title, so the ORDER BY clause is not technically needed anymore.

A: SELECT m.year, m.title, s.date AS last_seen
FROM movies m
WHERE exists
    (
      select 1 from movies_seen s
          where m.id = s.object_id
           and ( m.watchAgain = '0'
            AND m.id NOT IN (SELECT s.object_id FROM movies m INNER JOIN movies_seen s ON m.id = s.object_id)
            OR m.watchAgain = '1'
            )
    )
ORDER BY m.title


text:
Q: Two Poisson processes - conditional on total events, number of events from first. There are two Poisson processes that run for an equal amount of time. The rates are $\lambda_1$ and $\lambda_2$. Conditional on the total number of events (from both processes) seen being $n$, the number of events that came from the first process is distributed Binomial with $p=\frac{\lambda_1}{\lambda_1+\lambda_2}$ and $n$ number of trials. This is what the uniformly most powerful test for Poisson process rates is based on. How do I prove this? I have some vague intuition of each event belonging to the first process being a Bernoulli with $p$ as specified above and so, the sum of those Bernoulli's across all events being Binomial. But in terms of concrete proof's, I don't know where to start. Normally, we try and construct the CDF. But there is no nice closed form for the binomial CDF.
Now for the second part of my question and what I'm really after: replace the two Poisson processes with compound poisson processes. In other words, each time a Poisson arrivals happens, toss a fair die (with first six numbers) and those represent the number of point events for that arrival. Now, given that we observe $n$ events from both of them, what is the conditional distribution of the number of events from the first one? I have good reason to believe it isn't binomial. If it were, the orange line in the second graph here: https://stats.stackexchange.com/questions/425425/hypothesis-test-for-poisson-process-failure-rates-stays-just-as-powerful-for-com would have been a straight line.

A: There is really no reason to think the compound case will still be binomial, right?  E.g.

*

*$\lambda_1 = \lambda_2 = 10^{-9}$, i.e. super-low-rate Poisson

*You observe total number of points $= 6$
Let $X_1$ be the number of points from the $\lambda_1$ process.  Intuitively one would think $X_1$ is basically bimodal, i.e. it is either $0$ or $6$, right?  I.e. all $6$ events come from the same "burst" (rolling $6$ on the die), and the single burst could be from either process -- this case being much more likely than having two or more bursts (because of the tiny $\lambda$).

A: Using the approach proposed by @Nap D. Lover in the comments, we require:
$$P(X=j | X+Y=n) = \frac{P(X=j \cap X+Y=n)}{P(X+Y=n)}$$
$$=\frac{P(X=j)P(Y=n-j)}{P(X+Y=n)}$$
$$=\frac{\left(\frac{e^{-\lambda_1} \lambda_1^j}{j!}\right)\left(\frac{e^{-\lambda_2} \lambda_2^{n-j}}{(n-j)!}\right)}{\left(\frac{e^{-\lambda_1+\lambda_2} (\lambda_1+\lambda_2)^n}{ n!}\right)}$$
$$ ={n \choose j} \left(\frac{\lambda_1}{\lambda_1+\lambda_2}\right)^j \left(\frac{\lambda_2}{\lambda_1+\lambda_2}\right)^{n-j}$$
And this is the binomial PMF as expected.


text:
Q: SQL Server - High Performance Record Comparison Scenario : I have a collection of records to be inserted/updated into a table. Each record before getting inserted/updated in the table must be checked with the other rows in the table so as to find whether the same record already exists.
Currently used logic : Used the concept of cursor in an SQL server stored procedure to compare each record with every other record in the table before insertion/updation.
Limitations : As the number of records increases in the target table, performance is considerably decreased.
Can I get a better solution than what I have used?

A: Have you looked at using the Merge command, this was introduced in SQL Server 2008 and does an update or insert based on your matching criteria.
I use this for merging XML quite a lot and it seems very efficient.
MERGE [Database] AS TargetTABLE
USING (SELECT @Var1 AS [Value1]
    @Var2 AS [Value2],
    @Var3 AS [Value3]) AS SourceTABLE
ON TargetTABLE.[id] = SourceTABLE.[Value1]
WHEN MATCHED THEN
    UPDATE SET TargetTABLE.[Value2] = SourceTABLE.[Value2],
        TargetTABLE.[Value3] = SourceTABLE.[Value3]
WHEN NOT MATCHED THEN
    INSERT (
        [id],
        [Value1],
        [Value2],
        [Value3])
    VALUES (
        SourceTABLE.[Value1],
        SourceTABLE.[Value2],
        SourceTABLE.[Value3]
    );

Merge Command


text:
Q: How do I add constraint to pyomo with a range inequality I am working on a constraint optimization problem and I am using pyomo with abc solver and I am trying to add a constraint with a range.
The code I have written so far is
# Initialize model
model = ConcreteModel()

# binary variables representing if a worker is scheduled somewhere
model.works = Var(((worker, day, shift) for worker in workers for day in date for shift in days_shifts[day]),
                  within=Binary, initialize=0)

# binary variables representing if a worker is necessary
model.needed = Var(workers, within=Binary, initialize=0)

def obj_rule(m):
    c = len(workers)
    return sum(m.needed[worker] for worker in workers)

model.obj = Objective(rule=obj_rule, sense=minimize)

 # Create a set of constraints
model.constraints = ConstraintList()

for day in date:
    for shift in days_shifts[day]:
        model.constraints.add(33 == sum(model.works[worker, day, shift] for worker in workers))

# Constraint: no more than 52 hours worked
for worker in workers:
    model.constraints.add(
        52 >= sum(12 * model.works[worker, day, shift] for day in date for shift in days_shifts[day]))

The constraint I am trying to add that the minimum hours of shift should be 8 hours and maximum hours of shift should  be 12 hours. The total hours work in a week should not exceed 52 hours. I am following the below article for optimized shift allocations.
https://towardsdatascience.com/modeling-and-optimization-of-a-weekly-workforce-with-python-and-pyomo-29484ba065bb
The last constraint ensures of 12 hour shift, and I am not sure how to add a constraint for 8 hour shift.
I am very new to pyomo and optimization problem.

A: Is the length of a shift something that is given i.e. a model parameter or something that you want your model to decide i.e. a decision variable?
Depending on the case, you will need to define either a parameter or a variable, respectively, indexed per [day, shift] to represent this. If for instance, we call this shift_len[day, shift], then your constraint will become:
for worker in workers:
    model.constraints.add(
        52 >= sum(shift_len[day, shift] * model.works[worker, day, shift] for day in date for shift in days_shifts[day]))

Note that if it is a decision variable, then your model becomes nonlinear due to the product of two variables (there are still ways to linearize the product, though). If it is a parameter, then your model remains linear.


text:
Q: how to make vba UDF accept both scalar and array as arguments as Excel builtin functions and operators? Excel builtin functions and operators can accept both scalars (single values) and arrays (such as a range of cells) as arguments, and will return scalar or array accordingly as results, spilling when approriate.
To mimic this feature in user-defined functions (UDF) is not straightforward, however.  I have to test the arguments and handle them accordingly.  Is there a simple way to do this without doing this complex logic for each and every UDF?
I have done one such function as shown below, and hope someone can point me to a simpler way to doing this.  The function is not actually finished and has holes in it, but I hope you get the idea.
Note that the problem becomes even more complicated if both 'chars' and 'inText' are arrays.  But, Excel handles such situations just fine, and you just have to watch out for mixing columns and rows.
Function FindChar(chars As String, inText As Variant, Optional start_Num As Variant = 1) As Variant
' find any char in 'Chars' within 'inText' and return the index of found char or 0 if not found.
    If IsRange(inText) Then
        ' inText is range
        Dim ii As Long, res() As Variant
        ReDim res(1 To inText.Count)
        For ii = 1 To inText.Count
            If IsRealArray(start_Num) _
            Then res(ii) = FindChar(chars, inText(ii).Value, start_Num(ii)) _
            Else res(ii) = FindChar(chars, inText(ii).Value, start_Num)
        Next ii
        FindChar = res
        Exit Function
    End If
    If IsRealArray(inText) Then
        'inText is array
        Dim errMSG As String
        errMSG = "FindChar: cannot handle array yet"
        Debug.Print errMSG
        MsgBox errMSG
        Stop
        Exit Function
    End If
    ' inText is scalar
    If start_Num <= 0 Then
        FindChar = CVErr(xlErrValue)
        Exit Function
        End If
    If Not inText Like "*[" & chars & "]*" Then
        FindChar = 0
        Exit Function
    End If
    Dim jj As Integer, pos As Long, cc as string
    FindChar = 0
    For jj = 1 To Len(chars)
        cc = Mid(chars, jj, 1)
        pos = InStr(start_Num, inText, cc, vbTextCompare)
        If pos <> 0 Then
            FindChar=pos
            Exit Function
    Next jj
    FindChar = 0
End Function

Function IsRange(arg As Variant) As Boolean
    IsRange = "Range" = TypeName(arg)
End Function

Function IsRealArray(arg As Variant) As Boolean
' the built in function IsArray will return TRUE for range
' but this function will not
' because it looks for the '(' in TypeName
    IsRealArray = InStr(TypeName(arg), "(") > 0
End Function


text:
Q: What are the risks of using a hotspot application in my laptop? I downloaded hotspot application on my laptop, and all my friends using data through. Might my laptop have any problem with it?

A: Nothing wrong with it. Make hotspot on your laptop is always a best idea to share your Internet with other devices, mobile and laptoos, and use it forever.
Share your package with your friends. Hotspot and some others like Connectify are available for best performance.


text:
Q: Two-dimensional dict assignment not meeting expectations The function's return not meeting expectations.
My env py2.7.11 centos6.5.
I hope the function return the return like this
{'www.baidu.com': {'3xx': 0, 'response_time': 0.126, '5xx': 0, '4xx': 1},
'www.google.com': {'3xx': 0, 'response_time': 0, '5xx': 0, '4xx': 0}}

But in fact it is return like that. The send_dict['www.google.com']['response_time'] and send_dict['www.google.com']['response_code'] shouldn't be assigned. But why?
{'www.baidu.com': {'3xx': 0, 'response_time': 0.126, '5xx': 0, '4xx': 1},
'www.google.com': {'3xx': 0, 'response_time': 0.126, '5xx': 0, '4xx': 1}}

The Python code:
#!/usr/bin/python
# -*- coding: utf-8 -*-

sink_dict = {'sink_zabbix_monitor_keys': '3xx,4xx,5xx,response_time',
             'sink_zabbix_domain_keys': 'www.baidu.com,www.google.com'}
sub_send_dict = dict.fromkeys(sink_dict['sink_zabbix_monitor_keys'].split(','), 0)
send_dict = dict.fromkeys(sink_dict['sink_zabbix_domain_keys'].split(','), sub_send_dict)

def calculate_item(item):

    response_code_dict = dict.fromkeys(sink_dict['sink_zabbix_domain_keys'].split(','), 0)
    response_time_dict = dict.fromkeys(sink_dict['sink_zabbix_domain_keys'].split(','), 0)
    domain = item['domain']
    response_code_dict[domain] = int(item['response_code'])
    response_time_dict[domain] = float(item['response_time'])
    if domain in send_dict:
        print domain
        if response_time_dict[domain] > float(send_dict[domain]['response_time']):
            send_dict[domain]['response_time'] = response_time_dict[domain]
        send_dict[domain][str(response_code_dict[domain])[0] + "xx"] += 1
    return send_dict

tmp_item = {'domain': 'www.baidu.com', 'response_time': '0.126', 'response_code': '401'}
tmp_item1 = {'domain': 'www.google.com', 'response_time': '0.126', 'response_code': '401'}
tmp_item2 = {'domain': 'www.baidu.com', 'response_time': '0.166', 'response_code': '401'}

print calculate_item(tmp_item)

A: Here you go:
send_dict = {k: sub_send_dict.copy() for k in sink_dict['sink_zabbix_domain_keys'].split(',')}

This is called dict comprehension. This works because I'm assigning a shallow copy of the dictionary to the key. dict.fromkeys() will assign the value to every key, all keys will share the same sub_send_dict reference.
From the (linked) python docs:

Assignment statements in Python do not copy objects, they create bindings between a target and an object. For collections that are mutable or contain mutable items, a copy is sometimes needed so one can change one copy without changing the other.


text:
Q: Change the color of one character using JQuery without changing HTML tags I am trying to iterate through the DOM using JQuery and I want to change the color of every instance of the letter m. this is what I have so far:
$(document).ready(function(){
var m = "m"

$("body").children().each(function() {
        $(this).html($(this).html().replace(/m/g, m));
   });
});

The problem with this is that it also modifies the html elements like links in <href> and
I tried using
if (!$(this).is("a")) { //replace }

but that didn't work. also using .text() instead of .html() didn't work for me

A: To achieve what you want, you need to have a recursive fonction. In that function, you have to check if the element is a text node. Once you have a text node, you can then replace it's content. Else, you need to call the same function with the new element.
Here the said function :
letterScanner( $('body'), 'm' )

function letterScanner( $el, letter ){
  $el.contents().each( function(){
    if( this.nodeType == 3 ){
      $( this ).replaceWith( this.textContent.replace( new RegExp( '('+letter+'+)', 'g' ), "$1" ) );
    }else{
        letterScanner( $( this ), letter )
    }
  } );
}

Of course, change the body selector for the closest parent for better performance.
https://jsfiddle.net/ghb4p1p8/


text:
Q: ".findOneAndUpdate()" not updating database properly (Mongodb & Node.js) I try to use .findOneAndUpdate() to update my database.
No error message, but this part of the database is not updated with new data. The embedded document competitorAnalysisTextData is still empty.
// on routes that end in /users/competitorAnalysisTextData
// ----------------------------------------------------
router.route('/users/competitorAnalysisTextData/:userName')

// update the user info (accessed at PUT http://localhost:8080/api/users/competitorAnalysisTextData)
.post(function(req, res) {

    console.log('1');

// Just give instruction to mongodb to find document, change it;
// then finally after mongodb is done, return the result/error as callback.
User.findOneAndUpdate(
    { userName : req.params.userName},
    {
        $set:
        {   "competitorAnalysis.firstObservation" : req.body.firstObservation,
            "competitorAnalysis.secondObservation" : req.body.secondObservation,
            "competitorAnalysis.thirdObservation" : req.body.thirdObservation,
            "competitorAnalysis.brandName" : req.body.brandName,
            "competitorAnalysis.productCategory" : req.body.productCategory
        }
    },
    { upsert: true },
    function(err, user) {
        // after mongodb is done updating, you are receiving the updated file as callback
        console.log('2');
        // now you can send the error or updated file to client
        if (err)
            return res.send(err);

        return res.json({ message: 'User updated!' });
    });

})

Update
This is my "User" Schema part:
// grab the things we need
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

// Require the crypto module for password hash
'use strict';
var crypto = require('crypto');

// create competitorAnalysisSchema
var CompetitorAnalysis = new Schema({
    firstObservation: { type: String },
    secondObservation: { type: String },
    thirdObservation: { type: String },
    brandName: { type: String },
    productCategory: { type: String }
});
// create competitorAnalysisPhotoSchema
var CompetitorAnalysisPhoto = new Schema({
    photo1: {type: String},
    photo2: {type: String},
    photo3: {type: String},
    photo4: {type: String}
});
// create UserSchema
var UserSchema = new Schema({
    userName: { type: String, required: true, unique: true },
    email: { type: String, required: true, unique: true },
    password: { type: String, required: true },
    currentDemo: { type: String },
    nextDemo: { type: String },
    startTime: { type: String },
    startLocation: { type: String },
    arriveTime: { type: String },
    arriveLocation: { type: String },
    leaveTime: { type: String },
    leaveLocation: { type: String },
    competitorAnalysis: [CompetitorAnalysis],
    competitorAnalysisPhoto: [CompetitorAnalysisPhoto],
    created_at: Date,
    updated_at: Date
});

// the schema is useless so far
// we need to create a model using it
var User = mongoose.model('User', UserSchema);

// make this available to our users in our Node applications
module.exports = User;

A: in javascript if you wish to update an object inside an array, you need to pick the index
var arr = [{name: "person1"},{name:"person2"}]
arr[0].name = "myname"
arr[1].name = "myFriend"

So it's the same in mongodb, check this link for detail example, or you can manually input the index, for quick hack.
User.findOneAndUpdate(
  { userName : req.params.userName},
  {
    $set:
    {   "competitorAnalysis.0.firstObservation" : req.body.firstObservation,
        "competitorAnalysis.0.secondObservation" : req.body.secondObservation,
        "competitorAnalysis.0.thirdObservation" : req.body.thirdObservation,
        "competitorAnalysis.0.brandName" : req.body.brandName,
        "competitorAnalysis.0.productCategory" : req.body.productCategory
    }
  },
  { upsert: true },
  function(err, user) {
    // after mongodb is done updating, you are receiving the updated file as callback
    console.log('2');
    // now you can send the error or updated file to client
    if (err)
        return res.send(err);

    return res.json({ message: 'User updated!' });
  });

})

You should use the code above to update nested-array not to add to empty-array.
In javascript, if an array is still empty, we use .push() to add,  while in mongodb the command is $push
var arr = []
arr.push({name:"person1"})


text:
Q: how to fix cannot find method onLoginButtonClick in binding compoment I am  stuck in finding a solution to cannot find method onLoginButtonClick or in general android data binding bugs I want to make authentication in my app by using binding and room so this is my code
register layout
android:text="@{register.emailEditTextRegisterContext}"
android:text="@{register.passwordEditTextRegisterContext}"
android:onClick="@={()-> register.onButtonLoginRegisterClick(register)}"
android:text="@{register.confirmPasswordTextContext}"
android:text="@{register.nameRegisterContext}"

login layout
android:text="@{login.emailEditTextContext}"
android:text="@{login.PasswordEditTextContext}"
android:onClick="@={() -> login.onLoginButtonClick(login)}"

registerViewModel
private val _nameRegisterContext = MutableLiveData<String>()
val NameRegisterContext: LiveData<String>
    get() = _nameRegisterContext

private val _emailEditTextRegisterContext = MutableLiveData<String>()
val emailEditTextRegisterContext: LiveData<String>
    get() = _emailEditTextRegisterContext

private val _passwordEditTextRegisterContext = MutableLiveData<String>()
val passwordEditTextRegisterContext: LiveData<String>
    get() = _passwordEditTextRegisterContext

private val _confirmPasswordTextContext = MutableLiveData<String>()
val confirmPasswordTextContext: LiveData<String>
    get() = _confirmPasswordTextContext

private val _registerCompleted = MutableLiveData<Boolean>()
val registerCompleted: LiveData<Boolean>
    get() = _registerCompleted

fun onButtonLoginRegisterClick(view: View){

}

login layout
private val _emailedittextcontext = MutableLiveData<String>()
val emailEditTextContext: LiveData<String>
    get() = _emailedittextcontext

private val _passwordedittextcontext = MutableLiveData<String>()
val PasswordEditTextContext: LiveData<String>
    get() = _passwordedittextcontext

fun onLoginButtonClick(view : View){
        onLogingin()
    }

error(whenever I tried a solution it changes)
[kapt] An exception occurred: android.databinding.tool.util.LoggedErrorException: Found data binding errors.
****/ data binding error ****msg:cannot find method onButtonLoginRegisterClick(com.example.android.trackmysleepquality.register.RegisterViewModel) in class com.example.android.trackmysleepquality.register.RegisterViewModel
file:C:\Users\mehmet\Desktop\andfun-kotlin-sleep-tracker-with-recyclerview\app\src\main\res\layout\register_layout.xml
loc:87:32 - 87:81
****\ data binding error ****
****/ data binding error ****msg:cannot find method onLoginButtonClick(com.example.android.trackmysleepquality.login.Login_ViewModel) in class com.example.android.trackmysleepquality.login.Login_ViewModel
file:C:\Users\mehmet\Desktop\andfun-kotlin-sleep-tracker-with-recyclerview\app\src\main\res\layout\login_layout.xml
loc:76:32 - 76:68
****\ data binding error ****

please help!!

A: Wrong:
android:onClick="@={() -> login.onLoginButtonClick(login)}"

android:onClick="@={()-> register.onButtonLoginRegisterClick(register)}"

You are passing ViewModel object to these functions, not View as you want
Right:
android:onClick="@={(view) -> login.onLoginButtonClick()}"

android:onClick="@={(view)-> register.onButtonLoginRegisterClick()}"

Ref:
Listener Binding in official doc

A: Although answer posted by @Miller Go Dev corrects your code somewhat, it still doesn't satisfy the needs.
The correct way would be this,
android:onClick="@={(view) -> login.onLoginButtonClick(view)}"

android:onClick="@={(view)-> register.onButtonLoginRegisterClick(view)}"

    //pass the view parameter to their respective method

A: well, all I did to fix is to remove the = sign to make the data binding one-way
Wrong:
android:onClick="@={() -> login.onLoginButtonClick(login)}"

Right:
android:onClick="@{() -> login.onLoginButtonClick()}"


text:
Q: Extracting corresponding values in JSR223 post processor in JMeter Randomly Hi All / Dimitri T Could you please post your valuable thoughts on  extracting corresponding Values (For example ItemID1 and ItemSlot1) in one block of code randomly. I was able to write below Jsr223 postprocessor code and it is working fine. But when there are Blank spaces in ItemSlot id, then they are not fetching. From below code , i am passing ${rannum} under "Match No" in required regular expression.
Note: There will be more than 100 corresponding values. In some cases, we won't have ItemSlot1.i.e Blank/null values are appearing from server response. Hence, my script is not picking corresponding values.
Application Server Response:
"viewSaleListingLink": "https://Example.com/cars/item/search/-/listing/ItemID1/100011142",
"saleCountry": "",
"saleNote": "",
"bidLiveUrl": "https://Example.com/cars//registration?p_p_id=RegistrationPortlet_WAR_PWRWeb&p_p_lifecycle=1&p_p_state=normal&ItemSlot1=103009468",
JSR223PostProcessor Code
import java.math.MathContext;
import java.math.RoundingMode;
// Read occurance values from pervious response
def Max = Integer.parseInt( vars.get("ItemID1_matchNr"));
int min=1;
int rannum =  min + (int) (Math.random() * ((Max - min) + 1));
log.info("Values id ="+rannum);
vars.put("rannum",rannum.toString());
enter image description here

A: If you need to extract a random match/pair of matches from the response using Regular Expression Extractor - it's sufficient just to provide 0 as the "Match No" and it will automatically fetch the random match group so you won't have to write any code:

Also be aware that Post-Processors are executed in the order they appear (upside down) so:

*

*If your JSR223 PostProcessor is above the Regular Expression Extractor - ItemID1_matchNr will be undefined

*If your JSR223 PostProcessor is below the Regular Expression Extractor - your rannum variable won't have any value

Also your response seems to be JSON so it makes sense switching to JSON JMESPath Extractor which is more powerful and convenient


text:
Q: Delphi Application internationalization and localization I had read documentation about localizing Embarcadero DocWiki.
But I do not know how to:

*

*change language in Run-Time - for example I would to click in application menu change language to English or Polish

*Show translated text in dialogs, e.g: ShowMessage('Zmieniłeś język');

A: 1.
There was sample project (shipped with Delphi) called RichEdit which had run-time change of language. To achieve that, Reinit unit was used (you can take it from here) which actually reloads all the resources.
It's working normally on simple programs like that, but may be real pain to implement in something more complex, as all the controls on form are reverted to initial state in which they have been at start-up, so it's your responsibility to keep your data consistent.
Though in proper implementation where all the application logic is separated from GUI (so there are no vars on TForm, no storing user data in edit boxes etc), it should work normally.
See RichEdit sample's source code to understand how to use Reinit.pas
2.
 The classical approach is to use ResourceString. In interface section of your unit or better in separate unit, write:
ResourceString
  ChangeLanguageStr = 'Zmieniłeś język';
  //another strings here

and for showing message:
ShowMessage(ChangeLanguageStr);

These strings will be shown in translation manager.


text:
Q: "Unexpected color space /R11" while parsing a PDF file with text and image System.ArgumentException was unhandled by user code
  Message=Unexpected color space /R11
  Source=itextsharp
  StackTrace:
       at iTextSharp.text.pdf.parser.InlineImageUtils.GetComponentsPerPixel(PdfName colorSpaceName)
       at iTextSharp.text.pdf.parser.InlineImageUtils.ComputeBytesPerRow(PdfDictionary imageDictionary)
       at iTextSharp.text.pdf.parser.InlineImageUtils.ParseUnfilteredSamples(PdfDictionary imageDictionary, PdfContentParser ps)
       at iTextSharp.text.pdf.parser.InlineImageUtils.ParseInlineImageSamples(PdfDictionary imageDictionary, PdfContentParser ps)
       at iTextSharp.text.pdf.parser.InlineImageUtils.ParseInlineImage(PdfContentParser ps)
       at iTextSharp.text.pdf.parser.PdfContentStreamProcessor.ProcessContent(Byte[] contentBytes, PdfDictionary resources)
       at iTextSharp.text.pdf.parser.PdfReaderContentParser.ProcessContent[E](Int32 pageNumber, E renderListener)
       at iTextSharp.text.pdf.parser.PdfTextExtractor.GetTextFromPage(PdfReader reader, Int32 pageNumber, ITextExtractionStrategy strategy)
       at iTextSharp.text.pdf.parser.PdfTextExtractor.GetTextFromPage(PdfReader reader, Int32 pageNumber)
       at PDF_PdfToText.extractText(String src, String dest) in d:\QC\Backup\NRK\Current\QConform nrk - 2010\PDF\PdfToText.aspx.cs:line 29
       at PDF_PdfToText.Page_Load(Object sender, EventArgs e) in d:\QC\Backup\NRK\Current\QConform nrk - 2010\PDF\PdfToText.aspx.cs:line 17
       at System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e)
       at System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e)
       at System.Web.UI.Control.OnLoad(EventArgs e)
       at System.Web.UI.Control.LoadRecursive()
       at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
  InnerException:

A: iText's inline image parser has undergone some work recently.  If you're not using 5.0.5, you might be missing a relevant bug fix.
The whole .pdf.parser package is still under development unfortunately.  OTOH, if you do have the latest-n-greatest, and are still getting this exception, you've got an iText[sharp] bug.  Head on over to the itext-questions mailing list and post your stack trace along with the PDF that causes it if at all possible.  We'll take care of it.
Alternatively, you can report the bug via the sourceforge tracker.  Attached files there aren't Broadcast To The World, so you might be more comfortable with that.


text:
Q: Handling Multiple "Screens" In Android via TableLayouts I'm trying to make an Options "Menu" Screen. When the menu button is pressed the menu comes up with a "button" that says Options when that is clicked, the function clicks a button called optionsButton. When that button is pressed I want one TableLayout to become Invisible and one to become visible.
Here is the code I have to hide the layouts.
public void optionButton(View view)
{
    TableLayout mainTable = (TableLayout)findViewById(R.id.tableMain);
    TableLayout optionTable = (TableLayout)findViewById(R.id.tableOptions);
    mainTable.setVisibility(TableLayout.INVISIBLE);
    optionTable.setVisibility(TableLayout.VISIBLE);

}

And here is the XML that handles my optionButton <Button android:onClick="optionButton" android:id="@+id/optionsButton" android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="Button" android:visibility="invisible"></Button>
And here is the code that handles my "Menu Button"
public boolean onOptionsItemSelected(MenuItem item) {
    switch(item.getItemId()) {
    case R.id.options:
        Button optbtn = (Button)findViewById(R.id.optionsButton);
        optbtn.performClick();
        break;
    default:

        break;
    }

    return true;
}

The problem is that when the menu button is clicked, nothing happens. Any help on this issue would be greatly appreciated.

A: I fixed the problem by deleting the optionsTable and all of it's contents. Remaking it and putting it below the mainTable in the Graphical Editor of main.xml


text:
Q: Query Azure VM platform metrics using REST API I am trying to retrieve default platform-level Azure VM metric values using Azure Monitor REST API, in this case the "Percentage CPU" metric.
    $interval = "PT1M"
    $metricnamespace = "Microsoft.Compute/virtualMachines"
    $metricnames = "Percentage CPU"
    $aggregation = "Average"
    $Uri = "https://management.azure.com/$resourceURI/providers/microsoft.insights/metrics?interval=$interval&metricnames=$metricnames&aggregation=$aggregation&api-version=2018-01-01&metricnamespace=$metricnamespace"
    $Response = Invoke-RestMethod $Uri -Headers $headers -ContentType "application/json"

But when I try to fetch the metric values, I get no data and an empty timeseries object (also with a different timespan):
    "cost":  0,
    "timespan":  "2020-07-29T07:34:46Z/2020-07-29T08:34:46Z",
    "interval":  "PT1M",
    "value":  [
                  {
                      "id":  "/subscriptions/{subscriptionId}/resourceGroups/testpatchingVM/providers/Microsoft.Compute/virtualMachines/testpatchingVM/providers/Microsoft.Insights/metrics/Percentage CPU",
                      "type":  "Microsoft.Insights/metrics",
                      "name":  "@{value=Percentage CPU; localizedValue=Percentage CPU}",
                      "displayDescription":  "The percentage of allocated compute units that are currently in use by the Virtual Machine(s)",
                      "unit":  "Percent",
                      "timeseries":  "",
                      "errorCode":  "Success"
                  }
              ],
    "namespace":  "Microsoft.Compute/virtualMachines",
    "resourceregion":  "westeurope"

timeStamp
---------
2020-07-29T07:43:00Z
2020-07-29T07:44:00Z
2020-07-29T07:45:00Z
2020-07-29T07:46:00Z
2020-07-29T07:47:00Z
2020-07-29T07:48:00Z
2020-07-29T07:49:00Z
2020-07-29T07:50:00Z
2020-07-29T07:51:00Z
2020-07-29T07:52:00Z
2020-07-29T07:53:00Z
2020-07-29T07:54:00Z
2020-07-29T07:55:00Z
2020-07-29T07:56:00Z
2020-07-29T07:57:00Z
2020-07-29T07:58:00Z
2020-07-29T07:59:00Z
2020-07-29T08:00:00Z
2020-07-29T08:01:00Z
2020-07-29T08:02:00Z
2020-07-29T08:03:00Z
2020-07-29T08:04:00Z
2020-07-29T08:05:00Z
2020-07-29T08:06:00Z
2020-07-29T08:07:00Z
2020-07-29T08:08:00Z
2020-07-29T08:09:00Z
2020-07-29T08:10:00Z
2020-07-29T08:11:00Z
2020-07-29T08:12:00Z
...

Can anyone help me out?


text:
Q: How to load multiple js files after the loading of html page I am trying to load 6 js files after the loading of the html page. One of those 6 files is jquery file and the other 5 are jquery dependent. I'm loading jquery file first but still getting an error "$ is not defined". Its working fine when I load jquery file initially in the head section and then the other 5 files after the load. Pls tell me why it is happening like that.

A: How about using window.load which is fired after $(document).ready()?
$(window).load(function()
{
   document.write("<scr" + "ipt type=\"text/javascript\" src=\"/js/yourscript1\"></scr" + "ipt>");
   document.write("<scr" + "ipt type=\"text/javascript\" src=\"/js/yourscript2\"></scr" + "ipt>");
});

Since you have not loaded jQuery, would this do it for you?:
In your html
<body onload="myFunction()">

and then in the script (You also load your jQuery)
function myFunction()
{
   document.write("<scr" + "ipt type=\"text/javascript\" src=\"/js/yourscript1\"></scr" + "ipt>");
   document.write("<scr" + "ipt type=\"text/javascript\" src=\"/js/yourscript2\"></scr" + "ipt>");
});


text:
Q: VSCode & FNM - pre-commit: npx: not found I'm using VSCode and FNM (Fast Node Manager) instead of NVM. The issue seems to be that VSCode fails to see npx while committing from Source Control and throws out the following error:
> git -c user.useConfigOnly=true commit --quiet --allow-empty-message --file -
.husky/pre-commit: 6: npx: not found
husky - pre-commit hook exited with code 127 (error)

I've looked at other answers here and they all seem to be pointing towards a misconfigured path for NVM but I'm currently not using NVM. I'm on fnm: https://github.com/Schniz/fnm
Is there any way I can fix this?

A: I had the same problem after switching from nvm. Try to add
eval "$(fnm env --use-on-cd)" in your .zshrc file.
For me it was the solution. Maybe it helps you as well.


text:
Q: datas aren't showing after clicking event view Hello There im using a github project for a learning purpose and in that i have a option called events. in events we can add or view events and (add event working) once i click event to view this error occurs and i dont know how to fix it.so please help me with this if possible,
error name
Fatal error: Uncaught Error: Undefined constant "absolute" in C:\xampp\htdocs\Ip project\event-page.php:69 Stack trace: #0 {main} thrown in C:\xampp\htdocs\Ip project\event-page.php on line 69
in line 69 code
$diff=date_diff($date1,$date2, absolute); (this is the line 69)
datas aren't showing after clicking event view
full code if needed
    <link href="css/flipclock.css" rel="stylesheet">

    <?php include 'includes/navbar.php'; ?>

                <?php include 'includes/profile-card.php'; ?>

                <?php

                    $sql = "select e.event_date, e.event_id, e.event_by, e.title, e.event_image, i.description,
                                u.uidUsers, u.userImg, i.headline as e_headline
                            from events e, event_info i, users u
                            where e.event_id = ?
                            and e.event_by = u.idUsers
                            and e.event_id = i.event";

                    $stmt = mysqli_stmt_init($conn);

                    if (!mysqli_stmt_prepare($stmt, $sql))
                    {
                        die('SQL error');
                    }
                    else
                    {
                        mysqli_stmt_bind_param($stmt, "s", $eventId);
                        mysqli_stmt_execute($stmt);
                        $result = mysqli_stmt_get_result($stmt);

                        $row = mysqli_fetch_assoc($result);

                        $date1 = date_create(date("Y-m-d"));
                        $date2 = date_create($row['event_date']);

                        $diff=date_diff($date1,$date2, absolute);

                        $diff_sec = $diff->format('%r').(
                                        ($diff->s)+
                                        (60*($diff->i))+
                                        (60*60*($diff->h))+
                                        (24*60*60*($diff->d))+
                                        (30*24*60*60*($diff->m))+
                                        (365*24*60*60*($diff->y))
                                        );
                    }
                ?>

                <img class="blog-cover" src="uploads/<?php echo $row['event_image']; ?>">

                <img class="blog-author" src="uploads/<?php echo $row['userImg']; ?>">

<?php echo ucwords($row['title']) ?>

<?php echo ucwords($row['e_headline']) ?>

Event Countdown

<?php echo $row['description'] ?>

Organized By: <?php echo ucwords($row['uidUsers']); ?>


text:
Q: Combining base64 audio strings I am using react-native-live-audio-stream to capture microphone audio. It spits out base64 encoded audio chunks like so:
LiveAudioStream.on('data', data => {
  // base64-encoded audio data chunks
});

I am looking to combine these chunks to send off as a single base64 string that could be used as input to an speech-to-text service.
With the code above, I am doing the following:
let bufferedAudioData = [];
LiveAudioStream.on('data', data => {
    bufferedAudioData.push(data);
});

Then when appropriate, I am using the following code to combine the bufferedAudioData array by calling combineBase64Audio(bufferedAudioData):
export function combineBase64Audio(base64Strings) {
    // decode the base64 strings to ArrayBuffers
    const buffers = base64Strings.map(base64ToArrayBuffer);

    // create a new ArrayBuffer to hold the combined audio
    const combinedBuffer = new ArrayBuffer(buffers.reduce((totalLength, buffer) => totalLength + buffer.byteLength, 0));

    // create a view for each ArrayBuffer and copy the audio data into the combined buffer
    let offset = 0;
    buffers.forEach((buffer) => {
      const view = new Uint8Array(combinedBuffer, offset, buffer.byteLength);
      view.set(new Uint8Array(buffer));
      offset += buffer.byteLength;
    });

    // encode the combined ArrayBuffer as a base64 string
    return arrayBufferToBase64(combinedBuffer);
}

function base64ToArrayBuffer(base64) {
    // decode the base64 string to a Uint8Array
    const binaryString = Buffer(base64, 'base64').toString()
    const binaryLength = binaryString.length;
    const bytes = new Uint8Array(binaryLength);
    for (let i = 0; i < binaryLength; i++) {
        bytes[i] = binaryString.charCodeAt(i);
    }
    // return the Uint8Array as an ArrayBuffer
    return bytes.buffer;
}

function arrayBufferToBase64(arrayBuffer) {
    // create a Uint8Array view of the ArrayBuffer
    const bytes = new Uint8Array(arrayBuffer);
    // convert the Uint8Array to a binary string
    let binaryString = '';
    for (let i = 0; i < bytes.length; i++) {
        binaryString += String.fromCharCode(bytes[i]);
    }
    return Buffer(binaryString).toString('base64');
}

What Ive been doing is sending the final base64 encoded string to an API to save to a file on disk so that I can listen to it. Unfortunately the audio file sounds like gibberish. I am importing the file into Audacity as raw data and updating the settings accordingly. Im setting the encoding to "Signed 16-bit PCM" (which I think is correct) but the rest of the settings should be correct.
What am I doing wrong here? Im guessing that the way Im combining the base64 strings is the issue, but maybe Im not verifying the output correctly?
UPDATE: I listened to an individual decoded chunk of audio from LiveAudioStream.on('data' and it sounds fine. The culprit is my combining code. Still not sure what is wrong with it.