Why does mdadm write unusably slow when mounted synchronously?

Question: I have a 6 disk raid6 mdadm array I'd like to benchmark writes to:
root@ubuntu:~# cat /proc/mdstat
Personalities : [raid6] [raid5] [raid4]
md0 : active raid6 sda[0] sdf[5] sde[4] sdd[3] sdc[2] sdb[1]
      1953545984 blocks level 6, 64k chunk, algorithm 2 [6/6] [UUUUUU]

Benchmarks can be inaccurate because of cache - for example, notice the write speed here is higher than it should be:
root@ubuntu:/mnt/raid6# dd if=/dev/zero of=delme bs=1M count=100
100+0 records in
100+0 records out
104857600 bytes (105 MB) copied, 0.276026 s, 380 MB/s

Now we can disable each disk cache pretty easily:
root@ubuntu:~# hdparm -W0 /dev/sd*

/dev/sda:
 setting drive write-caching to 0 (off)
 write-caching =  0 (off)

/dev/sdb:
 setting drive write-caching to 0 (off)
 write-caching =  0 (off)

/dev/sdc:
 setting drive write-caching to 0 (off)
 write-caching =  0 (off)

/dev/sdd:
 setting drive write-caching to 0 (off)
 write-caching =  0 (off)

/dev/sde:
 setting drive write-caching to 0 (off)
 write-caching =  0 (off)

/dev/sdf:
 setting drive write-caching to 0 (off)
 write-caching =  0 (off)

But there is still Linux caching:
root@ubuntu:/mnt/raid6# dd if=/dev/zero of=delme bs=1M count=10
10+0 records in
10+0 records out
10485760 bytes (10 MB) copied, 0.00566339 s, 1.9 GB/s

To disable Linux caching, we can mount the filesystem synchronously:
mount -o remount,sync /mnt/raid6

But after this writes become way slower than they should be:
root@ubuntu:/mnt/raid6# dd if=/dev/zero of=delme bs=1M count=10
10+0 records in
10+0 records out
10485760 bytes (10 MB) copied, 23.3311 s, 449 kB/s

It's as if mdadm requires async mounts in order to function. What's going on here?
Answer: Quote by questioner:

But there is still Linux caching:
root@ubuntu:/mnt/raid6# dd if=/dev/zero of=delme bs=1M count=10
10+0 records in
10+0 records out
10485760 bytes (10 MB) copied, 0.00566339 s, 1.9 GB/s

To disable Linux caching, we can mount the filesystem synchronously:
mount -o remount,sync /mnt/raid6

That's not quite right... sync doesn't simply disable caching like you want in a benchmark. It makes every write result in a "sync" command, which means flushing cache all the way to the disk.
Here is a server over here, to explain better:
$ dd if=/dev/zero of=testfile bs=1M count=500
500+0 records in
500+0 records out
524288000 bytes (524 MB) copied, 0.183744 s, 2.9 GB/s

$ dd if=/dev/zero of=testfile bs=1M count=500 conv=fdatasync
500+0 records in
500+0 records out
524288000 bytes (524 MB) copied, 5.22062 s, 100 MB/s

conv=fdatasync simply means flush after the write, and tell you the time including that flush. Alternatively, you can do:
$ time ( dd if=/dev/zero of=testfile bs=1M count=500 ; sync )
500+0 records in
500+0 records out
524288000 bytes (524 MB) copied, 0.202687 s, 2.6 GB/s

real    0m2.950s
user    0m0.007s
sys     0m0.339s

And then calculate MB/s from the 2.95s real time rather than the above 0.2s. But that is uglier, and more work, since the stats printed by dd are not including the sync.
If you used "sync" you would flush every write... maybe that means every block, which would run very slow. "sync" should only be used on very strict systems, eg. databases where the loss of one single transaction due to a disk failure is unacceptable (eg. if I transfer a billion bucks from my bank account to yours, and the system crashes, and suddenly you have the money but so do I).
Here is another explanation with additional options, one I read about long ago.
http://romanrm.ru/en/dd-benchmark
And one more note: Your benchmark you are doing this way is totally valid in my opinion, although not valid in many others' opinions. But it is not a real-life test. It is a single threaded sequential write. If your real life use case is like that, eg. sending some big files over the network, then it may be a good benchmark. If your use case is different, eg. an ftp server with 500 people uploading small files at the same time, then it is not very good.
And also, you should use a randomly generated file on RAM for best results. It should be random data because some file systems are too smart when you feed them zeros. eg. on Linux using the ram file system tmpfs which is mounted on /dev/. And it should be a RAM fs instead of using /dev/urandom directly because /dev/random is really slow, and /dev/urandom is faster (eg. 75MB/s) but still slower than hdd.
dd if=/dev/urandom of=/dev/shm/randfile bs=1M count=500
dd if=/dev/shm/randfile bs=1M count=500 conv=fdatasync

Comment: @MrCalvin if your destination device is faster than /dev/random, it will show you a much slower result. So reading from RAM prevents that. (and really that should be urandom ... random is really slow...I'll edit that)
Comment: Why not get test-data directly from `/dev/random` and write it directly to the mdadm disk, why first make a file, something like `dd if=/dev/random of=testfile bs=1M count=500 conv=fdatasync`?
Comment: Whau `/dev/random` is really slow, I get around 243MB7s. I just expected it to be really fast, it must be a very thorough randomizer.
`/dev/zero` give me 22GB/s, just for public notice ;-)
Answer: Performance is dramatically worse because synchronous writing forces parity computation to hammer the disks.
In general, computing and writing parity is a relatively slow process, especially with RAID 6--in your case, not only does md have to fragment the data into four chunks, it then computes two chunks of parity for each stripe. In order to improve performance, RAID implementations (including md) will cache recently-used stripes in memory in order to compare the data to be written with the existing data and quickly recompute parity on write. If new data is written to a cached stripe, it can compare, fragment, and recompute parity without ever touching the disk, then flush it later. You've created a situation where md always misses the cache, in which case it has to read the stripe from disk, compare the data, fragment the new data, recompute parity, then flush the new stripe directly to disk. What would require zero reads and writes from/to disk on a cache hit becomes six reads and six writes for every stripe written.
Granted, the difference in performance you've observed is enormous (1.9GB/s versus 449KB/s), but I think it's all accounted for in how much work md is doing to maintain the integrity of the data.
This performance hit may be compounded by how you have the disks arranged... if you have them all on one controller, that much extra reading and writing will bring performance to a standstill.
Comment: Thanks for your answer but it doesn't quite make sense to me. Maybe I'm missing something?

First, the raid chunk size is 64k, and the dd block size is 1M, which will exactly contain 16 chunks per block. Second, this write is a sequential write. This means that pretty much no stripe should need to be rewritten, correct? So I don't see why this should take so many reads and writes.
Comment: dd's block size is irrelevant here; you're writing to a file system instead of a raw device (the write is forced to the FS block size). The parity algorithm is designed in such a way that bits in the stripe correspond to bits in parity, thus making parity computation much faster--instead of doing a full parity computation on write, the algorithm can do a bitwise scan of the data, flipping bits on the disk where it differs from the new data and bits in parity where necessary. A cache makes this much faster, but you've disabled the cache, so it has to read each stripe from disk every time.
Comment: I thought that stripes were created and parity was calculated before any of the corresponding data is written, but you're saying that parity is only calculated before the parity block is written (eg after some data has already been written)? If that's what's happening that would explain some serious slowdown. I don't see why md would have been written that way, but oh well.

How do you know so much about swallows^H^H^H^H^H^H^H^Hraid parity computation? Great point on dd blocksize.
Answer: Can you tell us how your 6 disks are made up?
Sounds to me as if they were part of SAN/DAS whatever targets - that propably consist of the same physical disks (so if all 6 reside on the same disk this will degrade performance compared to a single disk by 6).
Have a look at this link to anwerleaks.com.
So how did you set up your bitmap?
Comment: They are actually 6 distinct local SATA disks.


How to efficiently calculate gradients of all outputs with respect to parameters?

Question: I have a relatively simple requirement but surprisingly this does not seem to be straightforward to implement in pytorch. Given a neural network with $P$ parameters that outputs a vector of length $Y$ and a batch of $B$ data inputs, I would like to calculate the gradients of the outputs with respect to the model's parameters.
In other words, I would like the following function:
def calculate_gradients(model, X):
    """
    Args:
        nn module with P parameters in total that outputs a tensor of size (B, Y).
        torch tensor of shape (B, .).

    Returns:
        torch tensor of shape (B, Y, P)
    """
    # function logic here

Unfortunately, I don't currently see an obvious way of calculating this efficiently, especially without aggregating over the data or target dimensions. A minimal working example below involves looping over input and target dimensions, but surely there is a more efficient way?
import torch
from torchvision import datasets, transforms
import torch.nn as nn

###### SETUP ######

class MLP(nn.Module):
    def __init__(self, input_size, hidden_size, output_size):
        super(MLP, self).__init__()
        self.fc1 = nn.Linear(input_size, hidden_size)
        self.relu = nn.ReLU()
        self.fc2 = nn.Linear(hidden_size, output_size)

    def forward(self, x):
        h = self.fc1(x)
        pred = self.fc2(self.relu(h))
        return pred

train_dataset = datasets.MNIST(root='./data', train=True, download=True,
                            transform=transforms.Compose(
                                [transforms.ToTensor(),
                                    transforms.Normalize((0.5,), (0.5,))
        ]))

train_dataloader = torch.utils.data.DataLoader(train_dataset, batch_size=2, shuffle=False)

X, y = next(iter(train_dataloader))  # take a random batch of data

net = MLP(28*28, 20, 10)  # define a network

###### CALCULATE GRADIENTS ######
def calculate_gradients(model, X):
    # Create a tensor to hold the gradients
    gradients = torch.zeros(X.shape[0], 10, sum(p.numel() for p in model.parameters()))

    # Calculate the gradients for each input and target dimension
    for i in range(X.shape[0]):
        for j in range(10):
            model.zero_grad()
            output = model(X[i])
            # Calculate the gradients
            grads = torch.autograd.grad(output[j], model.parameters())
            # Flatten the gradients and store them
            gradients[i, j, :] = torch.cat([g.view(-1) for g in grads])

    return gradients

grads = calculate_gradients(net, X.view(X.shape[0], -1))

Edit:
I ran some quick benchmarks of Felix Zimmermann's solution which does indeed provide some nice speedups for this toy problem on my machine.
import time

start = time.time()
for _ in range(1000):
    grads = calculate_gradients(net, X.view(X.shape[0], -1))
end = time.time()
print('Loop solution', end - start)

start = time.time()
for _ in range(1000):
    params = {k: v.detach() for k, v in net.named_parameters()}
    buffers = {k: v.detach() for k, v in net.named_buffers()}
    grads2 = torch.vmap(one_sample)(X.flatten(1))
end = time.time()
print('Vmap solution', end - start)

Which outputs
Loop solution 8.408899307250977
Vmap solution 2.355229139328003

Note that the performance gains are likely to be much greater in more realistic settings with larger batches on GPUs.
Comment: Is there a limitation for your to compute `model(X)` straight away?
Comment: try torch.func.vmap
See this example https://pytorch.org/tutorials/intermediate/per_sample_grads.html
Answer: To solve this problem, we need three ideas:

The gradients of the outputs with respect the the parameters is the Jacobian of the network wrt the parameters. https://pytorch.org/functorch/stable/generated/functorch.jacrev.html

We can functionalize a pytorch model, that is transform a model into a function of its parameters https://pytorch.org/functorch/nightly/generated/functorch.functionalize.html

