Q:

стрелочные функции

При выводе на консоль, в obj1 свойство this.name не отображается. Как правильно сделать привязку данных, подскажите? Во втором obj2 использую стрелочную функцию, все отображается (стрелочные функции не имеют своего this). В третьем obj3 ошибка

Cannot read property 'forEach' of undefined

Можно ли свойством объекта делать стрелочную функцию? Спасибо.
window.addEventListener('load', function () {

 let obj1 = {
  name: 'value',
  numbers: [1, 2, 3],
  fun1: function () {
   this.numbers.forEach(function (value, index, array) {
    console.log(this.name + ' ' + value);
   })
  }
 };

 obj1.fun1();

 let obj2 = {
  name: 'value',
  numbers: [4, 5, 6],
  fun1: function () {
   this.numbers.forEach((value, index, array) => {
    console.log(this.name + ' ' + value);
   })
  }
 };

 obj2.fun1();

 let obj3 = {
  name: 'value',
  numbers: [7, 8, 9],
  fun1: () => {
   this.numbers.forEach((value, index, array) => {
    console.log(this.name + ' ' + value);
   })
  }
 };

 obj3.fun1();

});

A:

Стрелочные функции не удастся использовать как методы, потому что они не захватывают контекст вызова.. Использование this в них, аналогично использованию this там, где они объявлены.
Чаще всего, вне 'strict mode' this ссылается на глобальный объект.

window.data = 'Global data';
let test = {
  data: 'Object data',
  method() {
    console.log(this.data);
  },
  func: () => console.log(this.data)
}

test.method(); // Object data

test.func(); // Global data

let test2 = {
  data: 'Test2 data',
  method() {
    test.func2 = () => console.log(this.data);
  }
};

test2.method(); // в этом вызове this==test2
test.func2(); // Поэтому: Test2 data

В obj1 же, напротив. Функция обратного вызова forEach вызывается с пустым контекстом. Здесь как раз полезны стрелочные функции для доступа к внешнему this.
Разумеется, Вы вольны сохранить this любым другим способом:

let obj1 = {
  name: 'value',
  numbers: [1, 2, 3],
  f1: function () {
   this.numbers.forEach((value, index, array) => {
    console.log(this.name, value, 'arrow');
   })
  },
  f2: function() {
   this.numbers.forEach(function(value, index, array){
    console.log(this.name, value, 'bind');
   }.bind(this))
  },
  f3: function() {
   let that = this;
   this.numbers.forEach(function(value, index, array){
    console.log(that.name, value, 'variable');
   });
  },
  f4: function() {
   this.numbers.forEach(function(value, index, array){
    console.log(this.name, value, 'forEach thisArg');
   }, this);
  }
 };

 obj1.f1();
 obj1.f2();
 obj1.f3();
 obj1.f4();


Q:

What is the difference between zero-inflated and hurdle models?

I wonder if there is a clear-cut difference between the so-called zero-inflated distributions (models) and so-called hurdle-at-zero distributions (models)? The terms occur quite often in the literature and I suspect they are not the same, but would you please explain me the difference in simple terms?

A:

Thank you for the interesting question!
Difference: One  limitation  of standard  count models  is  that  the zeros and  the nonzeros (positives) are assumed  to  come from  the same data-generating process.  With hurdle models, these two processes are not constrained  to  be  the  same. The basic  idea is  that  a Bernoulli probability  governs the binary outcome  of  whether  a  count  variate  has a  zero  or positive realization.  If the  realization  is positive, the  hurdle is  crossed,  and  the  conditional  distribution  of the positives is governed  by a  truncated-at-zero  count  data  model. With zero-inflated models, the response variable is modelled as a mixture of a Bernoulli distribution (or call it a point mass at zero) and a Poisson distribution (or any other count distribution supported on
non-negative integers). For more detail and formulae, see, for example, Gurmu and Trivedi (2011) and Dalrymple, Hudson, and Ford (2003).
Example: Hurdle models can be motivated by sequential decision-making processes confronted by individuals. You first decide if you need to buy something, and then you decide on the quantity of that something (which must be positive). When you are allowed to (or can potentially) buy nothing after your decision to buy something is an example of a situation where zero-inflated model is appropriate. Zeros may come from two sources: a) no decision to buy; b) wanted to buy but ended up buying nothing (e.g. out of stock).
Beta: The hurdle model is a special case of the two-part model described in Chapter
16 of Frees (2011). There, we will see that for two-part models, the amount of health care utilized may be a continuous as well as a count variable. So what has been somewhat confusingly termed "zero-inflated beta distribution" in the literature is in fact belongs in the class of two-part distributions and models (so common in actuarial science), which is consistent with the above definition of a hurdle model. This excellent book discussed zero-inflated models in section 12.4.1 and hurdle models in section 12.4.2, with formulas and examples from actuarial applications.
History: zero-inflated Poisson (ZIP) models without covariates have a long history (see e.g., Johnson and Kotz, 1969). The general form of ZIP regression models incorporating covariates is due to Lambert (1992). Hurdle models were first proposed by a Canadian statistician Cragg (1971), and later developped further by Mullahy (1986). You may also consider Croston (1972), where positive geometric counts are used together with Bernoulli process to describe an integer-valued process dominated by zeros.
R: Finally, if you use R, there is package pscl for "Classes and Methods for R developed in the Political Science Computational Laboratory" by Simon Jackman, containing hurdle() and zeroinfl() functions by Achim Zeileis.
The following references have been consulted to produce the above:

Gurmu, S. & Trivedi, P. K. Excess Zeros in Count Models for Recreational Trips Journal of Business & Economic Statistics, 1996, 14, 469-477
Johnson, N., Kotz, S., Distributions in Statistics: Discrete Distributions. 1969, Houghton MiZin, Boston
Lambert, D., Zero-inflated Poisson regression with an application to defects in manufacturing. Technometrics, 1992, 34 (1), 1–14.
Cragg, J. G. Some Statistical Models for Limited Dependent Variables with Application to the Demand for Durable Goods Econometrica, 1971, 39, 829-844
Mullahy, J. Specification and testing of some modified count data models Journal of Econometrics, 1986, 33, 341-365
Frees, E. W. Regression Modeling with Actuarial and Financial Applications Cambridge University Press, 2011
Dalrymple, M. L.; Hudson, I. L. & Ford, R. P. K. Finite Mixture, Zero-inflated Poisson and Hurdle models with application to SIDS Computational Statistics & Data Analysis, 2003, 41, 491-504
Croston, J. D. Forecasting and Stock Control for Intermittent Demands Operational Research Quarterly, 1972, 23, 289-303

A:

Hurdle models assume that there is only one process by which a zero can be produced, while zero-inflated models assume that there are 2 different processes that can produce a zero.
Hurdle models assume 2 types of subjects: (1) those who never experience the outcome and (2) those who always experience the outcome at least once.  Zero-inflated models conceptualize subjects as (1) those who never experience the outcome and (2) those who can experience the outcome but don't always.
In simple terms: both zero-inflated and hurdle models are described in two parts.
The first is the on-off part, which is a binary process.  The system is "off" with probability $\pi$ and "on" with probability $1-\pi$.  (Here, $\pi$ is known as the inflation probability.)  When the system is "off," only zero counts are possible.  This part is the same for zero-inflated and hurdle models.
The second part is the counting part, which occurs when the system is "on."  This is where zero-inflated and hurdle models differ.  In zero-inflated models, counts can still be zero.  In hurdle models they must be nonzero.  For this part, zero-inflated models use a "usual" discrete probability distribution while hurdle models use a zero-truncated discrete probability distribution function.
Example of a hurdle model: An automobile manufacturer wants to compare two quality control programs for its automobiles.  It will compare them on the basis of the number of warranty claims filed.  For each program, a set of randomly selected customers are followed for 1 year and the number of warranty claims they file is counted.  The inflation probabilities for each of the two programs are then compared.  The “off” state is “filed zero claims” while the “on” state is “filed at least one claim.”
Example of a zero-inflated model:  In the same study above, the researchers find out that some repairs on the automobiles were fixed without the filing of a warranty claim.  In this way, the zeroes are a mixture of the absence of quality control problems as well as the presence of quality control problems that involved no warranty claims.  The “off” state means “filed zero claims” while the “on” state means “filed at least one claim OR had repairs fixed without filing a claim.”
See here for a study in which both types of models were applied to the same data set.

A:

in ZIP model $y_i$~0 with probability $\pi$ and $y_i$~ Poisson($\lambda$) distribution with probability $1-\pi$,
thus the ZIP model is mixture model with 2 components and:
$$\Pr (y_j = 0) = \pi + (1 - \pi) e^{-\lambda}$$
$$\Pr (y_j = x_i) = (1 - \pi) \frac{\lambda^{x_i} e^{-\lambda}} {x_i!},\qquad x_i \ge 1$$
and in an hurdle model $y_i$~ 0 with probability $\pi$ and $y_i$~ truncated Poisson($\lambda$) distribution with probability $1-\pi$, and:
$$\Pr (y_j = 0) = \pi $$
$$\Pr (y_j = x_i) = \frac{(1 - \pi)} {1-e^{-\lambda}} (\frac{\lambda^{x_i} e^{-\lambda}} {x_i!}),\qquad x_i \ge 1$$


Q:

How to filter and auto suggest Combo Box items based on text entered?

I have followed the following links to create a custom combo box. I have added a list of combo box items using c#.
If I type text in the custom combo box it is not filtering the items based on the search text whether an item contains the word.
The custom combo box just listing all the items in it.
I want my combo box to act like if type word it should filter the result and auto-suggest in the combo box search.
<local:FilteredComboBox x:Name="FilteredCmb"  IsEditable="True"
            IsTextSearchEnabled="True"
            Padding="4 3"
            MinWidth="200" Grid.ColumnSpan="6"
            Grid.Column="2" Margin="0,77,0,49" Grid.Row="1" />

How to achieve this?
Is this possible with a Default combo box.
The default combo box auto-suggests the items which start with the entered text not with checking whether the word is contained in an item.
Create Custom ComboBox1
Custom ComboBox2

A:

I have used combo box key up event to filter the result.
<local:FilteredComboBox x:Name="FilteredCmb"  IsEditable="True"
IsTextSearchEnabled="False" **KeyUp="FilteredCmb_KeyUp"** Padding="4 3" MinWidth="200"
Grid.ColumnSpan="6" Grid.Column="2" Margin="0,77,0,49" Grid.Row="1" />

C# Code
private void FilteredCmb_KeyUp(object sender, KeyEventArgs e)
{
    List<BoxItem> filteredItems = new List<BoxItem>();

    for (int i = 0; i < cmbItems.Count; i++)
    {
        string currentItem = cmbItems[i].Text.ToLower();

        // get the text in the editable combo box
        string typedText = FilteredCmb.Text.ToLower();

        if (currentItem.Contains(typedText))
        {
            filteredItems.Add(cmbItems[i]);
        }

    }

// Clear the combo box before adding new items to Combo Box

    foreach(BoxItem item in filteredItems)
    {
        FilteredCmb.Items.Add(item);
    }

    FilteredCmb.IsDropDownOpen = true;
}


Q:

Cakephp different sessions for different users

I have cakephp application which has two separate logins one for admin and one for employee. I am using session to store login details.but when i logged out from admin it automatically logouts from employee and vice versa. can i use two different sessions for that?
I am not using role based login. Instead i am using plugin for admin
admin App Controller
 $this->loadComponent('Auth', [
                'loginAction' => ['controller' => 'Users', 'action' => 'login'],
            'logoutRedirect' => [
                'controller' => 'Users',
                'action' => 'login',
            ],
                'authenticate' => [
                    'Form' => [
                        'userModel' => 'Users',
                        'fields' => ['username' => 'username', 'password' => 'password']
                    ]
                ],
                'authError' => 'Enter Credentials',
                'storage' => 'Session',
                'unauthorizedRedirect' => false

            ]
        );

