Expectation with order statistics

Question: Let $X_1,\ldots,X_n$ be non-negative i.i.d. random variables with cdf $F$ and let $X_{(n)}$ denote their maximum. For simplicity suppose that $X_1$ has a density $f$ and that $0\le X_1\le M$ almost surely.
Let $h: \mathbb R^n\to \mathbb R_{+}$ be some function that is strictly increasing in all components.
I am trying to calculate the conditional expectation
$$E(h(X_1,\ldots,X_n) | X_{(n)} = x)\tag{1}$$
but I get stuck on the density.
I guess we should have something like
$$E(h(X_1,\ldots,X_n) | X_{(n)} = x) = \int_0^M\ldots\int_0^M h(x_1,\ldots,x_n) \psi(x_1,\ldots,x_n, x) / (nF^{n-1}(x)f(x))dx_1\ldots dx_n,$$
where $nF^{n-1}(\cdot)f(\cdot)$ is the density of $X_{(n)}$ and the joint density $\psi$ should be zero outside the rectangle $[0,x]^n.$
I tried to get $\psi$ by differentiating the joint cdf with respect to $x_1,\ldots,x_n,x$ but this does not appear to work: Note that if $x_1,\ldots,x_n\le x$ we get that
$$P(X_1\le x_1,\ldots X_n\le x_n, X_{(n)} \le x) = P(X_1\le x_1,\ldots X_n\le x_n) = F(x_1)\ldots F(x_n)$$
and if $x_j > x$ for some $j$ we get
$$P(X_1\le x_1,\ldots X_n\le x_n, X_{(n)} \le x) = 0.$$
But then differentiating with respect to $x$ yields zero in any case, and $\psi=0$ everywhere cannot be correct.
Note that if $X_1$ were discrete we could simply write
$$E(h(X_1,\ldots,X_n) | X_{(n)} = x) \\
= \sum_{x_1,\ldots,x_n:x_{(n)} = x} h(x_1,\ldots,x_n) Pr(X_1=x_1,\ldots,X_n=x_n, X_{(n)}=x)/Pr(X_{(n)}=x)\\
= \sum_{x_1,\ldots,x_n:x_{(n)} = x} h(x_1,\ldots,x_n) Pr(X_1=x_1,\ldots,X_n=x_n)/Pr(X_{(n)}=x)\\
= \sum_{x_1,\ldots,x_n:x_{(n)} = x} h(x_1,\ldots,x_n) Pr(X_1=x_1)\ldots Pr(X_n=x_n)/Pr(X_1=x)^n$$
but I'm not sure how to generalize that intuition to the continuous case because the set $\{x_1,\ldots,x_n:x_{(n)} = x\}$ has probability zero.
In addition to the properties mentioned above I know that $h$ is symmetric in all components, that is $h(x_1,\ldots,x_n) = h(x_{\pi(1)},\ldots,x_{\pi(n)})$ for all permutations $\pi$ of $n$ letters. But I'm not sure if this is helpful for this calculation.
Comment: Hey, nice problem. One thing, are you sure that $X_{(n)}\thicksim n f^{n-1}$? [Wiki](https://en.wikipedia.org/wiki/Order_statistic#The_joint_distribution_of_the_order_statistics_of_an_absolutely_continuous_distribution) seems to say that the density should be $n F^{n-1} f$ where $F$ is cdf, but I don't know off the top of my head
Comment: @C.Windolf Thanks for noticing, I corrected this.
Answer: We have :
\begin{align}
\mathbb E&\left[h(X_1,\ldots,X_n)\mathbf{1}_{X_{(n)} \le x}\right] \\
&= \mathbb E\left[h(X_1,\ldots,X_n)\mathbf{1}_{X_{(n)} \le x}\sum_{k=1}^n \mathbf{1}_{X_k = X_{(n)}}\right]\\
&= \sum_{k=1}^n \mathbb E \left[h(X_1,\ldots,X_n)\mathbf{1}_{X_{(n)} \le x}\mathbf 1_{X_k = X_{(n)}}\right]\\
&= \sum_{k=1}^n \mathbb E\left[h(X_1,\ldots,X_n)\mathbf{1}_{X_k \le x}\prod_{j\neq k}\mathbf{1}_{X_j \le X_k}\right]\\
&= \sum_{k=1}^n \int_{\left[0,M\right]^n} h(x_1,\ldots, x_n)\mathbf{1}_{x_k \le x}\prod_{j\neq k}\mathbf{1}_{x_j \le x_k} \prod_{j=1}^n f(x_j) \prod_{j=1}^n \mathrm dx_j\\
&= \sum_{k=1}^n \int_{0}^x \left\{\int_{[0, x_k]^{n-1}} h(x_1,\ldots,x_{k-1}, x_k, x_{k+1}, \ldots, x_n) \prod_{j\neq k} f(x_j) \prod_{j\neq k} \mathrm dx_j\right\} f\left(x_k\right)\mathrm dx_k\\
&= \sum_{k=1}^n \int_{0}^x \left\{\int_{[0, u]^{n-1}} h(u,x_{1}, \ldots, x_{n-1}) \prod_{j=1}^{n-1} f(x_j) \prod_{j=1}^{n-1}\mathrm dx_j\right\}f(u)\mathrm du\\
&= n\int_{0}^x \left\{\int_{[0, u]^{n-1}} h(u,x_{1}, \ldots, x_{n-1}) \prod_{j=1}^{n-1} f(x_j) \prod_{j=1}^{n-1}\mathrm dx_j\right\} f(u)\mathrm du
\end{align}
Let $$g(x) = \mathbb E\left[h(X_1,\ldots,X_n)\Big|X_{(n)} = x\right]$$ and since :
\begin{align}
\mathbb E\left[h(X_1,\ldots,X_n)\mathbf{1}_{X_{(n)}\le x}\right] &= \mathbb E\left[\mathbb E \left[h(X_1,\ldots,X_n)\mathbf{1}_{X_{(n)}\le x}\Big | \sigma \left(X_{(n)}\right)\right]\right]\\
&= \mathbb E\left[\mathbb E \left[h(X_1,\ldots,X_n)\Big | \sigma \left(X_{(n)}\right)\right] \mathbf{1}_{X_{(n)}\le x}\right]\\
&= \mathbb E\left[g\left(X_{(n)}\right) \mathbf{1}_{X_{(n)}\le x}\right]\\
&= \int_{0}^x g(u) f_{X_{(n)}}(u)\mathrm d u
\end{align}
this proves that :
 $$\frac{\mathrm d}{\mathrm dx} \mathbb E\left[h(X_1,\ldots,X_n)\mathbf{1}_{X_{(n)}\le x}\right] = g(x) f_{X_{(n)}}(x) = ng(x) f(x) \left\{F(x)\right\}^{n-1}$$
By differentiating :
\begin{align}
\mathbb E\left[h(X_1,\ldots,X_n) \Big | X_{(n)} = x\right] &= \frac{n f(x)\left\{\displaystyle\int_{[0, x]^{n-1}} h(x,x_{1}, \ldots, x_{n-1}) \prod_{j=1}^{n-1} f(x_j) \prod_{j=1}^{n-1}\mathrm dx_j\right\}}{n f(x) \left\{F(x)\right\}^{n-1}}\\
&= \frac1{\left\{F(x)\right\}^{n-1}}\left\{\displaystyle\int_{[0, x]^{n-1}} h(x,x_{1}, \ldots, x_{n-1}) \prod_{j=1}^{n-1} f(x_j) \prod_{j=1}^{n-1}\mathrm dx_j\right\}
\end{align}
Comment: I did a mistake in my previous argument. I edited the answer with the correct answer.
Comment: I corrected it now.
Comment: The density of $X_k$ not of $X_{(n)}$
Comment: Thank you, this looks great. I did not know that
$$\frac{d}{dx} E[h(X_1,\ldots,X_n)\mathbf{1}(X_{(n)}\le x)] = E[h(X_1,\ldots,X_n)|X_{(n)}= x]$$
Could you point me to a reference for that?
Comment: Thanks for the update! I think the beginning should read
\begin{align}
\mathbb E\left[h(X_1,\ldots,X_n)\mathbf 1_{X_{(n)} \le x}\right] &= \int_{[0,M]^n} h(x_1,\ldots,x_n)\prod_{j=1}^n \mathbf 1_{x_j \le x}\prod_{j=1}^{n} f(x_j) \prod_{j=1}^{n}\mathrm dx_j\\
&= \sum_{k=1}^n \int_{0}^x \left\{\int_{[0, x_k]^{n-1}} h(x_1,\ldots,x_{k-1}, x_k, x_{k+1}, \ldots, x_n) \prod_{j\neq k} f(x_j) \prod_{j\neq k}  \mathrm dx_j\right\} \color{red}{f_{X_{(n)}}(x_k)} dx_k
\end{align}
and then after differentiating and dividing, the $f_{X_{(n)}}$ drops out, so your first answer was correct, I think.
Comment: I guess the density should be in there because we condition on $x_k$ being the largest variable.

Expectation with order statistics


How to manage a time delay (a short time period) in python

Question: I am working on an Temperature related app using Python(with tkinter), Raspberry Pi with DS18B20 Temperature Sensor. The basic requirement of app is

Display the temperature in every 3sec and check if temperature crossed over a threshold limit (say 10C) for continue 10min it should activate the A/C relay.

The code is working fine to display the temperature (in every 3sec) and activate the A/C relay, but I am unable to manage the 10min waiting window.
I am new to Python, so any help regarding the same would be appreciate.
Comment: Please provide a [mcve] that demonstrates your issue.
Answer: Since you didn't share the actual code, the only thing I can do is to describe what your strategy might be:

Create a variable called start_timestamp. Even before the first temperature check, assign the current time to it.
Every time you check that the current temperature is lower than or equal 10C, set start_timestamp to the current time once again.
Every time you check that the current temperature is higher than 10C, do nothing with start_timestamp.
After every temperature check, compare the current time to (start_timestamp plus 600 seconds). If it's greater, it means the last time the temperature turned out to be lower than 10C was at least 10 minutes ago.
Comment: Thanks @Buzzy, you shared the exactly what I want, I implemented it into code segment and its working absolutely fine.
Answer: Since you claim that you can update the temperature measurement every 3 seconds, assuming update_every_3_seconds is the function to do that, add:
high_temp_seconds = 0
...

def update_every_3_seconds():
    ...
    global high_temp_seconds
    if high_temp:
        high_temp_seconds += 3
    else:
        high_temp_seconds = 0
    if high_temp_seconds >= (10 * 60):
       activate_AC_relay()


Prove that $\sum_{n=1}^\infty\frac{\sin(nz)}{2^n}$ is analytic on $\{z\in\mathbb{C}:|\operatorname{Im}(z)|<\log(2)\}$

Question:
Prove that $f(z)=\sum_{n=1}^\infty\frac{\sin(nz)}{2^n}$ is analytic on $A=\{z\in\mathbb{C}:|\operatorname{Im}(z)|<\log(2)\}$

I tried expanding $\sin(nz)$ in terms of $e^{inz}$ but that did not help me unless I am doing something wrong.  I know Weierstrass's M-test comes in to play.
Answer: Using $\sin nz=\frac{1}{2i}(e^{inz}-e^{-inz})$ works. The constant is irrelevant for the convergence.
Deal with the two exponentials separately. Let $z=x+iy$. Then $|e^{inz}|=e^{-ny}$, and  $|e^{i((n+1)z}|=e^{-(n+1)y}$.
Thus, remembering about the $2^n$ in the denominator, we see that the norm of the ratio of two consecutive terms is $\frac{e^{-y}}{2}$.  This norm is $\lt 1$ precisely if $e^{-y} \lt 2$, that is, if $y\gt -\log 2$.
In the same way, for the term in $e^{-iz}$, the norm of the ratio of two consecutive terms is $\lt 1$ precisely if $y \lt \log 2$.  Thus, by the Weierstrass $M$-test, we have analyticity if $-\log 2\lt y\lt \log 2$.
Comment: Since the OP referred to Weierstrass $M$-test, I assumed the OP knew that in our region we have uniform convergence of a series of analytic functions.
Comment: Is it possible to prove the series diverge outside that area? Thank you!
Comment: I think I followed your proof, but I'm not entirely sure where you used the Weierstrass $M$-test. It looks like you essentially split the series into two using the definition of $sin(nz)$. Then used the fact that those two new series are just geometric series and so we require $r<1$ for both which leads to $-\ln(2)<y<\ln(2)$. Am I wrong?
Comment: Also is the radius of convergence then just $\ln(2)$?
Answer: We have
$$
f(z)=\frac{1}{2i}\sum_{n=0}^\infty\frac{e^{inz}-e^{-inz}}{2^n}
=\frac{1}{2i}\sum_{n=0}^\infty\left[\left(\frac{e^{iz}}{2}\right)^n-\left(\frac{e^{-iz}}{2}\right)^n\right]
$$
If $|e^{\pm iz}/2|=\frac{1}{2}e^{\mp\text{Im}(z)}<1$, i.e. $\mp\text{Im}(z)<\log2$ or $|\text{Im}(z)|<\log2$ then the series converges and
\begin{eqnarray}
f(z)&=&\frac{1}{2i}\left[\frac{e^{iz}}{2}\frac{1}{1-e^{iz}/2}-\frac{e^{-iz}}{2}\frac{1}{1-e^{-iz}/2}\right]\cr
&=&\frac{1}{2i}\left(\frac{e^{iz}}{2-e^{iz}}-\frac{e^{-iz}}{2-e^{-iz}}\right)\cr
&=&\frac{2e^{iz}-1-2e^{-iz}+1}{2i(4-2e^{iz}-2e^{-iz}+1)}\cr
&=&\frac{4i\sin z}{2i(5-4\cos z)}=\frac{2\sin z}{5-4\cos z}.
\end{eqnarray}
This function is obviously analytic!
Answer: Fix $\epsilon>0$.
If $|\Im(z)|<\log(2-\epsilon)$, then
$$|\sin(nz)|=\left |\frac{e^{inz}-e^{-inz}}{2i}\right |\leq\frac{1}{2}\left (|e^{inz}|+|e^{-inz}|\right )=\frac{1}{2}\left (e^{-n\Im(z)}+e^{n\Im(z)}\right )<(2-\epsilon)^n,$$
so that the series converges uniformly on $A_\epsilon=\{z\in\mathbb{C}:|\text{Im}(z)|<\log(2-\epsilon)\}$ by the M-test.
Since the result of differentiating the series in the definition of $f$ term-by-term is $\sum_{n=1}^\infty\frac{n\sin(nz)}{2^n}$ which converges absolutely on $A_\epsilon$, it follows that differentiating term-by-term is legitimate and that $f$ is complex differentiable on $A_\epsilon$.
Since $\epsilon$ was arbitrary, we conclude that $f$ is complex differentiable on $A$. In particular, $f$ is holomorphic and hence analytic on $A$.


How to prove $\sup(A) \leq \inf(B)$?

Question: I have the following problem:

Let $A, B \subseteq\mathbb{R}, A \neq \emptyset$ and $B \neq\emptyset$ such that $$(\forall a \in A \wedge b \in B): a \leq b$$
  Prove that $\sup(A) \leq \inf(B)$.

My attempt:
We know by definition that $A$ is bounded from below and $B$ is bounded from above, therefore by Completeness Axiom, we know there exist $\sup(A)$, and by theorem there exists $\inf(B)$.
Let $a \in A$ and $b \in B$, then $a \leq \sup(A)$ and $\inf(B) \leq b$. Hence, $a + \inf(B) \leq \sup(A) + b$
However, I don't have idea how to get $\sup(A) \leq \inf(B)$.
Hope you can help me :)
Comment: See also: [Prove that $\sup S \leq \inf T$](https://math.stackexchange.com/q/3508153)
Answer: $\sup A $ is the least upper bound of $A $, that is, it is the least number which is greater than or equal to all elements of  $A $ [1]. So by definition, $\sup A\leq b $ for all $b\in B $. Now, $\inf B $ is the greatest lower bound of $B $. And since $\sup A\leq b,\, \forall b\in B $, we have $\sup A\leq \inf B $.
Answer: Assume $y= \inf (B) \lt \sup(A) = x$.  By the definition of $\inf, \forall \epsilon \gt 0 \exists b \in B~(y \leq b \lt y+ \epsilon)$.  By the definition of $\sup, \forall \epsilon \gt 0 \exists a \in A~(x - \epsilon \lt a \leq x).$  Choose $\epsilon = \frac{x-y}{3}.$  Then $b \lt y+ \epsilon \lt x - \epsilon \lt a$, so $\exists a \in A, b \in B \text{ with } b \lt a$ contradicting our hypothesis.
Answer: Let $\sup A = s$ and $\inf B = d$, and suppose, for the sake of contradiction, that $s > d$. Then $s-d > 0$. Given $\varepsilon > 0$, there exist $x \in A$ and $y \in B$ such that $y-x < 2\varepsilon + d-s$. Choosing $\varepsilon =-\dfrac{d-s}{2}$, we have $y-x < -2 \cdot \dfrac{d-s}{2} + d-s = 0 \Rightarrow y < x$, which is a contradiction since $x \geq y$. Thus, $d \geq s$.

How to prove $\sup(A) \leq \inf(B)$?


PHP Global Vars

Question: I am breaking my head why the simplest thing is not working.
All I want is to access the variable declared in the included file.
I have file called connection.php in which I have a class called MySqlDatabase. In the bottom of the file I created the instance of the class and assiged it to variable called $database
// filename database.php begin

class MySqlDatabase(){

// code goes here

}

$database = new MySqlDatabase();

// filename database.php end

Now I included database.php in something.php and trying to access the $database variable like this
//something.php
require_once 'database.php';

function foo(){

global $database;

$sql = "some sql statement";
mysql_query($sql,$database->connection);
//and remainig code goes here...

}

When I run the something.php it is expected that the global variable $database should be available in the function foo() but it seems like the variable is null, I tested with is_object() function to check the object is available but it returning false.
For debugging purpose I added is_object() check in the database.php file and it is returning true.
Also I tried to access the global variable using other options like
$database =& $GLOBALS['database'];

But I still have no luck. I then printed the complete $GLOBALS array using print_r() function also but it doesnt have the $database variable, I also checked using get_defined_vars() but it also doesnt have the variable. But I am able to see them in the included file itself
I am breaking my head since two days to make this simple thing work but I compromised and copy pasting database connection code in all the files.
Comment: $database is not a global variable as such, you are essentially just making the variable $database available whilst using the `foo()` function.  Could we see the full `MySqlDatabase()` class, then the implementation of the class will become more clear.
Answer: I made some change in your code, this work for me.
database.php
<?php
// filename database.php begin
class MySqlDatabase
{
    public $connection;
    function MySqlDatabase()
    {
        $this->connection= mysql_connect('HOST','USER','PASSWORD');
        mysql_select_db('databaseName',$this->connection);
    }
}
$database = new MySqlDatabase();
// filename database.php end
?>

something.php
<?php
require_once 'database.php';
function foo( )
{
    global $database ;
    $sql = "select * from tableName";
    $rs=mysql_query($sql,$database->connection);
    while($row=mysql_fetch_array($rs))
    {
        print_r($row);
    }
    //and remainig code goes here...
}
foo();
?>

You might be manipulating $connection variable in wrong manor.
Answer: If you have included  the file then use the following:
//something.php
require_once 'database.php';

   /* Function FOO starts a new scope and doesn't see database object declared in database.php
    * Therefore, you pass on the database object from calling function and use that instead.
    */

function foo($dbObj){

    $sql = "some sql stagement";
    mysql_query($sql,$dbObj->connection);
    //and remainig code goes here...

}

foo($database);

Answer: There are only 3 possible reasons

$database defined not in the global scope
database.php being included not as a file
some typo invisible to reader
Answer: You could use a singleton pattern or set the variable static in database class.
Answer: Well, I figured out the problem. The issue is with the amfphp framework. This framework includes all my files (something.php). Its hard to explain it but in simple words I included the database.php in the one of the main php file related to the amfphp framework.
Thanks for you suggetions.

PHP Global Vars


Linux kernel crash analysis. Blocked processes, IO and uninterruptible wait

Question: I have a multiuser ERP application running on a CentOS 5.5 platform. The hardware is HP ProLiant DL380 G6. This has been a stable system for the past year, but there have been problems over the past week. The issue is a gradual rise in system load over the course of several hours to levels of 60+. The system remains responsive, but at some point, the HP ASR watchdog timer kicks in and reboots the server.
I have plenty of these systems in the field, but haven't had this particular issue before. The crash has occurred four times over the past week, but I was able to catch it this morning before the system became completely unresponsive.
This time, I found that the system load was about 75, but there were 14 zombie processes that I could not kill. The PPID's were 1, so I knew a reboot would be in order. Interestingly, the following is an excerpt of the dmesg output and contains messages that I didn't see in previous crashes. What do these entries mean? The PIDs correspond to the zombie processes that I could not kill. in.telnetd is the Telnet daemon for a particular user session and dbc is the per-user ERP application instance.
INFO: task in.telnetd:12210 blocked for more than 600 seconds.
"echo 0 > /proc/sys/kernel/hung_task_timeout_secs" disables this message.
in.telnetd    D ffff81000102e4a0     0 12210   8899         16297 12762 (L-TLB)
 ffff8103848d7d38 0000000000000046 ffff8108272c1738 ffff81082328ae80
 ffff81082644d9c0 0000000000000009 ffff8102d8d7a080 ffff81011c9df100
 00011ef007c2d74b 0000000000002358 ffff8102d8d7a268 0000000500000001
Call Trace:
 [<ffffffff80063c6f>] __mutex_lock_slowpath+0x60/0x9b
 [<ffffffff8003db0d>] lock_timer_base+0x1b/0x3c
 [<ffffffff80063cb9>] .text.lock.mutex+0xf/0x14
 [<ffffffff8009dc66>] flush_workqueue+0x3f/0x87
 [<ffffffff801a96ee>] release_dev+0x503/0x67b
 [<ffffffff800646f9>] __down_failed+0x35/0x3a
 [<ffffffff80225b40>] sock_destroy_inode+0x0/0x10
 [<ffffffff800537af>] tty_release+0x11/0x1a
 [<ffffffff80012ad9>] __fput+0xd3/0x1bd
 [<ffffffff80023c39>] filp_close+0x5c/0x64
 [<ffffffff80038f19>] put_files_struct+0x63/0xae
 [<ffffffff80015860>] do_exit+0x31c/0x911
 [<ffffffff800491a7>] cpuset_exit+0x0/0x88
 [<ffffffff8005d116>] system_call+0x7e/0x83

INFO: task dbc:9054 blocked for more than 600 seconds.
"echo 0 > /proc/sys/kernel/hung_task_timeout_secs" disables this message.
dbc           D ffff810001036b20     0  9054      1          3272  1795 (L-TLB)
 ffff81028e0c3d38 0000000000000046 0000000000000000 00000000000001d0
 0000000000000000 0000000000000009 ffff8107d60ff100 ffff81011c9ed080
 00011edea224420a 00000000000ebaee ffff8107d60ff2e8 0000000600000000
Call Trace:
 [<ffffffff80063c6f>] __mutex_lock_slowpath+0x60/0x9b
 [<ffffffff8003db0d>] lock_timer_base+0x1b/0x3c
 [<ffffffff80063cb9>] .text.lock.mutex+0xf/0x14
 [<ffffffff8009dc66>] flush_workqueue+0x3f/0x87
 [<ffffffff801a96ee>] release_dev+0x503/0x67b
 [<ffffffff8837dd1d>] :xfs:xfs_free_eofblocks+0x9d/0x1fe
 [<ffffffff800537af>] tty_release+0x11/0x1a
 [<ffffffff80012ad9>] __fput+0xd3/0x1bd
 [<ffffffff80023c39>] filp_close+0x5c/0x64
 [<ffffffff80038f19>] put_files_struct+0x63/0xae
 [<ffffffff80015860>] do_exit+0x31c/0x911
 [<ffffffff800491a7>] cpuset_exit+0x0/0x88
 [<ffffffff8006149d>] sysenter_do_call+0x1e/0x76

Comment: Keep in mind that these traces may very well just be more symptoms of the problem. The machine is hosed, causing filesystem operations which should complete quickly to instead hang, and the kernel is warning you about it.
Comment: Is the XFS drive out of space? Are there available inodes? What is the output of df -h and df -i?
Comment: Data partitions are all good - /dev/cciss/c0d0p9     1.1T  532G  518G  51% /data
Comment: Inode usage is 1%.
Comment: Ok, what Linux kernel is this?
Comment: CentOS 5.5, so the kernel is presumably kernel-2.6.18-194.26.1.el5
Answer: Those messages mean something is consuming all available I/O. This is either due to (a) failing hardware (disc/controller/etc) which results in the available I/O being 0 or (b) there being a process (or processes) using all the I/O.
The guilty process may not be the one listed in dmesg. It was the victim.
Since I doubt in.telnetd (aside: why would you have telnetd running ever?) touches /data and you have other systems that don't experience the issue I'm guessing c0d0 is bad or the firmware needs to be updated.
Run the HP Insight Diagnostics on it. Otherwise next time it happens see if you can run iostat to see if the disc is actually being overwhelmed.
Comment: It was a bad SCSI HBA.
Comment: Telnetd since this is an ERP application with point-of-sale terminals and wireless RF guns (which require telnet). The server was entirely responsive through this, so there were no problems with disk access to the onboard Smart Array controller. I've narrowed this down to a system board/PCI card issue... I think it's a bad SCSI adapter (for the tape drive).


Is there a way sort View by results of "Options" Rate/Voting API widget?

Question: I'm using the Rate module to allow voting on whether or not a given node is "Helpful" or "Unhelpful". I have a view with all nodes of this type, and the view includes a field for the Rate widget. I am having no problems displaying the widget itself, and the voting is working perfectly. However, I cannot for the life of me get any type of sorting functionality to work.
I've tried all of the sort types having to do with Vote, and all of them sort the nodes in no relevant order. It seems that the problem arises because I am using the value-type of "Options", and suggestions that I have found seem to require the value-type to be "Points". However, I'd much rather have user select between "Helpful" and "Unhelpful" than to use a thumbs up/down or +/- system of voting.
Does anybody know how I could sort by "most helpful" and "most unhelpful" and keep the value-type of "Options"?
Answer: You have to add a relationship Content: Vote Results with proper data filters

Value-type: Points
Vote-tag: Your rate widget vote tag
Aggregation-function: Number of vote

Then in views sort criteria add

(Vote results) Vote results: Value (desc/asc)
Comment: So, is there no way to do this when the widget's value-type is set to options? I believe I need to have it set to this in order to give users the ability to select either "Helpful" or "Unhelpful", and provide a total number of votes for each. I realize that I could do a thumbs up/down system where opposite votes cancel eachother out, but I would like to show each value independently.


what is the best method to encrypt and decrypt a value using c#?

Question: Hai guys,
   I hve a web page that has to send an encrypted value to another page in my asp.net web application... I want to know

what is the best method to encrypt and decrypt a value using c#?
Comment: What Matt suggests assumes an awfully liberal definition of 'encrypt'.  But it makes the point - you need to define what you mean by encryption.  Do you mean "so a casual observer can't read it" or do you mean "I don't want the NSA to know what's being passed"?
Comment: efficient? As in fastest? probably rot 13. http://www.tech-faq.com/rot-13.shtml
Answer: If by efficient you mean efficient development (not implementing your own solution), I would say using the algorithms in the System.Security.Cryptography namespace.  If instead you mean least-CPU-intensive, then probably rot 13 as mentioned by Matt Ellen.  (Edit: As others have mentioned, rot 13 is not secure.  Please consider that carefully.)
Between DES, 3DES, RC2, and Rijndael, this is what MS has to say:

With small data, we find that
  Rijndael, an AES (Advanced Encryption
  standard), is the fastest of all the
  methods. It has a variable block
  length and key length, which may be
  chosen to be any of 128, 192, or 256
  bits. It also has a variable number of
  rounds to produce the cipher text,
  which depends on the key length and
  the block length.
Answer: The method would depend on your use. I would not use rot 13 as it's nothing more than a basic letter replacement; not very secure.
I'd use 3DES or AES for any encryption.


IIS Process ID for pool

Question: How do you find out which process in the task manager belongs to what IIS app pool.
Answer: Use SysInternal's Process Explorer - It will show the command line for the proces, which shows the AppPool Name.
Answer: Run CMD as Administrator, run C:\Windows\System32\Inetsrv\appcmd.exe LIST WP
Answer: c:\windows\system32\cscript.exe c:\windows\system32\iisapp.vbs

Comment: this appears to be an IIS 6 only script.
Answer: Assuming IIS6, the best way is to use iisapp.vbs plus Task Manager.  iisapp.vbs maps the app pool id to the PID (which Task Manager doesn't do), but Task Manager gives you the real-time CPU and memory usage.  You can run iisapp simply by typing 'iisapp' from the command prompt.  In Task Manager make sure to add the PID column since it's not there by default on a new machine.
In IIS7 you would use "appcmd list wp" instead of iisapp.  For that you'll need to update your path or navigate to it.  The full command that will work is: "c:\windows\system32\inetsrv\appcmd list wp"
Answer: If I'm not mistaken, you can go into the Component Services management console, expand My Computer, select the Running Processes node in the left pane and you should see a list of running processes for each web sites application pool and their PID numbers.
Answer: Install the IIS "Debug Diagnostic Tool".
http://www.microsoft.com/downloads/details.aspx?FamilyID=28bd5941-c458-46f1-b24d-f60151d875a3&displaylang=en
Run it and look in the Processes tab. Look in the "Web application pool name" column.
Answer: Adding to @pradeep answer
Sometimes C:\Windows\System32\Inetsrv\appcmd.exe LIST WP  yields an empty list (i.e. yields nothing, no result, blank, zero lines).  This will occur if there have been no requests since IIS last restarted.  Get on your web-browser, and query (request a web page from) the server; that will start a worker process, and your next attempt with appcmd LIST WP will show the new process.

IIS Process ID for pool


Question about Ordering Promises from Block Event Listeners

Question: I am trying to figure out why block number data is not being returned sequentially. If I just print the block number within the event listener it provides block numbers sequentially, but right when I try to pull block information from that block number and chain with a "then" method it seems to delay the result enough to unorder the console logs. This is probably the result of me not fully understanding the event loop. Any help would be appreciated.
var ethers = require('ethers')
var dotenv = require('dotenv').config({path: '.env'})
var  provider =  new ethers.providers.JsonRpcProvider(process.env.infura_polygon_https)

provider.on('block', (blockNumber) => {
    Promise.resolve()
        .then(() => provider.getBlock(blockNumber))
        .then((message) => console.log(blockNumber + ': ' + message.transactions.length ))
})

console log results
Comment: If `block` events occur fast enough, and `provider.getBlock` of an earlier block takes longer than that of an earlier block, the logs will be out of order. I don't see what this has to do with the understanding of the event loop, or even with promises (callbacks would have the same behaviour), it's just basic independent asynchronous processes.
Comment: Why are you starting your promise chain with `Promise.resolve()`?
Comment: That's a good point doesn't seem necessary. Doesn't seem to change the output.
Comment: I'm sure you're right, but how do I force the script to block the program until the block information is returned?
Comment: You don't ever want to *block* the program :-) You want to delay the logging of the transaction count until all previous transaction counts have been logged. You can do that by queuing the promises.
Answer: You want to delay the logging of the transaction count until all previous transaction counts have been logged. You can do that by building a queue of the promises for these actions:
let queue = Promise.resolve()
provider.on('block', blockNumber => {
    queue = queue.then(() =>
        provider.getBlock(blockNumber)
    ).then(message => {
        console.log(blockNumber + ': ' + message.transactions.length)
    })
})

However, this is inefficient since all the getBlock calls must happen in sequence, and it doesn't handle errors properly (possibly breaking the entire chain). Better fetch each block already while still waiting for the previous logs being completed:
let queue = Promise.resolve()
provider.on('block', blockNumber => {
    queue = Promise.all([
        queue,
        provider.getBlock(blockNumber)
    ]).then(([, message] => {
        console.log(blockNumber + ': ' + message.transactions.length)
    }, err => {
        console.error(err.message)
    })
})

Comment: this works perfectly. thank you for the help on this. are you using the promise.all because you want to get the results of the queue and the new promise for proper error handling?
Comment: Because I want to wait for both the queue (i.e. the previous log) as well as for the block. The error handling is achieved through the second `.then()` argument


Symbolic Link Directory or File confusion

Question: Symbolic Links are awesome but I seem to have trouble remembering how to know whether it is the directory or the actual files in the directory that will be symlinked to a new place.
In this situation, I have some files located at ~/Documents/WD/CS/CSlides and I wish to symlink them INTO this directory ~/Documents/PDF/DB/CS/CSlides
I tried this:
ln -s "~/Documents/WD/CS/CSlides/" "~/Documents/PDF/DB/CS/CSlides/"

But that just put a new CSlides folder inside the one at the destination. I just want the source CSlides files to be linked. Not the directory itself.
Any thoughts?

This is about programming. I was trying to move so documents relating to my web development. Blimey, some peeps are a bit too pernickety but if it's closed then it's closed. I got it sorted out eventually. Thanks
Answer: You cannot "merge" directories, you have to link each file like this:
ln -s ~/Documents/WD/CS/CSlides/* ~/Documents/PDF/DB/CS/CSlides

Comment: Running that, I end up with a file entitled "*" as having been symlinked. I understand what it was trying to do but it didn't work
Comment: Well, don't remove it with `rm ~/Documents/WD/CS/CSlides/*` but use something like `rm -i ~/Documents/WD/CS/CSlides/?` !! Are you sure you did remove the double quotes from your command as I did ?


Moving an Existential quantifier out of an implication using fitch.

Question: I've looked just about every place I could think of and found the necessary rules multiple times, yet no proofs for those derived rules. Most proofs are for conjunctions, yet i have not found any for implications.
An example for such a statement and the corresponding target statement would be:
$\exists xPx\to\exists yPy\therefore\exists y(\exists xPx\to Py)$
I have made multiple attempts with $\to$I and $\neg$E but no luck so far. Can you guys give me a hint?
Answer: The hypothesis is a tautology, and thus is of no use in the proof.
From http://proofs.openlogicproject.org/:
Comment: @Gidelix It's the Law of the Excluded Middle.  It's $\vee E$ except starting from an unstated assumption of $\exists x Px \vee \neg \exists x Px$.
Comment: Thank you for the quick answer, but I am not familiar with the LEM-Rule. Give me a second to look it up and I'll go ahead and mark the question as solved.
Comment: Thank you! Marked as accepted answer, have a nice evening!
Answer: Here is a proof done in Fitch:
Comment: Thanks! The proof using $\vee$E from above works, but your proof doesn't use a tautology which is really handy when proving with no derived rules ^^!
Comment: @Gidelix You're welcome! :)


Keil µvision 5 header file shows an error, however it is compiled without problems

Question: I got access to this project. It is compiled in Keil µvision 5. When I compile the project it has no errors. However, when I access a header file it shows me an error, saying that s8 variable has the following error = error: unknown type name 's8'.
    typedef struct
    {
      s8 str[PARAM_TEXT_SIZE];
    }
    text_struct;

The variable is defined as follow:
   typedef char   s8;

I wonder whether I have misconfigured the compiler, or why this error is neglected after compiling.
PS: This is my first question in the StackOverflow site. Sorry if my question is not clear or is wrongly placed.
Comment: Who defines the variable and where? Which files are these located in? `s8` is not standard. In addition, it is a very bad idea to typedef `char` as signed 8, since it can be unsigned. What you should do (since the year 1999) is to use `stdint.h` and not some home-made junk types.
Comment: If this piece of code comes from a header it's totally possible that this header doesn't have the required include containing the typedef for `s8`, but the file that includes the one having this error does include it, so at compile time there's no problem but statically speaking the header is incomplete.
Comment: @Lundin '(since the year 1999)' --> Since the year your cross-compiler provider realizes the 21st century is a thing. *cries in 198X*.
(ARM compiler is quite up-to-date anyway)
Comment: Hello @Lundin, as I have said I got this code. Normally, I would use as you said the 'stdint.h'. But, this is a big code ( over 100k code-lines), and this variable is widely used in the code. It is define in the 'typedef_arm.h' file for the arm microcontroller. And it is defined as signed variable because it matters for the binary computation of the microcontroller.
Answer: If s8 is defined in a header, let's say foo.h, and your text_struct is defined in another header, call it bar.h then it compiles perfectly if the file that includes bar.h includes foo.h first. It is however not clean, it's usually a good practice not to rely on such pre-requisite includes.
Here's a very simple example :
foo.h
typedef int myType;

bar.h
typedef struct {
    myType x;
} myStruct;

main.c
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

#include "foo.h"
#include "bar.h"

myStruct y;

int main(void) {
    return 0;
}

This will compile without issue, however if bar.h is statically evaluated then it'll produce an error since myType is not known here. If bar.h is included without foo.h to be included as well, then you'll have a compilation error. Here's an example :
error.c
#include "bar.h"

myStruct z;

gcc -I. error.c -o error.o
In file included from error.c:1:0:
  bar.h:2:5: error: unknown type name 'myType'
       myType x;
Comment: Hello @TimF, I appreciate your answer! However, I forgot to mention, the declaration of the header file is like this:
`#ifndef _PARAM_H`
`#define _PARAM_H`
`code`
`#endif`
I am not so acquainted with this type of declaration, so i do not know if I am allowed to declare a header file here.
Comment: Yes you are. This `PARAM_H` is just a guard that prevents you to include your header more than once. It's standard to put it on top of each header and it should have the capitalized name of your header + H. In my example it would be `_FOO_H` and `_BAR_H`. See [Include Guard on Wikipedia](https://en.wikipedia.org/wiki/Include_guard).
If my answer was useful don't hesitate to upvote and accept it. Welcome on StackOverflow by the way !
Comment: Thanks @TimF! Worked fine for me. Thanks for the warm welcome ! :)


How can I enable HTML output for checkbox options?

Question: I am adding theme styling settings and I would like to have associated color to the checkbox in themes setting form. So far, i haven't been able to do so, because the output strips inline styling and then external styling is being reset for the admin view. How do you enable html output of the text next to the checkbox?
Here is my code so far:
function THEMENAME_form_system_theme_settings_alter(&$form, &$form_state){
       $form['theme_style'] = array(
        '#title' => 'Theme Style',
        '#type' => 'fieldset',
        '#collapsible' => FALSE,
        '#collapsed' => FALSE,
    );
    $form['theme_style']['color'] = array(
        '#title' => t('Color Skin'),
        '#type' => 'checkboxes',
        '#options' => color_schemas(),
//        '#process' => array(),
        '#pre_render' => array(),
        '#post_render' => array(),
        '#format' => array('text_format' => 'full_html'),
    );
}

function color_schemas(){
   $colors = array(
        'blue' => htmlentities('Blue'),
        'black' => 'Black',
        'maroon' => t('Maroon'),
        'grey' => t('Grey'),
        'white' => t('White'),
    );
    return $colors;
}

Here i try different things. To set the text format in '#format' attribute. I also attach 'id' element so could style in external style sheet but those are reset by admin imported CSS. I also try convert all html entities and output which works but it doesn't render the html correctly
Answer: For starters, if you're using an admin theme like Seven for your administration pages, nothing on those pages will ever be affected by another theme's code. If you need to write code that applies across any theme, then you should be putting that in a module.
Inline styles are an attack vector for XSS, which is why they're generally not allowed in any kind of markup that is the result of user input. That includes the label text for a form element, such as a checkbox: the label is constructed by theme_form_element_label(), which sanitizes the text with filter_xss_admin(). That's absolutely the correct thing to do.
The proper way to do this is to put your styles in an external spreadsheet, as you've mentioned. Consider whether you could implement your code as a module instead.
Comment: Thank You Les. I moved the CSS in external css file style-admin.php and then attached as following:
Comment: if(($user->uid)){
        drupal_add_css(drupal_get_path('theme',$GLOBALS['theme']) .'/css/style-admin.css', array('group' => 999, 'weight' => 999, 'type' => 'file'));
    }
Comment: however this doesn't work because the admin theme css is taking precedence over the style-admin.css no matter what the weight and group is set. why?
Comment: I don't believe it's a precedence issue. I think the issue is that you have two completely different themes running on your site. The code you put in your main site theme does not run at all on your admin pages, because your admin pages are using the "seven" theme. Try changing your "administration theme" in admin/appearance from "Seven" to your default theme to see what I'm talking about.
Comment: Thank You Les. I am not sure, but when i look what css is imported i can see all of my custom theme css files before the admin css with the reset.css between
Answer: You can use simple markup in the t() function, look at especially this comment, which indicates to this source: Dynamic or static links and HTML in translatable strings.

The general rule of thumb for translatable strings is that we keep inline markup for translation but avoid block tags (but do read the whole story before you make this your mantra).

According to this documentation, your code should be look like:
function color_schemas() {
  $colors = array(
    'blue' => t('Blue'),
    'black' => t('Black'),
    'maroon' => t('Maroon'),
    'grey' => t('Grey'),
    'white' => t('White'),
  );
  return $colors;
}

Though I would suggest you to use css classes for span instead of inline styling.
Comment: Thank you Elin. It still strips away all of the style attribute with its values wether in the 't' function or not. This is Drupal 7.2x with admin theme 'seven'. Any more ideas?


Hi :) I have a question about Taylor series and convergence.

Question: My function is $f(x)= \sqrt{1+\sin x}$ around $x_0=0$ .
Taylor series should look like (I guess so)
$f^{(2n)}(x)=\frac{(-1)^n}{2^{2n}}f(x) \quad\to\quad f^{(2n)}(0)=\frac{(-1)^n}{2^{2n}}$
$f^{(2n+1)}(x)=\frac{(-1)^n}{2^{2n+1}}f'(x)\quad\to\quad f^{(2n+1)}(0)=\frac{(-1)^n}{2^{2n+1}}$
I don't really understand how to show when it converges. I want to find out how will be x defined if exists a $\lim_{n\to\infty} T_n(x)$
Thank you.
Comment: How did you get those formulas for the derivatives?
Comment: Why do you believe those expressions are correct?
Comment: At first I solved it at the university and now I also found the same answer here https://math.stackexchange.com/questions/2015450/taylor-series-fx-sqrt1-sin-x-around-x-0-0
Answer: Note that your function $f(x)=\sqrt{1+\sin x}$ is the composit function of $\sqrt{1+x}$ and $\sin x$
The Taylor series for $\sqrt {1+x}$ converges for $|x|\le 1$ and we have $|\sin x|\le 1$ for all $x$
Thus your power series converges on $(-\infty,\infty)$
Comment: Thanks for your answer, but it means I have to find the taylor series of $\sqrt {1+x}$ at first and then to show that it converges for $|x|\le 1$ right? Or is it so clear, that it don't have to be proved? (However I don't understand it completely)
Comment: It is binomial series which is well known to converge on $[-1,1]$
Comment: I got it! Thank you so much :)
Comment: Thanks for your attention.
Answer: For your derivatives you got $|f^{(k)}(0)|=2^{-k}$. This means that the term-wise absolute series of the Taylor expansion is
$$
\sum_{k=0}^\infty \left|\frac{f^{(k)}(0)}{k!}x^k\right|=\sum_{k=0}^\infty \frac{|x/2|^k}{k!}=e^{|x|/2}
$$
which is finite for all $x\in\Bbb R$. Thus the Taylor expansion of $f$ is everywhere absolutely convergent.
Comment: Thank you so much


Jquery validate plugin - field that accepts numbers and letters - set maxlength if a number is entered

Question: I have a field that allows users to search for a store based on either a suburb or a post code.
I am using the Jquery validate plugin to validate the value entered in this field.
Basically, I want to set the maxlength to 4 ONLY if a number is entered. If a suburb is entered there there doesn't need to be a max length.
Any suggestions for the best approach?
Comment: You should really show an attempt at coding this yourself before asking for help.
Comment: I was asking for the best approach to take before taking the time to code a misguided solution.
Answer: You can use a validation rule like
<code>var validator = $('#myform').validate({
    rules: {
        search: {
            required: true,
            maxlength: {
                param: 4,
                depends: function(element){
                    var value = $.trim($(element).val());
                    return /^\d+$/.test(value);
                }
            }
        }
    },
    messages: {}
});
</code>
Demo: Fiddle


Get attribute of a generic foreign key

Question: I'm still trying to wrap my head around generic foreign keys in Django, so what I've come up with is quite basic so far. I'm trying to create a NotificationRecipient, which has a generic foreign key of 2 different models I've already created. These notification recipients can either be a Client or an Account. I may decide to add more recipients of a new model.
I want to create a get_email method in NotificationRecipient, where it checks if the recipient is a contact, client, or account. Then depending on which model it is, it pulls a different attribute.
My existing models look a little like this:
class Client(models.Model):
    primary_email = models.EmailField(blank=True)
    ...

class Account(AbstractNamedUser):
    email = models.EmailField(blank=True)
    ...

Try to get the email depending on the model:
class NotificationRecipient(models.Model):
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id')

    def get_email_addr(self):
        ''' Gets the model, then pulls the email address. '''
        # Get the model
        # if client:
            # return primary_email
        # elif account:
            # return email

How would I go about doing it?
Answer: You can check the content_type field to determine which kind the object is.
But rather than checking the type, you might consider defining an attribute on all the target models which returns the relevant attribute.
Answer: It is best to define a method on your targeted models rather than building all the business logic in your NotificationRecipient model.
The logic is that the NotificationRecipient model only needs to know that it requires an email address.
class Client(...):
    def get_email_addr(self):
        return primary_email

class Account(...):
    def get_email_addr(self):
        return email

class NotificationRecipient(models.Model):
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id')

    def get_email_addr(self):

        try:
            email = self.content_object.get_email_addr()

        # if you want to enforce the attribute
        except AttributeError:
            raise ImproperlyConfigured('Model requires an email address')

        # if you need a default
        if not email:
            return 'firstname.lastname@example.com'

        return email

Get attribute of a generic foreign key


How can I monitor new IPv4 connections in C#

Question: I need to monitor any new IPv4 connection made by a computer. The information I need is the process ID making the connection as well as the IP address the process is connecting to. I would need a callback function that gets called as soon as a new connection is discovered.
I have tried using ETW with Microsoft-Windows-Kernel-Network, but I only get integer representations of some daddr and saddr that I can't seem to map back to an IP address. Any help would be appreciated.
Comment: have you played a bit with TraceEvent and the Microsoft-Windows-TCPIP provider? Does it work?
Answer: You should use the Microsoft-Windows-TCPIP provider. You can use TraceEvent to create a Realtime session, and TraceEvent has a KernelSourceParser which allows you to parse for IP data
_kernelTraceEventParser = new KernelTraceEventParser(_source);
_kernelTraceEventParser.TcpIpConnect += KernelParserOnTcpIpConnect;

private void KernelParserOnTcpIpConnect(TcpIpConnectTraceData tcpIpConnectTraceData)
{
     lokalAddress = tcpIpConnectTraceData.saddr + ":" + tcpIpConnectTraceData.sport;
     serverAddress = tcpIpConnectTraceData.daddr + ":" + tcpIpConnectTraceData.dport;
}

Because TcpIpConnectTraceData is inherit from TraceEvent class you have access to ProcessName and ProcessID.
Comment: Is there any way to filter private data transfers?
Comment: I have no idea as I never tried this.
Answer: The function you are seeking for is called GetTcpTable, partial implementation in C# is available here. The latter also obtains the process so it completely fulfills you requirements.
It also seems to be available without inter-op as part of newer .NET implementations.


Pop-up for No Internet Connection in Android App

Question: I use Firebase in My Android App for Login & Registering. My Login Page is My Launcher Activity. I want if user is not connected to Internet or WiFi it's Shows the pop-up of No Internet Connection. How to Achieve It ?
Comment: if you are using retrofit in onfialure method put the dailog inside it
Answer: You can use this answer : How to catch an Exception if the Internet or Signal is down
Or check result / put try - catch around GoogleSignIn.getClient(this, gso);
Comment: the answer in the url  work even the no internet services
Answer: You should look at this question to detect if internet is connected.
If no, use AlertDialog (or any other "pop-ups") to show message to user.


how to improve insert into a list, use multi core

Question: I have to read 100.000 rows from database, I use this code :
List<elementClass> Listelement = new List<elementClass>();
using (DbDataReader reader = cmd.ExecuteReader())
{
    while (reader .Read())
    {
        elementClass element= new elementClass();
        DatabaseClass.ReadFromObject(reader , element);
        Listelement.Add(element);
    }
}

ReadFromObject  :
public static void ReadFromObject(DbDataReader dr, Object obj)
{
    DataTable tableDescriptor = dr.GetSchemaTable();

    try
    {
        //Id - Identifier
        obj.GetType().GetProperty("Id").SetValue(obj, dr.GetValue(dr.GetOrdinal("Id")), null);

        PropertyInfo[] properties = obj.GetType().GetProperties();
        foreach (PropertyInfo pi in properties)
        {
            if (!ExistColumn(tableDescriptor, pi.Name)) continue;   // field not found
            if (dr[pi.Name] == DBNull.Value) continue;

            if (pi.PropertyType.IsEnum) { }
            else
            {
                switch (pi.PropertyType.Name)
                {
                    case "DateTime":
                        object dateValue = null;
                        if (dr[pi.Name].GetType().Name == "String")
                            dateValue = F24Common.Utility.DateFromString(dr.GetString(dr.GetOrdinal(pi.Name)));
                        else
                            dateValue = dr.GetDateTime(dr.GetOrdinal(pi.Name));
                        pi.SetValue(obj, dateValue, null);
                        break;
                    default:
                         pi.SetValue(obj, dr.GetValue(dr.GetOrdinal(pi.Name)), null);
                        break;
                }
            }
        }

    }
    catch (Exception )
    {

    }
}

There is something definitely wrong with this code, it's too slow (the whole processing takes 45-50 minutes).
Is it possibile to fill the list using more than one CPU core (I have a quad-core CPU available) at the same time ?
Comment: Is the order of entries within the list important? Because if it isn't, the obvious thing to do is to build 4 lists, one in each thread, and concatenate them at the end. This avoids all locking.
Comment: @Damon : I was thinking to use that , but I have a file to generate after this list, and I don't know yet how to know the 4 list are completed to begin the file (I have to read a little) :)
Comment: You want a barrier for that. Once a thread is done, you have it hit the barrier, which will block it until the threshold is reached (i.e. all of them are done). Choose the threshold being 5, and have the main thread block on the barrier too. Workers exit after waking up, the main thread writes the file. I'm not a C# programmer, but it seems C# has one [readily available](http://msdn.microsoft.com/de-de/library/system.threading.barrier.aspx).
Answer: At a glance, I would think that the bottleneck lies with the amount of reflection. I'd suggest having a read of Jon Skeets excellent Making Reflection fly article. You can then cache the appropriate delegates keyed on the type of obj.
I would be hesitant to access the DataReader from multiple threads as I would doubt that it is safe to do so.
Comment: Yes, it totally is - this is about the worst (slowest) way at all to code any reflection. All the MethodInfo instances can be static and cached between method calls to ReadFromObject - if you actually want to stay with this primitive code and not use to a LINQ provider for that, which would REALLY speed things up.
Comment: ok I will read this article
and @TomTom : how to use Linq to change this ReadFromObject  !
Comment: SImple - there will not be any ReadFromObject method to start with.


How to return 2 function calls in the arrow function at once?

Question: Is there way to return 2 items in the same return of the arrow function?
useEffect(() => {
        return () =>
            removeEventListener('scroll', handleScroll) and setName('');
    }, []);

Please don't offer using useEffect twice
Comment: No need to set state in unmount. It won't be reflected anywhere if you think of i
Comment: Since none of the answers includes an explanation: If you want to include multiple statements (e.g. two function calls) in an arrow function then you declare with a body: `() => { ... statements here ... }`, pretty much like a normal function expression.
Answer: This should help
useEffect(() => {
   return () => {
     removeEventListener('scroll', handleScroll);
     setName('');
 }
}, []);

Answer: just change your code to this:
useEffect(() => {
        return () => {
            removeEventListener('scroll', handleScroll);
            setName('');
        }
    }, []);

But setting state on unMount is not suggested
Comment: Thanks for your answer. It works. Can you check please this question as well?
https://stackoverflow.com/questions/71022888/how-to-overcome-the-state-overwriting-in-the-bellow-sample-in-react


Finding the CDF of a random variable that has uniform distribution of outcomes.

Question: I want to find the CDF of a a random variable $X(\omega) = e^\omega$, with the sample space $\Omega = [-1,1]$. The outcomes of $\Omega$ are uniformly distributed.
What I've managed so far is to get to this point:
$F_X(x) = P(X<= x) = P(e^w <= x) = P(w <= ln(x))$
But I don't know where to go from here. I can't find anything about it in my books or from what I could gather on the net. All the help is welcome!
Comment: First figure out what values $X$ can take on.
Answer: Let $W$ be uniformly distributed on $[-1,1]$. Let $X=e^W$. We want the cdf of $X$.
We have
$$F_X(x)=\Pr(X\le x)=\Pr(e^W\le x)=\Pr(W\le \ln x).$$
So far, apart from a minor notational change,  this is exactly what you wrote.
If $\ln x\lt -1$, then $\Pr(W\le \ln x)=0$. Thus $F_X(x)=0$ if $x\lt e^{-1}$.
If $\ln x\ge 1$, then $\Pr(W\le ln x)=1$. Thus $F_X(x)=1$ if $x\ge e$.
For $-1\le \ln x\lt 1$, we have $\Pr(W\le \ln x)=\frac{\ln x-(-1)}{2}$.
Thus in the interval $[e^{-1},e)$  we have $F_X(x)=\frac{\ln x+1}{2}$.
If the density function $f_X(x)$ is desired, differentiate.


Recording Live Music at Home -- Microphone Help

Question: So I'm pretty new and I don't know the first thing about sound, but I think my question (and the answer to it) is pretty basic so I'm shooting my shot:
I bought a baritone ukulele and want to record videos of myself singing and playing at home. Simple, right? My instrument is not (and will not be) hooked up to an amp. When I sing and play at the same time, I notice my instrument is louder than my voice. So....I could be wrong, but I'm assuming just getting a mic and hooking it up to my amp (a Fender Frontman 10g) will solve the problem.
Questions: What kind of microphone is good for this (or home recording in general) that is of high quality that won't break the bank? Should I try to hook up a microphone to my amp? I've done some research and it seems Amazon has their own line mics, and I know that Shure makes good mics.
I'm sure these mics have to connect to something, so if not my amp, what else do I need to buy to connect these mics to? Budget is $50 - $150. I'm so eager and excited to start practicing more and recording at home, so any help towards this would be greatly appreciated.
Comment: Secondly… running a vocal mic through a guitar amp is, let's politely call it, "a bit specialist". It will not sound good unless you are doing it for an effect.
Comment: Why not just move your existing mic closer to your face? I think we're missing something here… are you recoding this all on some webcam or phone, so your mic recording position is tied to your camera position rather than being independently placeable? Alternatively, do what acoustic musicians have done for thousands of years - sing louder, play quieter.
Comment: If you want to connect a mic to your PC, what you need is a sound interface with a built-in mic pre-amp. You can find those at music retailers starting at ~100€. Some mics use phantom power, and not all sound interfaces have that.
Comment: As to which microphone is "good" - well, that is opinion-based and I'm not sure that kind of question goes over well on this platform. Try browsing the mic section at your preferred online music store and read the customer reviews.
Comment: @Tetsujin I have a USB condenser mic that hooks up to my computer, but I'm not trying to record songs using my computer. I want to record myself (that is, make a video of myself playing) using a camera (like my phone's camera or tablet camera). The condenser mic I currently own is this one: https://www.amazon.com/gp/product/B082HQVZW2/ It doesn't have an XLR attachment or anything to hook up to a speaker and I can't connect it to my amp either. I'd rather just get a new mic, as this can only connect to my PC. Like, I wouldn't be able to carry this mic with me on a stage to perform.
Comment: @Taschi I'm not looking for the best mic. Just what people generally use at home or some recommendations are fine. I've recently learned about "phantom power". Would buying a condenser mic along with something like this (to power it) suffice: https://www.amazon.com/dp/B01J5M2GO6
Comment: not unless you also buy something you can get that connected to your phone with. You should probably be looking at something like IK Multimedia - all sorts of devices for getting 'pro' signals into a phone. https://www.ikmultimedia.com/products/index.php?R=INIT&FV=product-type-menu-interfaces&CV=Product&PSEL=Interfaces
Answer: If you want the real simple solution; record into your phone, but put the phone further away from yourself so it isn't biased on where it's pointing.
More complex:
Use the condenser mic you have, and hook it to your computer. Record the sound there.
Also record the sound (and video) on your phone. Transfer that file to the computer.
Use music software to sync up the sound tracks together, which will bring the video into sync. Mute (or delete) the sound track from the phone. Export as an MP4.
For balance, be about 6 feet away from the mic; that should give you the room sound. Any issues with voice/uke balance will have to be corrected by yourself.
The Frontman 10g is a guitar amp. At the bottom end of the market, it's pretty decent for an electric guitar amp. But not ukulele or voice.


WooCommerce back button on product page

Question: I have made a "back" button on my product pages with the following code:
add_action( 'woocommerce_before_single_product', 'back_button', 10 );

function back_button() {
  global $product;
  echo ' <button class="product-back-button" type="button" onclick="history.back();"> << Vissza</button> ';
}

The only problem with it: when I make some action on the product page like "add to cart" and then hit the back button it just reloads the page and I need to push it again for the expected behavior.
Do you know any fix for that?
Thanks!
Comment: Sound like that the add to cart button manipulates the browser history. So when you add something, it goes one forward. If you press the back button now, you need to press it twice to go back. The only way to fix is is in my eyes to define a link or to call a custom JS function which checks how much times you have to go back. All in all a bit unlikely. So I would prefer the static link button.
Comment: You'd need to do a fair bit of Javascript coding to get this going. What you could do is store the [history.length](https://developer.mozilla.org/en-US/docs/Web/API/History/length) property using a [cookie](https://www.quirksmode.org/js/cookies.html) when you first enter the page, then your button could call the [History.Go()](https://developer.mozilla.org/en-US/docs/Web/API/History) method with the current history.length subtracted from the old history.length. With some special code to deal with the case where history.length has gone back to 0 after reaching 50.
Answer: I used
add_action( 'woocommerce_after_add_to_cart_button', 'back_button', 10 );
function back_button() {
global $product;
echo ' Go Back ';
}

to place a back 1 link next to cart button. I hope this helps a bit.

WooCommerce back button on product page


nx.Graph adding edges from a tuple in python

Question: I am fairly new to Python and need some help please.
I have a the edges for a network graph as a tuple in python:
edges = [(198704060004, 198704060010), (201501250041, 201501250045), (198608190006, 198608190007)]

and I am trying to plot a network graph. The code below only plots the first tuple pair.
import networkx as nx
g= nx.Graph()
g.add_edge(edges[0][0], edges[0][1])

nx.draw(g)
plt.show()

Can you please help me to make it automatically add all the edges. I tried writing a for loop but it seems I am writhing something wrong.
Many thanks!
Answer: You should iterate over edges and then add them one by one:
for source, target in edges:
    g.add_edge(source, target)


Modify default rendering of a custom content type defined in a module

Question: I am developing a module for importing, editing and exporting DocBook(XML) documents. In this module I define two new content types: docbook and  *docbook_section*. I have also defined new fields like: author, keywords, etc.
The default rendering of these content types is not quite handsome, so I would like to change and improve it. The classical Drupal way is to copy the template node.tpl.php to node--docbook.tpl.php and customize it. But this modification is done on the current theme, after the module has been installed. I would like to do the modification inside the module, so that as soon as it is installed it has a decent default look, without having to make any external modifications. Themes should also be able to override this template, in order to customize the look.
It may seem reasonable to place node--docbook.tpl.php inside the module, but that way it will not work: the theme/rendering engine will not be able to find and use the template. To solve this problem, I have defined hook_theme() on the module like this:
/**
 * Implements hook_theme().
 */
function docbook_theme($existing, $type, $theme, $path) {
  return array (
    'node__docbook' => array (
      //'variables' => array('view' => NULL,),
      'template' => 'node--docbook' ,
      'base hook' => 'node',
      'path' => drupal_get_path('module', 'docbook'),
      'preprocess functions' => array('template_preprocess_node__docbook'),
    ),
  );
}

This time it indeed finds the template node--docbook.tpl.php inside the module. Themes can also override the template if they define node--docbook.tpl.php. But I have some problems.
First, I call nowhere the function theme('docbook', $variables), so I don't see where I can assign the variables. Another option can be to assign them on the preprocess function like this:
function template_preprocess_node__docbook(&$variables) {
  $variables['test'] = 'ABC';
}

But this doesn't work either, and in fact, it seems that the function template_preprocess_node__docbook() is not called at all, although it has been listed on 'preprocess functions' as well (at the definition of hook_theme()).
So, I am stuck. Although I have been working with Drupal7 for two years, theme and template processing still seems to me like a huge maze and I am not able to find my way around. Can somebody help me?
Answer: This is the way that I solved this problem:
/**
 * Implements hook_theme().
 */
function docbook_theme($existing, $type, $theme, $path) {
  return array (
    'node__docbook' => array(
      'template' => 'node--docbook',
    ),
    'node__docbook_section' => array(
      'template' => 'node--docbook-section' ,
    ),
    'field__field_dbw_author' => array(
    ),
  );
}

/**
 * Implements hook_preprocess_HOOK().
 */
function docbook_preprocess_node(&$variables) {
  //krumo($variables);  //debug

  if ($variables['type'] == 'docbook') {
    $variables['variable1'] = 'hello1';
  }

  if ($variables['type'] == 'docbook_section') {
    $variables['variable2'] = 'hello2';
  }
}

/**
 * Implementing theme function theme_HOOK().
 */
function theme_field__field_dbw_author($variables) {
  //krumo($variables);  //debug

  $output = '';

  . . . . . . . . . . . . . . .

  return $output;
}

See more details on these commits:

https://github.com/dashohoxha/DocBookWiki/commit/0e15266fdfa9000bd32d2ddabce036b21fa55930
https://github.com/dashohoxha/DocBookWiki/commit/0fee64d261f66878166c215559234e01e185e6f1
https://github.com/dashohoxha/DocBookWiki/commit/0fb4ac1ca7da38067c647f362c22d167c62f5ae6
https://github.com/dashohoxha/DocBookWiki/commit/db15d8af013bfc91143029c84e7cd0134400af85
https://github.com/dashohoxha/DocBookWiki/commit/c9250ba89094fc2c8fa83945ffbee0be25d42d84

I would expect these solutions to work as well:
function docbook_preprocess(&$variables, $hook) {
  if ($hook == 'node__docbook') {
    $variables['my_new_variable'] = 'hello';
  }
}

function docbook_preprocess_node__docbook(&$variables) {
  $variables['my_new_variable'] = 'hello';
}

function template_preprocess_node__docbook(&$variables) {
  $variables['my_new_variable'] = 'hello';
}

But somehow they don't work. Either my understanding and expectations are wrong, or there is something wrong on the implementation of Drupal.


How to Recursively Delete wildcard files in TFS Build?

Question: I want to recursively delete files that match a certain pattern as part of my post-build cleanup routines in TFS Build. I've tried this...
<Delete Files="T:\DeploymentDir\**\A*" />

No errors in the build, but it doesn't work.
Answer: Modify your TFSBuild.proj file and add the following lines at the very end (just before closing ):
<Target Name="AfterDropBuild">
<ItemGroup>
   <FilesToDelete Include="$(DropLocation)\$(BuildNumber)\**\temp*.*" />
</ItemGroup>

<Delete Files="@(FilesToDelete)" TreatErrorsAsWarnings="true"/>
</Target>

Answer: I don't think the Delete task will automatically expand the wildcard. You'll need to specify an itemgroup first, then pass that into the Delete task:
<ItemGroup>
  <FilesToDelete Include="T:\DeploymentDir\**\A*"/>
</ItemGroup>

<Delete Files="@(FilesToDelete)"/>

With MSBuild 3.5 onwards you can include the ItemGroup in the same target as the Delete task.


MATLAB optimization of the function

Question: I want to optimize this function:
function Y_res = GetY( Y, P )
    cnt = length(P);
    denom = 0;
    for i = 1:cnt
        Y(i) = rand;
        denom = denom + P(i) / (1 - Y(i));
    end
    Y_res = 1 - 1 / denom;
    Y
    Y_res
end

This function receives Y and P. P is a constant array. I need to optimize Y array values. And I trying to do this:
Y = [0.3 0.2 0.1];     % need to be optimized
P = [0.65 0.2 0.15];   % constant array

fhnd_GetY = @(x) GetY(Y, P);

options = optimset('TolX', 1e-3);
optimal_x = fminbnd(fhnd_GetY, 0.2, 0.4, options);

But the result of optimal_x variable does not equals to Y_res, which you can see on the screen during iterations of GetY function. Why? I need to optimze Y_res between 0.2 and 0.4 for example. So as a result I need to receive Y_res between 0.2 and 0.4 (for example) and Y array with values by means of which I can receive Y_res.
Comment: Not entirely sure what you mean by "optimize Y array values". And the title reads - `optimization of the function`.
Comment: Did you realise that in the function `GetY(Y,P)`, you actually overwrite the value of `Y` with a random number?
Comment: So which function will generate Y values without generating random values?
Comment: Divakar, how I should call this subject?
Comment: I am not exactly sure about the terminologies used here - "optimize Y array", "constant array", "subject". Are you sure you are working with MATLAB?
Comment: @Gooman So, could you explain in a bit more detailed way on those three terms that you have used?
Comment: I need to receive Y_res in particular range, for example [0.2, 0.4]. In order to solve this problem I need to calculate (generate or optimize) Y array values. As you can see, function GetY calculates Y_res using Y and P arrays.
Comment: @Gooman So did the edits make solve it for you?
Answer: Assuming that you only intend to optimize the function GetY and given the fact that you are creating Y inside it and as such don't need to externally input Y into it, see if this modified function is optimized enough for you -
function [Y_res,Y] = GetY( P )

found = false;
while ~found
    Y = rand(size(P));
    Y_res = 1-1./sum(P./(1-Y));

    if Y_res>0.2 & Y_res<0.4
        found = true;
    end
end

return;

Please note that if you don't need Y as an output, you can use Yres = GetY([0.65 0.2 0.15]) instead, but most probably you would need that (my guess though).
Few sample runs -
>> [Yres,Y] = GetY([0.65 0.2 0.15])
Yres =
    0.3711
Y =
    0.4243    0.2703    0.1971
>> [Yres,Y] = GetY([0.65 0.2 0.15])
Yres =
    0.2723
Y =
    0.1897    0.4950    0.1476
>> [Yres,Y] = GetY([0.65 0.2 0.15])
Yres =
    0.3437
Y =
    0.3624    0.0495    0.4896

MATLAB optimization of the function


Criar lista com a soma dos números consecutivos iguais

Question: Essa é a minha estrutura, mas o if, elif e até o else (embora não estejam no código), não estão funcionando. O código está imprimindo várias linhas como se fossem if's separados e a função tem que somar números consecutivos iguais.
Exemplo: Se for inserido [1,2,2,2,3,4,4], o programa tem que retornar [1,6,3,8].
lista  = []
lista1 = []

while len(lista) + 1 < 8:
 lista.append(int(input("Digite o valor: ")))

print(lista)

for i in range(1, len(lista)):

    if lista[i - 1] == lista[i] and lista[i] == lista[i + 1]:

        lista1.append(lista[i - 1] + lista[i] + lista[i + 1])

    elif lista[i - 1] == lista[i]:

        lista1.append(lista[i - 1] + lista[i])

    elif lista[i - 1] != lista[i]:

        lista1.append(lista[i])
        print(lista[0], lista1)

print(lista1)

Answer: lista = [1,2,2,2,3,4,4]

def func(lista):
    resultado = []
    soma = lista[0]
    for i in range(1, len(lista)):
        if lista[i] == lista[i-1]:
            soma += lista[i]
            if i == len(lista)-1:
                resultado += [soma]
        else:
            resultado += [soma]
            soma = lista[i]
    return resultado

func(lista)

Answer: Um erro está no primeiro if. Como você faz o for i in range(1, len(lista)), o que acontece quando i chega em len(lista) - 1?
Por exemplo, para a lista [ 1, 2, 2, 2, 3, 4, 4 ], que tem 7 elementos, os índices válidos são de 0 a 6. Quando i chega em 6, você faz no primeiro if:
if lista[i - 1] == lista[i] and lista[i] == lista[i + 1]:

Quando você faz lista[i + 1], está tentando acessar o índice 7, que não existe na lista, e ocorre um IndexError. E o código está imprimindo várias linhas porque você colocou um print no último elif, então sempre que cair ali vai imprimir algo.
Mas o problema principal é o algoritmo em si. O primeiro if verifica se o elemento é igual ao anterior e ao próximo, e já insere a soma dos 3 na lista de resultados. Mas e se tiver 4 (ou mais) números consecutivos iguais?  Você só deveria inserir na lista de resultados quando o número mudasse (além de atualizar a soma enquanto o número não muda). Uma alternativa é fazer assim:
def somar_consecutivos(lista):
    sum = ant = lista[0]
    res = []
    for i in range(1, len(lista)):
        n = lista[i]
        if n == ant:
            sum += n
        else:
            res.append(sum)
            sum = n
        ant = n
    res.append(sum)
    return res

print(somar_consecutivos([1, 4, 4, 4, 0, 4, 3, 3, 1])) # [1, 12, 0, 4, 6, 1]
print(somar_consecutivos([5, 5, 5, 5, 5, 5, 0, 2, 3, 3])) # [30, 0, 2, 6]
print(somar_consecutivos([1, 2, 2, 2, 3, 4, 4])) # [1, 6, 3, 8]
print(somar_consecutivos([1, 2, 3, 4, 5])) # [1, 2, 3, 4, 5]

Eu começo com o primeiro elemento da lista, e depois, para os demais elementos, eu sempre verifico se ele é igual ao anterior. Se for, eu atualizo a soma, e se não for (ou seja, o número mudou), aí sim eu adiciono a soma acumulada até então na lista de resultados.
Answer: Você pode usar a função groupby() da biblioteca padrão itertools, veja só:
from itertools import groupby

entrada = [1,2,2,2,3,4,4]

saida = [sum(i) for _, i in groupby(entrada)]

print(saida)

Saída:
[1, 6, 3, 8]

Veja funcionando no Repl.it


How well does probability work in the real world?

Question: When I was first introduced to probability at the age of about 13, me and my classmates always used to ridicule the subject in a most immature manner. We used to take a deck of well shuffled cards and 'test' the results of probability. For instance the probability of picking a spade was 25%. That is a 1 in 4 chance. We tested this by picking four cards. We got 3 hearts and a dice. We didn't get the expected 1 spade card neither did we get the expected 2 black cards. Hence we decided the science was a silly one.
Looking back at those days when I'm currently majoring in math sure does make me laugh. Though I know that probability has more to it, I have not dealt with it at a theoretical level and neither do I know how to argue with children such as the ones we were once upon a time. If a child comes and claims that he tested the outcomes expected by probability and every test failed against probability's favour, I do not know how to argue with him. All I have are trust in Mathematics and the economics, sociology and quantum theory to which probability has proved to be an asset. But that is my opinion and not a proper answer.
But I want to answer the child some day....how is probability justified? What is the difference between a 50-50 chance and an indeterminable probability? Well, the 50-50 chance doesn't mean that the outcomes are going to vary alternatively (head, tail, head, tail....); the outcome is more likely (head, head, tail, tail, tail, head, tail....) doesn't my that mean it's indeterminate? If probability claims that the 50-50 chance works only in ideal situations does that mean that in such a hypothetical ideal world, the toss outcome will alternate uniformly?
I'm tempted to tell the child that the answer is that probability deals with idealised situations and that's why the results vary. But I shall be a criminal if the child assumes (because of me) that probability is simply a theoretical study of idealised situations that finds no use in real world situations. I cannot mislead the child and I cannot simply live on opinion and trust. What is the answer to the child's question?
Comment: See https://en.wikipedia.org/wiki/Law_of_large_numbers.
Comment: "Looking back at those days when I'm majoring in math currently sure does make me laugh." Why? Because you know you were wrong, for sure, but do you understand *why* you were wrong back then? If you do, explain this to the child asking.
Comment: @Lovsovs I do not know why I was wrong. Hence the question. There is no actual child other than myself (in the context of probability.)
Comment: That Probability, like any other mathematical and scientific branch, works with "idealized models" is quite sure. How the "models" fit to real world, well that is the QUESTION. Is a paper sheet a rectangle ? is the coin (and the tossing mechanism) "unbiased"? To make the model-reality bridge is somehow the basic task of engineering.
Comment: You might want to read "a Probability Perspective" by
Eric C.R. Hehner (from http://www.cs.toronto.edu/~hehner/best.html). He argues (if I summarize him correctly) that probability = information.
Answer: There's a lot that one could say in response to your question, but I'll just make a few quick remarks.
First, it's not a result of mathematical probability theory that the probability of picking a spade is $1/4$. That's an assumption that one would make in specifying a probability model.
Why would one make such an assumption? Well, that depends on what one takes probability to be and what phenomena one is trying to model. Debates about this still rage across various disciplines including applied math, statistics, philosophy, economics, etc.
To give just one example, if we interpret probability as subjective degree of belief (for more on this, you may be interested in my answer here), one might appeal to a principle of indifference to justify the assumption that the probability of drawing a spade is $1/4$: if one has no information about the distribution of the cards, it's rational to distribute probability uniformly over all the possible outcomes. This principle is highly contentious, however. See Bertrand's paradox.
So your question "How is probability justified?" depends on many things. Moreover, some would argue that standard, mathematical (i.e. measure theoretic) probability theory is not always justified, as your question seems to presuppose. Continuing with our example of subjective probability, many prominent theorists (Savage, Dubins, etc.), following De Finetti, have argued that subjective probabilities need not be countably additive, contra the definition of a measure. Kolmogorov himself, the founder of modern mathematical probability, regarded countable additivity as a mere "expedient", useful for dealing with infinite probability spaces. See this question and my answer to it.


Index Theory: Can a closed curve around a single unstable fixed point have index $0$?

Question: I know that a closed curve containing zero fixed points has index $0$.  Is the converse also always true?
Answer: The converse is not true in general. The index of a curve which encloses multiple fixed points is equal to the sum of the indices of curves which would enclose each fixed point on its own.
For example, if the curve encloses a stable fixed point and a saddle point, it will have $\text{index} = -1 + 1 = 0$, yet will enclose two fixed points.
Comment: Thanks you!  Although I had checked several time, the confirmation was very helpful.
Answer: In index theory, a closed curve around a fixed point is $1$ if the fixed point is a node, spiral, or center and $-1$ if it is a saddle and a curve around multiple fixed points in the sum of the indices.
To see that a saddle is $-1$, consider a vector field $\mathbf{V}(\theta)$.  Then
$$
\Theta(\theta) = \tan^{-1}\frac{\mathbf{V}_2(\theta)}{\mathbf{V}_1(\theta)}
$$
With a saddle, $\mathbf{V} = (x,-y)$ or $\mathbf{V} = (x,y)$ so $\Theta = -\theta$ and $\Theta = 0.5\pi - \theta$, respectively.  Thus, a saddle has index $-1$.
Comment: Thank you!  The additional depth was much appreciated.


Calcular em que dias da semana caem os dias do mês

Question: Criei uma função javascript que monta uma agenda. Preciso que essa agenda monte conforme a quantidade e os dias da semana do determinado mês. Ex(Dia 1 de agosto caiu em uma Terça-Feira). Preciso também que quando eu mudar o mês minha agenda monte conforme o mês selecionado.
Segue o código.
Função que monta minha agenda
$(document).ready(function () {
    var str = '';
    var aux = 1;
    var tr = '';
    var tbl = $('#calendar');

    for (var i = 1; i < 32; i++) {

        if (aux == 1) {
            tr = '
';
        }
        str += tr + '' + i + '	';
        if (aux == 7) {

            str = str + tr;
            aux = 0;
        }
        aux++;
        tr = '';
    }
    if (tr == '') {
        tr = '
';
        str = str + tr
    }
    tbl.append(str);
});

Função que seta o mês atual
 $(document).ready(function () {
    monName = new Array("Janeiro",
                        "Fevereiro",
                        "Março",
                        "Abril",
                        "Maio",
                        "Junho",
                        "Julho",
                        "Agosto",
                        "Setembro",
                        "Outubro",
                        "Novembro",
                        "Dezembro")
    hoje = new Date();
    var preenchemes = $('#mes');
    preenchemes.append(monName[hoje.getMonth()]);

});

Comment: Dá uma olhada aqui: https://jqueryui.com/datepicker/
Answer: Não sei se entendi, mas se você está tendo dificuldades em obter o dia da semana que suas Datas, você pode utilizar o método Date.prototype.getDay() que retorno o valor do dia da semana para a data, sendo:
Valor | Dia da semana
------|---------------
  0   |    Domingo
  1   |    Segunda
  2   |    Terça
  3   |    Quarta
  4   |    Quinta
  5   |    Sexta
  6   |    Sábado

Por exemplo:

var d = new Date();
var n = d.getDay();
document.getElementById("result").innerHTML = n;

Edit
Conforme comentário você precisa de:

Saber quantos dias tem determinado mês - que você pode fazer conforme este post no SOen, assim:

function daysInMonth(month, year) {
  return new Date(year, month + 1 /* para ir a proximo */ , 0 /* para voltar ao ultimo dia do mês anterior*/ ).getDate();
}

var d = new Date();
var result = daysInMonth(d.getMonth(), d.getFullYear());
document.getElementById("result").innerHTML = result;

E que dia cai dia 1° dia de determinado mês, quase na mesma ideia, algo assim:

function firstDayWeekInMonth(month,year) {
   return new Date(year, month, 1).getDay();
}

var d = new Date();
var result = firstDayWeekInMonth(d.getMonth(), d.getFullYear());
document.getElementById("result").innerHTML = result;

Obs: Sempre que estiver manipulando Datas, lembre-se que os meses não base 0 (0-based).
Comment: 0 = Domingo, 1 = Segunda, e assim por diante.
Comment: Então ainda não é isso. Eu tenho no meu html os dias da semana estáticos. O que eu preciso fazer é verificar quantos dias por exemplo tem o mês de agosto e em que dia da semana caiu o dia 1, pra minha agenda ser montada a partir disso.
Comment: @RaphaelGumm, adicionei informação a minha resposta original conforme seu esclarecimento nos comentários a resposta. Verifique se lhe ajuda!
Comment: Perfeito @Fernando, era exatamente isso que eu precisava. Obrigado mesmo.
Answer: para pegar o total de dias do mês, podemos usar um pequeno trick, que é pegar o dia 0 do proximo mês.

var month = document.getElementById("month");
var agenda = document.querySelector("#agenda tbody");
var lblDiaSemana = document.getElementById("lblDiaSemana");
var lblTotalDias = document.getElementById("lblTotalDias");
var tmplAgenda = Handlebars.compile(document.getElementById("tmplAgenda").innerHTML);
var diasSemana = [
  "Domingo",
  "Segunda",
  "Terça",
  "Quarta",
  "Quinta",
  "Sexta",
  "Sábado"
];

month.addEventListener("change", function (event) {
  var ano = parseInt(event.target.value.split("-")[0]);
  var mes = parseInt(event.target.value.split("-")[1]);

  var diaPrimeiro = new Date(ano, mes - 1, 1).getDay();
  var totalDias = new Date(ano, mes, 0).getDate();
  var mes = [];
  var inicio = diaPrimeiro;

  for (var diaMes = 0; diaMes < totalDias;) {
    var semana = [];
    for (var diaSemana = inicio; diaSemana < 7 && diaMes < totalDias; diaSemana++) {
      semana[diaSemana] = diaMes + 1;
      diaMes++;
    }
    mes.push(semana);
    inicio = 0;
  }

  // 00/09/2015 = 31/08/2015 ;D
  lblTotalDias.innerHTML = totalDias;
  lblDiaSemana.innerHTML = diasSemana[diaPrimeiro];
  agenda.innerHTML = tmplAgenda(mes);
});

  <input id="month" type="month" />

  Dia da Semana:

  Total de Dias:

        Domingo
        Segunda
        Terça
        Quarta
        Quinta
        Sexta
        Sábado

Answer: Como pegar a quantidade de dias do mês:
function daysInMonth(month,year) {
    return new Date(year, month, 0).getDate();
}

//Pegando a quantidade de dias do mês de fevereiro de 2015
alert(daysInMonth(2,2015)); // 28

Como pegar o dia da semana:
function getDayOfWeek(month, year){
    return new Date(year, (month-1), 1).getDay();
}

alert(getDayOfWeek(2,2015)); // 5 que é Sexta-Feira

Setando os valores na mesma função:
function getMonthInfos(month, year){
    var monthDays = daysInMonth(month,year);
    var weekDay = getDayOfWeek(month, year);
}


Animate scatter plot

Question: I'm building a Python tool for visualizing data structures in 3D. The code below is the full program, it's even set up to run a default test model with some random data; you just need numpy and matplotlib. Basically, you declare a Node, connect it to other Nodes, and it makes pretty 3D networks. I'd like to be able to call switchNode() and have it flip the color of a node between black and white. With the way it works right now, every time a Node is instantiated, the plot is added to with another data point. I'm not familiar enough with matplotlib's animation tools to know the best way of doing this (my attempt at following the example from another post is commented out on line 83, and hoped someone could offer me some tips. Thanks!!
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import matplotlib.animation as anim

# user-defined variables
debug = False
axisOn = False
labelsOn = True
maxNodes = 20
edgeColor = 'b'
dottedLine = ':'
darkGrey = '#191919'
lightGrey = '#a3a3a3'
plotBackgroundColor = lightGrey
fontColor = darkGrey
gridColor = 'k'
numFrames = 200

# global variables
fig = None
hTable = []
ax = None
numNodes = 0

# initialize plot
def initPlot():
    global ax, fontColor, fig
    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d', axisbg=plotBackgroundColor)
    if axisOn == False:
        ax.set_axis_off()
    else:
        ax.set_axis_on()
        fontColor = darkGrey

# gives n random float values between vmin and vmax
def randrange(n, vmin, vmax):
    return (vmax - vmin) * np.random.rand(n) + vmin

# builds an empty node with a given value, helper method for makeNode
def makeNodeS(value):
    global hTable, numNodes
    n = Node(value)
    hTable.append(n)
    numNodes = len(hTable)
    return n

# builds a node with given parameters
def makeNode(value, location, color, marker):
    n = makeNodeS(value)
    n.setLoc(location)
    n.setStyle(color, marker)
    if debug:
        print("Building node {} at {} with color = {}, marker = {}, and associations = {}.".format(value, location, color, marker, n.assocs))
    return n

# aggregate nodes in hTable and plot them in 3D
def plotNodes():
    global hTable
    if debug:
        print("Plotting Graph...")
    for elem in hTable:
        if debug:
            print(" Plotting node {}...".format(elem.value))
        global fig, numFrames
        scat = ax.scatter(elem.location[0], elem.location[1], elem.location[2], c=elem.color, marker=elem.marker)

        for c in elem.assocs:
            if (getNode(c).value != elem.value):
                if elem.count in getNode(c).assocs:   # if the two nodes are associated to each other, draw solid line
                    ax.plot([elem.location[0], getNode(c).location[0]], [elem.location[1], getNode(c).location[1]], [elem.location[2], getNode(c).location[2]], edgeColor)
                    if debug:
                        print("  Plotting double edge between {} and {}...".format(elem.value, getNode(c).value))
                else:
                    ax.plot([elem.location[0], getNode(c).location[0]], [elem.location[1], getNode(c).location[1]], [elem.location[2], getNode(c).location[2]], edgeColor + dottedLine)
                    if debug:
                        print("  Plotting single edge from {} to {}...".format(elem.value, getNode(c).value))

    #ani = anim.FuncAnimation(fig, update_plot, frames=xrange(numFrames), fargs=(['b', 'w'], scat))

# build single connection from node A to node B
def sConnect(nodeA, nodeB):
    nodeA.addAssoc(nodeB)
    if debug:
        print(" Drawing single connection from node {} to node {}...".format(nodeA.value, nodeB.value))

# build double connection from node A to node B, and from node B to node A
def dConnect(nodeA, nodeB):
    if debug:
        print("\nDouble node connection steps:")
    sConnect(nodeA, nodeB)
    sConnect(nodeB, nodeA)

# update scatter with new color data
def update_plot(i, data, scat):
    scat.set_array(data[i])
    return scat

# returns the node with given count
def getNode(count):
    global hTable
    n = hTable[count-1]
    return n

# set up axis info
def defineAxis():
    ax.set_xlabel('X Label')
    ax.xaxis.label.set_color(lightGrey)
    ax.tick_params(axis='x', colors=lightGrey)
    ax.set_ylabel('Y Label')
    ax.yaxis.label.set_color(lightGrey)
    ax.tick_params(axis='y', colors=lightGrey)
    ax.set_zlabel('Z Label')
    ax.zaxis.label.set_color(lightGrey)
    ax.tick_params(axis='z', colors=lightGrey)

# randomly populate nodes and connect them
def test():
    for i in range (0, maxNodes):
        rand = np.random.rand(2)
        if (0 <= rand[0] <= 0.25):
            q = makeNode(i, np.random.rand(3), 'r', '^')
        elif (0.25 < rand[0] <= 0.5):
            q = makeNode(i, np.random.rand(3), 'b', 'o')
        elif (0.5 < rand[0] <= 0.75):
            q = makeNode(i, np.random.rand(3), 'g', 'v')
        elif (0.75 < rand[0]):
            q = makeNode(i, np.random.rand(3), 'w', 'o')

        if (0 < i < maxNodes-1):
            if (rand[1] <= 0.2):
                dConnect(q, getNode(q.count-1))
            elif (rand[1] < 0.5):
                sConnect(q, getNode(q.count-1))

# randomly populate binary nodes and connect them
def test2():
    for i in range (0, maxNodes):
        rand = np.random.rand(2)
        if (0 <= rand[0] <= 0.80):
            q = makeNode(i, np.random.rand(3), 'k', 'o')
        else:
            q = makeNode(i, np.random.rand(3), 'w', 'o')
        if (i > 0):
            if (rand[1] <= 0.2):
                dConnect(q, getNode(q.count-1))
            elif (rand[1] > 0.2):
                sConnect(q, getNode(q.count-1))

# switches a binary node between black and white
def switchNode(count):
    q = getNode(count)
    if (q.color == 'b'):
        q.color = 'w'
    else:
        q.color = 'b'

# main program
def main():
    ## MAIN PROGRAM

    initPlot()

    test2()

    plotNodes()

    defineAxis()

    plt.show()

# class structure for Node class
class Node(str):
    value = None
    location = None
    assocs = None
    count = 0
    color = None
    marker = None

    # initiate node
    def __init__(self, val):
        self.value = val
        global numNodes
        numNodes += 1
        self.count = numNodes
        self.assocs = []
        self.color = 'b'
        self.marker = '^'

    # set node location and setup 3D text label
    def setLoc(self, coords):
        self.location = coords
        global labelsOn
        if labelsOn:
            ax.text(self.location[0], self.location[1], self.location[2], self.value, color=fontColor)

    # define node style
    def setStyle(self, color, marker):
        self.color = color
        self.marker = marker

    # define new association
    def addAssoc(self, newAssociation):
        self.assocs.append(newAssociation.count)
        if debug:
            print("  Informing node association:   Node {} ->  Node {}".format(self.value, newAssociation.value))

main()

Answer: Scatter returns a collection and you can change the colors of the points in a collection with set_facecolor. Here's an example you can adapt for your code:
plt.figure()
n = 3
# Plot 3 white points.
c = [(1,1,1), (1,1,1), (1,1,1)]
p = plt.scatter(np.random.rand(n), np.random.rand(n), c = c, s = 100)
# Change the color of the second point to black.
c[1] = (0,0,0)
p.set_facecolor(c)
plt.show()

Animate scatter plot


Verify 64 bit binary on windows

Question: How can I verify that a .exe file is built for 64 bit on Windows ? I am used to Linux where I can simply use the 'file' command to see this.
Answer: Take a look into the file using a HEX editor. There's a PE magic signature somewhere after the DOS stub, and the platform ID is close behind (some bytes later). For 64 bit builds, it is 0x8664 or so, which is quite easy to spot.
Comment: Thanks, for me it say 64 86. There are some description of the values at this page http://www.vowles-home.demon.co.uk/utils/windows_file_exe.htm and also links to windows versions of the file command.

Verify 64 bit binary on windows


Update Table A from loop data on table B

Question: I want to update table qcard with data every record from q_id table
q_id table field and have 5 record
---------------
q_id  groupcode
----  ---------
1     A01
2     A02
3     A03
4     A05
5     A06

qcard table now have data in field qcard 10001-2000
field loop q_id groupcode not data
qcard    loop  q_id    groupcode
-----    ----  ----    ---------
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010

I need to update qcard table with all record from q_id table for each loop (loop I set from 01,02,03,....to 99) if finish each loop have all record from q_id table
if works qcard table this data
-------------------------------
qcard   loop  q_id    groupcode
 -----   ----  ----    ---------
 10001   01   1      A01
 10002   01   2      A02
 10003   01   3      A03
 10004   01   4      A04
 10005   01   5      A05
 10006   02   1      A01
 10007   02   2      A02
 10008   02   3      A03
 10009   02   4      A04
 10010   02   5      A05
 ...... untill
 1xxxx   99    1     A01
 1xxxx   99    2     A02
 1xxxx   99    3     A03
 1xxxx   99    4     A04
 1xxxx   99    5     A05

Comment: You can use `ctrl+k` to format to code
Comment: Please check this link to know more on how to improve your questions going forward.https://spaghettidba.com/2015/04/24/how-to-post-a-t-sql-question-on-a-public-forum/
Answer: Try this Answer,
CREATE TABLE #Numbers(N INT)

INSERT INTO #NUMBERS(N)
SELECT TOP 495 ROW_NUMBER() OVER(ORDER BY T1.NUMBER) AS N
FROM   MASTER..spt_values T1
       CROSS JOIN MASTER..spt_values t2

SELECT N,CASE WHEN LEN(CAST((N+4)/5 as VARCHAR))<2 THEN '0'+CAST((N+4)/5 as VARCHAR) ELSE CAST((N+4)/5 as VARCHAR) END[Loop]
    ,CASE WHEN N%10 in(1,6) THEN 1 WHEN N%10 in(2,7) THEN 2 WHEN N%10 in(3,8) THEN 3 WHEN N%10 in(4,9) THEN 4 WHEN N%10 in(5,0) THEN 5 END q_id
from #Numbers

UPDATE A SET A.Loop=B.Loop, AND A.q_id=B.q_id
FROM qcard A,#Numbers B
WHERE (A.qcard%10000)=B.N

UPDATE B
SET B.groupcode=A.groupcode
FROM q_id A,qcard B
WHERE A.q_id=B.q_id

DROP TABLE #Numbers

Comment: sorry...in qcard table now have qcard field only running 10001,10002, 10003,......>>> 20000 .  I want to update field loop,q_id,groupcode on table qcard with all record from q_id table . I set loop is 01,02,03,.... >> 99 on each loop have all record from q_id ... 1 loop have 5 reccord
Comment: Are you try this? Is it helpful or not?


Hasmap is not being displayed on selectOneMenu

Question: I've been strugling with selectOneMenu dinamically populated by a HashMap without success for a day now, and can´t find what´s going on.
Followed the steps on
How to populate options of h:selectOneMenu from database?
but still no luck
Here´s my bean:
private Paciente selectedPaciente;
private Map<String, String> itensPacientes;

@PostConstruct
    public void init() {
        itensPacientes = new LinkedHashMap<String, String>();
        itensPacientes.put("1","teste1");
        itensPacientes.put("2","teste1");
        itensPacientes.put("3","teste1");
}

public Map<String, String> getItensPacientes() {
        return itensPacientes;
}

public Paciente getSelectedPaciente(){
        return selectedPaciente;
}

public void setSelectedPaciente(Paciente selectedPaciente){
        this.selectedPaciente = selectedPaciente;
}

and here's the jsf portion
    <h:selectOneMenu  value="#{beanAgenda.selectedPaciente}" required="true">
        <f:selectItem itemValue="#{null}" itemLabel="--select--" />
        <f:selectItems value="#{beanAgenda.itensPacientes}"
           itemValue="#{entry.key}" itemLabel="#{entry.value}"/>
    </h:selectOneMenu>

But when I run the code, I can only see the "--select--" option on the combobx.
Is there something I'm overlooking?
Thanks in advance
Answer: Try this:
<f:selectItems value="#{beanAgenda.itensPacientes.entrySet()}" var="entry"
       itemValue="#{entry.key}" itemLabel="#{entry.value}"/>

Answer and explanation from this post
Comment: Yeah I tried that but still not working
Comment: Found the problem. It was the beanName. I was using beanAgenda instead of agendaBean,


Prove the sequence of functions

Question: How can I prove the sequence of functions $x(1-x), x^2(1-x), ...$ converges uniformly on $[0,1]$?
I know it converges to $0$ and I know if I differentiate it attains a maximum at $x =\frac{n}{1+n}$ but I can't use that because I need to prove this by definition.
Comment: What do you mea "prove by definition". You want to show $\|f_n\|_{\infty} \to 0$, so is quite reasonable to first find out where $f_n$ attains its maximum. In fact, that gives a rather clean proof!
Comment: I think that is a very good approach, personally. Once you complete the proof, I recommend that you drop it in as an answer so that others can give you some reputation :)
Comment: @PrahladVaidyanathan So its okay if I take the derivative here? Because in my book it doesn't show examples of taking derivatives so I was hesitant to use it here. It shows it in the next chapter but not in this one. Is there another way of finding the maximum without using calculus techniques like differentiability ?
Comment: @PrahladVaidyanathan haha its my third post someone downvoted, idk why though. But I will do as you say. Thanks for the help.
Comment: @PrahladVaidyanathan Is the answer I given correct?
Answer: What we need to prove is that, given $\epsilon > 0$, there exists an $N$ such that for every $n > N$ and for every $x \in[0, 1]$, we have $|x^n(1 - x)-0| < \epsilon.$
$x^n$ and $(1-x)$ are both continuous functions and $x^n(1 - x)$ has a maximum on $[0, 1]$ at $x=\frac{n}{1+n}$ since $\frac{d}{dx}[x^n(1-x)] = -x^n +nx^{n-1}-nx^n = -x-nx+n$ thus $x=\frac{n}{1+n}$.
Then $|x^n(1-x)|<(\frac{n}{n+1})^n(\frac{1}{n+1})<\frac{1}{n+1}<\epsilon.$ Choose $N = \frac{1-\epsilon}{\epsilon}$ therefore for $n>N$ we have $|x^n(1-x)|<\epsilon.$
Comment: Yes, but you need to explain why $$\left ( \frac{n}{n+1}\right )^n < 1$$
Comment: @PrahladVaidyanathan Is this correct? since $x\in [0,1]$ we have either $x^n$ and $(1-x)$ is less than $1$ or at most $1$ and since the maximum is attained at $x = \frac{n}{n+1}$ we have $(\frac{n}{n+1})^n<1$?
Comment: No No. The variable $x$ has nothing to do with this. You need to know something about $$\lim_{n\to \infty} \left( \frac{n}{n+1} \right)^n$$
Comment: @PrahladVaidyanathan Ohh. We have $\lim_{n\to \infty} \left( \frac{n}{n+1} \right)^n = \lim (1+1/n)^n$ as $n\to \infty$ thus $<1$. Is that correct?
Comment: Well, You need that $$\lim_{n\to \infty} \left(1+\frac{1}{n}\right)^n = e > 1$$

Prove the sequence of functions


Como ler um arquivo JSON de forma dinâmica? (ANGULAR 2)

Question: Por exemplo ao iníciar quero que meu programa carregue todas as mensagens armazenadas anteriormente num arquivo JSON (mensagem.json)
ngOnInit() {
this.emissor = 'Victor';
this._http.get<PreparacaoDeMensagem[]>("../assets/db/mensagem.json")
  .subscribe(mensagem => {
    this.mensagem = mensagem
    //console.log('o valor é ', this.mensagem);
    this.adicionarMensagem(this.mensagem);
  })
}

Answer: Use o for, desta forma você garante que todos os itens do seu arquivo serão lidos:
for (let i = 0; i < mensagem.length; i++) {
    this.adicionarMensagem(this.mensagem[i]);
}

o .length será o que vai fazer o for pegar todo o tamanho do seu arquivo e ler até o final.
Answer: Se quiser algo diferente poderia utilizar o método do array .forEach
Ficaria algo assim
this.mensagem = mensagem
this.mensagem.forEach(men => {
  this.adicionarMensagem(men);
});

Esse método vai percorrer todo o array e executar o método para cada elemento do array.