Pytorch can vectorize over many operations using vmap https://pytorch.org/functorch/stable/generated/functorch.vmap.html

This is all part functorch / torch.func.
Putting it all together, this does the same as your code:
# extract the parameters and buffers for a funcional call
params = {k: v.detach() for k, v in net.named_parameters()}
buffers = {k: v.detach() for k, v in net.named_buffers()}

def one_sample(sample):
    # this will calculate the gradients for a single sample
    # we want the gradients for each output wrt to the parameters
    # this is the same as the jacobian of the network wrt the parameters

    # define a function that takes the as input returns the output of the network
    call = lambda x: torch.func.functional_call(net, (x, buffers), sample)

    # calculate the jacobian of the network wrt the parameters
    J = torch.func.jacrev(call)(params)

    # J is a dictionary with keys the names of the parameters and values the gradients
    # we want a tensor
    grads = torch.cat([v.flatten(1) for v in J.values()],-1)
    return grads

# no we can use vmap to calculate the gradients for all samples at once
grads2 = torch.vmap(one_sample)(X.flatten(1))

print(torch.allclose(grads,grads2))

It should run in parallel, you should try it out for bigger models etc, I did not benchmark it.
This is also related, to for example Pytorch: Gradient of output w.r.t parameters (which tbh doesn't have a great answer), and pytorch.org/tutorials/intermediate/per_sample_grads.html which shows some of the functions within torch.func for calculating the per sample gradients.
Comment: Thanks! This was indeed faster. I have added some quick benchmarking in an edit to the original question.
Comment: @SerafFej: Let me know if there is anything missing from this answer for you to accept it and I will try to add.


Open Cover for a Compact Subset

Question: I am doing some extra exercises for an Analysis class, and I found this one. We haven't seen much of what an open cover is, but I want to learn it. So, here it goes, and thank you everyone!
Let compact subset $S \in \mathbb{R} $, with $\mathcal O$ as its open cover. Complete to show that there exists some $\epsilon > 0$ so that for all $a \in S$, there is some $E \in \mathcal  O$ such that $D(a, \epsilon) \subset E$.
a) Clearly state the negation of "There exists some $\epsilon > 0$ so that for all $a$ in $S$, there is some $E \in \mathcal  O$ such that $D(a, \epsilon) \subset E$."
b) Assuming the above negation, explain why is true that: For each $n \in \mathbb{N}$, there is some $v_n \in S$ such that $D(v_n, 1/n)$ is not contained in any member of $\mathcal O$.
c) Since $S$ is compact, there is a subsequence $(v_{n_r})$ of $(v_n)$ that converges to some $v \in S$. Explain why there is some $G \in \mathcal  O$ and some $\epsilon > 0$ such that $D(v, \epsilon ) \subset G$.
d) Explain why there is some $r \in \mathbb{N}$  such that that $1/n_r < \epsilon/2$ and
 $|v_{n_r} - v| < \epsilon/2$.
e) Deduce: $D(v_{n_r} , 1/n_r) \subset D(v, \epsilon ) \subset G$.
f) Explain why we have reached a contradiction.
Comment: For what is worth, the number they are asking you to find is usually called a Lebesgue number for the cover $O$.
Comment: You have been giving a good sketch of proof, haven't you tried anything to follow it, and possibly provide a proof by yourself?
Comment: How far have you been able to get in this proof outline?
Comment: @PedroTamaroff I edited the question and I added what I have done. Any suggestions will be gladly appreciate it.
Comment: @OrchidFibio Great, can you continue with $b,c,d,e$ or state where you're stuck?
Comment: @PedroTamaroff added (b), I am stuck at (c). I will continue (d) and (e), and stuck at (f). Thanks!!!!!
Comment: @OrchidFibio The solution to $b$ is alright too, though you have mysteriously used both $u_n,v_n$ to denote the sequence. A hint for $(c)$: since $O$ covers the space, $v\in F$ for some $F\in O$. Now, $F$ is open and $v\in F$, so?
Comment: (**A comment** One usually uses a stylicized letters for covers or "collection of sets", for example, $\mathcal O$ or $\mathscr O$. Then one would denote an element of the cover, $O\in\mathcal O$, by a usual capitalized letter. One also uses $F$ to denote *closed* sets, from the French, fermé.)
Comment: @PedroTamaroff I am still learning to format, and it is very confusing. Many time i don't know how to write something. I have so many letters on my head spinning around, that i feel dizzy! I did part (d)... What do you think?
Comment: @PedroTamaroff I changed F to G to avoid confusions as you said. Many time different profs use different notation, and it can get horribly confusing. I hope it looks better now. How do you write in Latex that big O for collection of open sets?
Comment: @OrchidFibio You can use `\mathcal` or `\mathscr` followed by letters.
Comment: @PedroTamaroff What do you think of part (d)? Thanks!!
Comment: @OrchidFibio You have the right idea. You only need to write things clearly. See my answer, maybe it helps.
Answer: You have the right idea. I will paraphrase what you wrote, so one gets a complete proof.

CLAIM Let $S\subseteq \bf R$ be compact. Let  $\mathcal O$  be an open cover of $S$. Then there there exists an $\varepsilon >0$ such that for all $x\in S$ there is some $O\in \mathcal O$ such that $D(x,\varepsilon)\subseteq O$.

PROOF Suppose to the contrary. Then for every $\varepsilon'>0$ there is some $x\in S$ such that for no $O\in \mathcal O$ we have $D(x,\varepsilon')\subseteq O$. Now for each $n=1,2,3,\ldots$ pick $\varepsilon_n=\dfrac 1 n$. Then we obtain a sequence $\langle v_1,v_2,v_3,\ldots\rangle $ in $S$ such that for no $O\in\mathcal O$ we have $D(v_n,n^{-1})\subseteq O$. Since $S$ is compact, there is $v\in S$ and a subsequence $\langle v_{n_1},v_{n_2},\ldots \rangle$ with $n_1<n_2<n_3<\cdots$ such that $\lim\limits_{k\to\infty} v_{n_k}=v$. Now, $\mathcal O$ covers $S$; so there exists $O'\in\mathcal O$ such that $v\in O'$. Since $O'$ is open, there exists $\varepsilon >0$ such that $D(v,\varepsilon)\subseteq O'$. Since $v_{n_k}\to v$, there exists $K$ such that for any $k\geqslant K$ we have  $|v-v_{n_k}|<\dfrac \varepsilon 2$. If $n_K^{-1}<\dfrac \varepsilon 2$, we're done, we pick $n_K$ and $v_K$. Else, we can pick $K_1>K$ large enough so that $n_{K_1}^{-1}<\dfrac \varepsilon 2$, and by the above we still have $|v-v_{n_{K_1}}|<\dfrac \varepsilon 2$. In any case, we have found what we wanted with $K=k$ or $=K_1$. Now, pick $x\in D(v_{n_k},n_k^{-1})$. Then $$|v-x|\leqslant |v-v_{n_k}|+|v_{n_k}-x|<\frac\varepsilon 2+\frac\varepsilon 2=\varepsilon$$
that is, $|v-x|<\dfrac \varepsilon 2$. It follows that $D(v_{n_k},n_k^{-1})\subseteq D(v,\varepsilon)\subseteq O'$. But this contradicts the fact that no ball $D(v_n,n^{-1})$ could be contained in an $O\in \mathcal O$. Thus our assumption that no such $\varepsilon$ existed must have been false, and the theorem is proven. $\blacktriangle$
NOTE The above proof applies in more generality to any metric space $(X,d)$ having the Bolzano-Weiertrass property, that is, the property that every infinite subset has an accumulation point in $X$. The proof is conceptually the same, but a point has to be taken care of: if the sequence obtained $\langle v_1,v_2,\ldots\rangle$ is of finite range, that is, the set $\{v_1,v_2,\ldots\}$ is finite, then some element, call it $v$, repeats infinitely often.  Pick $O$ in the cover such that $v\in O$. Since $O$ is open, we obtain $\delta >0$ such that $B(v,\delta)\subseteq O$. If $v=v_{k}$,  pick $k'>k$ such that $k'^{-1}<\delta$ and $v_{k'}=v$. This can be done because by assumption $v$ repeats infinitely often. Then $B(v_{k'},k'^{-1})\subseteq B(v,\delta)\subseteq O$, a contradiction. If not, the set is infinite and we obtain an accumulation point. Then the proof is exactly the same as the above, save we don't talk about subsequences, rather work with the set itself, which has an accumulation point.
As a final comment, the number so obtained is called a Lebesgue number for the cover $\mathcal O$. Let $$L(\mathcal O)=\{\varepsilon >0:\varepsilon \text{ is a Lebesgue number for }\mathcal O\}$$ Then $\varepsilon_L=\sup L(\mathcal O)$ is called the Lebesgue number of $\mathcal O$. Thus, we have proven

PROP Let $(X,d)$ be a metric space with the Bolzano Weiertrass property. Then every open cover $\mathcal O$ of $(X,d)$ has a Lebesgue number.

In fact, with a little more work, one can prove

THM Let $(X,d)$ be a metric space. Then $X$ is compact $\iff$ it has the Bolzano Weiertrass property.
Comment: @OrchidFibio We all have things to straight out! =)
Comment: You are right! I have to straight things out! Let me make sure I understand fully what you did. Thanks!
Comment: The Lebesgue number, my prof calls it delta!
Comment: @OrchidFibio Ah, each author has their preference.

Open Cover for a Compact Subset


Need to fetch the column names(field names) along with the values in raw sql query

Question: views.py
def view(request):
    cursor = connection.cursor()
    with open('D:\Project-Management-Tools\Project-Management-Tools\query.sql','r') as inserts:
        query = inserts.read()
        cursor.execute(query)
        row = cursor.fetchall()
    return Response(row)

SQL query
SELECT PUBLIC."Users".ID,
            EMPLOYEE_NAME,
            BILLABLE_AND_NON_BILLABLE,
            PUBLIC."Job".PROJECT_ID,
            PUBLIC."Timelog".CLIENT_ID,date,PUBLIC."Timelog".HOURS
        FROM PUBLIC."Users"
        JOIN PUBLIC."Job" ON PUBLIC."Users".ID = PUBLIC."Job".USER_ID
        JOIN PUBLIC."Timelog" ON PUBLIC."Timelog".JOB_ID = PUBLIC."Job".ID

I have tried a raw query by inserting a sql file in cursor function. However I am getting the values alone as a response and I need to get the fields name along with the values in the response. Kindly help me to solve this issue.
Answer: One simplest way is to fetch the column names by using this querySELECT column_name FROM INFORMATION_SCHEMA.columns where table_name='accounts'
and then further you can query the values as separate query and create a mapping between two.
Comment: can you please elaborate it more i couldn't able to get it. I have added my sql query above please check and help to get this sorted. Thanks in advance!!


Angle of a triangle in a cube

Question:
Find the angle of a triangle in a cube.

I don't how to start on this problem. The only I have noticed is that it may be a isosceles triangle so the two angle should be the same.
Can somebody give me hints on how to solve it?
Comment: You can use vectors approach for this, all you need is the points coordinates and the dot product.
Comment: Could you elaborate on that?
Answer: Hint : the triangle is equilateral...
Comment: Don't you see that all the sides of the triangle are a diagonal of a side of your cube, so they have the same lenght ?
Comment: If it were so, the angle should be 60°C and not 75°C. But the website with the answers stated that 75°C is the correct one.
Comment: Yeah, I see it. Thank you for clarifying it. But the website had it wrong then.
Comment: Don't always trust what you read :)