Employee App controller
  $this->loadComponent('Auth', [
            'loginAction' => [
                'controller' => 'Employees',
                'action' => 'loginemp'
            ],
            'logoutRedirect' => [
                'controller' => 'Employees',
                'action' => 'loginemp',
            ],
            'authError' => 'Enter Credentials',
            'authenticate' => [
                'Form' => [
                    'userModel' => 'Employees',
                    'fields' => ['username' => 'username', 'password' => 'password']
                ]
            ],
            'storage' => 'Session',
            'unauthorizedRedirect' => false
        ]);

A:

Change
'storage' => 'Session'

to
'storage' => [                       // Add this array
                'className' => 'Session',
                'key' => 'Auth.Admin',
            ],

in your admin panel Auth cofiguration.
For e.g. Assuming below admin panel Auth configuration:
$this->loadComponent('Auth', [
                    'loginAction' => ['controller' => 'Users', 'action' => 'login'],
                'logoutRedirect' => [
                    'controller' => 'Users',
                    'action' => 'login',
                ],
                    'authenticate' => [
                        'Form' => [
                            'userModel' => 'Users',
                            'fields' => ['username' => 'username', 'password' => 'password']
                        ]
                    ],
                    'authError' => 'Enter Credentials',
                    'storage' => [              // Change this
                            'className' => 'Session',
                            'key' => 'Auth.Admin',
                    ],
                    'unauthorizedRedirect' => false

                ]
            );


Q:

Is $\frac{1}{\pi}\int_{0}^{\infty} \Gamma(\sigma +xi)^2\,\Gamma(\sigma-xi)^2 \,dx = \frac{\Gamma(2\,\sigma)^4}{\Gamma(4\,\sigma)}$?

Using the approach from the answer to this question, it can be shown that for $\sigma \in \mathbb{C}, x\in \mathbb{R}$:
$$\frac{1}{\pi}\int_{0}^{\infty} \Gamma(\sigma +xi)\,\Gamma(\sigma-xi) \,dx =\frac{\Gamma(2\sigma)}{2^{2\sigma}} \qquad \Re(\sigma)>0$$

In a nutshell:
$$\Gamma(s) = \int_0^\infty \frac{x^{s-1}}{e^{x}}dx \overset{(x \, =
 \,e^u)}= \int_{-\infty}^\infty \frac{e^{su}}{e^{e^u}}du =
 \int_{-\infty}^\infty \frac{e^{-su}}{e^{e^{-u}}}du$$
$\Gamma(s)$ is the Laplace transform of $\dfrac{1}{e^{e^{-u}}}$ and
   $F_\sigma(\xi) = \Gamma(\sigma+2i \pi \xi)$ is the Fourier transform
   of $f_\sigma(u) = \dfrac{e^{-\sigma u}}{e^{e^{-u}}}$. Apply the
   Parseval theorem
   and get: $$\int_{-\infty}^\infty |F_\sigma(\xi)|^2d\xi =
 \int_{-\infty}^\infty |f_\sigma(u)|^2du = \int_{-\infty}^\infty
 \frac{e^{-2\sigma u}}{(e^{e^{-u}})^2}du $$
$$=\int_{-\infty}^\infty \frac{e^{2\sigma u}}{(e^{e^{u}})^2}du
 \overset{(e^u \, = \,x)}= \int_0^\infty \frac{x^{2\sigma-1}}{e^{2x}}dx
 =  \frac{\Gamma(2\sigma)}{2^{2\sigma}}$$

For the slightly altered function, I derived from numerical testing that:
$$\frac{1}{\pi}\int_{0}^{\infty} \Gamma(\sigma +xi)^2\,\Gamma(\sigma-xi)^2 \,dx = \frac{\Gamma(2\,\sigma)^4}{\Gamma(4\,\sigma)}\ \qquad \Re(\sigma)>0$$
Could this be proven? (I tried a similar approach as above, however the squares got me stuck).
Thanks!

A:

Notice that it suffices to prove the following result:

Barnes' beta integral. For $a, b, c, d \in \{ z \in \Bbb{C} : \Re(z) > 0 \}$, we have
  $$ \begin{split}
&\frac{1}{2\pi} \int_{-\infty}^{\infty} \Gamma(a+it)\Gamma(b+it)\Gamma(c-it)\Gamma(d-it) \, \mathrm{d}t \\
&\hspace{12em} = \frac{\Gamma(a+c)\Gamma(a+d)\Gamma(b+c)\Gamma(b+d)}{\Gamma(a+b+c+d)}.
\end{split} \tag{1} $$

In view of the principle of analytic continuation, it suffices to consider the case when $a > b > 0$ and $c > d > 0$. If we denote by $B(a,b,c,d)$ the LHS of $\text{(1)}$, then it is easy to check that $B(a,b,c,d) \in \Bbb{R}$:
$$ \overline{B(a,b,c,d)} = \frac{1}{2\pi} \int_{-\infty}^{\infty} \Gamma(a-it)\Gamma(b-it)\Gamma(c+it)\Gamma(d+it) \, \mathrm{d}t = B(a,b,c,d) $$
by applying the substitution $t \mapsto -t$. Now in order to compute $B(a,b,c,d)$, we utilize the following formula formula for the beta function:
$$ \frac{\Gamma(a)\Gamma(b)}{\Gamma(a+b)} = \int_{0}^{\infty} \frac{u^{a-1}}{(1+u)^{a+b}} \, du. $$
Then we have
$$ B(a,b,c,d)
= \frac{1}{2\pi} \Gamma(a+c)\Gamma(b+d)\int_{-\infty}^{\infty} \mathrm{d}t \int_{0}^{\infty} \mathrm{d}x \int_{0}^{\infty} \mathrm{d}y \, \frac{x^{a-1+it}}{(1+x)^{a+c}} \frac{y^{b-1+it}}{(1+y)^{b+d}}. \tag{2} $$
In order to compute this nasty triple integral, we want to interchange the order of integral. Even if we pretend that the Fubini's theorem works, it turns out that the resulting integral fails to be improperly integrable. So we introduce a small trick using the following theorem:

Theorem. (Abel). If $f(x)e^{-\epsilon x} \in L^1([0,\infty))$ for all $\epsilon > 0$ and $I := \lim_{R\to\infty} \int_{0}^{R} f(x) \, \mathrm{d}x$ exists, then we have the following convergence:
  $$ \lim_{\epsilon \to 0^+} \int_{0}^{\infty} f(x) e^{-\epsilon x} \, dx = I. $$

Using this, the triple integral in the RHS of $\text{(2)}$ can be computed as
\begin{align*}
&\int_{-\infty}^{\infty} \mathrm{d}t \int_{0}^{\infty} \mathrm{d}x \int_{0}^{\infty} \mathrm{d}y \, \frac{x^{a-1+it}}{(1+x)^{a+c}} \frac{y^{b-1+it}}{(1+y)^{b+d}} \\
&\hspace{3em} \stackrel{\text{(3)}}{=} \int_{-\infty}^{\infty} \mathrm{d}t \int_{0}^{\infty} \mathrm{d}x \int_{0}^{\infty} \mathrm{d}y \, \frac{x^{a-1}}{(1+x)^{a+c}} \frac{y^{b-1}}{(1+y)^{b+d}} \, \cos(t\log(xy)) \\
&\hspace{3em} \stackrel{\text{(4)}}{=} \lim_{\epsilon \to 0^+} \int_{-\infty}^{\infty} \mathrm{d}t \int_{0}^{\infty} \mathrm{d}x \int_{0}^{\infty} \mathrm{d}y \, \frac{x^{a-1}}{(1+x)^{a+c}} \frac{y^{b-1}}{(1+y)^{b+d}} \, \cos(t\log(xy)) e^{-\epsilon |t|} \\
&\hspace{3em} \stackrel{\text{(5)}}{=} \lim_{\epsilon \to 0^+} \int_{0}^{\infty} \mathrm{d}x \int_{0}^{\infty} \mathrm{d}y \, \frac{x^{a-1}}{(1+x)^{a+c}} \frac{y^{b-1}}{(1+y)^{b+d}} \frac{2\epsilon}{\epsilon^2 + \log^2(xy)}.
\end{align*}
Here are some explanation to each step:

(3) is obtained by taking the real part of the integrand, since we know that the the integral is real.
(4) is an application of the theorem above.
(5) follows from the Fubini's theorem and the Laplace transform of the cosine function.

Now we apply the substitution $\log(xy) = \epsilon u$ to the inner integral. Then
\begin{align*}
&\int_{-\infty}^{\infty} \mathrm{d}t \int_{0}^{\infty} \mathrm{d}x \int_{0}^{\infty} \mathrm{d}y \, \frac{x^{a-1+it}}{(1+x)^{a+c}} \frac{y^{b-1+it}}{(1+y)^{b+d}} \\
&\hspace{3em} \stackrel{\text{(6)}}{=} \lim_{\epsilon \to 0^+} \int_{0}^{\infty} \mathrm{d}x \int_{-\infty}^{\infty} \mathrm{d}u \, \frac{x^{a+d-1}}{(1+x)^{a+c}} \frac{e^{\epsilon b u}}{(e^{\epsilon u} + x)^{b+d}} \frac{2}{1+u^2}.
\end{align*}
Now it is easy to check that
$$\frac{e^{\epsilon b u}}{(e^{\epsilon u} + x)^{b+d}} \leq 1+ x^{-b-d}.$$
Thus by the assumptions on the magnitude of $a, b, c, d$, the integrand of the RHS of $\text{(6)}$ is dominated by an integrable function. Then by the dominated convergence theorem, we can put the limit inside the integral and we have
\begin{align*}
&\int_{-\infty}^{\infty} \mathrm{d}t \int_{0}^{\infty} \mathrm{d}x \int_{0}^{\infty} \mathrm{d}y \, \frac{x^{a-1+it}}{(1+x)^{a+c}} \frac{y^{b-1+it}}{(1+y)^{b+d}} \\
&\hspace{3em} = \int_{0}^{\infty} \mathrm{d}x \int_{-\infty}^{\infty} \mathrm{d}u \, \frac{x^{a+d-1}}{(1+x)^{a+b+c+d}} \frac{2}{1+u^2} \\
&\hspace{3em} = 2\pi \frac{\Gamma(a+d)\Gamma(b+c)}{\Gamma(a+b+c+d)}.
\end{align*}
This completes the proof of $\text{(1)}$.

A:

If you're still interested in evaluating the integral using Parseval's theorem for the Mellin transform, we just have to show that $$2\int_{0}^{\infty} x^{s-1} K_{0}(2 \sqrt{x}) \, \mathrm dx = \Gamma^{2}(s) \; , \quad \Re(s) > 0\, ,  \tag{1}$$
where $K_{\alpha}(z)$ is the modified Bessel function of the second kind of order $\alpha$.
Then for $\sigma >0$,
$$ \int_{-\infty}^{\infty} \Gamma^{2} (\sigma +it) \Gamma^{2} (\sigma -it) \, \mathrm dt = 2 \pi \int_{-\infty}^{\infty} \lvert \Gamma^{2}(\sigma +it) \rvert ^{2} \, \mathrm dt = 8 \pi\int_{0}^{\infty} x^{2\sigma -1} \, K_{0}^{2}(2 \sqrt{x}) \, \mathrm dx .$$
To show $(1)$, we can use the integral representation $$K_{0}(z) = \int_{0}^{\infty} e^{-z \cosh t} \, \mathrm dt \, , \quad \operatorname{Re}(z) >0 $$
and then switch the order of integration (which is justified because the iterated integral converges absolutely).
$$ \begin{align} 2\int_{0}^{\infty} x^{s-1} K_{0}(2 \sqrt{x}) \, \mathrm dx &= 4 \int_{0}^{\infty} u^{2s-1} K_{0} (2u) \, \mathrm du \\ &= 4 \int_{0}^{\infty} u^{2s-1} \int_{0}^{\infty} e^{-2 u \cosh t} \, \mathrm dt \,\mathrm du \\ &=4 \int_{0}^{\infty} \int_{0}^{\infty} u^{2s-1} e^{-2u \cosh t} \, \mathrm du \, \mathrm dt \\ &=\frac{4 \, \Gamma(2s)}{2^{2s}}\int_{0}^{\infty} (\cosh t)^{-2s} \,   \, \mathrm dt  \\ &= \frac{2 \, \Gamma(2s)}{2^{2s-1}}  \frac{\sqrt{\pi}}{2} \frac{\Gamma(s)}{\Gamma(s+ \frac{1}{2})} \tag{2} \\ &= \Gamma^{2}(s) \tag{3} \end{align}$$

$(2)$ https://math.stackexchange.com/a/1379526
$(3)$ Legendre Duplication Forumula

If we then use the integral representation$$K_{0}^{2}(z) = 2 \int_{0}^{\infty} K_{0}(2z \cosh t) \, \mathrm dt \, , \quad \operatorname{Re}(z) >0 \tag{4}$$ (which I'll talk about at the end), we get
$$\begin{align}\int_{-\infty}^{\infty} \Gamma^{2} (\sigma +it) \Gamma^{2} (\sigma -it) \, \mathrm dt &=8 \pi\int_{0}^{\infty} x^{2\sigma -1} \, K_{0}^{2}(2 \sqrt{x}) \, \mathrm dx  \\ &= 16 \pi\int_{0}^{\infty} u^{4\sigma -1} \, K_{0}^{2}(2 u) \,  \mathrm du  \\ & =32 \pi \int_{0}^{\infty} u^{4 \sigma-1} \int_{0}^{\infty} K_{0}(4u \cosh v) \, \mathrm dv \, \mathrm du \\ &= 32 \pi \int_{0}^{\infty} u^{4 \sigma -1} \int_{0}^{\infty} \int_{0}^{\infty} e^{-4u \cosh v \cosh w} \, \mathrm dw \, \mathrm dv \, \mathrm du  \\ &= 32 \pi \int_{0}^{\infty} \int_{0}^{\infty} \int_{0}^{\infty} u ^{4 \sigma-1} e^{-4u \cosh v \cosh w} \, \mathrm du \, \mathrm dw \, \mathrm dv \\ &= 32 \pi \int_{0}^{\infty} \int_{0}^{\infty} (4 \cosh v \cosh w)^{-4 \sigma} \, \Gamma(4 \sigma) \, \mathrm dw \, \mathrm dv \\ &=  \frac{32 \pi \, \Gamma(4 \sigma)}{2^{8 \sigma}} \left(\int_{0}^{\infty} (\cosh v)^{- 4 \sigma}  \, \mathrm dv \right)^{2} \\ &= \frac{32 \pi \, \Gamma(4 \sigma)}{2^{8 \sigma}} \frac{\pi}{4} \frac{\Gamma^{2}(2 \sigma)}{\Gamma^{2}(2 \sigma + \frac{1}{2})} \\ &= \frac{32 \pi \, \Gamma(4 \sigma)}{2^{8 \sigma}} \frac{\pi}{4} \,  \Gamma^{2}(2 \sigma) \,  \frac{2^{8 \sigma-2} \,   \Gamma^{2}(2 \sigma)}{\pi \, \Gamma^{2}(4 \sigma)}  \\ &= \frac{2 \pi \, \Gamma^{4}(2 \sigma)}{\Gamma(4 \sigma)} \end{align}$$

Integral $(4)$ can be derived by first expressing $K_{0}^{2}(z)$ as the iterated integral $$\frac{1}{4} \int_{-\infty}^{\infty} \int_{-\infty}^{\infty} e^{- z \cosh t} e^{-z \cosh u} \, \mathrm dt \, \mathrm du.    $$ Then interpret the iterated integral as a double integral and make the transformation $ v = \frac{t+u}{2}$, $w= \frac{t-u}{2}$ (which does not change the limits of integration).
Finally use the identity $\cosh (v+w) + \cosh(v-w) = 2 \cosh(v) \cosh(w) $ and then integrate.
G.N. Watson uses this approach to derive the generalization of $ (4)$ that I linked to above.

A:

We have that $\Gamma(\sigma+ix)\,\Gamma(\sigma-ix)$ is an even function and since
$$\text{(Weierstrass product)}\qquad \Gamma(z)=e^{-\gamma z}\prod_{n\geq 1}\left(1+\frac{z}{n}\right)^{-1}e^{z/n} \tag{1}$$
we also have
$$ \Gamma(\sigma+ix)\,\Gamma(\sigma-ix) = e^{-2\gamma \sigma}\prod_{n\geq 1}\frac{\exp\left(\frac{2\sigma}{n}\right)}{\left(1+\frac{\sigma+ix}{n}\right)\left(1+\frac{\sigma-ix}{n}\right)}\tag{2}$$
and we may compute such integrals through the residue theorem and Legendre's duplication formula.


Q:

Turntable rotation with Y-axis up add-on

Blender is hardwired to work with the Z-axis pointing upward, which is pretty inconvenient if one wants to import the game engine's physic simulation to a third party framework which happens to have the Y-axis pointing upwards.
While the vertices data can be exported to most 3d modeling formats swapping two axis with no problem, the game physics exporter doesn't allow to swap the axis.
One solution is to rotate the view to place the Y-axis up, whis is my approach, but it has the inconvenient to mess the turntable mode rotation, which main axis of rotation is aligned parallel to the Z-axis.
So it would be very handy to have a turntable rotation mode with the main axis of rotation aligned parallel to the Y-axis.

Update:
Most third party game engines, would need two files to be exported, the vertices data (.obj in my case), and the physics simulation data (.bullet)
Objects can be modeled independently of the axis pointing upwards, as long as the exported data have the right axis up, there wouldn't be any problem.
The built-in physics simulation can't be exported with the axes swapped, let's say it is Y up hardwired.
Then there is the third party game engine, which happens to use OpenGL's Y-axis up convention.
So my approach is to leave the third party game engine, and the Blender's physics exporter untouched, then export the vertices data as is, without any axis swapping.
The only problem (sort of) is that it would require to use blender with Y-axis up, which at this point means to be able to navigate "naturally" with Y up.

A:

space_view3d_turntable_y_up.py
Enable turntable rotation with Y axis up.
space_view3d_turntable_z_up.py
Enable turntable rotation with Z axis up.
space_view3d_turntable_any_up.py
Enable turntable rotation with any axis up, the axis that is the most vertically aligned is the up axis for the turntable rotation until a new mouse gesture, i.e. until either the mouse button or the keyboard key modiffier is released.

All addons have the keyboard combination by default to
Ctrl+Left Mouse Drag because there is no need to install them all.
Neither disables the built-in view rotation, so that one can have both the trackball (built-in) and the turntable (addon) at the same time mapping them to diferent keys.


Q:

move UILabel randomly between 4 or 5 x/y coordinates

Im trying to figure out a way to move a UILabel to different pre determined points on the screen at random (that is, to choose from a list of pre determined points randomly and move there).
My initial thoughts is to write a  method that will choose randomly from an array but would I need two seperate arrays for the x and the Y? Any suggestions or a point in the right direction would be greatly appreciated.

A:

You could adapt the code from this question (getting a random object from an array)
Random Text Sent to UILabel
You could store the CGPoint in an NSValue, and then in the array (as you can't put a CGPoint directly in an NSArray as it's not an object) Eg:
NSArray *arrayOfPoints = [NSArray arrayWithObjects:[NSValue valueWithCGPoint:point1],
                          [NSValue valueWithCGPoint:CGPointMake(12, 14)],
                          nil];

(The example code just above stores just 2 points, you can have as many as you like, and the first value is if the CGPoint already exists/created dynamically and the second value is if you want to make the point on the spot)
Bringing the code across from the question I linked to, and adapted it to your question:
CGPoint randomPoint = [arrayOfPoints objectAtIndex:arc4random() % [arrayOfPoints count]];

myLabel.frame = CGRectMake(randomPoint.x, randomPoint.y, myLabel.frame.size.width, myLabel.frame.size.height);


Q:

Array storage in memory

I am reading a stream of chars and I need them straight as uint64_t values. I used the following approach. But it seems that the array is stored in backward order. However the memory locations are in order when I output their addresses. Sorry if this is a too dumb question. I am struggling to figure out my basic memory knowledge.
#include <iostream>

int main() {
    unsigned char ar[8] = {1, 0, 0, 0, 0, 0, 0, 0};
    uint64_t num = *((uint64_t*)ar);
    std::cout << num << std::endl;

    for(size_t i = 0; i < 8; i++) {
        std::printf("%lu %x\n", i, &ar[i]);
    }
}

Following is the output
1
0 ffffcc08
1 ffffcc09
2 ffffcc0a
3 ffffcc0b
4 ffffcc0c
5 ffffcc0d
6 ffffcc0e
7 ffffcc0f

I expected the result of num to be 2^56.

A:

The problem is the endian, your system is little endian and you read the uint64_t like you are in a big endian system.
there is one compile time solution without branching in c++20:
you can use std::endian to find the endian at compile time and use if constexpr to decide how your functions work.
#include<iostream>
#include <type_traits>

template <typename T>
void print()
{
    constexpr bool is_little_endian = (std::endian::native == std::endian::little);
    if constexpr (is_little_endian) {
        unsigned char ar[8] = {0, 0, 0, 0, 0, 0, 0, 1};
        T num = *((T*)ar);
        std::cout << num << std::endl;
    } else {
        unsigned char ar[8] = {1, 0, 0, 0, 0, 0, 0, 0};
        T num = *((T*)ar);
        std::cout << num << std::endl;
    }
}

int main()
{
    print<uint64_t>();
}

Output

72057594037927936

Live


Q:

Print file paths from a list in python using exec in a tkinter label

I want to display a list of file names in a tkinter window. the list consists of file paths.
I've successfully used the code below with a list of string items. I'm wondering if the fact that my list file_list is my problem because its file paths. Maybe file paths show up differently in my list so i need to handle differently?
for y in range(len(file_list)):
    exec(f'Label%d=Label(InfoWindow,text="%s")\nLabel%d.grid(row={y},
    column=0, sticky=W)'%(y,file_list[y],y))
    InfoWindow.mainloop()

I am expecting a file path from the list to show up in a each row of my window but it's not. instead i get this error message:
exec(f'Label%d=Label(InfoWindow,text="%s")\nLabel%d.grid(row={y}, column=0, sticky=W)'%(y,file_list[y],y))
  File "<string>", line 1
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 12-13: malformed \N character escape

A:

This will create labels for you in the window, also the dict can be used later for references.
name_dict = {}
for i in range(len(file_list)):
    name_dict[i] = tk.Label(InfoWindow,text=file_list[i]).grid(row=i,column=0, sticky='w')


Q:

Method Does Not Exist error message

My class subtracts the values of child account number fields from the current values of it's parent account number fields in a hierarchy. I need this class to run everytime a child account changes its parent (i.e the parent name field is edited to a new name). I'm attempting to have this trigger compare the old value and the new value of the parent field, when creating the logic for this trigger I keep recieving this error message:

Method does not exist or incorrect signature: void executeSub(Account)
  from the type Parent_Subtract

Class:
public class Parent_Subtract {
public static void executeSub(List<Account> scope) {

    Id CRecordType = Schema.SObjectType.Account.getRecordTypeInfosByName().get('Customer Account').getRecordTypeId();
    Id DRecordType = Schema.SObjectType.Account.getRecordTypeInfosByName().get('Division Account').getRecordTypeId();
    Id SRecordType = Schema.SObjectType.Account.getRecordTypeInfosByName().get('Site Account').getRecordTypeId();
    Id ERecordType = Schema.SObjectType.Account.getRecordTypeInfosByName().get('Enterprise Account').getRecordTypeId();
    Id DSAccounts = '01270000578681Y';

        List<Id> listIds = new List<Id>();
        Map<Id, Account> parentAccounts = new Map<Id, Account>([SELECT Id, RecordTypeId, Parent_Account__c, Total_CCF__c, Total_Revenue__c,
                                                                Total_Usage_kWh__c, Account_kw__c, AnnualRev FROM Account WHERE ID In :listIds]);
        Map<Id, Account> newParent = new Map<Id, Account>();
        Set<ID> setParentAcctID = new set<ID>();
        List<Account> listforFinalUpdate = new List<Account>();

    for(Account acc : scope){
        setParentAcctID.add(acc.Parent_Account__c);
    }

        List<account> listParentAcctData = [Select id, Total_CCF__c, Total_Revenue__c,
                                                                Total_Usage_kWh__c, Account_kw__c, AnnualRevenue
                                                                FROM account
                                                                WHERE id =: setParentAcctID];
        for(Account a : listParentAcctData)
        {
            newParent.put(a.id,a);
        }

      for(Account acc: scope)
      {
        Account acct = newParent.get(acc.Parent_Account__c);

            system.debug('acc.Total_Usage_kWh__c:'+acc.Total_Usage_kWh__c);
            system.debug('acc.Total_CCF__c:'+acc.Total_CCF__c);
            system.debug('acc.AnnualRev:'+acc.AnnualRev);
            system.debug('acc.Account_kw__c:'+acc.Account_kw__c);

            acct.Total_Usage_kWh__c -= acc.Total_Usage_kWh__c;
            acct.Total_CCF__c -= acc.Total_CCF__c;
            acct.AnnualRev -= acc.AnnualRev;
            acct.Account_kw__c -= acc.Account_kw__c;

                listforFinalUpdate.add(acct);
        }

        if(listforFinalUpdate.size() > 0)
        {
          update  listforFinalUpdate;
        }
    }

}

Trigger:
   if(Trigger.isUpdate){
        for(Account acc: Trigger.new){

            Account oldName = Trigger.oldMap.get(acc.Parent_Account__c);

            Account newName = Trigger.newMap.get(acc.Parent_Account__c);

                if(newName != oldName){
                      acct.add(acc);
            }

        }
        Parent_Subtract.executeSub(acct);
    }

   }