Angle of a triangle in a cube


Auto wrap td every 4 columns

Question: I have 8 td in my table and my problem is I would like to wrap the td every 4th column. So in short, I want the 5th td will display in new line. Please help me. Thanks.

            terdg
            yhr6t
            yhr6t
            yhr6t

            hgf
            gdrg
            tyht
            drf

Comment: So close the row after the fourth td. What's the actual problem?
Comment: What do you need? I mean if you can show in some image / mockup.
Answer: If you must retain the same HTML structure you can manage this with floats but  it's likely that you will lose the "tableness" of the cells and you may have to adjust accordingly.

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

::before,
::after {
  box-sizing: inherit;
}

table {}

td {
  float: left;
  width: 25%;
  padding: 1em;
  border: 1px solid grey;
  white-space: nowrap;
}

td:nth-child(4n + 1) {
  clear: both;
}

        cell 1
        cell 2
        cell 3
        cell 4
        cell 5
        cell 6
        cell 7
        cell 8
        cell 9
        cell 10
        cell 11
        cell 12

Answer:

            terdg
            yhr6t
            yhr6t
            yhr6t

            hgf

            gdrg
            tyht
            drf

Auto wrap td every 4 columns


How to debug errors on site running on Magento?

Question: I came to work this morning. The main site is down. The person that work on it is on vacation.
The site is running on Magento. I'm not familiar with Magento at all.
I think I can do something - if I got some suggestions.
I have the log-in for the admin.
But after I logged in the error message is also there as well.
I can't really do much.
Is this an easy fix for Magento newbie like me ? :( I'm being honest.
Is there anything that I can do at this moment to bring this site back up ?
I really appreciate your help.
Exact Error Message
There has been an error processing your request

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'biossusa_Magento.catalog_category_flat_store_1' doesn't exist

Trace:
#0 /home/website/public_html/store/includes/src/Varien_Db_Statement_Pdo_Mysql.php(110): Zend_Db_Statement_Pdo->_execute(Array)
#1 /home/website/public_html/store/includes/src/__default.php(63033): Varien_Db_Statement_Pdo_Mysql->_execute(Array)
#2 /home/website/public_html/store/includes/src/__default.php(52715): Zend_Db_Statement->execute(Array)
#3 /home/website/public_html/store/includes/src/__default.php(53751): Zend_Db_Adapter_Abstract->query('SELECT `catalog...', Array)
#4 /home/website/public_html/store/includes/src/__default.php(54587): Zend_Db_Adapter_Pdo_Abstract->query('SELECT `catalog...', Array)
#5 /home/website/public_html/store/includes/src/__default.php(53061): Varien_Db_Adapter_Pdo_Mysql->query(Object(Varien_Db_Select), Array)
#6 /home/website/public_html/store/includes/src/Mage_Catalog_Model_Resource_Category_Flat.php(1314): Zend_Db_Adapter_Abstract->fetchOne(Object(Varien_Db_Select))
#7 /home/website/public_html/store/includes/src/__default.php(6992): Mage_Catalog_Model_Resource_Category_Flat->checkId('2')
#8 /home/website/public_html/store/includes/src/Mage_Catalog_Helper_Category.php(74): Mage_Catalog_Model_Category->checkId('2')
#9 /home/website/public_html/store/includes/src/Mage_Catalog_Model_Observer.php(255): Mage_Catalog_Helper_Category->getStoreCategories()
#10 /home/website/public_html/store/includes/src/__default.php(21066): Mage_Catalog_Model_Observer->addCatalogToTopmenuItems(Object(Varien_Event_Observer))
#11 /home/website/public_html/store/includes/src/__default.php(21045): Mage_Core_Model_App->_callObserverMethod(Object(Mage_Catalog_Model_Observer), 'addCatalogToTop...', Object(Varien_Event_Observer))
#12 /home/website/public_html/store/app/Mage.php(447): Mage_Core_Model_App->dispatchEvent('page_block_html...', Array)
#13 /home/website/public_html/store/includes/src/Mage_Page_Block_Html_Topmenu.php(62): Mage::dispatchEvent('page_block_html...', Array)
#14 /home/website/public_html/store/app/design/frontend/default/grayscale/template/page/html/topmenu.phtml(48): Mage_Page_Block_Html_Topmenu->getHtml('level-top')
#15 /home/website/public_html/store/includes/src/__default.php(3223): include('/home/website/...')
#16 /home/website/public_html/store/includes/src/__default.php(3254): Mage_Core_Block_Template->fetchView('frontend/defaul...')
#17 /home/website/public_html/store/includes/src/__default.php(3268): Mage_Core_Block_Template->renderView()
#18 /home/website/public_html/store/includes/src/__default.php(2518): Mage_Core_Block_Template->_toHtml()
#19 /home/website/public_html/store/includes/src/__default.php(13181): Mage_Core_Block_Abstract->toHtml()
#20 /home/website/public_html/store/includes/src/__default.php(2518): Mage_Core_Block_Text_List->_toHtml()
#21 /home/website/public_html/store/includes/src/__default.php(2237): Mage_Core_Block_Abstract->toHtml()
#22 /home/website/public_html/store/includes/src/__default.php(2181): Mage_Core_Block_Abstract->_getChildHtml('topMenu', true)
#23 /home/website/public_html/store/app/design/frontend/default/grayscale/template/page/html/header.phtml(62): Mage_Core_Block_Abstract->getChildHtml('topMenu')
#24 /home/website/public_html/store/includes/src/__default.php(3223): include('/home/website/...')
#25 /home/website/public_html/store/includes/src/__default.php(3254): Mage_Core_Block_Template->fetchView('frontend/defaul...')
#26 /home/website/public_html/store/includes/src/__default.php(3268): Mage_Core_Block_Template->renderView()
#27 /home/website/public_html/store/includes/src/__default.php(2518): Mage_Core_Block_Template->_toHtml()
#28 /home/website/public_html/store/includes/src/__default.php(2237): Mage_Core_Block_Abstract->toHtml()
#29 /home/website/public_html/store/includes/src/__default.php(2181): Mage_Core_Block_Abstract->_getChildHtml('header', true)
#30 /home/website/public_html/store/app/design/frontend/default/grayscale/template/page/1column.phtml(55): Mage_Core_Block_Abstract->getChildHtml('header')
#31 /home/website/public_html/store/includes/src/__default.php(3223): include('/home/website/...')
#32 /home/website/public_html/store/includes/src/__default.php(3254): Mage_Core_Block_Template->fetchView('frontend/defaul...')
#33 /home/website/public_html/store/includes/src/__default.php(3268): Mage_Core_Block_Template->renderView()
#34 /home/website/public_html/store/includes/src/__default.php(2518): Mage_Core_Block_Template->_toHtml()
#35 /home/website/public_html/store/includes/src/__default.php(27414): Mage_Core_Block_Abstract->toHtml()
#36 /home/website/public_html/store/includes/src/__default.php(13574): Mage_Core_Model_Layout->getOutput()
#37 /home/website/public_html/store/includes/src/__default.php(10934): Mage_Core_Controller_Varien_Action->renderLayout()
#38 /home/website/public_html/store/includes/src/__default.php(10849): Mage_Cms_Helper_Page->_renderPage(Object(Mage_Cms_IndexController), 'home')
#39 /home/website/public_html/store/app/code/core/Mage/Cms/controllers/IndexController.php(45): Mage_Cms_Helper_Page->renderPage(Object(Mage_Cms_IndexController), 'home')
#40 /home/website/public_html/store/includes/src/__default.php(13603): Mage_Cms_IndexController->indexAction()
#41 /home/website/public_html/store/includes/src/__default.php(17948): Mage_Core_Controller_Varien_Action->dispatch('index')
#42 /home/website/public_html/store/includes/src/__default.php(17505): Mage_Core_Controller_Varien_Router_Standard->match(Object(Mage_Core_Controller_Request_Http))
#43 /home/website/public_html/store/includes/src/__default.php(20082): Mage_Core_Controller_Varien_Front->dispatch()
#44 /home/website/public_html/store/app/Mage.php(683): Mage_Core_Model_App->run(Array)
#45 /home/website/public_html/store/index.php(87): Mage::run('', 'store')
#46 {main}

Comment: Reindex your site - specifically the Category Flat Data index.
Comment: Do you know how to use SSH or run a script in Magento root using FTP?
Comment: Go to /shell , directory and run following command                     php -f indexer.php -- -reindex catalog_category_flat
Comment: @Muk : How do I do that ? I am new to Magento. Do you mind answer it with more details information ?
Comment: Yes. I know how to use SSH. I also know FTP, and I used to run a script before.
Comment: @Muk : Thanks for your efforts. Is there anything else that I need to do after `php -f indexer.php -- -reindex catalog_category_flat`
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/66931/discussion-between-muk-and-iggy).
Answer:
Reindex your site so that catalog flat table is generated :
http://www.magentocommerce.com/knowledge-base/entry/ce-18-indexing  will explain steps

else

switch flat category to off(in case you are not able to reindex catalog flat category)


What does "Normal Distribution is conjugate to Normal" mean?