Am I on the right track with this functionality and does anyone know why I am recieving this message?

A:

You're calling a method with a single Account parameter:
Parent_Subtract.executeSub(acct);

but this method is defined to take a List<Account> as its parameter:
public static void executeSub(List<Account> scope)

This method is bulkified: it is defined to run exactly one DML operation:
update  listforFinalUpdate;

regardless of how many Account records it receives. For this reason you need to be calling it with a List<Account>, not calling it repeatedly in a loop. Your trigger should accumulate a List<Account> inside your for loop, and then make a single call to executeSub() outside the loop.


Q:

Encapsulate ActiveX for JavaScript

I'm trying to develop an website that can use a specific mailing program (lotus-notes), but to do so, I need to create a Session with the application that usually was created using an ActiveXObject() object. The problem is that I won't be the end user of the website, and I do not want to create a website not user friendly, always asking for the user to add extensions in order to make the website functionalities work.
I am doing my best to find a workaround to the use of ActivateXObject(), encapsulating the application in the best way I can, so is there any kind of plugin that I can add through JavaScript to my website in order to use ActiveXObject() or any equivalent function?

A:

No, there isn't. To create a COM object (which is what ActiveXObject did), you'd need to use a browser with native support for ActiveX (old IE) or a browser you could use and/or write an old-style (NPAPI) "plugin" on.
All major browsers have discontinued or are actively (no pun) discontinuing support for the NPAPI plugin mechanism because of the security issues around it.
For instance, I think the SilverLight plugin might have been able to create COM objects, but as it's implemented as an NPAPI plugin, it is rapidly disappearing (and was EOL'd by Microsoft in 2012; they support SilverLight 5 through 2021, but that doesn't help you).
There is no replacement technology that can create COM objects from JavaScript code running in a web page in a standard browser at this time.


Q:

Intellij reformatter remove indent of empty lines

I have search widely but cannot find my answer. The place I work use eclipse for Java with a customize formatter, this formatter keep indent (a tab) for empty lines. However, in in intellij, the reformatter remove the tab which cause a gigantic modification of the code when use git diff. So I am wondering if there is any way to keep the indent when doing auto reformatting? I knew I can keep those when saving a file but not sure if it can be done when using reformatter.

A:

After several days trials, finally found it. Intellij can be enforced to keep indent on empty lines. See attached config


Q:

Error message when picture upload field is empty

How can make picture upload required on HMS testimonial module?
Here the code bribe about that field :

if (isset($_FILES['hms_testimonials_image']) && ($_FILES['hms_testimonials_image']['size'] > 0) && $settings['form_show_upload'] == 1) {

$get_file_type = wp_check_filetype( basename($_FILES['hms_testimonials_image']['name'] ) );
$uploaded_type = $get_file_type['type'];

if (!in_array($uploaded_type, $allowed))
$errors[] = apply_filters('hms_testimonials_sc_error_image', __('You have uploaded an invalid file type.', 'hms-testimonials') );

}

A:

You can check if no files uploaded using,
count($_FILES);

Above code will return 0 in case user have not uploaded any files.

If there are multiple file upload handling and you want to check for specific filed, You can use is_uploaded_file() to ensure file upload of specific field.
Like this,
if(!is_uploaded_file($_FILES["filed_name"]['tmp_name'])) {
   echo "Error: File not uploaded";
}

http://php.net/manual/en/function.is-uploaded-file.php


Q:

How to format drive after installing berryboot

When I first got my Raspberry PI, I decided that I would install Berryboot. Overall, It's really cool. But now my files are corrupt. I've lost 3 SD cards like this. When I go into windows, It doesn't show the ext4 partition, only the FAT boot partition. How would I go about formatting my drive as a whole?

A:

See this website: https://www.sdcard.org/downloads/formatter_4/
Download the software, run, select the SD card drive and it will completely format everything on the SD card no matter what file system was used.


Q:

how do I query sql for a latest record date and hour for each user

I have a table that is a collection entries to the progress of law processes.
id_andamento_processo   id_processo data_andamento  hora_andamento  descricao
1   18      2016-05-30  14:00:00
2   3122    2016-05-18  16:08:54    campo para o texto da PUBLICAÇÃO DO DIÁRIO OFICIAL
3   3122    2016-05-18  16:09:55    campo para o texto da PUBLICAÇÃO DO DIÁRIO OFICIAL
4   3122    2016-05-18  16:13:49    campo para o texto da PUBLICAÇÃO DO DIÁRIO OFICIAL
5   2001    2015-07-15  14:34:54    ANDAMENTO: 30/06/2014 Protocolo (E-Doc 12148046) 10003/2014 (LAT-Laudo Assistente Técnico): PROTOCOLO
6   2001    2015-07-15  14:34:54    ANDAMENTO: 03/07/2014 Protocolo (E-Doc 12174924) 10352/2014 (LPC-Laudo Pericial (Conhecimento)): PROTOCOLO
7   2001    2015-07-15  14:34:54    ANDAMENTO: 15/07/2014 Devolução de Carga

How do I create a query that would give me the latest date and hour for each process?
I have followed the aswer to this related question:
how do I query sql for a latest record date for each user
and I am able to get the latest date to each process.
select a.id_processo, a.data_andamento, a.hora_andamento, a.descricao_ptbr
from andamento_processo a
inner join (
    select id_processo, max(data_andamento) as Maxdata_andamento
    from andamento_processo
    group by id_processo
) am on a.id_processo = am.id_processo and a.data_andamento = am.Maxdata_andamento

However, this returns duplicate progress with the same date and different time:
id_processo     data_andamento  hora_andamento  descricao_ptbr
0   2016-06-09  11:03:00
18  2016-06-21  11:01:00
18  2016-06-21  11:12:00    Verificação teste para o RR juridico.
18  2016-06-21  11:37:00    Teste

I tried to do add a MAX on the hour of the progress, but didn't work, some progresses disappeared. I tried like this:
select a.id_processo, a.data_andamento, a.hora_andamento, a.descricao_ptbr
from andamento_processo a
inner join (
    select id_processo, max(data_andamento) as Maxdata_andamento,   max(hora_andamento) as Maxhora_andamento
from andamento_processo
group by id_processo
) am on a.id_processo = am.id_processo and a.data_andamento = am.Maxdata_andamento and a.hora_andamento = am.Maxhora_andamento

I am using MySQL. I need a query without duplicate progresses, like this:
id_processo     data_andamento  hora_andamento  descricao_ptbr
0               2016-06-09      11:03:00
18              2016-06-21      11:37:00        Teste
1006            2016-05-25      16:10:10        Descrição: Mero expediente (19/05/16) Descrição: Mero expediente (19/05/16)

A:

It is not clear why date and time are two separate columns. Maybe because they can be null for certain scenarios. So get those records for which both are given (and presumably belong together), combine them to one datetime and work with this.
select
  id_processo,
  max(timestamp(data_andamento, hora_andamento))
from andamento_processo
where data_andamento is not null
  and hora_andamento is not null
group by id_processo
order by id_processo;

If you want more data from the records with the max datetimes then use above as a subquery (derived table) and join the table again.
For completeness sake: Here the same query in an IN clause to get more data from the records:
select *
from andamento_processo
where (id_processo, timestamp(data_andamento, hora_andamento)) in
(
  select
    id_processo,
    max(timestamp(data_andamento, hora_andamento))
  from andamento_processo
  where data_andamento is not null
    and hora_andamento is not null
  group by id_processo
)
order by id_processo;


Q:

Hashing vs. Signing Binaries

If you want to ensure that a file is valid (untampered and came from the correct/expected source), there are two things you can do: hashing, and signing.
For the purposes of my question, hashing means providing a hash of the file (along with the file) to download. The client downloads the hash and the file, re-computes the hash, and verifies that it matches the downloaded hash; this "proves" that the file was untampered with.
Signing means using a public-private encryption scheme, where you sign the binary with a public key, and the client uses the private key to verify that you really did sign the key.
Based on these definitions, I don't really see what is the main benefit of signing something vs. hashing something. Both of them are supposed to prove that the file was not tampered with.
The only thing I can see is that with hashing, a compromised server could mean someone also compromising the hash and replacing a malicious binary with a matching key; but with a public-private scheme, as long as the private key remains private, there is no way to forge a malicious file.
Or am I missing something?

A:

The difference is as you said: a hacker can update a hash to match the tampered-with file, but cannot generate a valid signature.
Signing is done with the private key, verification with the public key. You said the opposite above. It's also typically done on the hash of the file and not the file itself for practical reasons.

A:

Signing verifies two things -- that the file has not been tampered with, and the identity of the signer.  If you can be sure that entity giving you the hash is absolutely the entity that is supposed to be giving you the file, then the two are equivalent.  Signing and certificate authorities are a way of ensuring that trust relationship.

A:

The big difference between providing some data (an executable a document, whatever) along with a hash and providing the same data with a signature is with the hash, both the data and the hash value come from the same place.  So, if someone can compromise one of them, he can probably also compromise the other.
For example, if I can hack into your web server, I can easily replace your executable with my own version and replace the hash value with the correct hash for my executable.
If you sign your executable, I can't just produce another signature for a different executable and replace your original signature.  The signature verifies both the hash of the original data (the data has not changed since being signed) and that the signature was generated by your private key.
Of course, this all assumes that people who receive your signed executable have received your public key in some trusted way.  If I can trick people into using my public key instead of yours, then I can hack into your website and replace your signed executable with my own.  That's why we have certificate authorities.
This page has a high level overview of digital signatures.


Q:

Why is the implementation of Object.equals() not using hashCode()?

or "Why do the Sun/Oracle guys force us to override both equals() and hashCode() everytime?"
Everyone knows that, if you override equals() or hashCode() of an object, you have to override the other one, too, because there is a contract between those two:

Note that it is generally necessary to override the hashCode method whenever this method [i.e. equals()] is overridden, so as to maintain the general contract for the hashCode method, which states that equal objects must have equal hash codes.
  -- API doc of Object.equals()

Why isn't it implemented that way in the Object class:
public boolean equals(Object obj) {
    return this.hashCode() == obj.hashCode()
}

If they did this, it would have saved the rest of the world from having to implement both methods. It would be enough to override only hashCode().
I guess the guys had some good reason not to do this. I just cannot see it - please clear this up for me.

A:

If a.equals(b) returns true then a.hashCode() == b.hashCode() must evaluate to true.
The opposite is not true! It's perfectly valid to have two objects where a.hashCode() == b.hashCode() is true, but a.equals(b) is false.
In fact, that's necessary. There are 232 possible return values for hashCode(). At any given moment a JVM can hold more than 232 objects (given there's enough memory, which is quite possible these days). Assuming that none of the objects are equal to each other (easy to do, just let them be "s1", "s2", ...), then you're bound to have a collision of checksums (see Pidgeonhole principle).
In fact, this is the simplest possible hashCode implementation that's correct (but otherwise terribly bad) for every class*:
public int hashCode() {
  return 0;
}

It magically fulfills all the requirements of the general hashCode() contract.
* except for those classes that have a defined and documented hashCode algorithm that they must implement, the prime example being String.hashCode().

A:

Joachim is correct, but there's another reason: Efficiency.
Calculating a hash code can be expensive, and this effort would be unnecessarily incurred if equals() was invoked, but hashCode() never was.
There are lots of cases where this would be the case; only classes like Hashtable (or those that use it) invoke hashCode().


Q:

best way to download multiiple small images

I found another similar question: Best way to download images from XML content in StackOverflow, but not exactly the same.
I have multiple small images from XML content and I have control over both server and client side. Shall I embed image bytes into XML or only pass urls for each image in XML and expect the client to initiate http calls again to download images? I am shooting for low latency but not a lot of images: 100 images of size 10-15k.
Any suggestion/comment is welcomed.

A:

You should use a single HTTP request and return a multi-part MIME response.


Q:

Using BASH how can I capture the last 5 lines of a log file without causing file locking

I have a file that is created by an application. The app is perpetually writing large volumes of data to the file.
I need to capture a copy of the last 10 lines of the file periodically and write it to another file without causing any file locking, which could impact the application writing the logFile.
How do I do that without impacting the application writing the logfile? i.e without causing any file locking.
logFile example
1452431219885,546,Item Details Request,200,OK,text,true,12562,91,91,271,ip-172-31-36-138,0,134
1452431219886,1300,Select Item Request,200,OK,text,true,28541,91,91,444,ip-172-31-36-138,0,209
1452431219889,210,Login Success Page Request,200,OK,text,true,29405,91,91,123,ip-172-31-36-137,0,27
1452431219898,217,Item Details Request,200,OK,text,true,10620,91,91,215,ip-172-31-36-135,0,106
1452431219900,1668,Logout and Exit Request,200,OK,text,true,19676,92,92,1133,ip-172-31-36-136,0,266
1452431219902,589,Search Page Request,200,OK,text,true,13392,91,91,296,ip-172-31-36-138,0,147
1452431219903,589,Save Basket Request,200,OK,text,true,17473,91,91,294,ip-172-31-36-138,0,147
1452431219908,1135,Search Results Request,200,OK,text,true,561615,91,91,229,ip-172-31-36-136,0,116
1452431219914,1114,Item Details Request,200,OK,text,true,93243,91,91,282,ip-172-31-36-138,0,138
1452431219921,825,Select Item Request,200,OK,text,true,24354,91,91,339,ip-172-31-36-135,0,161

A:

Under most operating systems (i.e. BSDs, Linux, Mac, essentially anything not Windows), files never get locked unless the program explicitly requests it.
Even then, locks in these operating systems are only advisory, so won't affect programs which don't care about them.
So the answer is: almost anything that can get the last lines of the log, will do so without locking.

A:

Obtain the last 10 lines
If i understand correctly, you can simply use:
# tail reads the input file and print out the last 10 lines (default)
tail /path/to/file.log > 10_lines.dump
# Change number of lines from default(10) to 5
tail -n 5 /path/to/file.log > 5_lines.dump

Show last lines every X seconds
If you need to do this periodically without saving the output you can use watch:
# watch show the output of the tail command every 5 seconds (default 2s)
watch -n 5 tail /path/to/file.log
# OR last 5 lines every 5 seconds
watch -n 5 tail -n 5 /path/to/file.log

Extract and save for future reference in background
Create a crontab file (name it file.crontab or as you wish) with an editor of your choice with this content:
# ** Crontab file schema **
# .------------------ [m]inute:           [0 - 59] OR */x (every x minutes)
# |   .-------------- [h]our:             [0 - 23] OR */x (every x hours)
# |   |   .---------- [d]ay [o]f [m]onth: [1 - 31]
# |   |   |   .------ [mon]th:            [1 - 12] OR jan,feb,mar,apr...
# |   |   |   |   .-- [d]ay [o]f [w]eek:  [0 - 6]  (Sunday can be 0 or 7)
# |   |   |   |   |                       (also: sun,mon,tue,wed,thu,fri,sat)
# m   h   d  mon dow
# *   *   *   *   *   command executed every minute with my user permission
# --
# Execute tail every 5 minutes and append last 10 lines of input to log.extract
*/5   *   *   *   *   tail "/path/to/file.log" >> "/path/to/log.extract"

Install it on your system using crontab:
crontab file.crontab


Q:

free() doesn't accept type of structure

#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>

typedef struct STATE STATE;
typedef struct TRANSITION TRANSITION;

struct STATE {
    char name[4];
    bool initial_state;
    bool final_state;
    TRANSITION *transitions;
    int numberTransitions;
};

struct TRANSITION {
    char c;
    STATE *destination;
};

STATE *create_state(char *name, bool is_initial, bool is_final);
void add_transition(STATE *source, char sign, STATE *dest);
void destroy_state(STATE **pp_state);

STATE *create_state(char *name, bool is_initial, bool is_final) {
    STATE *state = malloc(sizeof(STATE));
    strcpy(state->name, name);
    state->initial_state = is_initial;
    state->final_state = is_final;
    state->transitions = NULL;
    state->numberTransitions = 0;
    return state;
}

void add_transition(STATE *source, char sign, STATE *dest) {
    if (source->transitions == NULL) {
        TRANSITION *transitions = malloc(sizeof(TRANSITION));
        transitions->c = sign;
        transitions->destination = malloc(sizeof(STATE));
        transitions->destination = dest;
        source->transitions = transitions;
        source->numberTransitions = 1;
    } else {
        TRANSITION *transitions = source->transitions;
        int numberTransitions = source->numberTransitions;
        size_t new_size = sizeof(transitions) + sizeof(TRANSITION);
        transitions = realloc(transitions, new_size);
        transitions[numberTransitions].c = sign;
        transitions[numberTransitions].destination = dest;
        (source->numberTransitions)++;
    }
}

void destroy_state(STATE **pp_state) {
    TRANSITION *transitions = (*pp_state)->transitions;
    int numberTransitions = (*pp_state)->numberTransitions;
    int i = 0;
    for (i = 0; i < numberTransitions; i++) {
        free(transitions[i]);
        transitions[i] = NULL;
    }
}

My exception says that the type of transitions[i] is incompatible with the methods parameter. What is wrong with that method call? Transitions is a structure.
EDIT: I added the other methods because it was requested.
EDIT2: OK, I found out if my STATE has only one TRANSITION, I can free the TRANSITION pointer. So my guess is that I do a mistake with the reallocation when I try to realloc the memory for my additional transition.
size_t new_size = sizeof(transitions) + sizeof(TRANSITION);
transitions = realloc(transitions, new_size);

A:

free(transitions[i]);

transitions[i] is not any pointer type to be passed to free . transitions is a pointer to structure but transition[i] becomes structure variable(not pointer type) and thus should not be passed to free .
Do this -
free(transitions);


Q:

Srcset seems not to be working on mobile safari in iOS7?

For a logo on a website the following image tag is used:

It won't work for me on mobile safari on iOS7 iPhone and iPad mini retina, although multiple articles suggest it would work on Webkit and in mobile safari:

Improved support for high-resolution displays with the srcset image attribute
WebKit Has Implemented srcset, And It’s A Good Thing

High DPI Images for Variable Pixel Densities

I tried to check for srcset with JavaScript, to no avail, but did get a confirming false alert:
function isSrcsetImplemented() {
  var img = new Image();
  alert('srcset' in img);
}

isSrcsetImplemented();

Why doesn't it work for me? Did they take it out of Webkit in favor of an alternative?

A:

Update: 9/14/14
Supported now in iOS8 which was released to the public today, so expect very good penetration soon.

There is no support in Safari yet, mobile or desktop.
Although it was announced for webkit months ago it's only just been introduced in Chrome (desktop) as of Feb 2014. It's actually in the next public release (v34) which is the current beta as of 4/6/14. So by the time most people read this it should be available for testing on the destktop Chrome.
My current strategy/recommendation is to do this:

where
 high.png = 200x200
 low.png = 100x100

This will give retina graphics immediately on all mobile and desktops, scaled down by the browser for lower resolution screens.
When mobile safari introduces srcset then non-retina ipads can will revert to low.png automatically to save on bandwidth (who knows maybe Apple will even include a setting to only download low res images).
On desktop Chrome (v.34) and other browsers (eventually), the browser will essentially ignore src and you'll get high.png if you have a high res screen and low.png if you have standard resolution.
In addition even on 'regular' screens if your zoomlevel is above 1.0 (as you visit the page or refresh) then it will serve you the high.png file. This is a nice touch, and a good reason for using srcset over mediaqueries or javascript replacement techniques.

Advanced version (my actual real recommendation for today):
This has an obvious problem in that as of today you'll be serving everyone with high res images - until srcset support has improved which may take a while.
So I chose the following server side compromise, (given that my main consumer of high res images are retina iPads):
// server side(pseudocode)- (I made an ASP.NET MVC helper for this)
@if (Request.UserAgent.Contains("iPad")))
{

}
else {

}

Anyone with srcset support will always get the appropriate version. Desktop users (except Chrome v34) will get standard resolution images. ALL iPads will unconditionally get high resolution images - until Apple updates Safari at which time non-retina iPads will get the low resolution version.
Fortunately the website I'm designing won't be released for a month or two, and I'm hoping Safari will be updated within a few more months making this a future-proofing gamble I'm willing to take.
Tip: for testing high.png and low.png just put two completely different images for high.png and low.png - like a cat and a dog - then it'll be clear if it's working or not.


Q:

Try to show image but shows a broken link instead

I want to show a picture in my code but for some reason I get a big white almost blank page with a broken link img. I want to show the image and along with any other information.
I also want to resize the image(so it doesnt cover the whole page).
The code:
<?php

session_start()

?>

<!DOCTYPE html>

<meta charset="utf-8" />
<meta name="viewport" content="initial-scale=1.0" />
<link rel="stylesheet" href="css/style.css" />

Welcome!

<?php

include_once "navigation.php";

?>

<?php

if (isset($_GET['search'])) {
$Name = $_GET['search'];
mysql_connect("localhost","root","") or die ("Could not connect to the server!");
mysql_select_db("pictures") or die ("That database could not be found!");
$query = mysql_query("SELECT * FROM picture WHERE Name='$Name'") or die ("The query could not be completed, please try again later!");
    if (mysql_num_rows($wepquery) !=1) {
        die ("That name could not be found!");
    }
    while ($row = mysql_fetch_array($query, MYSQL_ASSOC, 0)) {
        $dbName = $row['Name'];
        $dbCreator = $row['Creator'];
        $dbDescription = $row['Description'];
        $imageData = $row['Image'];
    }
    header("Content-type: image/jpeg");
    if($Name != $dbName) {
        die ("There has been a fatal error. Please try again.");
    }
?>

<?php echo $Name; ?>

Creator: <?php echo $dbCreator;?>

Description:
<?php echo $dbDescription;?>

Picture:
<?php echo $imageData;?>

<?php
} else die ("You need to specify a submission!");