Question: I kind of understand the meaning of conjugate to something but can't really get the clear picture of the concept. Some video lectures on youtube talk about it but they all seem to just say "Normal Distribution is conjugate to Normal" but for me to understand, it wasn't enough to get it. Hope to hear with least mathematical terms.
Comment: Possible duplicate of [Gaussian is conjugate of Gaussian?](http://stats.stackexchange.com/questions/124623/gaussian-is-conjugate-of-gaussian) see also http://stats.stackexchange.com/questions/204920/do-conjugate-priors-just-lead-to-a-posterior-that-is-a-modification-of-the-param/204942#204942 and http://stats.stackexchange.com/questions/192554/aside-from-the-exponential-family-where-else-can-conjugate-priors-come-from
Comment: In Bayesian Statistics the normal distribution is a conjugate prior for the normal
Comment: The [table of conjugate priors in the Wikipedia conjugate prior article](https://en.wikipedia.org/wiki/Conjugate_prior#Table_of_conjugate_distributions) is quite instructive. The table lists the prior distribution, the likelihood distribution, and the parameterization of the posterior distribution. It may be a bit confusing at first, but working through a few of these examples may really help in understanding conjugate priors and the whole Bayesian approach.
Answer: Saying it in plain English: if you have some Bayesian model to estimate parameter of interest, then you use some prior distribution for it, likelihood to describe the probability of observing your data conditional on the parameter, so to obtain the posterior distribution. If you have a conjugate prior this means that the prior comes from the same family of distributions and there is a closed-form solution for such problem, so the posterior distribution is directly available. This is exactly the case when you use normal prior for mean parameter of normal distribution. Otherwise you would need some kind of numerical optimization or Markov Chain Monte Carlo to estimate the parameter.
Comment: I believe the concept of a conjugate prior is much stronger than merely having a "closed form": the posterior must be in the same finitely parameterized family as the prior.
Comment: @whuber I added such information but as the question asks about basic understanding I don't think that going into details is needed in here.
Comment: Although I still need to understand the relation between bernoulli and beta distribution for conjugate prior, somehow, your explanation helps me get closer to the point.
Comment: I believe that the closure of the family under updating is the essence of the concept of "conjugate prior," not the analytical tractability of the update.  Of course its *utility* derives from the fact that we choose to use conjugate priors that lead to simple calculations.


All the elements of the matrix $A + A^2 + A^3 + A^4 + A^5$ are non zero.

Question: If a graph with $10$ vertices has $5$ distinct eigenvalues, then all the elements of the matrix $$A + A^2 + A^3 + A^4 + A^5$$ are non zero.
We have to verify if the statement is True or False.
Here $A$ is the adjacency matrix of the graph.

I am not getting any clue how to approach the problem. Any hints will be useful.
Comment: Hint: Since it is adjacency matrix, what does each entry of $A+A^2+A^3+A^4+A^5$ counts for? The graph has $10$ vertices, we can have that if some of the entries are zero, if and only if the graph is disconnected. Now your work be: construct a disconnected graph with $5$ distinct eigenvalues, or prove that if the graph is disconnected, the number of distinct eigenvalues will be not $5$?
Comment: What does $A$ have to do with the graph?
Comment: A is the adjacency matrix
Answer: It is false.
Note that for each $u,v$, the $uv$-th entry of $A+A^2+A^3+A^4+A^5$ counts the number of walks in the underlying graph $G$ from $u$ to $v$ with $1,2,3,4$, or $5$ edges. So this is nonzero for each $u,v$ only if [but not necessarily if] the underlying graph $G$ is connected i.e., if every $u$ and $v$ are even reachable from each other in $G$.
In fact however we can construct a graph $G$ on $10$ vertices where both the adjavency matrix $A$ has precisely $5$ distinct eigenvalues, and also that $G$ is disconnected. Let one component of $G$ be a cycle on $4$ vertices, and let each of the remaining $6$ vertices each be in a matching with another vertex [so $3$ additional edges]. Then the distinct eigenvalues of $A$ are $2,0,-2$ [from the $4$-cycle] and $1,-1$ [from the matching w $3$ edges on the $6$ remaining vertices]. Furthermore, the eigenvalue $0$ has multiplicity two, and the eigenvalues $1,-1$ have multiplicity three each.
So as $A$ as in the previous paragraph has $5$ distinct eigenvalues but the underlying graph $G$ is disconnected, it follows from earlier that there is a $u,v$ such that the $uv$-th component of $A+A^2+A^3+A^4+A^5$ is $0$. So indeed, the statement as in the OP is false.
Comment: *"So this is nonzero for each , only if [but not necessarily if] the underlying graph  is connected"* -- note it is actually an **iff** in this case; a real symmetric matrix with 5 distinct eigenvalues tells you the minimal polynomial is degree 5
Comment: It may be true that connectedness $+ 5$ distinct eigenvalues implies $G$ has diameter $5$ or less [think of $5$ as the largest power of the adj matrix $A$ of $G$, not as the number of distinct eigenvalues] ***together*** gives all entries of $A+A^2+A^3+A^4+A^5$ nonzero. But I'm not seeing how the above comment establishes that, and you do need both conditions. The answer below shows $5$ distinct eigenvalues does not suffice. But neither does connectedness in and of itself; indeed take $G$ to be a path on $10$ vtcs.
Comment: *"But I'm not seeing how the above comment establishes that"* -- again, it is because $A$ has a *minimal polynomial* of degree 5; I take for granted that $A$ is real non-negative.  I.e. $\mathbf e_i^T A^k\mathbf e_j= 0$ for $k\in\big\{1,2,3,4,5\big\}$ for some $i,j$ implies there is no path from i to j since all positive integer powers of $A$ can be written as a linear combination of its first 5 powers.  (This logic of course works any time you have a minimal polynomial degree $\leq 5$.)
Comment: for avoidance of doubt: that was meant to read as $\mathbf e_i^T A^k\mathbf e_j= 0$ for *all* $k\in\big\{1,2,3,4,5\big\}$


new strings always relaxing. how do I speed up this process?

Question: every time I replace guitar strings, the strings will always relaxing for a few hours to become stable.
how do I speed up this process?
Comment: I do not think this is a duplicate. While the answer is covered in a different question, the question itself is different. The question linked above already assumes the answer to this question. A new user searching for this question would not find the link above. And if they did, they wouldn't necessarily realize that it was their answer.
Comment: See here: http://music.stackexchange.com/questions/1821/how-do-i-properly-stretch-my-newly-strung-strings
Answer: I used to stretch them in much the same manner as Alistair mentions, but I don't bother any more; I just tune 'em to pitch and deal with minor re-tuning.  I find that steel strings rapidly settle in.
If they aren't... It may be your string attachment procedure is not correct... Check out the Frets.com re-stringing guide to get the straight skinny.
Also, you don't mention, but nylon strings take MUCH longer to settle....
Answer: When I replace my strings, I follow the same process.
I take the old strings off, and then place the new one on. After this, I tune it to roughly the right pitch, and then place my thumb on the top of string and push down, while underneath my two fingers pull it up against the pressure of my thumb, stretching the length of the string a fair bit. This trick helps stretch the string ready for tuning, so that when it is tuned it settles quickly.
After that, I leave it, and repeat exactly the same process for each new string. At the end, I tune each string on the guitar up to pitch. The strings stay in tune very well after that, perhaps requiring a very small amount of fine-tuning after about 5 minutes, but they 'settle' very quickly.
Hope this helps!
Comment: That's pretty much what I do, or, just before I have it at true pitch I'll grab the string around the 12th fret and pull upwards a couple times to stretch it. It's basically the same after that. And, yes, I'll do another tune up after having played for a little bit and done some string bends. After that mine are stable for a long time. It takes a major string bend to make one go out a little bit.
Answer: Anwar,
When removing the old strings DON'T take them all of at once! :)
Remove the old string, then replace it with the corresponding new string.
If you remove all of the old strings at the same time, then proceed to string the guitar with the new strings you will be greatly decreasing, and then increasing, the tension on the neck.
This is not good for the neck, and could lead to tuning stability issues concerning the new strings you installed.
I usually remove/replace the strings ONE AT A TIME in this order and find it has greatly cut down on my tuning issues.
A G e B D E
Down then back up again. Remember to *stretch each string and tune to pitch about 3 or 4 times before moving on to the next string. Then when the guitar has all the new strings on it, go back and tune the entire guitar from low E to high e.
*Stretch a string by gently pushing it towards the floor then pulling it towards the ceiling a few times with the guitar in your lap. Then hold down the string at the 3rd fret and pull that string out, away from the body a few times; rinse and repeat at at frets 5, 7, 9, 11, 13, 15, 17, 19, 21. Careful not to pull or push to hard or you WILL break your new string! :(
Stringing a guitar takes some time. Maybe 20-25 minutes including setup and cleanup time.
Just don't rush through it and you'll be fine.
Hope this helps to solve your tuning issues!
Josh
Comment: A neck is much more stable than that. Removing all the strings won't cause any troubles. I remove all the strings at once when I restring and I have seen several sources both online and in books mention this approach as correct. Otherwise how do you clean/oil the neck? I also have had the strings removed for 2+ weeks on one of my guitars, beforehand I asked both a licensed Fender tech and on the TDPRI if it was ok and both assured me it was.
Comment: Of course it will cause trouble. Removing all strings dramatically changes the pressure exerted on the neck of the guitar. Relieving this pressure, and then quickly adding this pressure back by putting on a new set of strings can cause some serious problems for your instrument.
Comment: I clean and oil the neck without removing the strings so I don't see it as an issue. Removing all the strings and restringing may *shock* the neck when you release it from all of the tension that the strings provide. This decrease in tension/counter tension may require an adjustment of the truss rod, and will ultimately HAVE AN EFFECT on short-term tuning problems. IMO, unless you are an experienced luthier, it's best to restring one at a time in order to avoid the possibility of any complications. Assuming we are talking about traditional steel string electric and acoustic guitars, of course!
Answer: On guitars with Floyd Rose trems or similar, I just tune them about right, give them a good stretch by pulling back on the bar a few times and re-tune them.
That gets them pretty close so I just lock the nut at that point and any fine tuning can be done at gig time using the fine tuners at the bridge.
Comment: I also readjust my fine-tuners at that point to somewhere around the center point, otherwise I'll find one or two will bottom out just when I need it. :-/
Comment: Oo - good point! Although with mine I have them at almost the lowest point, as I invariably have to tune up, not down.


Prove that a funcion with greater derivative is greater

Question: Let $f,g\in C^1(I)$ where $I$ is a bounded open interval.
Let $x^*\in I$ and suppose that $g$ satisfy the equation $g'(x)=k\cdot g(x)^r$
and $f$ the inequality $f'(x)\geq k\cdot f(x)^r$ for all $x\geq x^*$. Where $k> 0$ and $r>1$.
I also have that $g(x^*)=f(x^*)>0$.
I'd like to show that $f(x)\geq g(x)\quad\forall x\geq x^*$ and I succeed when
$f'(x^*)>k\cdot f(x^*)^r$. But I don't know even if it's true when $f'(x^*)=k\cdot f(x^*)^r$.
Comment: See also [proof that $f(t)$ is less than or equal to $g(t)$](https://math.stackexchange.com/q/3366874/115115) for a more general statement of this situation.
Answer: The differential (in)equalities together with $g(x^*)=f(x^*)>0$ imply that both $f$ and $g$ are increasing and therefore strictly positive for $x \ge x^*$. Therefore we can conclude that
$$
\frac{f'(x)}{f(x)^r} \ge k = \frac{g'(x)}{g(x)^r}
$$
for $x \ge x^*$. Integrating this relation from $x^*$ to $x$ gives
$$
 \frac{1}{1-r} f(x)^{1-r} \ge \frac{1}{1-r} g(x)^{1-r}
$$
and consequently $f(x) \ge g(x)$.


WPF: Showing and hiding items in an ItemsControl with effects

Question: I've been using this great article as a basis for showing and hiding elements with a transition effect. It works very neatly in that it lets you bind the Visibility property just as normal, then define what happens when the visibility changes (e.g. animate its opacity or trigger a storyboard). When you hide an element, it uses value coercion to keep it visible until the transition is finished.
I'm looking for a similar solution to use with an ItemsControl and an ObservableCollection. In other words, I want to bind the ItemsSource to an ObservableCollection as normal, but control what happens when items are added and removed and trigger animations. I don't think using value coercion will work here, but obviously, items still need to stay in the list until their transitions finish. Does anyone know of any existing solutions that would make this easy?
I'd like any solution to be reasonably generic and easy to apply to lists of any kind of items. Ideally the style and animation behaviour would be separate, and applying it to a particular list would be a simple task such as giving it an attached property.
Comment: i have solution which will work for adding items... i am also looking for removing items thing...
Answer: Fade-in is easy, but for fade-out the items will need to stay in the source list until the animation is completed (like you said).
If we still want to be able to use the source ObservableCollection normally (Add/Remove etc.) then we would have to create a mirror collection that is constantly in sync with the source collection with a delay for delete until the animation is completed. This can be done with the CollectionChanged event.
Here is an implementation I made of this, using an attached behavior. It can be used for ItemsControl, ListBox, DataGrid or anything else that derives from ItemsControl.
Instead of Binding ItemsSource, bind the attached property ItemsSourceBehavior.ItemsSource. It will create a mirror ObservableCollection using Reflection, use the mirror as ItemsSource instead and handle the FadeIn/FadeOut animations.
Note that I haven't tested this extensively and there might be bugs and several improvements that can be made but it has worked great in my scenarios.
Sample Usage
<ListBox behaviors:ItemsSourceBehavior.ItemsSource="{Binding MyCollection}">
    <behaviors:ItemsSourceBehavior.FadeInAnimation>
        <Storyboard>
            <DoubleAnimation Storyboard.TargetProperty="Opacity"
                             From="0.0"
                             To="1.0"
                             Duration="0:0:3"/>
        </Storyboard>
    </behaviors:ItemsSourceBehavior.FadeInAnimation>
    <behaviors:ItemsSourceBehavior.FadeOutAnimation>
        <Storyboard>
            <DoubleAnimation Storyboard.TargetProperty="Opacity"
                             To="0.0"
                             Duration="0:0:1"/>
        </Storyboard>
    </behaviors:ItemsSourceBehavior.FadeOutAnimation>

</ListBox>

ItemsSourceBehavior
public class ItemsSourceBehavior
{
    public static readonly DependencyProperty ItemsSourceProperty =
        DependencyProperty.RegisterAttached("ItemsSource",
                                            typeof(IList),
                                            typeof(ItemsSourceBehavior),
                                            new UIPropertyMetadata(null, ItemsSourcePropertyChanged));
    public static void SetItemsSource(DependencyObject element, IList value)
    {
        element.SetValue(ItemsSourceProperty, value);
    }
    public static IList GetItemsSource(DependencyObject element)
    {
        return (IList)element.GetValue(ItemsSourceProperty);
    }

    private static void ItemsSourcePropertyChanged(DependencyObject source, DependencyPropertyChangedEventArgs e)
    {
        ItemsControl itemsControl = source as ItemsControl;
        IList itemsSource = e.NewValue as IList;
        if (itemsControl == null)
        {
            return;
        }
        if (itemsSource == null)
        {
            itemsControl.ItemsSource = null;
            return;
        }

        Type itemsSourceType = itemsSource.GetType();
        Type listType = typeof(ObservableCollection<>).MakeGenericType(itemsSourceType.GetGenericArguments()[0]);
        IList mirrorItemsSource = (IList)Activator.CreateInstance(listType);
        itemsControl.SetBinding(ItemsControl.ItemsSourceProperty, new Binding{ Source = mirrorItemsSource });

        foreach (object item in itemsSource)
        {
            mirrorItemsSource.Add(item);
        }
        FadeInContainers(itemsControl, itemsSource);

        (itemsSource as INotifyCollectionChanged).CollectionChanged +=
            (object sender, NotifyCollectionChangedEventArgs ne) =>
        {
            if (ne.Action == NotifyCollectionChangedAction.Add)
            {
                foreach (object newItem in ne.NewItems)
                {
                    mirrorItemsSource.Add(newItem);
                }
                FadeInContainers(itemsControl, ne.NewItems);
            }
            else if (ne.Action == NotifyCollectionChangedAction.Remove)
            {
                foreach (object oldItem in ne.OldItems)
                {
                    UIElement container = itemsControl.ItemContainerGenerator.ContainerFromItem(oldItem) as UIElement;
                    Storyboard fadeOutAnimation = GetFadeOutAnimation(itemsControl);
                    if (container != null && fadeOutAnimation != null)
                    {
                        Storyboard.SetTarget(fadeOutAnimation, container);

                        EventHandler onAnimationCompleted = null;
                        onAnimationCompleted = ((sender2, e2) =>
                        {
                            fadeOutAnimation.Completed -= onAnimationCompleted;
                            mirrorItemsSource.Remove(oldItem);
                        });

                        fadeOutAnimation.Completed += onAnimationCompleted;
                        fadeOutAnimation.Begin();
                    }
                    else
                    {
                        mirrorItemsSource.Remove(oldItem);
                    }
                }
            }
        };
    }

    private static void FadeInContainers(ItemsControl itemsControl, IList newItems)
    {
        EventHandler statusChanged = null;
        statusChanged = new EventHandler(delegate
        {
            if (itemsControl.ItemContainerGenerator.Status == GeneratorStatus.ContainersGenerated)
            {
                itemsControl.ItemContainerGenerator.StatusChanged -= statusChanged;
                foreach (object newItem in newItems)
                {
                    UIElement container = itemsControl.ItemContainerGenerator.ContainerFromItem(newItem) as UIElement;
                    Storyboard fadeInAnimation = GetFadeInAnimation(itemsControl);
                    if (container != null && fadeInAnimation != null)
                    {
                        Storyboard.SetTarget(fadeInAnimation, container);
                        fadeInAnimation.Begin();
                    }
                }
            }
        });
        itemsControl.ItemContainerGenerator.StatusChanged += statusChanged;
    }

    public static readonly DependencyProperty FadeInAnimationProperty =
        DependencyProperty.RegisterAttached("FadeInAnimation",
                                            typeof(Storyboard),
                                            typeof(ItemsSourceBehavior),
                                            new UIPropertyMetadata(null));
    public static void SetFadeInAnimation(DependencyObject element, Storyboard value)
    {
        element.SetValue(FadeInAnimationProperty, value);
    }
    public static Storyboard GetFadeInAnimation(DependencyObject element)
    {
        return (Storyboard)element.GetValue(FadeInAnimationProperty);
    }

    public static readonly DependencyProperty FadeOutAnimationProperty =
        DependencyProperty.RegisterAttached("FadeOutAnimation",
                                            typeof(Storyboard),
                                            typeof(ItemsSourceBehavior),
                                            new UIPropertyMetadata(null));
    public static void SetFadeOutAnimation(DependencyObject element, Storyboard value)
    {
        element.SetValue(FadeOutAnimationProperty, value);
    }
    public static Storyboard GetFadeOutAnimation(DependencyObject element)
    {
        return (Storyboard)element.GetValue(FadeOutAnimationProperty);
    }
}

Comment: This is a great solution! There was one small bug when starting the fade-out animation: the event handlers were not being removed from the storyboard so kept piling up resulting in multiple items being removed when one was removed. I've edited your answer and fixed the issue.
Comment: I'd got as far as the mirrored list previously but couldn't figure out how to attach the storyboard to items. My solution involved coercing the ItemsSource property to generate and return the mirrored list. That way you can continue using the same old ItemsSource property and set storyboards using styles. I'll post that solution here too if I get it working. Thanks Meleak.
Comment: @Tim Rogers: Coercing the ItemsSource property sounds great, will be interesting to see if you get it working! I'm also playing around with a move animation for 'NotifyCollectionChangedAction.Move', I'll update here as well if I manage to put something together
Comment: @Tim Rogers - this is just the thing I'm looking for. I'm just having trouble getting this working - would you have a sample project to show this more fully? Thanks.
Comment: It only began to work for me when I removed everything but `foreach` loop from `FadeInContainers`.
Comment: I updated the code so that the call to FadeInContainers happens before the items are added to the databound list as I was finding that the events that FadeInContainers was setting up to handle were being triggered immediately after the databound list was updated and therefore you were getting the previously added item faded in. This seems to be only an issue with ItemsControl and not a ListBox control.
Comment: Clone the Storyboard in the fadeout otherwise when 2 or more containers are being faded at the same time all Completed handlers will run when the first one Completes. Storyboard fadeOutAnimation = GetFadeOutAnimation(itemsControl).Clone();
Comment: Nice idea ! But the code does not work as expected (new Items are not faded in, instead older items are faded, fade out not working if multiple items are in the collection, and CollectionChanged event is never removed?). I'm using datatemplates ...
Answer: @Fredrik Hedblad
Nicely done. I do have a few remarks.

When adding an item the animation sometimes starts on the previously added item.
Inserting items into the list, added them all to the bottom (so no sorted list support)
(personal issue: needed separate animation for each item)

In code below in have an addapted version, which resolves the issues listed above.
public class ItemsSourceBehavior
{
    public static void SetItemsSource(DependencyObject element, IList value)
    {
        element.SetValue(ItemsSourceProperty, value);
    }

    public static IList GetItemsSource(DependencyObject element)
    {
        return (IList) element.GetValue(ItemsSourceProperty);
    }

    private static void ItemsSourcePropertyChanged(DependencyObject source, DependencyPropertyChangedEventArgs e)
    {
        //If animations need to be run together set this to 'false'.
        const bool separateAnimations = true;

        var itemsControl = source as ItemsControl;
        var itemsSource = e.NewValue as IList;
        if (itemsControl == null)
        {
            return;
        }
        if (itemsSource == null)
        {
            itemsControl.ItemsSource = null;
            return;
        }

        var itemsSourceType = itemsSource.GetType();
        var listType = typeof (ObservableCollection<>).MakeGenericType(itemsSourceType.GetGenericArguments()[0]);
        var mirrorItemsSource = (IList) Activator.CreateInstance(listType);
        itemsControl.SetBinding(ItemsControl.ItemsSourceProperty, new Binding {Source = mirrorItemsSource});

        foreach (var item in itemsSource)
        {
            mirrorItemsSource.Add(item);
            if (separateAnimations)
                StartFadeInAnimation(itemsControl, new List<object> {item});
        }

        if (!separateAnimations)
        {
            StartFadeInAnimation(itemsControl, itemsSource);
        }

        (itemsSource as INotifyCollectionChanged).CollectionChanged +=
            (object sender, NotifyCollectionChangedEventArgs ne) =>
            {
                if (ne.Action == NotifyCollectionChangedAction.Add)
                {
                    foreach (var newItem in ne.NewItems)
                    {
                        //insert the items instead of just adding them
                        //this brings support for sorted collections
                        mirrorItemsSource.Insert(ne.NewStartingIndex, newItem);

                        if (separateAnimations)
                        {
                            StartFadeInAnimation(itemsControl, new List<object> {newItem});
                        }
                    }

                    if (!separateAnimations)
                    {
                        StartFadeInAnimation(itemsControl, ne.NewItems);
                    }
                }
                else if (ne.Action == NotifyCollectionChangedAction.Remove)
                {
                    foreach (var oldItem in ne.OldItems)
                    {
                        var container = itemsControl.ItemContainerGenerator.ContainerFromItem(oldItem) as UIElement;
                        var fadeOutAnimation = GetFadeOutAnimation(itemsControl);
                        if (container != null && fadeOutAnimation != null)
                        {
                            Storyboard.SetTarget(fadeOutAnimation, container);

                            EventHandler onAnimationCompleted = null;
                            onAnimationCompleted = ((sender2, e2) =>
                            {
                                fadeOutAnimation.Completed -= onAnimationCompleted;
                                mirrorItemsSource.Remove(oldItem);
                            });

                            fadeOutAnimation.Completed += onAnimationCompleted;
                            fadeOutAnimation.Begin();
                        }
                        else
                        {
                            mirrorItemsSource.Remove(oldItem);
                        }
                    }
                }
            };
    }

    private static void StartFadeInAnimation(ItemsControl itemsControl, IList newItems)
    {
        foreach (var newItem in newItems)
        {
            var container = itemsControl.ItemContainerGenerator.ContainerFromItem(newItem) as UIElement;
            var fadeInAnimation = GetFadeInAnimation(itemsControl);
            if (container != null && fadeInAnimation != null)
            {
                Storyboard.SetTarget(fadeInAnimation, container);
                fadeInAnimation.Begin();
            }
        }
    }

    public static void SetFadeInAnimation(DependencyObject element, Storyboard value)
    {
        element.SetValue(FadeInAnimationProperty, value);
    }

    public static Storyboard GetFadeInAnimation(DependencyObject element)
    {
        return (Storyboard) element.GetValue(FadeInAnimationProperty);
    }

    public static void SetFadeOutAnimation(DependencyObject element, Storyboard value)
    {
        element.SetValue(FadeOutAnimationProperty, value);
    }

    public static Storyboard GetFadeOutAnimation(DependencyObject element)
    {
        return (Storyboard) element.GetValue(FadeOutAnimationProperty);
    }

    public static readonly DependencyProperty ItemsSourceProperty =
        DependencyProperty.RegisterAttached("ItemsSource",
            typeof (IList),
            typeof (ItemsSourceBehavior),
            new UIPropertyMetadata(null, ItemsSourcePropertyChanged));

    public static readonly DependencyProperty FadeInAnimationProperty =
        DependencyProperty.RegisterAttached("FadeInAnimation",
            typeof (Storyboard),
            typeof (ItemsSourceBehavior),
            new UIPropertyMetadata(null));

    public static readonly DependencyProperty FadeOutAnimationProperty =
        DependencyProperty.RegisterAttached("FadeOutAnimation",
            typeof (Storyboard),
            typeof (ItemsSourceBehavior),
            new UIPropertyMetadata(null));
}

Answer: Present framework does something similar to this. Here is a demo of it. You can make use of it or do something similar with VisualStateManager.
Comment: Similar, but it doesn't help me bind to an `ObservableCollection` and hook onto its events as far as I can see.


Como alterar um pull request de um fork que já excluí?

Question: Fiz um fork de um repositório, realizei as mudanças e fiz um pull request. Antes de aceitarem meu PR, eu excluí o fork, mas pediram para eu fazer alterações no código.
Como posso acessar a branch no qual eu tinha feito o pull request novamente, mesmo com meu fork excluído?
Comment: excluiu local e remoto? se sim, so sorry só se tiver backup, se tiver local pode fazer um push novamente
Answer: Isso só é possível pois o GitHub ainda tem suas alterações internamente, já que o pull request está aberto.
Com o origin configurado no remoto do repositório principal, você pode fazer um pull no seu pull request. Mude o número no exemplo abaixo, 1731, pelo número do seu PR:
git fetch origin pull/1731/head:minha-branch
git checkout minha-branch

Comment: Muito obrigado, funcionou!


Add basic page title and its teaser view in basic page

Question: I wanted to have one basic page, that allows me to add brief data about other basic pages like title and some data in teaser view. ie to create basic page, whose content is, some content of other basic pages.
I know that we can achieve this by using view. But I wanted to know if there is module available that allows me to do this, so that I can select the pages which are to be embed in the page I am creating.
Comment: If you know that views can solve your problem, why don't you go for it? It'll enable you to do what you require, rather than reinventing the wheel again.
Comment: But for that I have to create another content type for the pages that I need to embed, because I am not able to filter out the pages to be embed in this way.
Comment: You can filter the data on any other value, or create a new field to specify which ones you want (can be hidden in output). So you don't have to create a new content type.
Answer: You can try Node Embed module.
Node Embed provides an input filter for CKEditor & FCKEditor integration allowing a content editor the ability to embed the rendering of nodes within the body/fields of another node.
Nice documentation for this module can be found here.


Is a frequency modulated (in an FM synth) signal perceived by our ears in the same way as two signals played at the same time?

Question: Setup 1: oscillator with the carrier frequency and a oscillator modulating the carrier frequency.
Setup 2: two independent oscillators, one set to the carrier frequency and one with the modulation frequency.
Do we hear the same sound and/or timbre?
If so, this would mean that our ear just does what the FM synth does internally.
This was a side question in this thread and thank you for answering already @Kevin Reid, but I still would like to discuss this.
The following article shows two signals, playing together, and there are two graphs, one how they overlap and one how they are heared by our ears. Can anyone explain me, how that second graph would differ, if that previous signal would just be frequency-modulated before its played?
Background: I have the possibility to create many signals, but have only one frequency modulator parameter per signal. I have the idea, that I can just play the sounds together to "simulate" a signal going through multiple modulators. But somehow I think this is not working in practice.
Answer:
Setup 1: oscillator with the carrier frequency and a oscillator
modulating the carrier frequency.
Setup 2: two independent oscillators, one set to the carrier frequency and one with the
modulation frequency.
Do we hear the same sound and/or timber?

In general, no. Frequency-modulating a carrier with a modulator doesn't give you a result that just contains the frequencies of the carrier and the modulator; normally, the output signal is seen as containing a number of side bands.
See https://www.soundonsound.com/techniques/introduction-frequency-modulation and https://www.sfu.ca/~truax/fmtut.html for more details on the maths.

I have the idea, that I can just play the sounds together to "simulate" a signal going through multiple modulators

That wouldn't be modulation at all, but simply mixing.
Comment: @spikey I'm not an expert on the maths of FM, but mixing does mean adding in the "time domain", and FM doesn't mean multiplying in the "time domain". You are right that mixing a number of sinusoids is effectively additive synthesis (which is more my bag than FM!)
Comment: Thank you. I will invest some more time to look at the maths, I think they would help me too to understand the side bands. Is it wrong to say FM means multiplying and mixing means adding? (sorry, that was the first idea just that came to my mind, bevor I could reserve some time for studying the maths behind instead of just reading about the waves and application).
Comment: Ok, I think I got it (glad being corrected if not) for frequency modulation its not multiplication it is "recursion": `sin(2*Pi*Fc*t + I*sin(2*Pi*Fm*t)`.And playing two signals together, better refered as "mixing" is additive snythesis, where the cos() in sin() values are added up (sorry for this simplification of the fourier's expression).


Namespaces in .net

Question: I thought I knew the answer to this, but a compile error is telling me different.  I have created two separate libraries which contain the same stem namepsace; for example:
MyLib1.dll

contains
Common.MyFuncs.DoSomeStuff

And
MyLib2.dll

contains
Common.MyFuncs.DoOtherStuff

MyLib2.dll references myLib1.dll
When I include references to both in my project, MyLib1.dll is masking MyLib2.dll.  My question is simply, is this correct - i.e. is this what .net does?  I know it's possible to use extern for conflicting namepsaces, but I'm sure that I've seen namespaces shared across assemblies before (in fact, I'm sure that I've done it before), but I can't seem to find anything online to indicate I'm right or wrong.
Comment: You can use **aliases** (check properties page for each reference) to access _types_ in conflict (same name and same namespace from different DLLs). You can, for example, access `MyLib1.dll` types using `lib1::Common.MyFuncs` and `MyLib2.dll` types using `lib2::Common.MyFuncs`. By default they're all imported with the `global::` alias.
Answer: Namespaces don't "mask" each other, the same namespace can quite happily co-exist in multiple assemblies (in fact there are some System.* namespaces that exist across multiple assemblies). Are you sure that you don't have the same types defined in each assembly (maybe you've moved code but didn't rememove the original?), that way you won't get collisions between your types.
When you reference both projects, you still need to include a using Common.MyFuncs.[whatever]; statement at the top of each code file that needs to use the types from it.
Comment: I was fully qualifying the types.  The problem turned out to be a VS2013 taking a funny turn.  After a restart it all sprung to life again.

Namespaces in .net


Probability of picking 3 different colors from 56 Skittles

Question: Suppose that you have a bag full of Skittles. In the bag are exactly 12 red Skittles, 16 orange Skittles, 10 yellow Skittles, and 18 green Skittles.  If you reach into the bag and select three Skittles at random, what's the probability that the three Skittles will be of three different colors?
If I picked a red skittle the first time, the probability would be (12/56)(44/55)(???/54) How can I account for the fact that I can choose 1 of 3 colors for the second skittle? That would change the number of skittles I can choose for the third skittle.
Comment: With questions like this, it's usually best to think about the number of ways to end up with a desirable outcome, and then divide that number by the total number of possible outcomes.
Answer: I apologize for my previous answer...I didn't read the problem carefully.
Let's focus on the number of ways we can pick 3 skittles such that they are all the different. Let's first look at the number of ways to pick a red, orange, and yellow skittle. There are $12$ red skittles, $16$ orange skittles, and $10$ yellow skittles so there are $12 \cdot 16 \cdot 10$ different ways of picking a red, orange, and yellow skittle.
To get the total number of ways to pick 3 skittles of different colors, just consider all the ways to pick $3$ colors out of $4$ and find the number of ways for each color combination. Doing this, we get a total of
$$12 \cdot 16 \cdot 10 + 12\cdot 16 \cdot 18 + 16 \cdot 10 \cdot 18+12\cdot 10 \cdot 18$$
ways to pick $3$ skittles all of different colors.
Since there are ${12+16+10+18 \choose 3}$ ways to pick $3$ skittles in general, the probability is,
$$\frac{12 \cdot 16 \cdot 10 + 12\cdot 16 \cdot 18 + 16 \cdot 10 \cdot 18+12\cdot 10 \cdot 18}{{12+16+10+18 \choose 3}}$$
Comment: ...hm? Where's $12×10×18$?
Comment: @ParclyTaxel Oops, somehow forgot to include that combination. I edited my answer.
Answer: Skittles usually have a little s on them. We rub them out here and write the numbers 1–56 in their place so they are all distinct. The number of ways to choose 3 Skittles from 56 distinct ones is $\binom{56}3=27720$.
The number of such selections with the three colours distinct can be found case-by-case. Suppose the colours are red, orange and yellow; there are 12, 16 and 10 Skittles of the respective colours, and the number of selections with one of each is $12×16×10=1920$. Similar products apply for the other chromatically distinct combinations:

$12×16×18=3456$ for red/orange/green
$12×10×18=2160$ for red/yellow/green
$16×10×18=2880$ for orange/yellow/green

The total number of possibilities for three differently coloured Skittles is 10416. The final probability is then
$$\frac{10416}{27720}=\frac{62}{165}=0.376\text{ (3 dp)}$$


Generators of $GL(2, \mathbb{F}_3)$

Question: I came across the statement that for $GL(2, \mathbb{F}_3)$ we can choose generators $x$, $y$, $z$, that satisfy relations $x^4=y^3=z^2=xyz$, $(xyz)^2=1$. What matrices can I take for $x$, $y$, $z$?
Answer: The statement is not true, though it is close.  You can check this using the small groups library from within the computer algebra system GAP:
gap> f := FreeGroup( "x", "y", "z" );;
gap> g := f / ParseRelators( GeneratorsOfGroup(f),
> "x^4 = y^3 = z^2 = xyz, (xyz)^2 = 1" );;
gap> IdGroup( g );
[ 48, 28 ]
gap> IdGroup( GL(2,3) );
[ 48, 29 ]
gap> StructureDescription(g/Intersection(DerivedSubgroup(g),Center(g)));
"S4"

Thus the group defined by that presentation is a group of order 48 that is a double cover of S4 ≅ PGL(2,3), but it is the "other" Schur cover, not GL(2,3).  One important difference between these groups is their 2-local structure.  The Sylow 2-subgroup of GL(2,3) is a quasi-dihedral group of order 16, while the Sylow 2-subgroup of the "other" group is quaternion of order 16.  This might be easier to see at the element level: GL(2,3) has two different conjugacy classes of involutions (elements of order 2), while the "other" group has a unique class of involutions (both of these statements are also true for their Sylow 2-subgroups).
If you want matrices for this "other" group, you can again use GAP:
# In GAP 4.5:
gap> g := SchurCoverOfSymmetricGroup(4,3,1);;
# In GAP 4.4:
gap> g := Group([ [ [ 0*Z(3), Z(3) ], [ Z(3)^0, Z(3^2)^6 ] ],
> [ [ Z(3^2)^2, 0*Z(3) ], [ 0*Z(3), Z(3^2)^6 ] ] ]);;
# In either:
gap> xyz := Filtered( Tuples(g,3),
>  function(xyz)
>    local x,y,z;
>    x:=xyz[1];
>    y:=xyz[2];
>    z:=xyz[3];
>    return x^4 = y^3 and y^3 = z^2 and z^2 = x*y*z and (x*y*z)^2 = x^0
>    and Subgroup( g, xyz ) = g;
>  end );;
gap> orb := Orbits( AutomorphismGroup(g), xyz, OnTuples );;
gap> Size(orb);
1

so there is only one such generating set up to isomorphism.  We can display it in GAP:
gap> Display(orb[1][1][1]);
gap> Display(orb[1][1][2]);
gap> Display(orb[1][1][3]);

But TeX is a bit nicer:
$$
x = \left(\begin{array}{rr}0&1\\-1&\sqrt{2}\end{array}\right), \quad
y = \left(\begin{array}{rr}1&\sqrt{-1}\\\sqrt{-1}&0\end{array}\right), \quad
z = \left(\begin{array}{rr}\sqrt{-1}&0\\-1+\sqrt{-2}&-\sqrt{-1}\end{array}\right), \quad
$$
where √2 ≡ −√−1 mod 3, and √−2 ≡ 1 mod 3.
This defines a subgroup of GL(2,9) that is isoclinic but not isomorphic to GL(2,3).  Multiplying x and z by √−1 gives an isomorphic copy of GL(2,3).
Comment: Thanks, but I don't know what is GAP. Is it possible to see that we have two different groups by comparing some invariants of the groups such as number of elements of fixed order, automorphisms or any other invariants.
Comment: @Alex: I added a link to gap and a reasonably clear difference with their elements of order 2: the "other" group has a unique element of order 2, while GL(2,3) has 13 elements of order 2.
Comment: A Sylow 2-subgroup of your $\langle x,y,z:x^4=y^3=z^2=xyz, (xyz)^2=1\rangle$ is generated by $x$ and $yx^{-1}y$ and you can use the 2-dimensional representation in my answer to easily check that the subgroup is quaternion of order 16.
Answer: I just remark that ${\rm GL}(2,3)$ has a presentation $\langle x,y,z : x^8 = y^3 = z^2 = (xyz) = [x^4,y ] = 1 \rangle.$ This presentation gives a double cover of $S_4,$ but one which contains more than one involution, since $z \neq x^4.$
You can take $z = \left( \begin{array}{crclcr} 1 & 0\\ 0 & 2 \end{array} \right)$ and $y = \left( \begin{array}{clcr} 2 & 2\\1 & 0 \end{array} \right) .$

Generators of $GL(2, \mathbb{F}_3)$


Solve $\log_x (4x^{\log_5 x} + 5) = 2log_5 x$

Question: My attempt
$\log_5(4x^{log_5x}+5)=2(log_5x)^2$      Using $\log_ab=\frac{\log_cb}{\log_ca}$
$4x^{log_5x}+5=5^{2(log_5x)^2}$
Let $f=x^{log_5x}\Rightarrow \log_5 f = (log_5x)^2 \Rightarrow f= 5^{(\log_5 x)^2} $
We arrive at,
$ 4 *5^{(\log_5 x)^2}+5=5^{2(log_5x)^2};$        Let $5^{(\log_5 x)^2} = z$
$z^2-4z-5=0$
It gives;
$z=-1, 5$
$z=5$ gives $x=5, \frac{1}{5}.$ [Real solution]
$z=-1$ gives $5^{\sqrt{\log_5 (-1)}} = -0.0941629 - 4.90284 I$   [Complex solution]
Ques: I am suspecting that this complex solution should not be there, Could you please help me ?
Answer: It is so simple, check the domain and range of
$$5^{(\log_5 x)^2}$$
We know that
$$(\log_5 x)^2\ge0$$
So,
we get
$$5^{(\log_5 x)^2}\ge1$$
or $$z\ge 1$$
So,
$$z=5 $$ is the only solution.
Comment: oh!, I missed this point. thank you very much


Why do min/max width/height values don't allow the element to fill out its parent div?

Question: HTML:

CSS:
.content {
    min-height: 350px;
    min-width: 320px;
    max-width: 350px;
    padding: 15px;
}

.card {
    width: 100%;
    height: 100%;
    background-color: black;
}

http://jsfiddle.net/aJhEF/1/
When examined with console, it shows that .content has functioning width and height. Then why does the child element, with its width and height being set to 100% not fill out its parent's width and height?
Comment: You need to give it an explicit width/height, rather than only minimum and maximum values.
Answer: Child elements don't inherit their parents min-height property
This is why the .card element has a height of 0
As far as width is concerned, .card does fill out it's parent's width.
Comment: @styke After some googling I found [this post](http://stackoverflow.com/a/3808701/703717) - :)
Comment: This seems like strange behaviour. Do you know why they don't inherit min-height property?
Comment: It does not fill out it's parent as long as the padding is there. Padding is extra space on the INSIDE of the parent element, therefore this extra space is non-filled space of the parent element.
Comment: @Danield thanks Daniel, the post you found contains a workaround too. Take care.
Answer: Danield is right.
You might solve this by using relative and absolute positions, combined with a negative margin (to compensate the padding):
.content {
    min-height: 350px;
    min-width: 320px;
    max-width: 350px;
    padding: 15px;
    position: relative;
}

.card {
    width: 100%;
    height: 100%;
    background-color: black;
    position: absolute;
    margin: -15px;
}

Answer: Because you gave the parent a set padding.
Remove padding: 15px; to fill out the div.
padding is extra space at the inside of the elements borders. If you want space around the outside, use margin.
You stated that you wanted your child to fill out the parent element, and since padding it is extra space on the inside of the parent element, the child will not fill out it's parent as long as the padding is there.
Edit: The reason you don't see the results you wanted is because you have your element a min-height and min-width instead of actual sizes. You need to give this element set size (be it pixels or %). This is due to the fact that your child element doesn't inherit the min and max width/height of it's parent.
See JSFiddle
Comment: I've noticed if you remove the `min` prefixes, it fills it out, sans padding.


selecting column N of matrix/dataframe where N is based on another vector

Question: I have a dataframe X with several columns and want to select column N for each row where N is different for each row depending on some vector ( in this example : values in column sel)
    A   B   C   D   sel
16/04/2012  NA  -1.25   -1.25   0.25    1
17/04/2012  NA  20  21.25   17.25   1
18/04/2012  -5.25   -5.25   -5.75   -1  2
19/04/2012  -6  -6  -6.25   -12 2
20/04/2012  2.5 2.5 2.75    NA  2
23/04/2012  NA  -12.25  -12 NA  2
24/04/2012  NA  7.25    7.5 7.25    2
25/04/2012  NA  17.5    17  18.25   4
26/04/2012  NA  9.5 10  11.5    4
27/04/2012  NA  2   1   -3.25   4
30/04/2012  NA  -4.75   -4  -1  4
01/05/2012  NA  6.25    5.75    17  3
02/05/2012  NA  -3  -2.75   -16 3
03/05/2012  NA  -11.5   -11.5   -6.75   4
04/05/2012  NA  -23.5   -23.75  -23 4

so i would end up with
16/04/2012  NA
17/04/2012  NA
18/04/2012  -5.25
19/04/2012  -6
20/04/2012  2.5
23/04/2012  -12.25
24/04/2012  7.25
25/04/2012  18.25
26/04/2012  11.5
27/04/2012  -3.25
30/04/2012  -1
01/05/2012  5.75
02/05/2012  -2.75
03/05/2012  -6.75
04/05/2012  -23

X[,X$sel]
gave me a square matrix equal to nrow(X), not quite what i need.
is there some sort of "Excel's INDEX' type of functions i can use maybe inside an apply function?
Answer: You could use the method of subsetting a data frame by passing a two-column matrix with row numbers in the first column and column numbers in the second column. So:
X[matrix(ncol=2, c(1:nrow(X), X$sel)]

will give you a vector of those selected elements, which you can then build into whatever result data frame you're aiming for. Or just add to the existing data frame like this:
X$selected_values <- X[matrix(ncol=2, c(1:nrow(X), X$sel)]


Trying to show divs at bottomwhile hovering over menu items

Question: Please have a look at the codes (HTML and CSS) and please let me know how can I hover over one menu item and them the corresponding divs appear at the bottom. Let me know what is wrong with my code!!!
<!DOCTYPE html>

    <meta charset="utf-8">
        <title>Trying to show a div while hover over menu items</title>

                Home

            about

Comment: Not possible with the current HTML structure. The hovered `li` do not share a parent with `div` to be shown so your code will not work. I recommend a JS/JQ solution.
Comment: Hi, can you explain more clearly what you are after? what action are you after when you hover over menu_div element?
Comment: I recommend reading up on some JQuery, it will allow you to do slide-down effects. The way I would handle what you are trying to do would be to use a JQuery effect, on mouseenter you use the slideDown function which will reveal your div, and on mouseleave you use the slideUp function to hide the div again, this will give your site a 'flow' to it instead of jumpy hide and reveal effects. That being said, I don't see a way to do what you want without Javascript or Jquery.
Comment: @Harry, I want to hover over a menu item (e.g: Home) and want a div appear bellow the home button, and so on for other menu items as well.
Comment: @Paulie_d, can you please tell me what will be the correct code?
Answer: Your CSS selectors, although they may seem to be logically using the + adjacency operator, in fact, arent.
The direct adjacency selector is for DOM elements that come directly after one another. In your HTML, in order to reach the elements you wish to show you have to first traverse the DOM 'upward' to the parent menu_div element, then across to its sibling show_div and then down to the correct child. CSS cannot do this.
More on this from MDN

(+) This is referred to as an adjacent selector. It will select only
  the specified element that immediately follows the former specified
  element.

You will need to change your code per the below, to place the element you wish to show immediately following the element you wish to hover on, you may also want to control its positioning by setting position:absolute
Demo Fiddle

 Home

show me!

 about

show me!

CSS
  .menu_div {
      width: 300px;
      height: 50px;
      background-color:red;
      display: block;
  }
  .menu_div ul li {
      list-style: none;
      display:inline-block;
  }
  .show_div ul li {
      display: inline-block;
  }
  .show_div_one, .show_div_two {
      width: 300px;
      height: 50px;
      background-color: orange;
      margin-top: 50px;
      display: none;
      position:absolute; /* <--- keep the flow you anticipate */
  }
  .menu_div ul li.menu_item_one a:hover + .show_div_one {
      display:block;
  }
  .menu_div ul li.menu_item_two a:hover + .show_div_two {
      display:block;
  }

Comment: it works fine, Thanks, but where does this CSS code comes from:.show_div ul li {
      display: inline-block;
Comment: @user3812012 - its in your original code in your question
Answer: Why not use JQuery as this will be far better than relying on CSS alone.
Example: Fiddle
$( document ).ready( function() {
     $('.show_div_one').hide();

    $('.menu_item_one').hover(
    function(){
        $('.show_div_one').show();
    },
    function(){
        $('.show_div_one').hide();
    }
    );
});

Not tested, but thats the general idea for each one you would want to appear and disappear based on hover.


libvirtError that domain already exists, but virsh list doesn't show it

Question: When I try to launch an instance with OpenStack, I get the following error in nova-compute.log:
(nova.rpc): TRACE: libvirtError: operation failed: domain 'instance-0000000a' already exists with uuid 5f81a7d2-1b0f-8c72-4e1e-377c275e9289

However, virsh doesn't show any domains:
$ sudo virsh list
 Id Name                 State
----------------------------------

Why isn't that domain showing up in virsh if it's there?
Answer: Your domain may be shut down. Run virsh list --all to see all domains.
Comment: In case `virsh list --all` is empty but the problem persists you may want to try restarting the service `service libvirtd restart`.
Answer: Not yet familiar with OpenStack, but in regular old libvirt, that error usually implies not that there's a RUNNING instance, but that there's a DEFINED instance. "virsh list" only shows currently active VM's, not every defined VM. Try:
virsh edit instance-0000000a

If that pops open vim and has a bunch of XML in there, there's already a defined 'instance-0000000a' VM. If you are 100% sure you don't want it, quit out of the editor and use:
virsh undefine instance-0000000a

And then have OpenStack try whatever you were doing again, and it should work.
By the way, if you DO want what's there, you can start it with:
virsh start instance-0000000a

But again, not familiar with OpenStack, it may not like you doing that, no idea.
Comment: I don't know how I forgot "virsh list --all".. thanks to daff for reminding me. Use that instead of "virsh edit" to determine if the domain exists.
Comment: Thanks, 'virsh undefine' is exactly what I needed in the same situation.
Answer: Scenario 1:
Are you certain that virsh on the command line is talking to the same hypervisor as your OpenStack controller?  This would be the simplest explanation as two why virsh is not showing the running instance.
Scenario 2:
If you use ps, do you see any qemu-kvm instances running?  Try:
ps -fe | grep qemu-kvm

If there are qemu-kvm instances running, they'll have a -name parameter that should match the name used in virsh.  You can just kill -9 these processes if they're supposed to be dead anyway.
Comment: Or what @daff said.  That's probably it.
Answer: My issue was name resolution. The service libvirtd was not starting properly because the hostname wasn't resolving to the system's IP.
Added an entry to /etc/hosts for local system name and IP, then I could connect to VM guest.
Answer: Check if  you have installed
qemu-system-x86-xen
if not - install
apt install qemu-system-x86-xen
that helped me
Comment: This does not provide an answer to the question. Once you have sufficient [reputation](https://serverfault.com/help/whats-reputation) you will be able to [comment on any post](https://serverfault.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/late-answers/500526)


Problemas com sobreposição de elementos rotacionados

Question: Eu gostaria de poder girar uma div, e para isso usei  'transform', no CSS, porém eu gostaria que uma div ficasse sobreposta. Eis o código:

#divgirada {
  width: 500px;
  height: 500px;
  background: red;
  transition-duration: 1s;
}

#divgirada:hover {
  transform: rotate(10deg);
}

#divparada {
  width: 500px;
  height: 500px;
  background: blue;
  margin-top: -200px;
  margin-left: 200px;
}

  <title>Teste de rotação</title>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

O problema é que, apesar da div azul ficar em cima, no momento em que a div vermelha gira ela sobrepõe a azul. Como girar a div vermelha mas fazer com que a div azul continue em cima?
Answer: Como no que pus em baixo, bastou adicionar um position:relative nas 2 divs e pôr z-index em ambos, pondo o azul com o valor maior para ficar por cima

#divgirada {
  position:relative;
  z-index:998;
  width: 500px;
  height: 500px;
  background: red;
  transition-duration: 1s;
}

#divgirada:hover {
  transform: rotate(10deg);
}

#divparada {
  position:relative;
  z-index:999;
  width: 500px;
  height: 500px;
  background: blue;
  margin-top: -200px;
  margin-left: 200px;
}

  <title>Teste de rotação</title>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">


Linhas e colunas em html

Question: Não estou conseguindo fazer com que as colunas fiquem na mesma linha, estou utilizando o código abaixo, porém as colunas saem uma do lado da outra, e quero que fique na mesma linha.
    <!DOCTYPE html>

    <meta charset="UTF-8">
    <title></title>

algo aqui 1

algo aqui 2

algo aqui 3

Comment: @AnthraxisBR na tag da pergunta esta Bootstrap-3, mas inclui essa observação do BS3 ou BS4 na resposta de para deixar mais claro.
Comment: Você importou os estilos do bootstrap na pagina ?
Comment: Eu adicionei o código abaixo para importar o bootstrap
Comment: Mesmo com o Bootstrap não vai funciona com a classe col-4, tem que ser col-tamanho-numero (onde tamanho é lg, md, etc... e numero é o número de colunas que vc quer ocupar, de 1 a 12). Veja a minha resposta para entender melhor.
Comment: Você ta usando o bootstrap 4 ou o 3 ? para o 3 você precisa usar o indicador de tamanho col-md-3 ou outro tamanho, no 4 voce pode usar só col-3
Comment: @hugocsl não prestei atenção nisso, positivei a resposta ali
Answer: É porque vc está usando as classes do Grid de forma errada nas

Não deve ser col-4 deve ser assim: col-md-4 (onde está o MD, pode ser lg, md, sm, ou xs)
Documentação oficial do Grid do Bootstrap3: https://getbootstrap.com/docs/3.3/css/#grid
Dessa forma vai dar certo veja:

<meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" type="text/css" media="screen" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
    <link rel="stylesheet" type="text/css" media="screen" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" />

algo aqui 1

algo aqui 2

algo aqui 3

OBS: No exemplo usei XS para sempre ficar em 3 colunas, mesmo em telas pequenas

Se vc estiver usando Bootstrap 4 vc pode usar as colunas apenas como col-4 mesmo. Nesse caso o seu problema seria com a indexação do Bootstrap na  da sua página.
Veja o Exemplo no Bootstrap4

<link rel="stylesheet" type="text/css" media="screen" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous" />

algo aqui 1

algo aqui 2

algo aqui 3

Comment: Deu certo obrigada eu estou usando o Bootstrap 4 e não tinha indexado como na sua ultima resposta

Linhas e colunas em html


How can I link to a specific comment on drupal.org?

Question: I'm aware that you can use [#1234] syntax in posts on drupal.org issue pages.
However, is there any syntax to point to the specific comment, like: [#1234:12]?
I was using it before, but I forgot the syntax and I can't find it anywhere.
Comment: I usually mouse over the comment number, right click, and select copy link address.
Answer:
References to project issues in the form of [#1234] (or [#1234-2] for comments) turn into links automatically

That is from the very bottom of compose tips.
So just replace the colon with a hyphen and your guess would have been perfect.


Performance Ajax

Question: Desenvolvendo uma aplicação, e testando algumas chamadas ajax me deparei com duas situações diferentes, mas que, em ambas, tenho o retorno que preciso.
O que quero saber é, se existe alguma forma mais indicada, e qual a diferença entre elas, se alguma é mais rápida, etc...
Situação Primeira
Javascript
// ajax
get_ajax(1, true);
function get_ajax(id, aguardar) {
    $.ajax({
        type: 'GET',
        contentType: 'application/json; charset=utf-8',
        async: !aguardar,
        data: { id: id },
        url: 'controller/get_ajax',
        success: (...)
        error:(...)
    });
}

PHP
// controller
public function get_ajax()
{
    $id = $this->input->get('id');
    print_r($id);
}

Situação Segunda
Javascript
// ajax
get_ajax(1, true);
function get_ajax(id, aguardar) {
    $.ajax({
        type: 'GET',
        contentType: 'application/json; charset=utf-8',
        async: !aguardar,
        url: 'controller/get_ajax/' + id,
        success: (...)
        error:(...)
    });
}

PHP
// controller
public function get_ajax($id)
{
    print_r($id);
}

Aparentemente são iguais, exceto a forma como o argumento id está sendo passado.
Na primeira situação, estou enviando o id através de data: e recuperando no controller através do método GET.
Na segunda situação, estou enviando o id através da URL do ajax, e recuperando através do parâmetro.
Comment: Não há diferença significativa quanto à performance, principalmente quando usa o `jQuery`.
Comment: E não use `async:false`
Comment: Por qual motivo não usar false?
Answer: As duas formas estão corretas, o resultado vai ser o mesmo e acredito que não vá ter uma diferença de desempenho considerável.
Eu usaria a primeira situação só por achar mais organizado.

Performance Ajax


Python3 socket "AttributeError: '_io.BufferedReader' object has no attribute 'encode'"

Question: I'm new with coding but i'm trying to send a file via sockets. In this case a jpg but the idea is to make it send whatever files in whatever size. I can't find enough information on this and i have been trying to google and checking on stackoverflow but wont find anything that will help me so i decided to ask here on stackoverflow. I'm using PYTHON3
the idea is a server and a client. The client will send a file to the server. Here is the code....Thankful for help.
#SERVER CODE

import socket
import os
import sys

try:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    print("socket created...")
except:
    print("failed creating a socket.")

def srv_1(host, port):
    s.bind((host, port))
    s.listen(5)
    print("...Server Listening on port:", port, host)

    while True:
        c, addr = s.accept()
        print("ACCEPTED CONNECTION:-> ", addr)
        recivedData = c.recv(1024).decode() #this is going to be the
bits of file
        print("file size is :", recivedData)
        inpa = input("ACCEPT THE FILE? Y/N : ")
        if inpa == 'Y':
            acceptingFile = c.recv(1024).decode()
            while recivedData > 1024:
                data = c.recv(1024).decode()
                print("Reciving entire file:", recivedData)
                f = open(data,+"jpg", "wb")
                print("...Done saving...")
        elif inpa == 'N':
            s.close()
            print("...SOCKET CLOSED...")
    f = open(data,+"jpg", "wb")

if __name__ == '__main__':
    srv_1('127.0.0.1', 5460)

#CLIENT CODE
import socket
import os

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

host = "127.0.0.1"
port = 5460

def myC_F():

    try:
        s.connect((host, port))
        print("connected to socket")
    except:
        print("failed connecting to: ", host, port)

    fPath = input("Enter file to send:> ")
    fSize = os.path.getsize(fPath)
    fSize = str(fSize)
    s.send(fSize.encode())
    print("...DONE SENDING SIZE :", fSize)
    while True:
        with open(fPath, "rb") as f:
            s.sendall(f.encode())

myC_F()

The error i am getting is
$python3 my_vers_CLIENT.py
connected to socket
Enter file to send:> /home/pythonious/Desktop/171.jpg
...DONE SENDING SIZE : 41846
Traceback (most recent call last):
  File "my_vers_CLIENT.py", line 30, in <module>
    myC_F()
  File "my_vers_CLIENT.py", line 24, in myC_F
    s.sendall(f.encode())
AttributeError: '_io.BufferedReader' object has no attribute 'encode'

Answer: You probably wanted to use s.sendall(f.read()) instead of s.sendall(f.encode())


can't upload files from computer in any wysiwyg editor

Question: When I want to upload an image from an editor it only allows me to insert a URL and the ability to browse and upload a file is missing.
So there's something that behind all the wysiwyg editor that is preventing me from doing this and honestly don't know where to start looking for this.
Tried FCKeditor, CKeditor, jwysywig and TinyMCE and in all those cases I can only insert a URL but not upload from hard drive
There's a tutorial I found on youtube here. At 0:19 you'll see 4 tabs called 'Image Info', 'Links', 'Upload' and 'Advanced' respectively.
So my problem is the 'Upload' tab is missing from my editor as well as all other editor where this upload function is supposed to be.
Answer: The IMCE project provides upload capabilities to a variety of WYSIWYG editors. Check the project page for the appropriate way to install it for your particular editor.
Comment: It works. With you, does it enable you to upload your files from anywhere your local computer or just from folder on your server (online or offline)? With me, all IMCE does is create a button in my dialog window that says 'browse server'. That would be ok for me as builder of the site but the idea is to have users create their blog entries and be able to insert pictures via the wysiwyg editor from folders on their hard drive.
Comment: You should have an upload button in the IMCE toolbar. Each user then can upload assets to whatever directories IMCE is configured for (see /admin/config/media/imce). Then the assets can be placed in WYSIWYG content. Hope this helps.
Answer: If you are using D7 and need simple image upload from computer, CKEditor and One Click Upload will be another solution. No need IMCE in this case.