?>

The database:
id, Name, Creator, Description, Image_name, Image(mediumblob).
The last two fields as you can see is dedicated to pictures. Yes I know about PDO and MySQLi, but I just want to finish this code first. Any help?

A:

Images need to either be served by URL or the blob needs to be converted to a data URI like so:

Creator: <?php echo $dbCreator;?>

Description:
<?php echo $dbDescription;?>

Picture:
<?php echo ""; ?>


Q:

Gradle Android unit tests that depend on an 'aar' for build tool 0.11.+

I am using gradle build system to run Roboletric tests however I've encountered the problem that was described here Gradle Android unit tests that depend on an 'aar' but the solution only works for build tool version 0.9.+ and not 0.11.+
as I cannot find the exploded-aar directory. Any ideas?
Here's the partial build file
configurations {
    testLocalCompile {
        extendsFrom compile
    }
}

sourceSets {
    testLocal {
        java.srcDir file('src/test/java')
        resources.srcDir file('src/test/res')
        compileClasspath += configurations.testLocalCompile
        runtimeClasspath += compileClasspath
    }
}

dependencies {
testLocalCompile fileTree(dir: "$project.buildDir/intermediates/exploded-aar", include: "**/classes.jar")

}

task localTest(type: Test, dependsOn: assemble) {
    testClassesDir = sourceSets.testLocal.output.classesDir

    android.sourceSets.main.java.srcDirs.each { dir ->
        def buildDir = dir.getAbsolutePath().split('/')
        buildDir =  (buildDir[0..(buildDir.length - 4)] + ['build', 'intermediates', 'classes', 'debug']).join('/')

        sourceSets.testLocal.compileClasspath += files(buildDir)
        sourceSets.testLocal.runtimeClasspath += files(buildDir)
    }

    classpath = sourceSets.testLocal.runtimeClasspath
}

check.dependsOn localTest

A:

That change again in 0.12.2
http://tools.android.com/tech-docs/new-build-system

Move unzipped aar back in each project as a temporary fix for a possible race condition.

So you have to change the dependency back:

unitTestCompile fileTree(dir: "$project.buildDir/intermediates/exploded-aar/", include:"**/classes.jar")

(PS: do not know if is it the right way to post this in stackoverflow)

A:

Fixed it: it seems like in the 0.11.+ build tool the exploded-aar folder is moved to root. I had to change the dependency:
testLocalCompile fileTree(dir: "${rootDir}/build/exploded-aar", include: "**/classes.jar")


Q:

Query LIKE on date type

I am doing queries on the free DB of W3School and I have to do a query where I print every record that has year = 1996, month = 07 and any day.
I searched and I tried this form:
SELECT Customers.Country
FROM Customers, Orders
WHERE Customers.CustomerID = Orders.CustomerID
AND (DATEPART(yy, OrderDate) = 1996
AND DATEPART(mm, OrderDate) = 07);

But it doesn't work...
I can use this form:
SELECT *
FROM Orders
WHERE OrderDate BETWEEN #07/15/1996# AND #07/31/1996#;

but this still don't know why other forms don't work!

A:

I believe that w3schools actually uses SQL-lite for their editor and then this would work:
SELECT c.Country
FROM Customers c
join Orders o on c.CustomerID = o.CustomerID
where strftime('%Y', o.OrderDate) = '1996'
and strftime('%m', o.OrderDate) = '07'

I would like to give you few advice's with this code:

Use aliases for your tables (aliases are this letters c and o and they are used so the code can be more readable. If you can use something with more sense than one letter do it like that, for example cust for customers or ord for orders table).
Use modern join like this:
FROM Customers c
join Orders o on c.CustomerID = o.CustomerID

and not like this:
FROM Customers, Orders
WHERE Customers.CustomerID = Orders.CustomerID

You do not need to put this two AND conditions inside brackets.
To make this work result of strftime function needs to be compared with values between single quotes. This is tested and works here https://www.w3schools.com/sql/trysql.asp?filename=trysql_select_all

I have also installed Firefox on my PC (Firefox is under "WebSQL Browser Support") and this is the code that works on Firefox:
SELECT c.Country
FROM Customers c, Orders o
where c.CustomerID = o.CustomerID
and year(o.OrderDate) = 1996
and month(o.OrderDate) = 7


Q:

Hiding GetHashCode/Equals/ToString from fluent interface classes intellisense in Visual Studio for C#?

I have a fluent interface for an IoC container registration process, and this contains some classes that are used to build up the registrations.
For instance, I can do this:
builder.Register<IFoo>().From.ConcreteType<Foo>();

However, at each step after a dot, intellisense pops up showing the four standard methods from the Object class, GetHashCode, Equals, GetType, and ToString.
I tried overriding these methods in a couple of the classes, attaching the EditorBrowsableAttribute attribute to each, but they still show up. Is there no way for me to hide them?
Note that I'm not trying to hide them from the class itself, just from intellisense.
Basically, I'd like this:
                         +---------------+
builder.Register<IFoo>().|As             |
                         |By             |
                         |Equals         | <-- remove this
                         |From           |
                         |GetHashCode    | <-- and this
                         |GetType        | <-- as well as this
                         |ToString       | <-- and finally this
                         +---------------+

Here's what I tried in the class that is returned from Register<T>:
[EditorBrowsable(EditorBrowsableState.Never)]
public override Boolean Equals(Object obj)
{
    return base.Equals(obj);
}

[EditorBrowsable(EditorBrowsableState.Never)]
public override Int32 GetHashCode()
{
    return base.GetHashCode();
}

[EditorBrowsable(EditorBrowsableState.Never)]
public override String ToString()
{
    return base.ToString();
}

This clearly did not work. Is there anything else I can try?
I also tried adding a new method, not overridden from Object, and applying the same attribute to that, and that too shows up, so clearly the attribute is not doing what I thought it would do.
I noticed the note in the documentation about not hiding things from the same assembly, but I tried creating a new project and they still show up there.

A:

Ok, I found the solution, it was partly my fault, and partly incomplete documentation.
My fault was that I had not tagged all the methods in the correct class, but even when correcting that, the methods still showed up.
Turns out the note in the documentation, which reads:

In Visual C#, EditorBrowsableAttribute does not suppress members from a class in the same assembly.

Should actually be (emphasis mine):

In Visual C#, EditorBrowsableAttribute does not suppress members from a class in the same open solution.

I tagged the methods in the appropriate class, did a full rebuild, created a new project outside of the solution file, made file references to the compiled files from my IoC project, and lo and behold, the methods disappeared.
I'll leave the question up in case someone else has this problem.

A:

According to thread, it is by design.  The methods/properties decorated with EditorBrowsable(EditorBrowsableState.Never) are only hidden from intellisense if they're part of a class that is in another referenced assembly.  The assembly should not be part of the same solution.


Q:

Heat Vs Medieval Shields

Lets say magic is capable of summoning fire of varying intensities for different amounts of time, how effective would a shield of wood covered in leather or metal? What would it take to melt or set the shield ablaze? What shield shape would be best at dispersing said heat? And at what point would the heat become fatal to the person holding it?(Suppose the wizard does not know about concentrating heat on a small point, the fire originates from the hand and the user is approximately 20 feet away, the fires heat remains constant throughout the blaze, and it is a flame like that of a propane flamethrower)

A:

Wood is a good insulator
From that perspective, wood will give you a good deal of protection. Heat transfer is governed by Fourier's law $$q = -k\Delta u.$$
The thermal conductivity ($k$) of wood is about 0.2 W/m/K. Lets say you want to keep heat transfer below 1000 W. That is about a microwave oven's worth of heat. Definitely painful, deadly after a while, but survivable for a short time. The thickness of a shield is maybe 2.5 cm (about an inch), and area is about 0.3 m$^2$ (or 3 square feet). The heat flux is measured in units of W/m$^2$. The temperature gradient $u$ is in units of K/m.
$$\frac{-1000 \text{ W}}{0.3 \text{ m}^2} = -0.2 \frac{\text{W}}{\text{m}\cdot\text{K}}\frac{T \text{ K}}{0.025 \text{ m}}.$$
I solve this as 417 K. Assuming that it is uncomfortably hot on your side of the shield (320 K), that means you can be hit with a constant heat source at around 750 K, hot enough to melt lead, for probably a couple minutes.
Wood is also flammable
Wood will autoignite at around 600 K. Canvas made from cotton will ignite even lower, although I think properly prepared wool would be more fire resistant.
Conclusion
Wood will protect you from a fire, up until the point that the wood itself catches fire. This is around 600 K, which is also around 600 F.
The heat flux needed to ignite wood might be in the 10-50 kW per m$^2$. Considering that our knight behind the shield is seeing 3 kW per m$^2$, it won't take long (less than a minute) for your shield to go up in flames if any of it is made of wood (or canvas or leather).

A:

Different kinds of wood and different metal alloys have different combustion and melting temperatures. Listing them here would not be productive - you can find results online with a few searches.
The shape of the shield would have negligible effect on heat dispersion. You would need very weird, "unshieldly" shapes to get a useful effect (think of a heat sink, see below).

As for the effects that would have on the shield bearer...
Wood might make a good thermal insulation layer as long as it doesn't combust. If it does get into combustion, then you have flames on your arm. Enough said... Best option for the poor soul is to unstrap the shield and either jump in a body of water or roll on the floor. If fine sand is available, that can help put down the fires too. The results of such an attack are obvious - depending on how long you got exposed to it, and the amount and kind of clothing between the flames and your arm, you get from small burns to 2nd or 3rd degree ones.
Metal is a worse protection in this case... Most metals are good thermal conductors. You don't have to melt the shield to cause grave damage. Even at 100 degrees Celsius (212 F), you are going to get seriously burned. If the metal goes red hot (around 430 Celsius/800 F), you are sure to get 3rd degree burns.
Burned skin can easily get infected. In medieval Earth people had zero knowledge about antibiotics, and doctors would not wash their hands before helping patients. Unless your world also has some healing spells, people who get their arms burned this way are probably going to need amputations. Ironically, the usual way to close and sterilize the stump resulting from an amputation is through cauterization.
Finally, if you want to kill someone behind a shield with magical fire, it would be much more productive to just burn the person rather than the shield. If the magical fire is delivered in a manner similar to a flame thrower's fire, just aim at the target's feet or around the shield. It would take a very large shield to completely cover someone, but then that person is stuck. If the shield is easily flammable or metallic it's just a matter of time until they get serious hand and forearm burns.
Remember that human hair and most kinds of clothing are flammable, and metal armor is just as conductive as a shield. Burning the shield instead, in a medieval setting, is more likely to cause a slow death and thus is much more cruel than a quick kill.

A:

Shield Construction
Wooden shields rarely have exposed wood, they are covered in metal, leather, or painted canvas. Even the few known uncovered viking shields are believed to be burial shields not utility ones.  more on viking shield construction and usage.
metal shields are split into two groups as only smaller metal shields were ever solid metal which may not provide any protection depending on how the "fire" is delivered. larger metal shields were metal sheething over wood, some got even more complex, the famous spartan shields were layered wood and leather covered in a layer of bronze.
source
Effects on the shield
An agricultural flamethrower (propane) will take quite a long time to burn through a wooden shield and a metal sheathed shield might prevent heat transfer even through prolonged exposure. Gas based torches are remarkably bad at igniting a flat smooth wood surface, to the point it can be used for decorative highlighting of grain. They just do not transfer heat very efficiently if not enclosed. Leather covering will make them far more resistant, to the point it will take minutes of constant exposure to breach the shield. With metal sheathing it may not be able to reach the ignition point of the wood understructure even after several minutes of exposure, especially as the wood will char into an even worse conductor first.
Either type of shield will allow the soldier to close the distance and dispatch the wizard with plenty of time to spare, likely without the shield even igniting even in the worse case scenario. the exception being some painted canvas coated shields as the canvas may ignite even if the wood underneath goes unharmed which should at least provide a decent distraction.
smaller shields and bucklers may not be able to defend against the flame at all depending on how big it is, if they do have the coverage even these solid metal shields will still be able to defend for a considerable amount of time as far as combat is concerned. Again more than enough time for the soldier to close the distance and attack the wizard.
Why this doesn't matter for the flame as a weapon.
The biggest advantage the wizard will have is sight and mobility, as the defender will not be able to see the wizard while using the shield to block the fire. So the wizard can easily move the flame to target the legs or even just step to the side and hit an undefended angle, without the defender being able to react or even know until it is too late. So this flame will still make an effective weapon because shields do not have total coverage. Used with skill the flame will work quite well as a weapon but it will not brute force its way through a shield.


Q:

Rails Active Record: How to reduce number of trips to database?

In my rails project, I have a feature that shows users whether any of their facebook friends are already on the site. After authenticating, I load their facebook friends into @fb_friends and then do this:
  @fb_friends.each do |friend|
    friend_find = Authorization.find_by_uid_and_provider(friend[:identifier], 'facebook')
    if friend_find
      @fb_friends_on_cody << friend_find.user_id
      @fb_friends.delete(friend)
    end
  end

Basically, if a match is found (via the Authorization table), I push that record to @fb_friends_on_cody. This proves to be a very expensive operation:

This hits the database once per friend. So in my case there are a total of 582 queries executed.
Each Authorization.find_by_uid_and_provider has poor performance. I have add an index like so:
add_index "authorizations", ["uid", "provider"], :name => "index_authorizations_on_uid_and_provider", :unique => true

I imagine a lot of performance gains can be seen by addressing the first point. And perhaps there are some ways to make the query itself more efficient. Appreciate any tips on these fronts.
Solution
Using Unixmonkey's guidance, I was able to cut down the number of queries from 582 to 1! Here's the final code:
  friend_ids = @fb_friends.map{|f| f[:identifier] }
  authorizations = Authorization.where('provider = ? AND uid IN (?)','facebook',friend_ids)
  @fb_friends_on_cody = authorizations.map{ |a| { user_id: a.user_id, uid: a.uid }}
  @fb_friends.reject!{|f| @fb_friends_on_cody.map{|f| f[:uid]}.include?(f[:identifier]) }

A:

I think this should work
friend_ids = @fb_friends.map(&:id)
authorizations = Authorization.where('provider = ? AND uid IN (?)','facebook',friend_ids)
@fb_friends_on_cody = authorizations.map(&:user_id)
@fb_friends.delete_all('id in (?)', @fb_friends_on_cody)


Q:

WordPress submenu hover with gradient image background over the parent LI and children LI's (submenu UL)

I have the next situation/menu: http://inturnets.com/test/
It is a WordPress generated menu structure.
Please hover your mouse over "Menu #1". When mouse is hovered, i need the Menu #1, Menu #1 - 1 and Menu #1 - 2 to look like http://inturnets.com/test/images/whatineed.jpg
It has a that background image with gradient effect on it. It should start from the top of the menu when hovered, from the top of Menu #1 and to end on the LI's of the submenu UL. When the bg image ends (no-repeat) should continue the colour from the last pixel of it's bottom. In our example for a better visual experience let's take the #ff0000 :)
Does anyone have any clue how to solve that?
For now I tried the next css code:
#menu-top-navigation ul:hover { background: url(images/bg-menutest.jpg) repeat-x center top; }

But as you can see, with this only the LI's are covered on hover. I mean the submenu UL. I think there we need a hover rule for the hovered LI, some rounded corners with radius and another hover rule for the submenu UL with a corner radius and to look with continuity from the top over the bottom, like it looks on the linked image.

A:

try to specify background color with selector like this:
#menu-top-navigation > li:hover

This way, you should be able to specify one gradient for whole LI content (in your case UL and LI). Strongly reccomend to use CSS3 gradients.
If this wont help you might need to specify on gradient for
#menu-top-navigation > li:hover {gradient color of XXX to YYY}

and one for
#menu-top-navigation > li:hover > ul {gradient color of YYY to ZZZ}

Note: gradient spec is just an example, it is not the actual syntax. Just wanted to make easier to understand.
Let me know if you have any questions.


Q:

AJAX in WP Plugin returns 0 always

I'm trying to implement WP AJAX in one of my Under-dev Plugin after successful implementation in WP Theme.
function deactivate_ad() {

    if( isset( $_POST['id'] ) ) {
        echo $_POST['id'];
        echo 'Deactivated';
        die;
    } else {
        echo 'Sorry, not done';
        die;
    }
    wp_die(); // ajax call must die to avoid trailing 0 in your response
}

add_action('wp_ajax_deactivate_ad', 'deactivate_ad');
//add_action( 'wp_ajax_nopriv_deactivate_ad', 'deactivate_ad'); //not logged in users

And beneath the function somewhere, I added my form with dynamic ID:
<form action="" enctype="multipart/form-data" method="post">

<?php
        //after the db Query, within the foreach loop
        foreach( $ad_query as $the_ad ){
            $element_id = 'deactivate_' . $the_ad->id . '_' . wp_create_nonce('deactivate_' . $the_ad->id );
            // I'm just checking with the 'Deactivate' button first
            echo ( $the_ad->ad_status == 1 ? 'Deactivate' : 'id .'&activate=true&success=true">Activate' );
        }
?>
</form>

I'm just trying to activate the AJAX so that I can do whatever I want then. But with first alert(id) I can alert the id with nonce successfully, but the alert(data) it's always returning 0 (zero).
I am enqueueing  the latest jQuery (http://code.jquery.com/jquery-latest.min.js) at the beginning and checked all the instances. What am I doing wrong this time - the process I acquired worked in a theme - I worked earlier.

A:

You should re-place the following code from adzonia-view.php to wp-adzonia.php
function deactivate_ad() {

if( isset( $_POST['id'] ) ) { echo $_POST['id']; echo 'Deactivated';

} else { echo 'Sorry, not done';

} die();

}

add_action('wp_ajax_deactivate_ad', 'deactivate_ad');

Reason:
Because you wrote the functions in a menu page. It's already hooked in with may be admin_menu hook. So it's too late to add actions in wp_ajax_*.


Q:

how to update status active or Unsubcribed of subscriber in _ListSubscribers

I'm trying to do it this way, but I'm getting 500 error
%%[

var @SubscriberKey, @ListID, @ListType

set @SubscriberKey = "example"
set @ListID= 123
SET @ListType= "Publication List"

IF Not Empty(@SubscriberKey) THEN

set @UpsertData = UpsertData("_ListSubscribers",3,"SubscriberKey", @SubscriberKey, "ListID", @ListID, "ListType", @ListType, "Status", "Active")
OUTPUTLINE(CONCAT("<br>Rows updated: ",@UpsertData))

ENDIF

]%%

A:

If you are looking to just change status for subscriber inside of a list, you will need to use SFMC SSJS Core functions or WSProxy. You can use the AMPScript API functions, but this is highly inefficient and requires a ton of unnecessary processing.
For Core, you would look at using List.Subscribers:
For making a user active, you would want to do List.Subscribers.Update like so:
var myList = List.Init("myList");
var status = myList.Subscribers.Update("mySubscriberKey","Active");

For unsubscribing, you can use the Core function List.Subscribers.Unsubscribe like so:
var myList = List.Init("myList");
var status = myList.Subscribers.Unsubscribe("mySubscriberKey");

One note on this is that if you are trying to create an unsub event (tying the unsubscribe to a job with reason, etc.) then this is not your preferred path. You will want to use the 'LogUnsubEvent' API call. This is best accomplished via WSProxy:
<script runat="server">
try {
    var prox = new Script.Util.WSProxy();

    /* Set ClientID */
    prox.setClientId({ "ID": mid}); //Impersonates the BU

    var props = [
       { Name: "SubscriberKey", Value: "sample@sample.com" },
       { Name: "EmailAddress", Value: "sample@sample.com" },
       { Name: "JobID", Value: 18099 },
       { Name: "ListID", Value: 8675309 },
       { Name: "BatchID", Value: 0 }
    ];
    var data = prox.execute(props, "LogUnsubEvent");

    Platform.Response.Write(Platform.Function.Stringify(data));
} catch(e) {
    Platform.Response.Write(Platform.Function.Stringify(e));
}
</script>

Here is an article I wrote about doing it.
That being said, if you are looking to do the changes in bulk, then WSProxy is the better way to go as it has batch options.
<script runat="server">

  var prox = new Script.Util.WSProxy();
  var subArr = [];
  var myArr = //my Array containing the sub info needed to be changed

  for(i=1;i<myArr;i++) {
    //iterate through your 'myArr' to grab the correct info and insert into below
    var subObj = {
        SubscriberKey: subkey,
        EmailAddress: email,
        Lists: [{
            ID: '12345',
            Status: 'Active'
        }]
    };
    subArr.push(subObj);
  }

  var options = {
    SaveOptions: [{
      PropertyName: "*",
      SaveAction: "UpdateAdd"
    }]
  };

 var resp = prox.createBatch("Subscriber", subArr, options);
</script>

If you desperately want to do it via AMPScript API functionality, I would look at this article by Zuzanna that details out the LogUnsubEvent calls for you in both AMPScript and SSJS.


Q:

Advanced Nested List Comprehension Syntax

I was playing around with list comprehensions to get a better understanding of them and I ran into some unexpected output that I am not able to explain. I haven't found this question asked before, but if it /is/ a repeat question, I apologize.
I was essentially trying to write a generator which generated generators. A simple generator that uses list comprehension would look like this:
(x for x in range(10) if x%2==0) # generates all even integers in range(10)

What I was trying to do was write a generator that generated two generators - the first of which generated the even numbers in range(10) and the second of which generated the odd numbers in range(10). For this, I did:
>>> (x for x in range(10) if x%2==i for i in range(2))
<generator object <genexpr> at 0x7f6b90948f00>

>>> for i in g.next(): print i
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in <genexpr>
UnboundLocalError: local variable 'i' referenced before assignment
>>> g.next()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
>>> g = (x for x in range(10) if x%2==i for i in range(2))
>>> g
<generator object <genexpr> at 0x7f6b90969730>
>>> g.next()
Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "<stdin>", line 1, in <genexpr>
    UnboundLocalError: local variable 'i' referenced before assignment

I don't understand why 'i' is being referenced before assignment
I thought it might have had something to do with i in range(2), so I did:
>>> g = (x for x in range(10) if x%2==i for i in [0.1])
>>> g
<generator object <genexpr> at 0x7f6b90948f00>
>>> g.next()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in <genexpr>
UnboundLocalError: local variable 'i' referenced before assignment

This didn't make sense to me, so I thought it best to try something simpler first. So I went back to lists and tried:
>>> [x for x in range(10) if x%2==i for i in range(2)]
[1, 1, 3, 3, 5, 5, 7, 7, 9, 9]

which I expected to be the same as:
>>> l = []
>>> for i in range(2):
...     for x in range(10):
...             if x%2==i:
...                     l.append(x)
...
>>> l
[0, 2, 4, 6, 8, 1, 3, 5, 7, 9] # so where is my list comprehension malformed?

But when I tried it on a hunch, this worked:
>>> [[x for x in range(10) if x%2==i] for i in range(2)]
[[0, 2, 4, 6, 8], [1, 3, 5, 7, 9]] # so nested lists in nested list comprehension somehow affect the scope of if statements? :S

So I thought it might be a problem with what level of scope the if statement operates in. So I tried this:
>>> [x for x in range(10) for i in range(2) if x%2==i]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

And now I'm thoroughly confused. Can someone please explain this behavior. I don't understand why my list comprehensions seem to be malformed, nor do I understand how the scoping of the if statements work.
PS: While proof-reading the question, I realized that this does look a bit like a homework question - it is not.

A:

you need to use some parentheses:
((x for x in range(10) if x%2==i) for i in range(2))

This didn't make sense to me, so I
  thought it best to try something
  simpler first. So I went back to lists
  and tried:
[>>> [x for x in range(10) if x%2==i for i in range(2)]
  [1, 1, 3, 3, 5, 5, 7, 7, 9, 9]

That worked because a previous list comprehension leaks the i variable to the enclosing scope, and become the i for the current one. Try starting a fresh python interpreter, and that would fail due to NameError. The counter's leaking behavior has been removed in Python 3.
EDIT:
The equivalent for loop for:
(x for x in range(10) if x%2==i for i in range(2))

would be:
l = []
for x in range(10):
    if x%2 == i:
        for i in range(2):
            l.append(x)

which also gives a name error.
EDIT2:
the parenthesed version:
((x for x in range(10) if x%2==i) for i in range(2))

is equivalent to:
li = []
for i in range(2):
    lx = []
    for x in range(10):
        if x%2==i:
            lx.append(x)
    li.append(lx)

A:

Lie Ryan's for-loop equivalent leads me to the following, which does seem to work just fine:
[x for i in range(2) for x in range(10) if i == x%2]

outputs
[0, 2, 4, 6, 8, 1, 3, 5, 7, 9]

A:

Expanding on Lie Ryan's answer a bit:
something = (x for x in range(10) if x%2==i for i in range(2))
is equivalent to:
def _gen1():
    for x in range(10):
        if x%2 == i:
            for i in range(2):
                yield x
something = _gen1()

whereas the parenthesised version is equivalent to:
def _gen1():
    def _gen2():
        for x in range(10):
            if x%2 == i:
                yield x

    for i in range(2):
        yield _gen2()
something = _gen1()

This does actually yield the two generators:
[<generator object <genexpr> at 0x02A0A968>, <generator object <genexpr> at 0x02A0A990>]

Unfortunately the generators it yields are somewhat unstable as the output will depend on how you consume them:
>>> gens = ((x for x in range(10) if x%2==i) for i in range(2))
>>> for g in gens:
        print(list(g))

[0, 2, 4, 6, 8]
[1, 3, 5, 7, 9]
>>> gens = ((x for x in range(10) if x%2==i) for i in range(2))
>>> for g in list(gens):
        print(list(g))

[1, 3, 5, 7, 9]
[1, 3, 5, 7, 9]

My advice is to write the generator functions out in full: I think trying to get the correct scoping on i without doing that may be all but impossible.


Q:

A basic question on diameter of a metric space

A set S of real numbers is bounded if it has both upper and lower bounds. Therefore, a set of real numbers is bounded if it is contained in a finite interval.
While in a metric space a non-empty subset $S$ of metric space $X$ is said to be bounded set if its diameter is finite.
My question is: are both the definitions of boundedness are equivalent?
Is it possible to determine diameter of every subset?
Is there any other criterion also to determine whether given subset of a metric space is bounded or not?

A:

The diameter of a nonempty subset $S\subseteq X$ is defined to be $$\sup_{x,y\in S}d(x,y),$$ which is always defined (though it may be infinite). Thus you can always determine the diameter of a nonempty subset.
A nonempty subset $S\subseteq X$ having finite diameter is equivalent to $S$ being contained in some ball $B(x,r)$ for some $x\in X$ and some $r>0$. To see this, first suppose that $S$ has finite diameter $\Delta<\infty$. Pick any $x\in S$. Then $S\subseteq B(x,2\Delta)$, since $d(x,y)\leq \Delta$ for every $y\in S$. On the other hand, suppose that $S$ is contained in some ball $B(x,r)$, where $x\in X$ and $r>0$. Then for any two points $y,z\in S$, one has $d(y,z)\leq d(y,x) + d(x,z)\leq 2r$, so the diameter of $S$ is $\leq 2r$. I hope that answered your question!


Q:

Long datatype throwing numberformatexception

A datatype long in Java 7 is throwing numberformatexception when it is exceeding 20 digits. Is there any alternative here?

A:

You can use BigIntegers to do mathematical operations with higher number of digits.
But in division, it is doing integer division.(As in integer data types). For large decimal number calculations, you can use BigDecimal
An Example using BigInteger is shown below..
    BigInteger b1 = new BigInteger("100000000000000000000000000000000000000000");
    BigInteger b2 = new BigInteger("100000");

    System.out.println("Addition: " + b1.add(b2));
    System.out.println("Subtraction: " + b1.subtract(b2));
    System.out.println("Division: " + b1.divide(b2));
    System.out.println("Multiplication: " + b1.multiply(b2));
    System.out.println("Power: " + b1.pow(1000));

For more information you can just google how to use biginteger in java


Q:

Filesystemwatcher and GAC

For the Past few months I was using Filesystemwatcher to find the file system changes in the system. However When I install an Assembly in GAC, Filesystemwatcher doesnot capture the dll registered in GAC. Here is the code.  Though the file is created at the location C:\Windows\assembly\GAC_MSIL\ConsoleApplication2\1.0.0.0__aea873120d858924\consoleapplication2.dll, I could not find that in the "str" variable. Instead I have the directory path of it. Does anyone have any idea where it goes wrong.
static void Main(string[] args)
    {

        str = new List<string>();
        FileSystemWatcher fs = new FileSystemWatcher(@"c:\");
        fs.IncludeSubdirectories = true;
        fs.Created += new FileSystemEventHandler(OnFileCreate);
        fs.Changed += new FileSystemEventHandler(OnFileCreate);
        fs.EnableRaisingEvents = true;
        new System.EnterpriseServices.Internal.Publish().GacInstall(@"C:\Users\jijiadmin\Documents\Visual Studio 2008\Projects\ConsoleApplication2\ConsoleApplication2\bin\Debug\consoleapplication2.dll");
        Console.ReadKey();
     }
     static void OnFileCreate(object e, FileSystemEventArgs ev)
    {
            str.Add(ev.FullPath);
    }

A:

This seems to be Issue with filesystemwatcher and raised it to Microsoft.
Thanks for all your replies.


Q:

Git init não criou branch master

Eu estou tentando dar um git init no meu projeto, ele retorna com sucesso:
Initialized empty Git repository in C:/myprojetPath/.git/

Mas porque quando eu digito git branch, ele não retorna nenhum branch?
$ git branch

(Não retorna nenhum branch)
myuser@WKS054 MINGW64 myprojetPath (master)
$

Mas no meu terminal (Git bash, na verdade) mostra que estou no branch master.
Porêm quando eu troco de branch, não consigo voltar para branch master com git checkout master, ele informa que o branch não existe

A:

Parece que quando se acaba de criar um repositório isso é comum.
Fiz alguns testes aqui e só aparece o branch quando fiz o seguinte:
git init
touch um_arquivo_incial
git add um_arquivo_inicial
git commit -am "Primeiro commit"

Depois, se você fizer git branch, então verá:
 >*master


Q:

Does a computer do only two things?

According to the book, Introduction to Computation And Programming Using Python by John V Guttag, a computer does only two things:

Store data
Manipulate data

But is this all? I mean, without I/O, can a computer be considered useful?

A:

The statement is obviously false: my computer can make sounds and it's hard to see that that as either storing or manipulating data.  I suggest you just ignore it and move on, since producing this kind of list does nothing to help your understanding of computers, programming or anything else.

A:

I think the author is over simplifying to make a point. Obviously a computer needs to take input and produce an output to have any value. But usually, when you press a key on your keyboard, it is altering data in a reserved memory location and that's how the computer even knows you pressed something, because it sees that data changed. That's what a "memory mapped I/O" is--specific places in memory that the computer looks for input changes. So depending on how you look at it, input and output is still just storing and manipulating data. But if you attach a motor to it, then your computer can do just about anything.


Q:

Manipulating a query so that null values are not shown in a full outer join

How would you manipulate a query so that the rows with null values in a table resulting from a full outer join do not show up in the result?

A:

WHERE value IS NOT NULL
You can find a full explanation here:
http://www.w3schools.com/sql/sql_null_values.asp


Q:

When/how REST replaced SOAP

I am currently writing my thesis about IT technologies etc. etc. and I have one chapter where i compare REST and SOAP, but I can not find how and when (i mean some king of events in the past) REST started (mainly in Web) to replace SOAP as technology of web services.
Could you help me with this issue ? ;)

Thank you for this important information, but i mean something else.
I would like to show you a graph in Google Insights for Search Tool :
Google Insights
As you can see in 2008 there was some king of intersection number of keywords searche for rest api and soap api. So, i would like to rely on some sources (of coures I do not have them) or events/facts why this intersection may occured... event in the recent past.
Do you get my point of view ? I know that could be quite unique approach to the topic, but i would like to explain of this soap and rest swap.
EDIT
Does anyone have any idea? I know that is different approach to the topic of soap and rest apis but maybe someone knows how 'bite' the topic ;)

A:

The term Representational state transfer (REST) was introduced in 2000 by Roy Fielding in his doctoral dissertation. REST described a web architecture that was not specific to web API's, but has become very popular now as a method for developing web API's. SOAP became a W3C Recommendation in June of 2003. So technically REST was defined before SOAP, but SOAP was very popular method for some time for developing web services and in the beginning more popular than REST. But then developers found that SOAP was bloated and overly complex for developing web services/API's and that REST served their needs just fine.  The simplicity of REST seems to make it more popular and the fact that it adheres to basic HTTP principles makes it much more portable across heterogeneous platforms.  So there is probably not a certain milestone or event in history that caused this transition from SOAP to REST. It was just a gradual transition to what worked best for developers needs.
Clarification on SOAP history
SOAP version 1.0 was actually introduced by Microsoft in December of 1999, so the two technologies are close on when they were defined. But it was not given to the W3C to become a standard until May of of 2000 and was not made a Recommendation until 2003. I would argue that until it became a general standard it could not be considered by the whole development community as something viable for developing web services for a heterogeneous environment, which was one of the big promises of web services and SOA. Until that time it was just something that could be used on Microsoft platforms.
Update Based on Comments on API Trends
The Google Insights graph shown by @GarciaPL is very interesting and I think I understand what he is trying to show in his thesis. But I would be careful with this data in drawing strong conclusions.  This same Google Insights search was shown in the blog post "REST in peace, SOAP". Probably what is more concrete in this blog post is the graph showing out of 2,000 API's the trend from 2008 to 2010 was to move to REST.  The original source of this information is here.  This does show a trend towards REST for publicly exposed API's. Is the thesis specifically on the use of publicly exposed API's or is it on web service development in general?  If it is web services in general I am less certain.  For developers on Microsoft platforms developing internal projects the term used today is not SOAP, it is Windows Communication Foundation (WCF).  Although SOAP is under the hood there is little need to discuss the plumbing as WCF hides a lot of the internals.  If I do a Google Insights search on "rest web service", "soap web service", and "wcf web service" you get much different results, showing them actually converging.  Or if you do a search on "restful service", "soap service", and "wcf service" it actually shows WCF taking over in 2008 with a gradual uptick for REST.
For API's REST makes sense because they are portable, simple to use, scalable, and easy to integrate with.  For development of web services in general I am not so sure.  I think WCF is still very popular with Microsoft developers and it fits well with certain types of projects.  It is just a matter of picking the right tool for the job.  I will reiterate what I said before, I do not think their is a significant historical event that caused the transition to RESTful API's.  I think it was just developers learning what the right tool for the job was.

A:

The best place for you is book from Jim Webber "REST in Practice: Hypermedia and Systems Architecture"
http://www.amazon.com/REST-Practice-Hypermedia-Systems-Architecture/dp/0596805829
In book is a special chapter for that - Chapter 11 "The Web and WS-*".
When you are writting thesis about REST than this book is must have for you.